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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d786844386c0972a3304d71394c26317bf74ebf3 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/order/bounded_lattice.lean | 409d9ce00d9784504570835ed3aff30b8179377c | [
"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 | 50,359 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import data.option.basic
import logic.nontrivial
import order.lattice
import order.order_dual
import tactic.pi_instances
/-!
# ⊤ and ⊥, bounded lattices and variants
This file defines top and bottom elements (greatest and least elements) of a type, the bounded
variants of different kinds of lattices, sets up the typeclass hierarchy between them and provides
instances for `Prop` and `fun`.
## Main declarations
* `has_<top/bot> α`: Typeclasses to declare the `⊤`/`⊥` notation.
* `order_<top/bot> α`: Order mixin for a top/bottom element.
* `with_<top/bot> α`: Equips `option α` with the order on `α` plus `none` as the top/bottom element.
* `semilattice_<sup/inf>_<top/bot>`: Semilattice with a join/meet and a top/bottom element (all four
combinations). Typical examples include `ℕ`.
* `bounded_lattice α`: Lattice with a top and bottom element.
* `distrib_lattice_bot α`: Distributive lattice with a bottom element. It captures the properties
of `disjoint` that are common to `generalized_boolean_algebra` and `bounded_distrib_lattice`.
* `bounded_distrib_lattice α`: Bounded and distributive lattice. Typical examples include `Prop` and
`set α`.
* `is_compl x y`: In a bounded lattice, predicate for "`x` is a complement of `y`". Note that in a
non distributive lattice, an element can have several complements.
* `is_complemented α`: Typeclass stating that any element of a lattice has a complement.
## Implementation notes
We didn't define `distrib_lattice_top` because the dual notion of `disjoint` isn't really used
anywhere.
-/
/-! ### Top, bottom element -/
set_option old_structure_cmd true
universes u v
variables {α : Type u} {β : Type v}
/-- Typeclass for the `⊤` (`\top`) notation -/
@[notation_class] class has_top (α : Type u) := (top : α)
/-- Typeclass for the `⊥` (`\bot`) notation -/
@[notation_class] class has_bot (α : Type u) := (bot : α)
notation `⊤` := has_top.top
notation `⊥` := has_bot.bot
@[priority 100] instance has_top_nonempty (α : Type u) [has_top α] : nonempty α := ⟨⊤⟩
@[priority 100] instance has_bot_nonempty (α : Type u) [has_bot α] : nonempty α := ⟨⊥⟩
attribute [pattern] has_bot.bot has_top.top
/-- An order is an `order_top` if it has a greatest element.
We state this using a data mixin, holding the value of `⊤` and the greatest element constraint. -/
@[ancestor has_top]
class order_top (α : Type u) [has_le α] extends has_top α :=
(le_top : ∀ a : α, a ≤ ⊤)
section order_top
variables [partial_order α] [order_top α] {a b : α}
@[simp] theorem le_top {α : Type u} [has_le α] [order_top α] {a : α} : a ≤ ⊤ :=
order_top.le_top a
@[simp] theorem not_top_lt {α : Type u} [preorder α] [order_top α] {a : α} : ¬ ⊤ < a :=
λ h, lt_irrefl a (lt_of_le_of_lt le_top h)
theorem top_unique (h : ⊤ ≤ a) : a = ⊤ :=
le_top.antisymm h
-- TODO: delete in favor of the next?
theorem eq_top_iff : a = ⊤ ↔ ⊤ ≤ a :=
⟨λ eq, eq.symm ▸ le_refl ⊤, top_unique⟩
@[simp] theorem top_le_iff : ⊤ ≤ a ↔ a = ⊤ :=
⟨top_unique, λ h, h.symm ▸ le_refl ⊤⟩
@[simp] theorem is_top_iff_eq_top : is_top a ↔ a = ⊤ :=
⟨λ h, h.unique le_top, λ h b, h.symm ▸ le_top⟩
theorem eq_top_mono (h : a ≤ b) (h₂ : a = ⊤) : b = ⊤ :=
top_le_iff.1 $ h₂ ▸ h
lemma lt_top_iff_ne_top : a < ⊤ ↔ a ≠ ⊤ := le_top.lt_iff_ne
lemma ne_top_of_lt (h : a < b) : a ≠ ⊤ :=
lt_top_iff_ne_top.1 $ lt_of_lt_of_le h le_top
alias ne_top_of_lt ← has_lt.lt.ne_top
theorem ne_top_of_le_ne_top {a b : α} (hb : b ≠ ⊤) (hab : a ≤ b) : a ≠ ⊤ :=
λ ha, hb $ top_unique $ ha ▸ hab
lemma eq_top_of_maximal (h : ∀ b, ¬ a < b) : a = ⊤ :=
or.elim (lt_or_eq_of_le le_top) (λ hlt, absurd hlt (h ⊤)) (λ he, he)
lemma ne.lt_top (h : a ≠ ⊤) : a < ⊤ := lt_top_iff_ne_top.mpr h
lemma ne.lt_top' (h : ⊤ ≠ a) : a < ⊤ := h.symm.lt_top
end order_top
lemma strict_mono.maximal_preimage_top [linear_order α] [preorder β] [order_top β]
{f : α → β} (H : strict_mono f) {a} (h_top : f a = ⊤) (x : α) :
x ≤ a :=
H.maximal_of_maximal_image (λ p, by { rw h_top, exact le_top }) x
theorem order_top.ext_top {α} {hA : partial_order α} (A : order_top α)
{hB : partial_order α} (B : order_top α)
(H : ∀ x y : α, (by haveI := hA; exact x ≤ y) ↔ x ≤ y) :
(by haveI := A; exact ⊤ : α) = ⊤ :=
top_unique $ by rw ← H; apply le_top
theorem order_top.ext {α} [partial_order α] {A B : order_top α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
have tt := order_top.ext_top A B H,
casesI A with _ ha, casesI B with _ hb,
congr,
exact le_antisymm (hb _) (ha _)
end
/-- An order is an `order_bot` if it has a least element.
We state this using a data mixin, holding the value of `⊥` and the least element constraint. -/
@[ancestor has_bot]
class order_bot (α : Type u) [has_le α] extends has_bot α :=
(bot_le : ∀ a : α, ⊥ ≤ a)
section order_bot
variables [partial_order α] [order_bot α] {a b : α}
@[simp] theorem bot_le {α : Type u} [has_le α] [order_bot α] {a : α} : ⊥ ≤ a := order_bot.bot_le a
@[simp] theorem not_lt_bot {α : Type u} [preorder α] [order_bot α] {a : α} : ¬ a < ⊥ :=
λ h, lt_irrefl a (lt_of_lt_of_le h bot_le)
theorem bot_unique (h : a ≤ ⊥) : a = ⊥ :=
h.antisymm bot_le
-- TODO: delete?
theorem eq_bot_iff : a = ⊥ ↔ a ≤ ⊥ :=
⟨λ eq, eq.symm ▸ le_refl ⊥, bot_unique⟩
@[simp] theorem le_bot_iff : a ≤ ⊥ ↔ a = ⊥ :=
⟨bot_unique, λ h, h.symm ▸ le_refl ⊥⟩
@[simp] theorem is_bot_iff_eq_bot : is_bot a ↔ a = ⊥ :=
⟨λ h, h.unique bot_le, λ h b, h.symm ▸ bot_le⟩
theorem ne_bot_of_le_ne_bot {a b : α} (hb : b ≠ ⊥) (hab : b ≤ a) : a ≠ ⊥ :=
λ ha, hb $ bot_unique $ ha ▸ hab
theorem eq_bot_mono (h : a ≤ b) (h₂ : b = ⊥) : a = ⊥ :=
le_bot_iff.1 $ h₂ ▸ h
lemma bot_lt_iff_ne_bot : ⊥ < a ↔ a ≠ ⊥ :=
begin
haveI := classical.dec_eq α,
haveI : decidable (a ≤ ⊥) := decidable_of_iff' _ le_bot_iff,
simp only [lt_iff_le_not_le, not_iff_not.mpr le_bot_iff, true_and, bot_le],
end
lemma ne_bot_of_gt (h : a < b) : b ≠ ⊥ :=
bot_lt_iff_ne_bot.1 $ lt_of_le_of_lt bot_le h
alias ne_bot_of_gt ← has_lt.lt.ne_bot
lemma eq_bot_of_minimal (h : ∀ b, ¬ b < a) : a = ⊥ :=
or.elim (lt_or_eq_of_le bot_le) (λ hlt, absurd hlt (h ⊥)) (λ he, he.symm)
lemma ne.bot_lt (h : a ≠ ⊥) : ⊥ < a := bot_lt_iff_ne_bot.mpr h
lemma ne.bot_lt' (h : ⊥ ≠ a) : ⊥ < a := h.symm.bot_lt
end order_bot
lemma strict_mono.minimal_preimage_bot [linear_order α] [partial_order β] [order_bot β]
{f : α → β} (H : strict_mono f) {a} (h_bot : f a = ⊥) (x : α) :
a ≤ x :=
H.minimal_of_minimal_image (λ p, by { rw h_bot, exact bot_le }) x
theorem order_bot.ext_bot {α} [partial_order α] (A B : order_bot α)
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) :
(by haveI := A; exact ⊥ : α) = ⊥ :=
bot_unique $ by rw ← H; apply bot_le
theorem order_bot.ext {α} [partial_order α] {A B : order_bot α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
have := partial_order.ext H,
have tt := order_bot.ext_bot A B H,
casesI A with a ha, casesI B with b hb,
congr,
exact le_antisymm (ha _) (hb _)
end
/-- A `semilattice_sup_top` is a semilattice with top and join. -/
class semilattice_sup_top (α : Type u) extends semilattice_sup α, has_top α :=
(le_top : ∀ a : α, a ≤ ⊤)
section semilattice_sup_top
variables [semilattice_sup_top α] {a : α}
@[priority 100] -- see Note [lower instance priority]
instance semilattice_sup_top.to_order_top : order_top α :=
{ top := ⊤,
le_top := semilattice_sup_top.le_top }
@[simp] theorem top_sup_eq : ⊤ ⊔ a = ⊤ :=
sup_of_le_left le_top
@[simp] theorem sup_top_eq : a ⊔ ⊤ = ⊤ :=
sup_of_le_right le_top
end semilattice_sup_top
/-- A `semilattice_sup_bot` is a semilattice with bottom and join. -/
class semilattice_sup_bot (α : Type u) extends semilattice_sup α, has_bot α :=
(bot_le : ∀ a : α, ⊥ ≤ a)
section semilattice_sup_bot
variables [semilattice_sup_bot α] {a b : α}
@[priority 100] -- see Note [lower instance priority]
instance semilattice_sup_bot.to_order_bot : order_bot α :=
{ bot := ⊥,
bot_le := semilattice_sup_bot.bot_le }
@[simp] theorem bot_sup_eq : ⊥ ⊔ a = a :=
sup_of_le_right bot_le
@[simp] theorem sup_bot_eq : a ⊔ ⊥ = a :=
sup_of_le_left bot_le
@[simp] theorem sup_eq_bot_iff : a ⊔ b = ⊥ ↔ (a = ⊥ ∧ b = ⊥) :=
by rw [eq_bot_iff, sup_le_iff]; simp
end semilattice_sup_bot
instance nat.semilattice_sup_bot : semilattice_sup_bot ℕ :=
{ bot := 0, bot_le := nat.zero_le, .. nat.distrib_lattice }
/-- A `semilattice_inf_top` is a semilattice with top and meet. -/
class semilattice_inf_top (α : Type u) extends semilattice_inf α, has_top α :=
(le_top : ∀ a : α, a ≤ ⊤)
section semilattice_inf_top
variables [semilattice_inf_top α] {a b : α}
@[priority 100] -- see Note [lower instance priority]
instance semilattice_inf_top.to_order_top : order_top α :=
{ top := ⊤,
le_top := semilattice_inf_top.le_top }
@[simp] theorem top_inf_eq : ⊤ ⊓ a = a :=
inf_of_le_right le_top
@[simp] theorem inf_top_eq : a ⊓ ⊤ = a :=
inf_of_le_left le_top
@[simp] theorem inf_eq_top_iff : a ⊓ b = ⊤ ↔ (a = ⊤ ∧ b = ⊤) :=
by rw [eq_top_iff, le_inf_iff]; simp
end semilattice_inf_top
/-- A `semilattice_inf_bot` is a semilattice with bottom and meet. -/
class semilattice_inf_bot (α : Type u) extends semilattice_inf α, has_bot α :=
(bot_le : ∀ a : α, ⊥ ≤ a)
section semilattice_inf_bot
variables [semilattice_inf_bot α] {a : α}
@[priority 100] -- see Note [lower instance priority]
instance semilattice_inf_bot.to_order_bot : order_bot α :=
{ bot := ⊥,
bot_le := semilattice_inf_bot.bot_le }
@[simp] theorem bot_inf_eq : ⊥ ⊓ a = ⊥ :=
inf_of_le_left bot_le
@[simp] theorem inf_bot_eq : a ⊓ ⊥ = ⊥ :=
inf_of_le_right bot_le
end semilattice_inf_bot
/-! ### Bounded lattice -/
/-- A bounded lattice is a lattice with a top and bottom element,
denoted `⊤` and `⊥` respectively. This allows for the interpretation
of all finite suprema and infima, taking `inf ∅ = ⊤` and `sup ∅ = ⊥`. -/
class bounded_lattice (α : Type u) extends lattice α, has_top α, has_bot α :=
(le_top : ∀ a : α, a ≤ ⊤)
(bot_le : ∀ a : α, ⊥ ≤ a)
@[priority 100] -- see Note [lower instance priority]
instance semilattice_inf_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] :
semilattice_inf_top α :=
{ ..bl }
@[priority 100] -- see Note [lower instance priority]
instance semilattice_inf_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] :
semilattice_inf_bot α :=
{ ..bl }
@[priority 100] -- see Note [lower instance priority]
instance semilattice_sup_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] :
semilattice_sup_top α :=
{ ..bl }
@[priority 100] -- see Note [lower instance priority]
instance semilattice_sup_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] :
semilattice_sup_bot α :=
{ ..bl }
theorem bounded_lattice.ext {α} {A B : bounded_lattice α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
have H1 : @bounded_lattice.to_lattice α A =
@bounded_lattice.to_lattice α B := lattice.ext H,
have H2 := partial_order.ext H,
letI : partial_order α := by apply_instance,
casesI A,
casesI B,
injection H1 with h1 h2 h3 h4,
injection H2,
convert rfl,
{ exact h1.symm },
{ exact h2.symm },
{ exact h3.symm },
{ exact h4.symm },
have : A_le = B_le := h2,
subst A_le,
{ exact le_antisymm (A_le_top _) (B_le_top _) },
refine le_antisymm (B_bot_le _) _,
convert A_bot_le _,
convert rfl
end
/-- A `distrib_lattice_bot` is a distributive lattice with a least element. -/
class distrib_lattice_bot α extends distrib_lattice α, semilattice_inf_bot α, semilattice_sup_bot α
/-- A bounded distributive lattice is exactly what it sounds like. -/
class bounded_distrib_lattice α extends distrib_lattice_bot α, bounded_lattice α
/-- Propositions form a bounded distributive lattice. -/
instance Prop.bounded_distrib_lattice : bounded_distrib_lattice Prop :=
{ le := λ a b, a → b,
le_refl := λ _, id,
le_trans := λ a b c f g, g ∘ f,
le_antisymm := λ a b Hab Hba, propext ⟨Hab, Hba⟩,
sup := or,
le_sup_left := @or.inl,
le_sup_right := @or.inr,
sup_le := λ a b c, or.rec,
inf := and,
inf_le_left := @and.left,
inf_le_right := @and.right,
le_inf := λ a b c Hab Hac Ha, and.intro (Hab Ha) (Hac Ha),
le_sup_inf := λ a b c H, or_iff_not_imp_left.2 $
λ Ha, ⟨H.1.resolve_left Ha, H.2.resolve_left Ha⟩,
top := true,
le_top := λ a Ha, true.intro,
bot := false,
bot_le := @false.elim }
noncomputable instance Prop.linear_order : linear_order Prop :=
@lattice.to_linear_order Prop _ (classical.dec_eq _) (classical.dec_rel _) (classical.dec_rel _) $
λ p q, by { change (p → q) ∨ (q → p), tauto! }
@[simp] lemma le_Prop_eq : ((≤) : Prop → Prop → Prop) = (→) := rfl
@[simp] lemma sup_Prop_eq : (⊔) = (∨) := rfl
@[simp] lemma inf_Prop_eq : (⊓) = (∧) := rfl
section logic
variable [preorder α]
theorem monotone_and {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) :
monotone (λ x, p x ∧ q x) :=
λ a b h, and.imp (m_p h) (m_q h)
-- Note: by finish [monotone] doesn't work
theorem monotone_or {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) :
monotone (λ x, p x ∨ q x) :=
λ a b h, or.imp (m_p h) (m_q h)
end logic
instance pi.order_bot {α : Type*} {β : α → Type*} [∀ a, preorder $ β a] [∀ a, order_bot $ β a] :
order_bot (Π a, β a) :=
{ bot := λ _, ⊥,
bot_le := λ x a, bot_le }
/-! ### Function lattices -/
namespace pi
variables {ι : Type*} {α' : ι → Type*}
instance [Π i, has_bot (α' i)] : has_bot (Π i, α' i) := ⟨λ i, ⊥⟩
@[simp] lemma bot_apply [Π i, has_bot (α' i)] (i : ι) : (⊥ : Π i, α' i) i = ⊥ := rfl
lemma bot_def [Π i, has_bot (α' i)] : (⊥ : Π i, α' i) = λ i, ⊥ := rfl
instance [Π i, has_top (α' i)] : has_top (Π i, α' i) := ⟨λ i, ⊤⟩
@[simp] lemma top_apply [Π i, has_top (α' i)] (i : ι) : (⊤ : Π i, α' i) i = ⊤ := rfl
lemma top_def [Π i, has_top (α' i)] : (⊤ : Π i, α' i) = λ i, ⊤ := rfl
instance [Π i, semilattice_inf_bot (α' i)] : semilattice_inf_bot (Π i, α' i) :=
by refine_struct { inf := (⊓), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field
instance [Π i, semilattice_inf_top (α' i)] : semilattice_inf_top (Π i, α' i) :=
by refine_struct { inf := (⊓), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field
instance [Π i, semilattice_sup_bot (α' i)] : semilattice_sup_bot (Π i, α' i) :=
by refine_struct { sup := (⊔), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field
instance [Π i, semilattice_sup_top (α' i)] : semilattice_sup_top (Π i, α' i) :=
by refine_struct { sup := (⊔), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field
instance [Π i, bounded_lattice (α' i)] : bounded_lattice (Π i, α' i) :=
{ .. pi.semilattice_sup_top, .. pi.semilattice_inf_bot }
instance [Π i, distrib_lattice_bot (α' i)] : distrib_lattice_bot (Π i, α' i) :=
{ bot := λ _, ⊥,
bot_le := λ _ _, bot_le,
.. pi.distrib_lattice }
instance [Π i, bounded_distrib_lattice (α' i)] : bounded_distrib_lattice (Π i, α' i) :=
{ .. pi.bounded_lattice, .. pi.distrib_lattice }
end pi
lemma eq_bot_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = ⊤) (x : α) :
x = (⊥ : α) :=
eq_bot_mono le_top (eq.symm hα)
lemma eq_top_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = ⊤) (x : α) :
x = (⊤ : α) :=
eq_top_mono bot_le hα
lemma subsingleton_of_top_le_bot {α : Type*} [bounded_lattice α] (h : (⊤ : α) ≤ (⊥ : α)) :
subsingleton α :=
⟨λ a b, le_antisymm (le_trans le_top $ le_trans h bot_le) (le_trans le_top $ le_trans h bot_le)⟩
lemma subsingleton_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = (⊤ : α)) :
subsingleton α :=
subsingleton_of_top_le_bot (ge_of_eq hα)
lemma subsingleton_iff_bot_eq_top {α : Type*} [bounded_lattice α] :
(⊥ : α) = (⊤ : α) ↔ subsingleton α :=
⟨subsingleton_of_bot_eq_top, λ h, by exactI subsingleton.elim ⊥ ⊤⟩
/-! ### `with_bot`, `with_top` -/
/-- Attach `⊥` to a type. -/
def with_bot (α : Type*) := option α
namespace with_bot
meta instance {α} [has_to_format α] : has_to_format (with_bot α) :=
{ to_format := λ x,
match x with
| none := "⊥"
| (some x) := to_fmt x
end }
instance : has_coe_t α (with_bot α) := ⟨some⟩
instance has_bot : has_bot (with_bot α) := ⟨none⟩
instance : inhabited (with_bot α) := ⟨⊥⟩
lemma none_eq_bot : (none : with_bot α) = (⊥ : with_bot α) := rfl
lemma some_eq_coe (a : α) : (some a : with_bot α) = (↑a : with_bot α) := rfl
@[simp] theorem bot_ne_coe (a : α) : ⊥ ≠ (a : with_bot α) .
@[simp] theorem coe_ne_bot (a : α) : (a : with_bot α) ≠ ⊥ .
/-- Recursor for `with_bot` using the preferred forms `⊥` and `↑a`. -/
@[elab_as_eliminator]
def rec_bot_coe {C : with_bot α → Sort*} (h₁ : C ⊥) (h₂ : Π (a : α), C a) :
Π (n : with_bot α), C n :=
option.rec h₁ h₂
@[norm_cast]
theorem coe_eq_coe {a b : α} : (a : with_bot α) = b ↔ a = b :=
by rw [← option.some.inj_eq a b]; refl
lemma ne_bot_iff_exists {x : with_bot α} : x ≠ ⊥ ↔ ∃ (a : α), ↑a = x :=
option.ne_none_iff_exists
/-- Deconstruct a `x : with_bot α` to the underlying value in `α`, given a proof that `x ≠ ⊥`. -/
def unbot : Π (x : with_bot α), x ≠ ⊥ → α
| ⊥ h := absurd rfl h
| (some x) h := x
@[simp] lemma coe_unbot {α : Type*} (x : with_bot α) (h : x ≠ ⊥) :
(x.unbot h : with_bot α) = x :=
by { cases x, simpa using h, refl, }
@[simp] lemma unbot_coe (x : α) (h : (x : with_bot α) ≠ ⊥ := coe_ne_bot _) :
(x : with_bot α).unbot h = x := rfl
@[priority 10]
instance has_le [has_le α] : has_le (with_bot α) :=
{ le := λ o₁ o₂ : option α, ∀ a ∈ o₁, ∃ b ∈ o₂, a ≤ b }
@[priority 10]
instance has_lt [has_lt α] : has_lt (with_bot α) :=
{ lt := λ o₁ o₂ : option α, ∃ b ∈ o₂, ∀ a ∈ o₁, a < b }
@[simp] theorem some_lt_some [has_lt α] {a b : α} :
@has_lt.lt (with_bot α) _ (some a) (some b) ↔ a < b :=
by simp [(<)]
lemma none_lt_some [has_lt α] (a : α) :
@has_lt.lt (with_bot α) _ none (some a) :=
⟨a, rfl, λ b hb, (option.not_mem_none _ hb).elim⟩
lemma bot_lt_coe [has_lt α] (a : α) : (⊥ : with_bot α) < a := none_lt_some a
instance : can_lift (with_bot α) α :=
{ coe := coe,
cond := λ r, r ≠ ⊥,
prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ }
instance [preorder α] : preorder (with_bot α) :=
{ le := (≤),
lt := (<),
lt_iff_le_not_le := by intros; cases a; cases b;
simp [lt_iff_le_not_le]; simp [(≤), (<)];
split; refl,
le_refl := λ o a ha, ⟨a, ha, le_refl _⟩,
le_trans := λ o₁ o₂ o₃ h₁ h₂ a ha,
let ⟨b, hb, ab⟩ := h₁ a ha, ⟨c, hc, bc⟩ := h₂ b hb in
⟨c, hc, le_trans ab bc⟩ }
instance partial_order [partial_order α] : partial_order (with_bot α) :=
{ le_antisymm := λ o₁ o₂ h₁ h₂, begin
cases o₁ with a,
{ cases o₂ with b, {refl},
rcases h₂ b rfl with ⟨_, ⟨⟩, _⟩ },
{ rcases h₁ a rfl with ⟨b, ⟨⟩, h₁'⟩,
rcases h₂ b rfl with ⟨_, ⟨⟩, h₂'⟩,
rw le_antisymm h₁' h₂' }
end,
.. with_bot.preorder }
instance order_bot [has_le α] : order_bot (with_bot α) :=
{ bot_le := λ a a' h, option.no_confusion h,
..with_bot.has_bot }
@[simp, norm_cast] theorem coe_le_coe [has_le α] {a b : α} :
(a : with_bot α) ≤ b ↔ a ≤ b :=
⟨λ h, by rcases h a rfl with ⟨_, ⟨⟩, h⟩; exact h,
λ h a' e, option.some_inj.1 e ▸ ⟨b, rfl, h⟩⟩
@[simp] theorem some_le_some [has_le α] {a b : α} :
@has_le.le (with_bot α) _ (some a) (some b) ↔ a ≤ b := coe_le_coe
theorem coe_le [has_le α] {a b : α} :
∀ {o : option α}, b ∈ o → ((a : with_bot α) ≤ o ↔ a ≤ b)
| _ rfl := coe_le_coe
@[norm_cast]
lemma coe_lt_coe [has_lt α] {a b : α} : (a : with_bot α) < b ↔ a < b := some_lt_some
lemma le_coe_get_or_else [preorder α] : ∀ (a : with_bot α) (b : α), a ≤ a.get_or_else b
| (some a) b := le_refl a
| none b := λ _ h, option.no_confusion h
@[simp] lemma get_or_else_bot (a : α) : option.get_or_else (⊥ : with_bot α) a = a := rfl
lemma get_or_else_bot_le_iff [has_le α] [order_bot α] {a : with_bot α} {b : α} :
a.get_or_else ⊥ ≤ b ↔ a ≤ b :=
by cases a; simp [none_eq_bot, some_eq_coe]
instance decidable_le [has_le α] [@decidable_rel α (≤)] : @decidable_rel (with_bot α) (≤)
| none x := is_true $ λ a h, option.no_confusion h
| (some x) (some y) :=
if h : x ≤ y
then is_true (some_le_some.2 h)
else is_false $ by simp *
| (some x) none := is_false $ λ h, by rcases h x rfl with ⟨y, ⟨_⟩, _⟩
instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_bot α) (<)
| none (some x) := is_true $ by existsi [x,rfl]; rintros _ ⟨⟩
| (some x) (some y) :=
if h : x < y
then is_true $ by simp *
else is_false $ by simp *
| x none := is_false $ by rintro ⟨a,⟨⟨⟩⟩⟩
instance [partial_order α] [is_total α (≤)] : is_total (with_bot α) (≤) :=
{ total := λ a b, match a, b with
| none , _ := or.inl bot_le
| _ , none := or.inr bot_le
| some x, some y := by simp only [some_le_some, total_of]
end }
instance semilattice_sup [semilattice_sup α] : semilattice_sup_bot (with_bot α) :=
{ sup := option.lift_or_get (⊔),
le_sup_left := λ o₁ o₂ a ha,
by cases ha; cases o₂; simp [option.lift_or_get],
le_sup_right := λ o₁ o₂ a ha,
by cases ha; cases o₁; simp [option.lift_or_get],
sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases o₁ with b; cases o₂ with c; cases ha,
{ exact h₂ a rfl },
{ exact h₁ a rfl },
{ rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩,
simp at h₂,
exact ⟨d, rfl, sup_le h₁' h₂⟩ }
end,
..with_bot.order_bot,
..with_bot.partial_order }
lemma coe_sup [semilattice_sup α] (a b : α) : ((a ⊔ b : α) : with_bot α) = a ⊔ b := rfl
instance semilattice_inf [semilattice_inf α] : semilattice_inf_bot (with_bot α) :=
{ inf := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊓ b)),
inf_le_left := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, inf_le_left⟩
end,
inf_le_right := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, inf_le_right⟩
end,
le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases ha,
rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩,
rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩,
exact ⟨_, rfl, le_inf ab ac⟩
end,
..with_bot.order_bot,
..with_bot.partial_order }
lemma coe_inf [semilattice_inf α] (a b : α) : ((a ⊓ b : α) : with_bot α) = a ⊓ b := rfl
instance lattice [lattice α] : lattice (with_bot α) :=
{ ..with_bot.semilattice_sup, ..with_bot.semilattice_inf }
instance linear_order [linear_order α] : linear_order (with_bot α) :=
lattice.to_linear_order _ $ λ o₁ o₂,
begin
cases o₁ with a, {exact or.inl bot_le},
cases o₂ with b, {exact or.inr bot_le},
simp [le_total]
end
@[norm_cast] -- this is not marked simp because the corresponding with_top lemmas are used
lemma coe_min [linear_order α] (x y : α) : ((min x y : α) : with_bot α) = min x y := rfl
@[norm_cast] -- this is not marked simp because the corresponding with_top lemmas are used
lemma coe_max [linear_order α] (x y : α) : ((max x y : α) : with_bot α) = max x y := rfl
instance order_top [has_le α] [order_top α] : order_top (with_bot α) :=
{ top := some ⊤,
le_top := λ o a ha, by cases ha; exact ⟨_, rfl, le_top⟩ }
instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_bot α) :=
{ ..with_bot.lattice, ..with_bot.order_top, ..with_bot.order_bot }
lemma well_founded_lt [partial_order α] (h : well_founded ((<) : α → α → Prop)) :
well_founded ((<) : with_bot α → with_bot α → Prop) :=
have acc_bot : acc ((<) : with_bot α → with_bot α → Prop) ⊥ :=
acc.intro _ (λ a ha, (not_le_of_gt ha bot_le).elim),
⟨λ a, option.rec_on a acc_bot (λ a, acc.intro _ (λ b, option.rec_on b (λ _, acc_bot)
(λ b, well_founded.induction h b
(show ∀ b : α, (∀ c, c < b → (c : with_bot α) < a →
acc ((<) : with_bot α → with_bot α → Prop) c) → (b : with_bot α) < a →
acc ((<) : with_bot α → with_bot α → Prop) b,
from λ b ih hba, acc.intro _ (λ c, option.rec_on c (λ _, acc_bot)
(λ c hc, ih _ (some_lt_some.1 hc) (lt_trans hc hba)))))))⟩
instance densely_ordered [partial_order α] [densely_ordered α] [no_bot_order α] :
densely_ordered (with_bot α) :=
⟨ λ a b,
match a, b with
| a, none := λ h : a < ⊥, (not_lt_bot h).elim
| none, some b := λ h, let ⟨a, ha⟩ := no_bot b in ⟨a, bot_lt_coe a, coe_lt_coe.2 ha⟩
| some a, some b := λ h, let ⟨a, ha₁, ha₂⟩ := exists_between (coe_lt_coe.1 h) in
⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩
end⟩
instance {α : Type*} [preorder α] [no_top_order α] [nonempty α] : no_top_order (with_bot α) :=
⟨begin
apply with_bot.rec_bot_coe,
{ apply ‹nonempty α›.elim,
exact λ a, ⟨a, with_bot.bot_lt_coe a⟩, },
{ intro a,
obtain ⟨b, ha⟩ := no_top a,
exact ⟨b, with_bot.coe_lt_coe.mpr ha⟩, }
end⟩
end with_bot
--TODO(Mario): Construct using order dual on with_bot
/-- Attach `⊤` to a type. -/
def with_top (α : Type*) := option α
namespace with_top
meta instance {α} [has_to_format α] : has_to_format (with_top α) :=
{ to_format := λ x,
match x with
| none := "⊤"
| (some x) := to_fmt x
end }
instance : has_coe_t α (with_top α) := ⟨some⟩
instance has_top : has_top (with_top α) := ⟨none⟩
instance : inhabited (with_top α) := ⟨⊤⟩
lemma none_eq_top : (none : with_top α) = (⊤ : with_top α) := rfl
lemma some_eq_coe (a : α) : (some a : with_top α) = (↑a : with_top α) := rfl
/-- Recursor for `with_top` using the preferred forms `⊤` and `↑a`. -/
@[elab_as_eliminator]
def rec_top_coe {C : with_top α → Sort*} (h₁ : C ⊤) (h₂ : Π (a : α), C a) :
Π (n : with_top α), C n :=
option.rec h₁ h₂
@[norm_cast]
theorem coe_eq_coe {a b : α} : (a : with_top α) = b ↔ a = b :=
by rw [← option.some.inj_eq a b]; refl
@[simp] theorem top_ne_coe {a : α} : ⊤ ≠ (a : with_top α) .
@[simp] theorem coe_ne_top {a : α} : (a : with_top α) ≠ ⊤ .
lemma ne_top_iff_exists {x : with_top α} : x ≠ ⊤ ↔ ∃ (a : α), ↑a = x :=
option.ne_none_iff_exists
/-- Deconstruct a `x : with_top α` to the underlying value in `α`, given a proof that `x ≠ ⊤`. -/
def untop : Π (x : with_top α), x ≠ ⊤ → α :=
with_bot.unbot
@[simp] lemma coe_untop {α : Type*} (x : with_top α) (h : x ≠ ⊤) :
(x.untop h : with_top α) = x :=
by { cases x, simpa using h, refl, }
@[simp] lemma untop_coe (x : α) (h : (x : with_top α) ≠ ⊤ := coe_ne_top) :
(x : with_top α).untop h = x := rfl
@[priority 10]
instance has_lt [has_lt α] : has_lt (with_top α) :=
{ lt := λ o₁ o₂ : option α, ∃ b ∈ o₁, ∀ a ∈ o₂, b < a }
@[priority 10]
instance has_le [has_le α] : has_le (with_top α) :=
{ le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a }
@[simp] theorem some_lt_some [has_lt α] {a b : α} :
@has_lt.lt (with_top α) _ (some a) (some b) ↔ a < b :=
by simp [(<)]
@[simp] theorem some_le_some [has_le α] {a b : α} :
@has_le.le (with_top α) _ (some a) (some b) ↔ a ≤ b :=
by simp [(≤)]
@[simp] theorem le_none [has_le α] {a : with_top α} :
@has_le.le (with_top α) _ a none :=
by simp [(≤)]
@[simp] theorem some_lt_none [has_lt α] (a : α) :
@has_lt.lt (with_top α) _ (some a) none :=
by simp [(<)]; existsi a; refl
instance : can_lift (with_top α) α :=
{ coe := coe,
cond := λ r, r ≠ ⊤,
prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ }
instance [preorder α] : preorder (with_top α) :=
{ le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a,
lt := (<),
lt_iff_le_not_le := by { intros; cases a; cases b;
simp [lt_iff_le_not_le]; simp [(<),(≤)] },
le_refl := λ o a ha, ⟨a, ha, le_refl _⟩,
le_trans := λ o₁ o₂ o₃ h₁ h₂ c hc,
let ⟨b, hb, bc⟩ := h₂ c hc, ⟨a, ha, ab⟩ := h₁ b hb in
⟨a, ha, le_trans ab bc⟩,
}
instance partial_order [partial_order α] : partial_order (with_top α) :=
{ le_antisymm := λ o₁ o₂ h₁ h₂, begin
cases o₂ with b,
{ cases o₁ with a, {refl},
rcases h₂ a rfl with ⟨_, ⟨⟩, _⟩ },
{ rcases h₁ b rfl with ⟨a, ⟨⟩, h₁'⟩,
rcases h₂ a rfl with ⟨_, ⟨⟩, h₂'⟩,
rw le_antisymm h₁' h₂' }
end,
.. with_top.preorder }
instance order_top [has_le α] : order_top (with_top α) :=
{ le_top := λ a a' h, option.no_confusion h,
.. with_top.has_top }
@[simp, norm_cast] theorem coe_le_coe [has_le α] {a b : α} :
(a : with_top α) ≤ b ↔ a ≤ b :=
⟨λ h, by rcases h b rfl with ⟨_, ⟨⟩, h⟩; exact h,
λ h a' e, option.some_inj.1 e ▸ ⟨a, rfl, h⟩⟩
theorem le_coe [has_le α] {a b : α} :
∀ {o : option α}, a ∈ o →
(@has_le.le (with_top α) _ o b ↔ a ≤ b)
| _ rfl := coe_le_coe
theorem le_coe_iff [partial_order α] {b : α} : ∀{x : with_top α}, x ≤ b ↔ (∃a:α, x = a ∧ a ≤ b)
| (some a) := by simp [some_eq_coe, coe_eq_coe]
| none := by simp [none_eq_top]
theorem coe_le_iff [partial_order α] {a : α} : ∀{x : with_top α}, ↑a ≤ x ↔ (∀b:α, x = ↑b → a ≤ b)
| (some b) := by simp [some_eq_coe, coe_eq_coe]
| none := by simp [none_eq_top]
theorem lt_iff_exists_coe [partial_order α] : ∀{a b : with_top α}, a < b ↔ (∃p:α, a = p ∧ ↑p < b)
| (some a) b := by simp [some_eq_coe, coe_eq_coe]
| none b := by simp [none_eq_top]
@[norm_cast]
lemma coe_lt_coe [has_lt α] {a b : α} : (a : with_top α) < b ↔ a < b := some_lt_some
lemma coe_lt_top [has_lt α] (a : α) : (a : with_top α) < ⊤ := some_lt_none a
theorem coe_lt_iff [preorder α] {a : α} : ∀{x : with_top α}, ↑a < x ↔ (∀b:α, x = ↑b → a < b)
| (some b) := by simp [some_eq_coe, coe_eq_coe, coe_lt_coe]
| none := by simp [none_eq_top, coe_lt_top]
lemma not_top_le_coe [preorder α] (a : α) : ¬ (⊤:with_top α) ≤ ↑a :=
λ h, (lt_irrefl ⊤ (lt_of_le_of_lt h (coe_lt_top a))).elim
instance decidable_le [has_le α] [@decidable_rel α (≤)] : @decidable_rel (with_top α) (≤) :=
λ x y, @with_bot.decidable_le (order_dual α) _ _ y x
instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_top α) (<) :=
λ x y, @with_bot.decidable_lt (order_dual α) _ _ y x
instance [partial_order α] [is_total α (≤)] : is_total (with_top α) (≤) :=
{ total := λ a b, match a, b with
| none , _ := or.inr le_top
| _ , none := or.inl le_top
| some x, some y := by simp only [some_le_some, total_of]
end }
instance semilattice_inf [semilattice_inf α] : semilattice_inf_top (with_top α) :=
{ inf := option.lift_or_get (⊓),
inf_le_left := λ o₁ o₂ a ha,
by cases ha; cases o₂; simp [option.lift_or_get],
inf_le_right := λ o₁ o₂ a ha,
by cases ha; cases o₁; simp [option.lift_or_get],
le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases o₂ with b; cases o₃ with c; cases ha,
{ exact h₂ a rfl },
{ exact h₁ a rfl },
{ rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩,
simp at h₂,
exact ⟨d, rfl, le_inf h₁' h₂⟩ }
end,
..with_top.order_top,
..with_top.partial_order }
lemma coe_inf [semilattice_inf α] (a b : α) : ((a ⊓ b : α) : with_top α) = a ⊓ b := rfl
instance semilattice_sup [semilattice_sup α] : semilattice_sup_top (with_top α) :=
{ sup := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊔ b)),
le_sup_left := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, le_sup_left⟩
end,
le_sup_right := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, le_sup_right⟩
end,
sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases ha,
rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩,
rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩,
exact ⟨_, rfl, sup_le ab ac⟩
end,
..with_top.order_top,
..with_top.partial_order }
lemma coe_sup [semilattice_sup α] (a b : α) : ((a ⊔ b : α) : with_top α) = a ⊔ b := rfl
instance lattice [lattice α] : lattice (with_top α) :=
{ ..with_top.semilattice_sup, ..with_top.semilattice_inf }
instance linear_order [linear_order α] : linear_order (with_top α) :=
lattice.to_linear_order _ $ λ o₁ o₂,
begin
cases o₁ with a, {exact or.inr le_top},
cases o₂ with b, {exact or.inl le_top},
simp [le_total]
end
@[simp, norm_cast]
lemma coe_min [linear_order α] (x y : α) : ((min x y : α) : with_top α) = min x y := rfl
@[simp, norm_cast]
lemma coe_max [linear_order α] (x y : α) : ((max x y : α) : with_top α) = max x y := rfl
instance order_bot [has_le α] [order_bot α] : order_bot (with_top α) :=
{ bot := some ⊥,
bot_le := λ o a ha, by cases ha; exact ⟨_, rfl, bot_le⟩ }
instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_top α) :=
{ ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot }
lemma well_founded_lt {α : Type*} [partial_order α] (h : well_founded ((<) : α → α → Prop)) :
well_founded ((<) : with_top α → with_top α → Prop) :=
have acc_some : ∀ a : α, acc ((<) : with_top α → with_top α → Prop) (some a) :=
λ a, acc.intro _ (well_founded.induction h a
(show ∀ b, (∀ c, c < b → ∀ d : with_top α, d < some c → acc (<) d) →
∀ y : with_top α, y < some b → acc (<) y,
from λ b ih c, option.rec_on c (λ hc, (not_lt_of_ge le_top hc).elim)
(λ c hc, acc.intro _ (ih _ (some_lt_some.1 hc))))),
⟨λ a, option.rec_on a (acc.intro _ (λ y, option.rec_on y (λ h, (lt_irrefl _ h).elim)
(λ _ _, acc_some _))) acc_some⟩
instance densely_ordered [partial_order α] [densely_ordered α] [no_top_order α] :
densely_ordered (with_top α) :=
⟨ λ a b,
match a, b with
| none, a := λ h : ⊤ < a, (not_top_lt h).elim
| some a, none := λ h, let ⟨b, hb⟩ := no_top a in ⟨b, coe_lt_coe.2 hb, coe_lt_top b⟩
| some a, some b := λ h, let ⟨a, ha₁, ha₂⟩ := exists_between (coe_lt_coe.1 h) in
⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩
end⟩
lemma lt_iff_exists_coe_btwn [partial_order α] [densely_ordered α] [no_top_order α]
{a b : with_top α} :
(a < b) ↔ (∃ x : α, a < ↑x ∧ ↑x < b) :=
⟨λ h, let ⟨y, hy⟩ := exists_between h, ⟨x, hx⟩ := lt_iff_exists_coe.1 hy.2 in ⟨x, hx.1 ▸ hy⟩,
λ ⟨x, hx⟩, lt_trans hx.1 hx.2⟩
instance {α : Type*} [preorder α] [no_bot_order α] [nonempty α] : no_bot_order (with_top α) :=
⟨begin
apply with_top.rec_top_coe,
{ apply ‹nonempty α›.elim,
exact λ a, ⟨a, with_top.coe_lt_top a⟩, },
{ intro a,
obtain ⟨b, ha⟩ := no_bot a,
exact ⟨b, with_top.coe_lt_coe.mpr ha⟩, }
end⟩
end with_top
/-! ### Subtype, order dual, product lattices -/
namespace subtype
/-- A subtype forms a `⊔`-`⊥`-semilattice if `⊥` and `⊔` preserve the property.
See note [reducible non-instances]. -/
@[reducible]
protected def semilattice_sup_bot [semilattice_sup_bot α] {P : α → Prop}
(Pbot : P ⊥) (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup_bot {x : α // P x} :=
{ bot := ⟨⊥, Pbot⟩,
bot_le := λ _, bot_le,
..subtype.semilattice_sup Psup }
/-- A subtype forms a `⊓`-`⊥`-semilattice if `⊥` and `⊓` preserve the property.
See note [reducible non-instances]. -/
@[reducible]
protected def semilattice_inf_bot [semilattice_inf_bot α] {P : α → Prop}
(Pbot : P ⊥) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf_bot {x : α // P x} :=
{ bot := ⟨⊥, Pbot⟩,
bot_le := λ _, bot_le,
..subtype.semilattice_inf Pinf }
/-- A subtype forms a `⊔`-`⊤`-semilattice if `⊤` and `⊔` preserve the property.
See note [reducible non-instances]. -/
@[reducible]
protected def semilattice_sup_top [semilattice_sup_top α] {P : α → Prop}
(Ptop : P ⊤) (Psup : ∀{{x y}}, P x → P y → P (x ⊔ y)) : semilattice_sup_top {x : α // P x} :=
{ top := ⟨⊤, Ptop⟩,
le_top := λ _, le_top,
..subtype.semilattice_sup Psup }
/-- A subtype forms a `⊓`-`⊤`-semilattice if `⊤` and `⊓` preserve the property.
See note [reducible non-instances]. -/
@[reducible]
protected def semilattice_inf_top [semilattice_inf_top α] {P : α → Prop}
(Ptop : P ⊤) (Pinf : ∀{{x y}}, P x → P y → P (x ⊓ y)) : semilattice_inf_top {x : α // P x} :=
{ top := ⟨⊤, Ptop⟩,
le_top := λ _, le_top,
..subtype.semilattice_inf Pinf }
end subtype
namespace order_dual
variable (α)
instance [has_bot α] : has_top (order_dual α) := ⟨(⊥ : α)⟩
instance [has_top α] : has_bot (order_dual α) := ⟨(⊤ : α)⟩
instance [has_le α] [order_bot α] : order_top (order_dual α) :=
{ le_top := @bot_le α _ _,
.. order_dual.has_top α }
instance [has_le α] [order_top α] : order_bot (order_dual α) :=
{ bot_le := @le_top α _ _,
.. order_dual.has_bot α }
instance [semilattice_inf_bot α] : semilattice_sup_top (order_dual α) :=
{ .. order_dual.semilattice_sup α, .. order_dual.order_top α }
instance [semilattice_inf_top α] : semilattice_sup_bot (order_dual α) :=
{ .. order_dual.semilattice_sup α, .. order_dual.order_bot α }
instance [semilattice_sup_bot α] : semilattice_inf_top (order_dual α) :=
{ .. order_dual.semilattice_inf α, .. order_dual.order_top α }
instance [semilattice_sup_top α] : semilattice_inf_bot (order_dual α) :=
{ .. order_dual.semilattice_inf α, .. order_dual.order_bot α }
instance [bounded_lattice α] : bounded_lattice (order_dual α) :=
{ .. order_dual.lattice α, .. order_dual.order_top α, .. order_dual.order_bot α }
/- If you define `distrib_lattice_top`, add the `order_dual` instances between `distrib_lattice_bot`
and `distrib_lattice_top` here -/
instance [bounded_distrib_lattice α] : bounded_distrib_lattice (order_dual α) :=
{ .. order_dual.bounded_lattice α, .. order_dual.distrib_lattice α }
end order_dual
namespace prod
variables (α β)
instance [has_top α] [has_top β] : has_top (α × β) := ⟨⟨⊤, ⊤⟩⟩
instance [has_bot α] [has_bot β] : has_bot (α × β) := ⟨⟨⊥, ⊥⟩⟩
instance [has_le α] [has_le β] [order_top α] [order_top β] : order_top (α × β) :=
{ le_top := λ a, ⟨le_top, le_top⟩,
.. prod.has_top α β }
instance [has_le α] [has_le β] [order_bot α] [order_bot β] : order_bot (α × β) :=
{ bot_le := λ a, ⟨bot_le, bot_le⟩,
.. prod.has_bot α β }
instance [semilattice_sup_top α] [semilattice_sup_top β] : semilattice_sup_top (α × β) :=
{ .. prod.semilattice_sup α β, .. prod.order_top α β }
instance [semilattice_inf_top α] [semilattice_inf_top β] : semilattice_inf_top (α × β) :=
{ .. prod.semilattice_inf α β, .. prod.order_top α β }
instance [semilattice_sup_bot α] [semilattice_sup_bot β] : semilattice_sup_bot (α × β) :=
{ .. prod.semilattice_sup α β, .. prod.order_bot α β }
instance [semilattice_inf_bot α] [semilattice_inf_bot β] : semilattice_inf_bot (α × β) :=
{ .. prod.semilattice_inf α β, .. prod.order_bot α β }
instance [bounded_lattice α] [bounded_lattice β] : bounded_lattice (α × β) :=
{ .. prod.lattice α β, .. prod.order_top α β, .. prod.order_bot α β }
instance [distrib_lattice_bot α] [distrib_lattice_bot β] :
distrib_lattice_bot (α × β) :=
{ .. prod.distrib_lattice α β, .. prod.order_bot α β }
instance [bounded_distrib_lattice α] [bounded_distrib_lattice β] :
bounded_distrib_lattice (α × β) :=
{ .. prod.bounded_lattice α β, .. prod.distrib_lattice α β }
end prod
/-! ### Disjointness and complements -/
section disjoint
section semilattice_inf_bot
variable [semilattice_inf_bot α]
/-- Two elements of a lattice are disjoint if their inf is the bottom element.
(This generalizes disjoint sets, viewed as members of the subset lattice.) -/
def disjoint (a b : α) : Prop := a ⊓ b ≤ ⊥
theorem disjoint.eq_bot {a b : α} (h : disjoint a b) : a ⊓ b = ⊥ :=
eq_bot_iff.2 h
theorem disjoint_iff {a b : α} : disjoint a b ↔ a ⊓ b = ⊥ :=
eq_bot_iff.symm
theorem disjoint.comm {a b : α} : disjoint a b ↔ disjoint b a :=
by rw [disjoint, disjoint, inf_comm]
@[symm] theorem disjoint.symm ⦃a b : α⦄ : disjoint a b → disjoint b a :=
disjoint.comm.1
lemma symmetric_disjoint : symmetric (disjoint : α → α → Prop) := disjoint.symm
@[simp] theorem disjoint_bot_left {a : α} : disjoint ⊥ a := inf_le_left
@[simp] theorem disjoint_bot_right {a : α} : disjoint a ⊥ := inf_le_right
theorem disjoint.mono {a b c d : α} (h₁ : a ≤ b) (h₂ : c ≤ d) :
disjoint b d → disjoint a c := le_trans (inf_le_inf h₁ h₂)
theorem disjoint.mono_left {a b c : α} (h : a ≤ b) : disjoint b c → disjoint a c :=
disjoint.mono h (le_refl _)
theorem disjoint.mono_right {a b c : α} (h : b ≤ c) : disjoint a c → disjoint a b :=
disjoint.mono (le_refl _) h
@[simp] lemma disjoint_self {a : α} : disjoint a a ↔ a = ⊥ :=
by simp [disjoint]
lemma disjoint.ne {a b : α} (ha : a ≠ ⊥) (hab : disjoint a b) : a ≠ b :=
by { intro h, rw [←h, disjoint_self] at hab, exact ha hab }
lemma disjoint.eq_bot_of_le {a b : α} (hab : disjoint a b) (h : a ≤ b) : a = ⊥ :=
eq_bot_iff.2 (by rwa ←inf_eq_left.2 h)
lemma disjoint.of_disjoint_inf_of_le {a b c : α} (h : disjoint (a ⊓ b) c) (hle : a ≤ c) :
disjoint a b := by rw [disjoint_iff, h.eq_bot_of_le (inf_le_left.trans hle)]
lemma disjoint.of_disjoint_inf_of_le' {a b c : α} (h : disjoint (a ⊓ b) c) (hle : b ≤ c) :
disjoint a b := by rw [disjoint_iff, h.eq_bot_of_le (inf_le_right.trans hle)]
end semilattice_inf_bot
section bounded_lattice
variables [bounded_lattice α] {a : α}
@[simp] theorem disjoint_top : disjoint a ⊤ ↔ a = ⊥ := by simp [disjoint_iff]
@[simp] theorem top_disjoint : disjoint ⊤ a ↔ a = ⊥ := by simp [disjoint_iff]
lemma eq_bot_of_disjoint_absorbs
{a b : α} (w : disjoint a b) (h : a ⊔ b = a) : b = ⊥ :=
begin
rw disjoint_iff at w,
rw [←w, right_eq_inf],
rwa sup_eq_left at h,
end
end bounded_lattice
section distrib_lattice_bot
variables [distrib_lattice_bot α] {a b c : α}
@[simp] lemma disjoint_sup_left : disjoint (a ⊔ b) c ↔ disjoint a c ∧ disjoint b c :=
by simp only [disjoint_iff, inf_sup_right, sup_eq_bot_iff]
@[simp] lemma disjoint_sup_right : disjoint a (b ⊔ c) ↔ disjoint a b ∧ disjoint a c :=
by simp only [disjoint_iff, inf_sup_left, sup_eq_bot_iff]
lemma disjoint.sup_left (ha : disjoint a c) (hb : disjoint b c) : disjoint (a ⊔ b) c :=
disjoint_sup_left.2 ⟨ha, hb⟩
lemma disjoint.sup_right (hb : disjoint a b) (hc : disjoint a c) : disjoint a (b ⊔ c) :=
disjoint_sup_right.2 ⟨hb, hc⟩
lemma disjoint.left_le_of_le_sup_right {a b c : α} (h : a ≤ b ⊔ c) (hd : disjoint a c) : a ≤ b :=
(λ x, le_of_inf_le_sup_le x (sup_le h le_sup_right)) ((disjoint_iff.mp hd).symm ▸ bot_le)
lemma disjoint.left_le_of_le_sup_left {a b c : α} (h : a ≤ c ⊔ b) (hd : disjoint a c) : a ≤ b :=
@le_of_inf_le_sup_le _ _ a b c ((disjoint_iff.mp hd).symm ▸ bot_le)
((@sup_comm _ _ c b) ▸ (sup_le h le_sup_left))
end distrib_lattice_bot
section semilattice_inf_bot
variables [semilattice_inf_bot α] {a b : α} (c : α)
lemma disjoint.inf_left (h : disjoint a b) : disjoint (a ⊓ c) b :=
h.mono_left inf_le_left
lemma disjoint.inf_left' (h : disjoint a b) : disjoint (c ⊓ a) b :=
h.mono_left inf_le_right
lemma disjoint.inf_right (h : disjoint a b) : disjoint a (b ⊓ c) :=
h.mono_right inf_le_left
lemma disjoint.inf_right' (h : disjoint a b) : disjoint a (c ⊓ b) :=
h.mono_right inf_le_right
end semilattice_inf_bot
end disjoint
section is_compl
/-- Two elements `x` and `y` are complements of each other if `x ⊔ y = ⊤` and `x ⊓ y = ⊥`. -/
structure is_compl [bounded_lattice α] (x y : α) : Prop :=
(inf_le_bot : x ⊓ y ≤ ⊥)
(top_le_sup : ⊤ ≤ x ⊔ y)
namespace is_compl
section bounded_lattice
variables [bounded_lattice α] {x y z : α}
protected lemma disjoint (h : is_compl x y) : disjoint x y := h.1
@[symm] protected lemma symm (h : is_compl x y) : is_compl y x :=
⟨by { rw inf_comm, exact h.1 }, by { rw sup_comm, exact h.2 }⟩
lemma of_eq (h₁ : x ⊓ y = ⊥) (h₂ : x ⊔ y = ⊤) : is_compl x y :=
⟨le_of_eq h₁, le_of_eq h₂.symm⟩
lemma inf_eq_bot (h : is_compl x y) : x ⊓ y = ⊥ := h.disjoint.eq_bot
lemma sup_eq_top (h : is_compl x y) : x ⊔ y = ⊤ := top_unique h.top_le_sup
open order_dual (to_dual)
lemma to_order_dual (h : is_compl x y) : is_compl (to_dual x) (to_dual y) := ⟨h.2, h.1⟩
end bounded_lattice
variables [bounded_distrib_lattice α] {a b x y z : α}
lemma inf_left_le_of_le_sup_right (h : is_compl x y) (hle : a ≤ b ⊔ y) : a ⊓ x ≤ b :=
calc a ⊓ x ≤ (b ⊔ y) ⊓ x : inf_le_inf hle le_rfl
... = (b ⊓ x) ⊔ (y ⊓ x) : inf_sup_right
... = b ⊓ x : by rw [h.symm.inf_eq_bot, sup_bot_eq]
... ≤ b : inf_le_left
lemma le_sup_right_iff_inf_left_le {a b} (h : is_compl x y) : a ≤ b ⊔ y ↔ a ⊓ x ≤ b :=
⟨h.inf_left_le_of_le_sup_right, h.symm.to_order_dual.inf_left_le_of_le_sup_right⟩
lemma inf_left_eq_bot_iff (h : is_compl y z) : x ⊓ y = ⊥ ↔ x ≤ z :=
by rw [← le_bot_iff, ← h.le_sup_right_iff_inf_left_le, bot_sup_eq]
lemma inf_right_eq_bot_iff (h : is_compl y z) : x ⊓ z = ⊥ ↔ x ≤ y :=
h.symm.inf_left_eq_bot_iff
lemma disjoint_left_iff (h : is_compl y z) : disjoint x y ↔ x ≤ z :=
by { rw disjoint_iff, exact h.inf_left_eq_bot_iff }
lemma disjoint_right_iff (h : is_compl y z) : disjoint x z ↔ x ≤ y :=
h.symm.disjoint_left_iff
lemma le_left_iff (h : is_compl x y) : z ≤ x ↔ disjoint z y :=
h.disjoint_right_iff.symm
lemma le_right_iff (h : is_compl x y) : z ≤ y ↔ disjoint z x :=
h.symm.le_left_iff
lemma left_le_iff (h : is_compl x y) : x ≤ z ↔ ⊤ ≤ z ⊔ y :=
h.to_order_dual.le_left_iff
lemma right_le_iff (h : is_compl x y) : y ≤ z ↔ ⊤ ≤ z ⊔ x :=
h.symm.left_le_iff
protected lemma antitone {x' y'} (h : is_compl x y) (h' : is_compl x' y') (hx : x ≤ x') :
y' ≤ y :=
h'.right_le_iff.2 $ le_trans h.symm.top_le_sup (sup_le_sup_left hx _)
lemma right_unique (hxy : is_compl x y) (hxz : is_compl x z) :
y = z :=
le_antisymm (hxz.antitone hxy $ le_refl x) (hxy.antitone hxz $ le_refl x)
lemma left_unique (hxz : is_compl x z) (hyz : is_compl y z) :
x = y :=
hxz.symm.right_unique hyz.symm
lemma sup_inf {x' y'} (h : is_compl x y) (h' : is_compl x' y') :
is_compl (x ⊔ x') (y ⊓ y') :=
of_eq
(by rw [inf_sup_right, ← inf_assoc, h.inf_eq_bot, bot_inf_eq, bot_sup_eq, inf_left_comm,
h'.inf_eq_bot, inf_bot_eq])
(by rw [sup_inf_left, @sup_comm _ _ x, sup_assoc, h.sup_eq_top, sup_top_eq, top_inf_eq,
sup_assoc, sup_left_comm, h'.sup_eq_top, sup_top_eq])
lemma inf_sup {x' y'} (h : is_compl x y) (h' : is_compl x' y') :
is_compl (x ⊓ x') (y ⊔ y') :=
(h.symm.sup_inf h'.symm).symm
end is_compl
lemma is_compl_bot_top [bounded_lattice α] : is_compl (⊥ : α) ⊤ :=
is_compl.of_eq bot_inf_eq sup_top_eq
lemma is_compl_top_bot [bounded_lattice α] : is_compl (⊤ : α) ⊥ :=
is_compl.of_eq inf_bot_eq top_sup_eq
section
variables [bounded_lattice α] {x : α}
lemma eq_top_of_is_compl_bot (h : is_compl x ⊥) : x = ⊤ :=
sup_bot_eq.symm.trans h.sup_eq_top
lemma eq_top_of_bot_is_compl (h : is_compl ⊥ x) : x = ⊤ :=
eq_top_of_is_compl_bot h.symm
lemma eq_bot_of_is_compl_top (h : is_compl x ⊤) : x = ⊥ :=
eq_top_of_is_compl_bot h.to_order_dual
lemma eq_bot_of_top_is_compl (h : is_compl ⊤ x) : x = ⊥ :=
eq_top_of_bot_is_compl h.to_order_dual
end
/-- A complemented bounded lattice is one where every element has a (not necessarily unique)
complement. -/
class is_complemented (α) [bounded_lattice α] : Prop :=
(exists_is_compl : ∀ (a : α), ∃ (b : α), is_compl a b)
export is_complemented (exists_is_compl)
namespace is_complemented
variables [bounded_lattice α] [is_complemented α]
instance : is_complemented (order_dual α) :=
⟨λ a, let ⟨b, hb⟩ := exists_is_compl (show α, from a) in ⟨b, hb.to_order_dual⟩⟩
end is_complemented
end is_compl
section nontrivial
variables [bounded_lattice α] [nontrivial α]
lemma bot_ne_top : (⊥ : α) ≠ ⊤ :=
λ H, not_nontrivial_iff_subsingleton.mpr (subsingleton_of_bot_eq_top H) ‹_›
lemma top_ne_bot : (⊤ : α) ≠ ⊥ := ne.symm bot_ne_top
end nontrivial
namespace bool
-- Could be generalised to `bounded_distrib_lattice` and `is_complemented`
instance : bounded_lattice bool :=
{ top := tt,
le_top := λ x, le_tt,
bot := ff,
bot_le := λ x, ff_le,
.. (infer_instance : lattice bool)}
end bool
section bool
@[simp] lemma top_eq_tt : ⊤ = tt := rfl
@[simp] lemma bot_eq_ff : ⊥ = ff := rfl
end bool
|
beab6edacac151b5be4d09586514d36ec7df715c | 76c77df8a58af24dbf1d75c7012076a42244d728 | /tutorial_src/exercises/03_forall_or.lean | af038ca6b893ffd2c4e2e60517c70d6392c839fa | [] | no_license | kris-brown/theorem_proving_in_lean | 7a7a584ba2c657a35335dc895d49d991c997a0c9 | 774460c21bf857daff158210741bd88d1c8323cd | refs/heads/master | 1,668,278,123,743 | 1,593,445,161,000 | 1,593,445,161,000 | 265,748,924 | 0 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 9,177 | lean | import data.real.basic
import algebra.pi_instances
set_option pp.beta true
/-
In this file, we'll learn about the ∀ quantifier, and the disjunction
operator ∨ (logical OR).
Let P be a predicate on a type X. This means for every mathematical
object x with type X, we get a mathematical statement P x.
In Lean, P x has type Prop.
Lean sees a proof h of `∀ x, P x` as a function sending any `x : X` to
a proof `h x` of `P x`.
This already explains the main way to use an assumption or lemma which
starts with a ∀.
In order to prove `∀ x, P x`, we use `intros x` to fix an arbitrary object
with type X, and call it x.
Note also we don't need to give the type of x in the expression `∀ x, P x`
as long as the type of P is clear to Lean, which can then infer the type of x.
Let's define two predicates to play with ∀.
-/
def even_fun (f : ℝ → ℝ) := ∀ x, f (-x) = f x
def odd_fun (f : ℝ → ℝ) := ∀ x, f (-x) = -f x
/-
In the next proof, we also take the opportunity to introduce the
`unfold` tactic, which simply unfolds definitions. Here this is purely
for didactic reason, Lean doesn't need those `unfold` invocations.
We will also use `rfl` which is a term proving equalities that are true
by definition (in a very strong sense to be discussed later).
-/
example (f g : ℝ → ℝ) : even_fun f → even_fun g → even_fun (f + g) :=
begin
-- Assume f is even
intros hf,
-- which means ∀ x, f (-x) = f x
--unfold even_fun at hf,
-- and the same for g
intros hg,
--unfold even_fun at hg,
-- We need to prove ∀ x, (f+g)(-x) = (f+g)(x)
--unfold even_fun,
-- Let x be any real number
intros x,
-- and let's compute
calc (f + g) (-x) = f (-x) + g (-x) : rfl
... = f x + g (-x) : by rw hf x
... = f x + g x : by rw hg x
--... = (f + g) x : rfl
end
/-
In the preceding proof, all `unfold` lines are purely for
psychological comfort.
Sometimes unfolding is necessary because we want to apply a tactic
that operates purely on the syntactical level.
The main such tactic is `rw`.
The same property of `rw` explain why the first computation line
is necessary, although its proof is simply `rfl`.
Before that line, `rw hf x` won't find anything like `f (-x)` hence
will give up.
The last line is not necessary however, since it only proves
something that is true by definition, and is not followed by
a `rw`.
Also, Lean doesn't need to be told that hf should be specialized to
x before rewriting, exactly as in the first file 01_equality_rewriting.
We can also gather several rewrites using a list of expressions.
Hence we can compress the above proof to:
-/
example (f g : ℝ → ℝ) : even_fun f → even_fun g → even_fun (f + g) :=
begin
intros hf hg x,
calc (f + g) (-x) = f (-x) + g (-x) : rfl
... = f x + g x : by rw [hf, hg]
end
/-
Note that the tactic state displays changes when we
move the cursor inside the list of expressions given to `rw`.
Now let's practice.
-/
-- 0023
example (f g : ℝ → ℝ) : even_fun f → even_fun (g ∘ f) :=
begin
intros hf x,
calc (g ∘ f) (-x) = g(f(-x)) : rfl
... = g(f(x)) : by rw hf
end
-- 0024
example (f g : ℝ → ℝ) : odd_fun f → odd_fun g → odd_fun (g ∘ f) :=
begin
intros hf hg x,
calc (g ∘ f) (-x) = g(f(-x)) : rfl
... = g(-f(x)) : by rw[hf]
... = -g(f(x)) : by rw[hg]
end
/-
Let's have more quantifiers, and play with forward and backward reasoning.
In the next definitions, note how `∀ x₁, ∀ x₂` is abreviated to `∀ x₁ x₂`.
-/
def non_decreasing (f : ℝ → ℝ) := ∀ x₁ x₂, x₁ ≤ x₂ → f x₁ ≤ f x₂
def non_increasing (f : ℝ → ℝ) := ∀ x₁ x₂, x₁ ≤ x₂ → f x₁ ≥ f x₂
/- Let's be very explicit and use forward reasonning first. -/
example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_decreasing g) : non_decreasing (g ∘ f) :=
begin
-- Let x₁ and x₂ be real numbers such that x₁ ≤ x₂
intros x₁ x₂ h,
-- Since f is non-decreasing, f x₁ ≤ f x₂.
have step₁ : f x₁ ≤ f x₂,
exact hf x₁ x₂ h,
-- Since g is non-decreasing, we then get g (f x₁) ≤ g (f x₂).
exact hg (f x₁) (f x₂) step₁,
end
/-
In the above proof, note how inconvenient it is to specify x₁ and x₂ in `hf x₁ x₂ h` since
they could be inferred from the type of h.
We could have written `hf _ _ h` and Lean would have filled the holes denoted by _.
Even better we could have written the definition
of `non_decreasing` as: ∀ {x₁ x₂}, x₁ ≤ x₂ → f x₁ ≤ f x₂, with curly braces to denote
implicit arguments.
But let's leave that aside for now. One possible variation on the above proof is to
use the `specialize` tactic to replace hf by its specialization to the relevant value.
-/
example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_decreasing g) : non_decreasing (g ∘ f) :=
begin
intros x₁ x₂ h,
specialize hf x₁ x₂ h,
exact hg (f x₁) (f x₂) hf,
end
/-
This `specialize` tactic is mostly useful for exploration, or in preparation for rewriting
in the assumption. One can very often replace its use by using more complicated expressions
directly involving the original assumption, as in the next variation:
-/
example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_decreasing g) : non_decreasing (g ∘ f) :=
begin
intros x₁ x₂ h,
exact hg (f x₁) (f x₂) (hf x₁ x₂ h),
end
/-
Since the above proof uses only `intros` and `exact`, we could very easily replace it by the
raw proof term:
-/
example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_decreasing g) : non_decreasing (g ∘ f) :=
λ x₁ x₂ h, hg (f x₁) (f x₂) (hf x₁ x₂ h)
/-
Of course the above proof is difficult to decipher. The principle in mathlib is to use
such a proof when the result is obvious and you don't want to read the proof anyway.
Instead of pursuing this style, let's see how backward reasoning would look like here.
As usual with this style, we use `apply` and enjoy Lean specializing assumptions for us
using unification.
-/
example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_decreasing g) : non_decreasing (g ∘ f) :=
begin
-- Let x₁ and x₂ be real numbers such that x₁ ≤ x₂
intros x₁ x₂ h,
-- We need to prove (g ∘ f) x₁ ≤ (g ∘ f) x₂.
-- Since g is non-decreasing, it suffices to prove f x₁ ≤ f x₂
apply hg,
-- which follows from our assumption on f
apply hf,
-- and on x₁ and x₂
exact h
end
-- 0025
example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_increasing g) : non_increasing (g ∘ f) :=
begin
intros x1 x2 h,
apply hg, apply hf, exact h
end
/-
Let's switch to disjunctions now. Lean denotes by ∨ the
logical OR operator.
In order to make use of an assumption
hyp : P ∨ Q
we use the cases tactic:
cases hyp with hP hQ
which creates two proof branches: one branch assuming hP : P,
and one branch assuming hQ : Q.
In order to directly prove a goal P ∨ Q,
we use either the `left` tactic and prove P or the `right`
tactic and prove Q.
In the next proof we use `ring` and `linarith` to get rid of
easy computations or inequalities, as well as one lemma:
mul_eq_zero : a*b = 0 ↔ a = 0 ∨ b = 0
-/
example (a b : ℝ) : a = a*b → a = 0 ∨ b = 1 :=
begin
intro hyp,
have H : a*(1 - b) = 0,
{ calc a*(1 - b) = a - a*b : by ring
... = 0 : by linarith, },
rw mul_eq_zero at H,
cases H with Ha Hb,
{ left,
exact Ha, },
{ right,
linarith, },
end
-- 0026
example (x y : ℝ) : x^2 = y^2 → x = y ∨ x = -y :=
begin
assume hx2y2 : x^2 = y^2,
have H : (x+y)*(x-y) = 0, {
calc (x+y)*(x-y) = x^2-y^2 : by ring
... = 0 : by linarith,
},
rw mul_eq_zero at H,
cases H with Ha Hb,
{right, linarith},
{left, linarith}
end
/-
In the next exercise, we can use:
eq_or_lt_of_le : x ≤ y → x = y ∨ x < y
-/
-- 0027
example (f : ℝ → ℝ) : non_decreasing f ↔ ∀ x y, x < y → f x ≤ f y :=
begin
split,
{
intros hf x y hxy,
unfold non_decreasing at hf,
have hxy' : x = y ∨ x < y, from or.inr hxy,
rw [<-le_iff_eq_or_lt] at hxy',
exact hf x y hxy'
},
{
intros h x y hxy,
have hxy' : x = y ∨ x < y, from eq_or_lt_of_le hxy,
cases hxy' with Ha Hb,
{have hh : f x = f y, by rw Ha,
have hh' : f x = f y ∨ f x < f y, from or.inl hh,
rw [<- le_iff_eq_or_lt] at hh',
exact hh'},
{exact h x y Hb}
}
end
/-
In the next exercise, we can use:
le_total x y : x ≤ y ∨ y ≤ x
-/
-- 0028
example (f : ℝ → ℝ) (h : non_decreasing f) (h' : ∀ x, f (f x) = x) : ∀ x, f x = x :=
begin
intros x,
unfold non_decreasing at h,
have hor : x ≤ (f x) ∨ (f x) ≤ x, from le_total x (f x),
cases hor with Ha Hb,
{have hc : f x ≤ x, by {
have hd : f x ≤ f (f x) , from h x (f x) Ha,
rwa h' at hd,
},
show f x = x, by linarith},
{have hc : x ≤ f x, by {
have hd : f (f x) ≤ f x, from h (f x) x Hb,
rwa h' at hd,
},
show f x = x, by linarith},
end
|
8d37d3fed1a0c1beebf0fab7ea5a895a1334f418 | 367134ba5a65885e863bdc4507601606690974c1 | /src/tactic/push_neg.lean | 2547ff6f1eb53f886532848c13218a7d29b37902 | [
"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 | 7,973 | lean | /-
Copyright (c) 2019 Patrick Massot All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Patrick Massot, Simon Hudon
A tactic pushing negations into an expression
-/
import logic.basic
import algebra.order
open tactic expr
namespace push_neg
section
universe u
variable {α : Sort u}
variables (p q : Prop)
variable (s : α → Prop)
local attribute [instance, priority 10] classical.prop_decidable
theorem not_not_eq : (¬ ¬ p) = p := propext not_not
theorem not_and_eq : (¬ (p ∧ q)) = (p → ¬ q) := propext not_and
theorem not_or_eq : (¬ (p ∨ q)) = (¬ p ∧ ¬ q) := propext not_or_distrib
theorem not_forall_eq : (¬ ∀ x, s x) = (∃ x, ¬ s x) := propext not_forall
theorem not_exists_eq : (¬ ∃ x, s x) = (∀ x, ¬ s x) := propext not_exists
theorem not_implies_eq : (¬ (p → q)) = (p ∧ ¬ q) := propext not_imp
theorem classical.implies_iff_not_or : (p → q) ↔ (¬ p ∨ q) := imp_iff_not_or
theorem not_eq (a b : α) : (¬ a = b) ↔ (a ≠ b) := iff.rfl
variable {β : Type u}
variable [linear_order β]
theorem not_le_eq (a b : β) : (¬ (a ≤ b)) = (b < a) := propext not_le
theorem not_lt_eq (a b : β) : (¬ (a < b)) = (b ≤ a) := propext not_lt
end
meta def whnf_reducible (e : expr) : tactic expr := whnf e reducible
private meta def transform_negation_step (e : expr) :
tactic (option (expr × expr)) :=
do e ← whnf_reducible e,
match e with
| `(¬ %%ne) :=
(do ne ← whnf_reducible ne,
match ne with
| `(¬ %%a) := do pr ← mk_app ``not_not_eq [a],
return (some (a, pr))
| `(%%a ∧ %%b) := do pr ← mk_app ``not_and_eq [a, b],
return (some (`((%%a : Prop) → ¬ %%b), pr))
| `(%%a ∨ %%b) := do pr ← mk_app ``not_or_eq [a, b],
return (some (`(¬ %%a ∧ ¬ %%b), pr))
| `(%%a ≤ %%b) := do e ← to_expr ``(%%b < %%a),
pr ← mk_app ``not_le_eq [a, b],
return (some (e, pr))
| `(%%a < %%b) := do e ← to_expr ``(%%b ≤ %%a),
pr ← mk_app ``not_lt_eq [a, b],
return (some (e, pr))
| `(Exists %%p) := do pr ← mk_app ``not_exists_eq [p],
e ← match p with
| (lam n bi typ bo) := do
body ← mk_app ``not [bo],
return (pi n bi typ body)
| _ := tactic.fail "Unexpected failure negating ∃"
end,
return (some (e, pr))
| (pi n bi d p) := if p.has_var then do
pr ← mk_app ``not_forall_eq [lam n bi d p],
body ← mk_app ``not [p],
e ← mk_app ``Exists [lam n bi d body],
return (some (e, pr))
else do
pr ← mk_app ``not_implies_eq [d, p],
`(%%_ = %%e') ← infer_type pr,
return (some (e', pr))
| _ := return none
end)
| _ := return none
end
private meta def transform_negation : expr → tactic (option (expr × expr))
| e :=
do (some (e', pr)) ← transform_negation_step e | return none,
(some (e'', pr')) ← transform_negation e' | return (some (e', pr)),
pr'' ← mk_eq_trans pr pr',
return (some (e'', pr''))
meta def normalize_negations (t : expr) : tactic (expr × expr) :=
do (_, e, pr) ← simplify_top_down ()
(λ _, λ e, do
oepr ← transform_negation e,
match oepr with
| (some (e', pr)) := return ((), e', pr)
| none := do pr ← mk_eq_refl e, return ((), e, pr)
end)
t { eta := ff },
return (e, pr)
meta def push_neg_at_hyp (h : name) : tactic unit :=
do H ← get_local h,
t ← infer_type H,
(e, pr) ← normalize_negations t,
replace_hyp H e pr,
skip
meta def push_neg_at_goal : tactic unit :=
do H ← target,
(e, pr) ← normalize_negations H,
replace_target e pr
end push_neg
open interactive (parse loc.ns loc.wildcard)
open interactive.types (location texpr)
open lean.parser (tk ident many) interactive.loc
local postfix `?`:9001 := optional
local postfix *:9001 := many
open push_neg
/--
Push negations in the goal of some assumption.
For instance, a hypothesis `h : ¬ ∀ x, ∃ y, x ≤ y` will be transformed by `push_neg at h` into
`h : ∃ x, ∀ y, y < x`. Variables names are conserved.
This tactic pushes negations inside expressions. For instance, given an assumption
```lean
h : ¬ ∀ ε > 0, ∃ δ > 0, ∀ x, |x - x₀| ≤ δ → |f x - y₀| ≤ ε)
```
writing `push_neg at h` will turn `h` into
```lean
h : ∃ ε, ε > 0 ∧ ∀ δ, δ > 0 → (∃ x, |x - x₀| ≤ δ ∧ ε < |f x - y₀|),
```
(the pretty printer does *not* use the abreviations `∀ δ > 0` and `∃ ε > 0` but this issue
has nothing to do with `push_neg`).
Note that names are conserved by this tactic, contrary to what would happen with `simp`
using the relevant lemmas. One can also use this tactic at the goal using `push_neg`,
at every assumption and the goal using `push_neg at *` or at selected assumptions and the goal
using say `push_neg at h h' ⊢` as usual.
-/
meta def tactic.interactive.push_neg : parse location → tactic unit
| (loc.ns loc_l) :=
loc_l.mmap'
(λ l, match l with
| some h := do push_neg_at_hyp h,
try $ interactive.simp_core { eta := ff } failed tt
[simp_arg_type.expr ``(push_neg.not_eq)] []
(interactive.loc.ns [some h])
| none := do push_neg_at_goal,
try `[simp only [push_neg.not_eq] { eta := ff }]
end)
| loc.wildcard := do
push_neg_at_goal,
local_context >>= mmap' (λ h, push_neg_at_hyp (local_pp_name h)) ,
try `[simp only [push_neg.not_eq] at * { eta := ff }]
add_tactic_doc
{ name := "push_neg",
category := doc_category.tactic,
decl_names := [`tactic.interactive.push_neg],
tags := ["logic"] }
lemma imp_of_not_imp_not (P Q : Prop) : (¬ Q → ¬ P) → (P → Q) :=
λ h hP, classical.by_contradiction (λ h', h h' hP)
/-- Matches either an identifier "h" or a pair of identifiers "h with k" -/
meta def name_with_opt : lean.parser (name × option name) :=
prod.mk <$> ident <*> (some <$> (tk "with" >> ident) <|> return none)
/--
Transforms the goal into its contrapositive.
* `contrapose` turns a goal `P → Q` into `¬ Q → ¬ P`
* `contrapose!` turns a goal `P → Q` into `¬ Q → ¬ P` and pushes negations inside `P` and `Q`
using `push_neg`
* `contrapose h` first reverts the local assumption `h`, and then uses `contrapose` and `intro h`
* `contrapose! h` first reverts the local assumption `h`, and then uses `contrapose!` and `intro h`
* `contrapose h with new_h` uses the name `new_h` for the introduced hypothesis
-/
meta def tactic.interactive.contrapose (push : parse (tk "!" )?) : parse name_with_opt? → tactic unit
| (some (h, h')) := get_local h >>= revert >> tactic.interactive.contrapose none >> intro (h'.get_or_else h) >> skip
| none :=
do `(%%P → %%Q) ← target | fail "The goal is not an implication, and you didn't specify an assumption",
cp ← mk_mapp ``imp_of_not_imp_not [P, Q] <|> fail "contrapose only applies to nondependent arrows between props",
apply cp,
when push.is_some $ try (tactic.interactive.push_neg (loc.ns [none]))
add_tactic_doc
{ name := "contrapose",
category := doc_category.tactic,
decl_names := [`tactic.interactive.contrapose],
tags := ["logic"] }
|
2e6f86516449e15c175003a072e796fb3ad136ff | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/cc4.lean | 7cc4b4156b94bb87c13729d51e3e3458d4c24963 | [
"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 | 741 | lean | import data.vector open tactic
universe variables u
axiom app : Π {α : Type u} {n m : nat}, vector α m → vector α n → vector α (m+n)
example (n1 n2 n3 : nat) (v1 w1 : vector nat n1) (w1' : vector nat n3) (v2 w2 : vector nat n2) :
n1 = n3 → v1 = w1 → w1 == w1' → v2 = w2 → app v1 v2 == app w1' w2 :=
by cc
example (n1 n2 n3 : nat) (v1 w1 : vector nat n1) (w1' : vector nat n3) (v2 w2 : vector nat n2) :
n1 == n3 → v1 = w1 → w1 == w1' → v2 == w2 → app v1 v2 == app w1' w2 :=
by cc
example (n1 n2 n3 : nat) (v1 w1 v : vector nat n1) (w1' : vector nat n3) (v2 w2 w : vector nat n2) :
n1 == n3 → v1 = w1 → w1 == w1' → v2 == w2 → app w1' w2 == app v w → app v1 v2 = app v w :=
by cc
|
47b7c22ae60e1f9b74c3fb7012e849d254c27c5f | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/analysis/special_functions/log/base.lean | b7a3e10678ea8c302461cbb1215592ed93b2534b | [
"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 | 13,932 | lean | /-
Copyright (c) 2022 Bolton Bailey. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bolton Bailey, Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne
-/
import analysis.special_functions.pow.real
import data.int.log
/-!
# Real logarithm base `b`
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file we define `real.logb` to be the logarithm of a real number in a given base `b`. We
define this as the division of the natural logarithms of the argument and the base, so that we have
a globally defined function with `logb b 0 = 0`, `logb b (-x) = logb b x` `logb 0 x = 0` and
`logb (-b) x = logb b x`.
We prove some basic properties of this function and its relation to `rpow`.
## Tags
logarithm, continuity
-/
open set filter function
open_locale topology
noncomputable theory
namespace real
variables {b x y : ℝ}
/-- The real logarithm in a given base. As with the natural logarithm, we define `logb b x` to
be `logb b |x|` for `x < 0`, and `0` for `x = 0`.-/
@[pp_nodot] noncomputable def logb (b x : ℝ) : ℝ := log x / log b
lemma log_div_log : log x / log b = logb b x := rfl
@[simp] lemma logb_zero : logb b 0 = 0 := by simp [logb]
@[simp] lemma logb_one : logb b 1 = 0 := by simp [logb]
@[simp] lemma logb_abs (x : ℝ) : logb b (|x|) = logb b x := by rw [logb, logb, log_abs]
@[simp] lemma logb_neg_eq_logb (x : ℝ) : logb b (-x) = logb b x :=
by rw [← logb_abs x, ← logb_abs (-x), abs_neg]
lemma logb_mul (hx : x ≠ 0) (hy : y ≠ 0) : logb b (x * y) = logb b x + logb b y :=
by simp_rw [logb, log_mul hx hy, add_div]
lemma logb_div (hx : x ≠ 0) (hy : y ≠ 0) : logb b (x / y) = logb b x - logb b y :=
by simp_rw [logb, log_div hx hy, sub_div]
@[simp] lemma logb_inv (x : ℝ) : logb b (x⁻¹) = -logb b x := by simp [logb, neg_div]
lemma inv_logb (a b : ℝ) : (logb a b)⁻¹ = logb b a := by simp_rw [logb, inv_div]
theorem inv_logb_mul_base {a b : ℝ} (h₁ : a ≠ 0) (h₂ : b ≠ 0) (c : ℝ) :
(logb (a * b) c)⁻¹ = (logb a c)⁻¹ + (logb b c)⁻¹ :=
by simp_rw inv_logb; exact logb_mul h₁ h₂
theorem inv_logb_div_base {a b : ℝ} (h₁ : a ≠ 0) (h₂ : b ≠ 0) (c : ℝ) :
(logb (a / b) c)⁻¹ = (logb a c)⁻¹ - (logb b c)⁻¹ :=
by simp_rw inv_logb; exact logb_div h₁ h₂
theorem logb_mul_base {a b : ℝ} (h₁ : a ≠ 0) (h₂ : b ≠ 0) (c : ℝ) :
logb (a * b) c = ((logb a c)⁻¹ + (logb b c)⁻¹)⁻¹ :=
by rw [←inv_logb_mul_base h₁ h₂ c, inv_inv]
theorem logb_div_base {a b : ℝ} (h₁ : a ≠ 0) (h₂ : b ≠ 0) (c : ℝ) :
logb (a / b) c = ((logb a c)⁻¹ - (logb b c)⁻¹)⁻¹ :=
by rw [←inv_logb_div_base h₁ h₂ c, inv_inv]
theorem mul_logb {a b c : ℝ} (h₁ : b ≠ 0) (h₂ : b ≠ 1) (h₃ : b ≠ -1) :
logb a b * logb b c = logb a c :=
begin
unfold logb,
rw [mul_comm, div_mul_div_cancel _ (log_ne_zero.mpr ⟨h₁, h₂, h₃⟩)],
end
theorem div_logb {a b c : ℝ} (h₁ : c ≠ 0) (h₂ : c ≠ 1) (h₃ : c ≠ -1) :
logb a c / logb b c = logb a b :=
begin
unfold logb,
-- TODO: div_div_div_cancel_left is missing for `group_with_zero`,
rw [div_div_div_eq, mul_comm, mul_div_mul_right _ _ (log_ne_zero.mpr ⟨h₁, h₂, h₃⟩)],
end
section b_pos_and_ne_one
variable (b_pos : 0 < b)
variable (b_ne_one : b ≠ 1)
include b_pos b_ne_one
private lemma log_b_ne_zero : log b ≠ 0 :=
begin
have b_ne_zero : b ≠ 0, linarith,
have b_ne_minus_one : b ≠ -1, linarith,
simp [b_ne_one, b_ne_zero, b_ne_minus_one],
end
@[simp] lemma logb_rpow :
logb b (b ^ x) = x :=
begin
rw [logb, div_eq_iff, log_rpow b_pos],
exact log_b_ne_zero b_pos b_ne_one,
end
lemma rpow_logb_eq_abs (hx : x ≠ 0) : b ^ (logb b x) = |x| :=
begin
apply log_inj_on_pos,
simp only [set.mem_Ioi],
apply rpow_pos_of_pos b_pos,
simp only [abs_pos, mem_Ioi, ne.def, hx, not_false_iff],
rw [log_rpow b_pos, logb, log_abs],
field_simp [log_b_ne_zero b_pos b_ne_one],
end
@[simp] lemma rpow_logb (hx : 0 < x) : b ^ (logb b x) = x :=
by { rw rpow_logb_eq_abs b_pos b_ne_one (hx.ne'), exact abs_of_pos hx, }
lemma rpow_logb_of_neg (hx : x < 0) : b ^ (logb b x) = -x :=
by { rw rpow_logb_eq_abs b_pos b_ne_one (ne_of_lt hx), exact abs_of_neg hx }
lemma surj_on_logb : surj_on (logb b) (Ioi 0) univ :=
λ x _, ⟨rpow b x, rpow_pos_of_pos b_pos x, logb_rpow b_pos b_ne_one⟩
lemma logb_surjective : surjective (logb b) :=
λ x, ⟨b ^ x, logb_rpow b_pos b_ne_one⟩
@[simp] lemma range_logb : range (logb b) = univ :=
(logb_surjective b_pos b_ne_one).range_eq
lemma surj_on_logb' : surj_on (logb b) (Iio 0) univ :=
begin
intros x x_in_univ,
use -b ^ x,
split,
{ simp only [right.neg_neg_iff, set.mem_Iio], apply rpow_pos_of_pos b_pos, },
{ rw [logb_neg_eq_logb, logb_rpow b_pos b_ne_one], },
end
end b_pos_and_ne_one
section one_lt_b
variable (hb : 1 < b)
include hb
private lemma b_pos : 0 < b := by linarith
private lemma b_ne_one : b ≠ 1 := by linarith
@[simp] lemma logb_le_logb (h : 0 < x) (h₁ : 0 < y) :
logb b x ≤ logb b y ↔ x ≤ y :=
by { rw [logb, logb, div_le_div_right (log_pos hb), log_le_log h h₁], }
lemma logb_lt_logb (hx : 0 < x) (hxy : x < y) : logb b x < logb b y :=
by { rw [logb, logb, div_lt_div_right (log_pos hb)], exact log_lt_log hx hxy, }
@[simp] lemma logb_lt_logb_iff (hx : 0 < x) (hy : 0 < y) :
logb b x < logb b y ↔ x < y :=
by { rw [logb, logb, div_lt_div_right (log_pos hb)], exact log_lt_log_iff hx hy, }
lemma logb_le_iff_le_rpow (hx : 0 < x) : logb b x ≤ y ↔ x ≤ b ^ y :=
by rw [←rpow_le_rpow_left_iff hb, rpow_logb (b_pos hb) (b_ne_one hb) hx]
lemma logb_lt_iff_lt_rpow (hx : 0 < x) : logb b x < y ↔ x < b ^ y :=
by rw [←rpow_lt_rpow_left_iff hb, rpow_logb (b_pos hb) (b_ne_one hb) hx]
lemma le_logb_iff_rpow_le (hy : 0 < y) : x ≤ logb b y ↔ b ^ x ≤ y :=
by rw [←rpow_le_rpow_left_iff hb, rpow_logb (b_pos hb) (b_ne_one hb) hy]
lemma lt_logb_iff_rpow_lt (hy : 0 < y) : x < logb b y ↔ b ^ x < y :=
by rw [←rpow_lt_rpow_left_iff hb, rpow_logb (b_pos hb) (b_ne_one hb) hy]
lemma logb_pos_iff (hx : 0 < x) : 0 < logb b x ↔ 1 < x :=
by { rw ← @logb_one b, rw logb_lt_logb_iff hb zero_lt_one hx, }
lemma logb_pos (hx : 1 < x) : 0 < logb b x :=
by { rw logb_pos_iff hb (lt_trans zero_lt_one hx), exact hx, }
lemma logb_neg_iff (h : 0 < x) : logb b x < 0 ↔ x < 1 :=
by { rw ← logb_one, exact logb_lt_logb_iff hb h zero_lt_one, }
lemma logb_neg (h0 : 0 < x) (h1 : x < 1) : logb b x < 0 :=
(logb_neg_iff hb h0).2 h1
lemma logb_nonneg_iff (hx : 0 < x) : 0 ≤ logb b x ↔ 1 ≤ x :=
by rw [← not_lt, logb_neg_iff hb hx, not_lt]
lemma logb_nonneg (hx : 1 ≤ x) : 0 ≤ logb b x :=
(logb_nonneg_iff hb (zero_lt_one.trans_le hx)).2 hx
lemma logb_nonpos_iff (hx : 0 < x) : logb b x ≤ 0 ↔ x ≤ 1 :=
by rw [← not_lt, logb_pos_iff hb hx, not_lt]
lemma logb_nonpos_iff' (hx : 0 ≤ x) : logb b x ≤ 0 ↔ x ≤ 1 :=
begin
rcases hx.eq_or_lt with (rfl|hx),
{ simp [le_refl, zero_le_one] },
exact logb_nonpos_iff hb hx,
end
lemma logb_nonpos (hx : 0 ≤ x) (h'x : x ≤ 1) : logb b x ≤ 0 :=
(logb_nonpos_iff' hb hx).2 h'x
lemma strict_mono_on_logb : strict_mono_on (logb b) (set.Ioi 0) :=
λ x hx y hy hxy, logb_lt_logb hb hx hxy
lemma strict_anti_on_logb : strict_anti_on (logb b) (set.Iio 0) :=
begin
rintros x (hx : x < 0) y (hy : y < 0) hxy,
rw [← logb_abs y, ← logb_abs x],
refine logb_lt_logb hb (abs_pos.2 hy.ne) _,
rwa [abs_of_neg hy, abs_of_neg hx, neg_lt_neg_iff],
end
lemma logb_inj_on_pos : set.inj_on (logb b) (set.Ioi 0) :=
(strict_mono_on_logb hb).inj_on
lemma eq_one_of_pos_of_logb_eq_zero (h₁ : 0 < x) (h₂ : logb b x = 0) :
x = 1 :=
logb_inj_on_pos hb (set.mem_Ioi.2 h₁) (set.mem_Ioi.2 zero_lt_one)
(h₂.trans real.logb_one.symm)
lemma logb_ne_zero_of_pos_of_ne_one (hx_pos : 0 < x) (hx : x ≠ 1) :
logb b x ≠ 0 :=
mt (eq_one_of_pos_of_logb_eq_zero hb hx_pos) hx
lemma tendsto_logb_at_top : tendsto (logb b) at_top at_top :=
tendsto.at_top_div_const (log_pos hb) tendsto_log_at_top
end one_lt_b
section b_pos_and_b_lt_one
variable (b_pos : 0 < b)
variable (b_lt_one : b < 1)
include b_lt_one
private lemma b_ne_one : b ≠ 1 := by linarith
include b_pos
@[simp] lemma logb_le_logb_of_base_lt_one (h : 0 < x) (h₁ : 0 < y) :
logb b x ≤ logb b y ↔ y ≤ x :=
by { rw [logb, logb, div_le_div_right_of_neg (log_neg b_pos b_lt_one), log_le_log h₁ h], }
lemma logb_lt_logb_of_base_lt_one (hx : 0 < x) (hxy : x < y) : logb b y < logb b x :=
by { rw [logb, logb, div_lt_div_right_of_neg (log_neg b_pos b_lt_one)], exact log_lt_log hx hxy, }
@[simp] lemma logb_lt_logb_iff_of_base_lt_one (hx : 0 < x) (hy : 0 < y) :
logb b x < logb b y ↔ y < x :=
by { rw [logb, logb, div_lt_div_right_of_neg (log_neg b_pos b_lt_one)], exact log_lt_log_iff hy hx }
lemma logb_le_iff_le_rpow_of_base_lt_one (hx : 0 < x) : logb b x ≤ y ↔ b ^ y ≤ x :=
by rw [←rpow_le_rpow_left_iff_of_base_lt_one b_pos b_lt_one, rpow_logb b_pos (b_ne_one b_lt_one) hx]
lemma logb_lt_iff_lt_rpow_of_base_lt_one (hx : 0 < x) : logb b x < y ↔ b ^ y < x :=
by rw [←rpow_lt_rpow_left_iff_of_base_lt_one b_pos b_lt_one, rpow_logb b_pos (b_ne_one b_lt_one) hx]
lemma le_logb_iff_rpow_le_of_base_lt_one (hy : 0 < y) : x ≤ logb b y ↔ y ≤ b ^ x :=
by rw [←rpow_le_rpow_left_iff_of_base_lt_one b_pos b_lt_one, rpow_logb b_pos (b_ne_one b_lt_one) hy]
lemma lt_logb_iff_rpow_lt_of_base_lt_one (hy : 0 < y) : x < logb b y ↔ y < b ^ x :=
by rw [←rpow_lt_rpow_left_iff_of_base_lt_one b_pos b_lt_one, rpow_logb b_pos (b_ne_one b_lt_one) hy]
lemma logb_pos_iff_of_base_lt_one (hx : 0 < x) : 0 < logb b x ↔ x < 1 :=
by rw [← @logb_one b, logb_lt_logb_iff_of_base_lt_one b_pos b_lt_one zero_lt_one hx]
lemma logb_pos_of_base_lt_one (hx : 0 < x) (hx' : x < 1) : 0 < logb b x :=
by { rw logb_pos_iff_of_base_lt_one b_pos b_lt_one hx, exact hx', }
lemma logb_neg_iff_of_base_lt_one (h : 0 < x) : logb b x < 0 ↔ 1 < x :=
by rw [← @logb_one b, logb_lt_logb_iff_of_base_lt_one b_pos b_lt_one h zero_lt_one]
lemma logb_neg_of_base_lt_one (h1 : 1 < x) : logb b x < 0 :=
(logb_neg_iff_of_base_lt_one b_pos b_lt_one (lt_trans zero_lt_one h1)).2 h1
lemma logb_nonneg_iff_of_base_lt_one (hx : 0 < x) : 0 ≤ logb b x ↔ x ≤ 1 :=
by rw [← not_lt, logb_neg_iff_of_base_lt_one b_pos b_lt_one hx, not_lt]
lemma logb_nonneg_of_base_lt_one (hx : 0 < x) (hx' : x ≤ 1) : 0 ≤ logb b x :=
by {rw [logb_nonneg_iff_of_base_lt_one b_pos b_lt_one hx], exact hx' }
lemma logb_nonpos_iff_of_base_lt_one (hx : 0 < x) : logb b x ≤ 0 ↔ 1 ≤ x :=
by rw [← not_lt, logb_pos_iff_of_base_lt_one b_pos b_lt_one hx, not_lt]
lemma strict_anti_on_logb_of_base_lt_one : strict_anti_on (logb b) (set.Ioi 0) :=
λ x hx y hy hxy, logb_lt_logb_of_base_lt_one b_pos b_lt_one hx hxy
lemma strict_mono_on_logb_of_base_lt_one : strict_mono_on (logb b) (set.Iio 0) :=
begin
rintros x (hx : x < 0) y (hy : y < 0) hxy,
rw [← logb_abs y, ← logb_abs x],
refine logb_lt_logb_of_base_lt_one b_pos b_lt_one (abs_pos.2 hy.ne) _,
rwa [abs_of_neg hy, abs_of_neg hx, neg_lt_neg_iff],
end
lemma logb_inj_on_pos_of_base_lt_one : set.inj_on (logb b) (set.Ioi 0) :=
(strict_anti_on_logb_of_base_lt_one b_pos b_lt_one).inj_on
lemma eq_one_of_pos_of_logb_eq_zero_of_base_lt_one (h₁ : 0 < x) (h₂ : logb b x = 0) :
x = 1 :=
logb_inj_on_pos_of_base_lt_one b_pos b_lt_one (set.mem_Ioi.2 h₁) (set.mem_Ioi.2 zero_lt_one)
(h₂.trans real.logb_one.symm)
lemma logb_ne_zero_of_pos_of_ne_one_of_base_lt_one (hx_pos : 0 < x) (hx : x ≠ 1) :
logb b x ≠ 0 :=
mt (eq_one_of_pos_of_logb_eq_zero_of_base_lt_one b_pos b_lt_one hx_pos) hx
lemma tendsto_logb_at_top_of_base_lt_one : tendsto (logb b) at_top at_bot :=
begin
rw tendsto_at_top_at_bot,
intro e,
use 1 ⊔ b ^ e,
intro a,
simp only [and_imp, sup_le_iff],
intro ha,
rw logb_le_iff_le_rpow_of_base_lt_one b_pos b_lt_one,
tauto,
exact lt_of_lt_of_le zero_lt_one ha,
end
end b_pos_and_b_lt_one
lemma floor_logb_nat_cast {b : ℕ} {r : ℝ} (hb : 1 < b) (hr : 0 ≤ r) : ⌊logb b r⌋ = int.log b r :=
begin
obtain rfl | hr := hr.eq_or_lt,
{ rw [logb_zero, int.log_zero_right, int.floor_zero] },
have hb1' : 1 < (b : ℝ) := nat.one_lt_cast.mpr hb,
apply le_antisymm,
{ rw [←int.zpow_le_iff_le_log hb hr, ←rpow_int_cast b],
refine le_of_le_of_eq _ (rpow_logb (zero_lt_one.trans hb1') hb1'.ne' hr),
exact rpow_le_rpow_of_exponent_le hb1'.le (int.floor_le _) },
{ rw [int.le_floor, le_logb_iff_rpow_le hb1' hr, rpow_int_cast],
exact int.zpow_log_le_self hb hr }
end
lemma ceil_logb_nat_cast {b : ℕ} {r : ℝ} (hb : 1 < b) (hr : 0 ≤ r) : ⌈logb b r⌉ = int.clog b r :=
begin
obtain rfl | hr := hr.eq_or_lt,
{ rw [logb_zero, int.clog_zero_right, int.ceil_zero] },
have hb1' : 1 < (b : ℝ) := nat.one_lt_cast.mpr hb,
apply le_antisymm,
{ rw [int.ceil_le, logb_le_iff_le_rpow hb1' hr, rpow_int_cast],
refine int.self_le_zpow_clog hb r },
{ rw [←int.le_zpow_iff_clog_le hb hr, ←rpow_int_cast b],
refine (rpow_logb (zero_lt_one.trans hb1') hb1'.ne' hr).symm.trans_le _,
exact rpow_le_rpow_of_exponent_le hb1'.le (int.le_ceil _) },
end
@[simp] lemma logb_eq_zero :
logb b x = 0 ↔ b = 0 ∨ b = 1 ∨ b = -1 ∨ x = 0 ∨ x = 1 ∨ x = -1 :=
begin
simp_rw [logb, div_eq_zero_iff, log_eq_zero],
tauto,
end
/- TODO add other limits and continuous API lemmas analogous to those in log.lean -/
open_locale big_operators
lemma logb_prod {α : Type*} (s : finset α) (f : α → ℝ) (hf : ∀ x ∈ s, f x ≠ 0):
logb b (∏ i in s, f i) = ∑ i in s, logb b (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, logb_mul hf.1 (finset.prod_ne_zero_iff.2 hf.2)],
end
end real
|
68432fad734b41b57d9ec87ee54b56162ded2902 | e00ea76a720126cf9f6d732ad6216b5b824d20a7 | /src/topology/algebra/module.lean | 8ef924f662cce303c809dcfd3695e114e14677a8 | [
"Apache-2.0"
] | permissive | vaibhavkarve/mathlib | a574aaf68c0a431a47fa82ce0637f0f769826bfe | 17f8340912468f49bdc30acdb9a9fa02eeb0473a | refs/heads/master | 1,621,263,802,637 | 1,585,399,588,000 | 1,585,399,588,000 | 250,833,447 | 0 | 0 | Apache-2.0 | 1,585,410,341,000 | 1,585,410,341,000 | null | UTF-8 | Lean | false | false | 23,359 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jan-David Salchow, Sébastien Gouëzel, Jean Lo
-/
import topology.algebra.ring linear_algebra.basic ring_theory.algebra
/-!
# Theory of topological modules and continuous linear maps.
We define classes `topological_semimodule`, `topological_module` and `topological_vector_spaces`,
as extensions of the corresponding algebraic classes where the algebraic operations are continuous.
We also define continuous linear maps, as linear maps between topological modules which are
continuous. The set of continuous linear maps between the topological `R`-modules `M` and `M₂` is
denoted by `M →L[R] M₂`.
Continuous linear equivalences are denoted by `M ≃L[R] M₂`.
## Implementation notes
Topological vector spaces are defined as an `abbreviation` for topological modules,
if the base ring is a field. This has as advantage that topological vector spaces are completely
transparent for type class inference, which means that all instances for topological modules
are immediately picked up for vector spaces as well.
A cosmetic disadvantage is that one can not extend topological vector spaces.
The solution is to extend `topological_module` instead.
-/
open filter
open_locale topological_space
universes u v w u'
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A topological semimodule, over a semiring which is also a topological space, is a
semimodule in which scalar multiplication is continuous. In applications, R will be a topological
semiring and M a topological additive semigroup, but this is not needed for the definition -/
class topological_semimodule (R : Type u) (M : Type v)
[semiring R] [topological_space R]
[topological_space M] [add_comm_monoid M]
[semimodule R M] : Prop :=
(continuous_smul : continuous (λp : R × M, p.1 • p.2))
end prio
section
variables {R : Type u} {M : Type v}
[semiring R] [topological_space R]
[topological_space M] [add_comm_monoid M]
[semimodule R M] [topological_semimodule R M]
lemma continuous_smul : continuous (λp:R×M, p.1 • p.2) :=
topological_semimodule.continuous_smul R M
lemma continuous.smul {α : Type*} [topological_space α] {f : α → R} {g : α → M}
(hf : continuous f) (hg : continuous g) : continuous (λp, f p • g p) :=
continuous_smul.comp (hf.prod_mk hg)
lemma tendsto_smul {c : R} {x : M} : tendsto (λp:R×M, p.fst • p.snd) (𝓝 (c, x)) (𝓝 (c • x)) :=
continuous_smul.tendsto _
lemma filter.tendsto.smul {α : Type*} {l : filter α} {f : α → R} {g : α → M} {c : R} {x : M}
(hf : tendsto f l (𝓝 c)) (hg : tendsto g l (𝓝 x)) : tendsto (λ a, f a • g a) l (𝓝 (c • x)) :=
tendsto_smul.comp (hf.prod_mk_nhds hg)
end
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A topological module, over a ring which is also a topological space, is a module in which
scalar multiplication is continuous. In applications, `R` will be a topological ring and `M` a
topological additive group, but this is not needed for the definition -/
class topological_module (R : Type u) (M : Type v)
[ring R] [topological_space R]
[topological_space M] [add_comm_group M]
[module R M]
extends topological_semimodule R M : Prop
/-- A topological vector space is a topological module over a field. -/
abbreviation topological_vector_space (R : Type u) (M : Type v)
[field R] [topological_space R]
[topological_space M] [add_comm_group M] [module R M] :=
topological_module R M
end prio
section
variables {R : Type*} {M : Type*}
[ring R] [topological_space R]
[topological_space M] [add_comm_group M]
[module R M] [topological_module R M]
/-- Scalar multiplication by a unit is a homeomorphism from a
topological module onto itself. -/
protected def homeomorph.smul_of_unit (a : units R) : M ≃ₜ M :=
{ to_fun := λ x, (a : R) • x,
inv_fun := λ x, ((a⁻¹ : units R) : R) • x,
right_inv := λ x, calc (a : R) • ((a⁻¹ : units R) : R) • x = x :
by rw [smul_smul, units.mul_inv, one_smul],
left_inv := λ x, calc ((a⁻¹ : units R) : R) • (a : R) • x = x :
by rw [smul_smul, units.inv_mul, one_smul],
continuous_to_fun := continuous_const.smul continuous_id,
continuous_inv_fun := continuous_const.smul continuous_id }
lemma is_open_map_smul_of_unit (a : units R) : is_open_map (λ (x : M), (a : R) • x) :=
(homeomorph.smul_of_unit a).is_open_map
lemma is_closed_map_smul_of_unit (a : units R) : is_closed_map (λ (x : M), (a : R) • x) :=
(homeomorph.smul_of_unit a).is_closed_map
/-- If `M` is a topological module over `R` and `0` is a limit of invertible elements of `R`, then
`⊤` is the only submodule of `M` with a nonempty interior. See also
`submodule.eq_top_of_nonempty_interior` for a `normed_space` version. -/
lemma submodule.eq_top_of_nonempty_interior' [topological_add_monoid M]
(h : nhds_within (0:R) {x | is_unit x} ≠ ⊥)
(s : submodule R M) (hs : (interior (s:set M)).nonempty) :
s = ⊤ :=
begin
rcases hs with ⟨y, hy⟩,
refine (submodule.eq_top_iff'.2 $ λ x, _),
rw [mem_interior_iff_mem_nhds] at hy,
have : tendsto (λ c:R, y + c • x) (nhds_within 0 {x | is_unit x}) (𝓝 (y + (0:R) • x)),
from tendsto_const_nhds.add ((tendsto_nhds_within_of_tendsto_nhds tendsto_id).smul
tendsto_const_nhds),
rw [zero_smul, add_zero] at this,
rcases nonempty_of_mem_sets h (inter_mem_sets (mem_map.1 (this hy)) self_mem_nhds_within)
with ⟨_, hu, u, rfl⟩,
have hy' : y ∈ ↑s := mem_of_nhds hy,
exact (s.smul_mem_iff' _).1 ((s.add_mem_iff_right hy').1 hu)
end
end
section
variables {R : Type*} {M : Type*} {a : R}
[field R] [topological_space R]
[topological_space M] [add_comm_group M]
[vector_space R M] [topological_vector_space R M]
set_option class.instance_max_depth 36
/-- Scalar multiplication by a non-zero field element is a
homeomorphism from a topological vector space onto itself. -/
protected def homeomorph.smul_of_ne_zero (ha : a ≠ 0) : M ≃ₜ M :=
{.. homeomorph.smul_of_unit (units.mk0 a ha)}
lemma is_open_map_smul_of_ne_zero (ha : a ≠ 0) : is_open_map (λ (x : M), a • x) :=
(homeomorph.smul_of_ne_zero ha).is_open_map
lemma is_closed_map_smul_of_ne_zero (ha : a ≠ 0) : is_closed_map (λ (x : M), a • x) :=
(homeomorph.smul_of_ne_zero ha).is_closed_map
end
/-- Continuous linear maps between modules. We only put the type classes that are necessary for the
definition, although in applications `M` and `M₂` will be topological modules over the topological
ring `R`. -/
structure continuous_linear_map
(R : Type*) [ring R]
(M : Type*) [topological_space M] [add_comm_group M]
(M₂ : Type*) [topological_space M₂] [add_comm_group M₂]
[module R M] [module R M₂]
extends linear_map R M M₂ :=
(cont : continuous to_fun)
notation M ` →L[`:25 R `] ` M₂ := continuous_linear_map R M M₂
/-- Continuous linear equivalences between modules. We only put the type classes that are necessary
for the definition, although in applications `M` and `M₂` will be topological modules over the
topological ring `R`. -/
structure continuous_linear_equiv
(R : Type*) [ring R]
(M : Type*) [topological_space M] [add_comm_group M]
(M₂ : Type*) [topological_space M₂] [add_comm_group M₂]
[module R M] [module R M₂]
extends linear_equiv R M M₂ :=
(continuous_to_fun : continuous to_fun)
(continuous_inv_fun : continuous inv_fun)
notation M ` ≃L[`:50 R `] ` M₂ := continuous_linear_equiv R M M₂
namespace continuous_linear_map
section general_ring
/- Properties that hold for non-necessarily commutative rings. -/
variables
{R : Type*} [ring R]
{M : Type*} [topological_space M] [add_comm_group M]
{M₂ : Type*} [topological_space M₂] [add_comm_group M₂]
{M₃ : Type*} [topological_space M₃] [add_comm_group M₃]
{M₄ : Type*} [topological_space M₄] [add_comm_group M₄]
[module R M] [module R M₂] [module R M₃] [module R M₄]
/-- Coerce continuous linear maps to linear maps. -/
instance : has_coe (M →L[R] M₂) (M →ₗ[R] M₂) := ⟨to_linear_map⟩
/-- Coerce continuous linear maps to functions. -/
instance to_fun : has_coe_to_fun $ M →L[R] M₂ := ⟨_, λ f, f.to_fun⟩
protected lemma continuous (f : M →L[R] M₂) : continuous f := f.2
@[ext] theorem ext {f g : M →L[R] M₂} (h : ∀ x, f x = g x) : f = g :=
by cases f; cases g; congr' 1; ext x; apply h
theorem ext_iff {f g : M →L[R] M₂} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, by rw h, by ext⟩
variables (c : R) (f g : M →L[R] M₂) (h : M₂ →L[R] M₃) (x y z : M)
-- make some straightforward lemmas available to `simp`.
@[simp] lemma map_zero : f (0 : M) = 0 := (to_linear_map _).map_zero
@[simp] lemma map_add : f (x + y) = f x + f y := (to_linear_map _).map_add _ _
@[simp] lemma map_sub : f (x - y) = f x - f y := (to_linear_map _).map_sub _ _
@[simp] lemma map_smul : f (c • x) = c • f x := (to_linear_map _).map_smul _ _
@[simp] lemma map_neg : f (-x) = - (f x) := (to_linear_map _).map_neg _
@[simp, squash_cast] lemma coe_coe : ((f : M →ₗ[R] M₂) : (M → M₂)) = (f : M → M₂) := rfl
/-- The continuous map that is constantly zero. -/
instance: has_zero (M →L[R] M₂) := ⟨⟨0, continuous_const⟩⟩
instance : inhabited (M →L[R] M₂) := ⟨0⟩
@[simp] lemma zero_apply : (0 : M →L[R] M₂) x = 0 := rfl
@[simp, elim_cast] lemma coe_zero : ((0 : M →L[R] M₂) : M →ₗ[R] M₂) = 0 := rfl
/- no simp attribute on the next line as simp does not always simplify `0 x` to `0`
when `0` is the zero function, while it does for the zero continuous linear map,
and this is the most important property we care about. -/
@[elim_cast] lemma coe_zero' : ((0 : M →L[R] M₂) : M → M₂) = 0 := rfl
/-- the identity map as a continuous linear map. -/
def id : M →L[R] M :=
⟨linear_map.id, continuous_id⟩
instance : has_one (M →L[R] M) := ⟨id⟩
lemma id_apply : (id : M →L[R] M) x = x := rfl
@[simp, elim_cast] lemma coe_id : ((id : M →L[R] M) : M →ₗ[R] M) = linear_map.id := rfl
@[simp, elim_cast] lemma coe_id' : ((id : M →L[R] M) : M → M) = _root_.id := rfl
@[simp] lemma one_apply : (1 : M →L[R] M) x = x := rfl
section add
variables [topological_add_group M₂]
instance : has_add (M →L[R] M₂) :=
⟨λ f g, ⟨f + g, f.2.add g.2⟩⟩
@[simp] lemma add_apply : (f + g) x = f x + g x := rfl
@[simp, move_cast] lemma coe_add : (((f + g) : M →L[R] M₂) : M →ₗ[R] M₂) = (f : M →ₗ[R] M₂) + g := rfl
@[move_cast] lemma coe_add' : (((f + g) : M →L[R] M₂) : M → M₂) = (f : M → M₂) + g := rfl
instance : has_neg (M →L[R] M₂) := ⟨λ f, ⟨-f, f.2.neg⟩⟩
@[simp] lemma neg_apply : (-f) x = - (f x) := rfl
@[simp, move_cast] lemma coe_neg : (((-f) : M →L[R] M₂) : M →ₗ[R] M₂) = -(f : M →ₗ[R] M₂) := rfl
@[move_cast] lemma coe_neg' : (((-f) : M →L[R] M₂) : M → M₂) = -(f : M → M₂) := rfl
instance : add_comm_group (M →L[R] M₂) :=
by { refine {zero := 0, add := (+), neg := has_neg.neg, ..}; intros; ext;
apply_rules [zero_add, add_assoc, add_zero, add_left_neg, add_comm] }
lemma sub_apply (x : M) : (f - g) x = f x - g x := rfl
@[simp, move_cast] lemma coe_sub : (((f - g) : M →L[R] M₂) : M →ₗ[R] M₂) = (f : M →ₗ[R] M₂) - g := rfl
@[simp, move_cast] lemma coe_sub' : (((f - g) : M →L[R] M₂) : M → M₂) = (f : M → M₂) - g := rfl
end add
@[simp] lemma sub_apply' (x : M) : ((f : M →ₗ[R] M₂) - g) x = f x - g x := rfl
/-- Composition of bounded linear maps. -/
def comp (g : M₂ →L[R] M₃) (f : M →L[R] M₂) : M →L[R] M₃ :=
⟨linear_map.comp g.to_linear_map f.to_linear_map, g.2.comp f.2⟩
@[simp, move_cast] lemma coe_comp : ((h.comp f) : (M →ₗ[R] M₃)) = (h : M₂ →ₗ[R] M₃).comp f := rfl
@[simp, move_cast] lemma coe_comp' : ((h.comp f) : (M → M₃)) = (h : M₂ → M₃) ∘ f := rfl
@[simp] theorem comp_id : f.comp id = f :=
ext $ λ x, rfl
@[simp] theorem id_comp : id.comp f = f :=
ext $ λ x, rfl
@[simp] theorem comp_zero : f.comp (0 : M₃ →L[R] M) = 0 :=
by { ext, simp }
@[simp] theorem zero_comp : (0 : M₂ →L[R] M₃).comp f = 0 :=
by { ext, simp }
@[simp] lemma comp_add [topological_add_group M₂] [topological_add_group M₃]
(g : M₂ →L[R] M₃) (f₁ f₂ : M →L[R] M₂) :
g.comp (f₁ + f₂) = g.comp f₁ + g.comp f₂ :=
by { ext, simp }
@[simp] lemma add_comp [topological_add_group M₃]
(g₁ g₂ : M₂ →L[R] M₃) (f : M →L[R] M₂) :
(g₁ + g₂).comp f = g₁.comp f + g₂.comp f :=
by { ext, simp }
theorem comp_assoc (h : M₃ →L[R] M₄) (g : M₂ →L[R] M₃) (f : M →L[R] M₂) :
(h.comp g).comp f = h.comp (g.comp f) :=
rfl
instance : has_mul (M →L[R] M) := ⟨comp⟩
instance [topological_add_group M] : ring (M →L[R] M) :=
{ mul := (*),
one := 1,
mul_one := λ _, ext $ λ _, rfl,
one_mul := λ _, ext $ λ _, rfl,
mul_assoc := λ _ _ _, ext $ λ _, rfl,
left_distrib := λ _ _ _, ext $ λ _, map_add _ _ _,
right_distrib := λ _ _ _, ext $ λ _, linear_map.add_apply _ _ _,
..continuous_linear_map.add_comm_group }
/-- The cartesian product of two bounded linear maps, as a bounded linear map. -/
protected def prod (f₁ : M →L[R] M₂) (f₂ : M →L[R] M₃) : M →L[R] (M₂ × M₃) :=
{ cont := f₁.2.prod_mk f₂.2,
..f₁.to_linear_map.prod f₂.to_linear_map }
@[simp, move_cast] lemma coe_prod (f₁ : M →L[R] M₂) (f₂ : M →L[R] M₃) :
(f₁.prod f₂ : M →ₗ[R] M₂ × M₃) = linear_map.prod f₁ f₂ :=
rfl
@[simp, move_cast] lemma prod_apply (f₁ : M →L[R] M₂) (f₂ : M →L[R] M₃) (x : M) :
f₁.prod f₂ x = (f₁ x, f₂ x) :=
rfl
variables (R M M₂)
/-- `prod.fst` as a `continuous_linear_map`. -/
protected def fst : M × M₂ →L[R] M :=
{ cont := continuous_fst, to_linear_map := linear_map.fst R M M₂ }
/-- `prod.snd` as a `continuous_linear_map`. -/
protected def snd : M × M₂ →L[R] M₂ :=
{ cont := continuous_snd, to_linear_map := linear_map.snd R M M₂ }
variables {R M M₂}
@[simp, move_cast] lemma coe_fst :
(continuous_linear_map.fst R M M₂ : M × M₂ →ₗ[R] M) = linear_map.fst R M M₂ :=
rfl
@[simp, move_cast] lemma coe_fst' :
(continuous_linear_map.fst R M M₂ : M × M₂ → M) = prod.fst :=
rfl
@[simp, move_cast] lemma coe_snd :
(continuous_linear_map.snd R M M₂ : M × M₂ →ₗ[R] M₂) = linear_map.snd R M M₂ :=
rfl
@[simp, move_cast] lemma coe_snd' :
(continuous_linear_map.snd R M M₂ : M × M₂ → M₂) = prod.snd :=
rfl
end general_ring
section comm_ring
variables
{R : Type*} [comm_ring R] [topological_space R]
{M : Type*} [topological_space M] [add_comm_group M]
{M₂ : Type*} [topological_space M₂] [add_comm_group M₂]
{M₃ : Type*} [topological_space M₃] [add_comm_group M₃]
[module R M] [module R M₂] [module R M₃] [topological_module R M₃]
instance : has_scalar R (M →L[R] M₃) :=
⟨λ c f, ⟨c • f, continuous_const.smul f.2⟩⟩
variables (c : R) (h : M₂ →L[R] M₃) (f g : M →L[R] M₂) (x y z : M)
@[simp] lemma smul_comp : (c • h).comp f = c • (h.comp f) := rfl
variable [topological_module R M₂]
@[simp] lemma smul_apply : (c • f) x = c • (f x) := rfl
@[simp, move_cast] lemma coe_apply : (((c • f) : M →L[R] M₂) : M →ₗ[R] M₂) = c • (f : M →ₗ[R] M₂) := rfl
@[move_cast] lemma coe_apply' : (((c • f) : M →L[R] M₂) : M → M₂) = c • (f : M → M₂) := rfl
@[simp] lemma comp_smul : h.comp (c • f) = c • (h.comp f) := by { ext, simp }
/-- The linear map `λ x, c x • f`. Associates to a scalar-valued linear map and an element of
`M₂` the `M₂`-valued linear map obtained by multiplying the two (a.k.a. tensoring by `M₂`) -/
def smul_right (c : M →L[R] R) (f : M₂) : M →L[R] M₂ :=
{ cont := c.2.smul continuous_const,
..c.to_linear_map.smul_right f }
@[simp]
lemma smul_right_apply {c : M →L[R] R} {f : M₂} {x : M} :
(smul_right c f : M → M₂) x = (c : M → R) x • f :=
rfl
@[simp]
lemma smul_right_one_one (c : R →L[R] M₂) : smul_right 1 ((c : R → M₂) 1) = c :=
by ext; simp [-continuous_linear_map.map_smul, (continuous_linear_map.map_smul _ _ _).symm]
@[simp]
lemma smul_right_one_eq_iff {f f' : M₂} :
smul_right (1 : R →L[R] R) f = smul_right 1 f' ↔ f = f' :=
⟨λ h, have (smul_right (1 : R →L[R] R) f : R → M₂) 1 = (smul_right (1 : R →L[R] R) f' : R → M₂) 1,
by rw h,
by simp at this; assumption,
by cc⟩
variable [topological_add_group M₂]
instance : module R (M →L[R] M₂) :=
{ smul_zero := λ _, ext $ λ _, smul_zero _,
zero_smul := λ _, ext $ λ _, zero_smul _ _,
one_smul := λ _, ext $ λ _, one_smul _ _,
mul_smul := λ _ _ _, ext $ λ _, mul_smul _ _ _,
add_smul := λ _ _ _, ext $ λ _, add_smul _ _ _,
smul_add := λ _ _ _, ext $ λ _, smul_add _ _ _ }
set_option class.instance_max_depth 55
instance : is_ring_hom (λ c : R, c • (1 : M₂ →L[R] M₂)) :=
{ map_one := one_smul _ _,
map_add := λ _ _, ext $ λ _, add_smul _ _ _,
map_mul := λ _ _, ext $ λ _, mul_smul _ _ _ }
instance : algebra R (M₂ →L[R] M₂) :=
{ to_fun := λ c, c • 1,
smul_def' := λ _ _, rfl,
commutes' := λ _ _, ext $ λ _, map_smul _ _ _ }
end comm_ring
end continuous_linear_map
namespace continuous_linear_equiv
variables {R : Type*} [ring R]
{M : Type*} [topological_space M] [add_comm_group M]
{M₂ : Type*} [topological_space M₂] [add_comm_group M₂]
{M₃ : Type*} [topological_space M₃] [add_comm_group M₃]
[module R M] [module R M₂] [module R M₃]
/-- A continuous linear equivalence induces a continuous linear map. -/
def to_continuous_linear_map (e : M ≃L[R] M₂) : M →L[R] M₂ :=
{ cont := e.continuous_to_fun,
..e.to_linear_equiv.to_linear_map }
/-- Coerce continuous linear equivs to continuous linear maps. -/
instance : has_coe (M ≃L[R] M₂) (M →L[R] M₂) := ⟨to_continuous_linear_map⟩
/-- Coerce continuous linear equivs to maps. -/
instance : has_coe_to_fun (M ≃L[R] M₂) := ⟨_, λ f, ((f : M →L[R] M₂) : M → M₂)⟩
@[simp] theorem coe_apply (e : M ≃L[R] M₂) (b : M) : (e : M →L[R] M₂) b = e b := rfl
@[squash_cast] lemma coe_coe (e : M ≃L[R] M₂) : ((e : M →L[R] M₂) : M → M₂) = e := rfl
@[ext] lemma ext {f g : M ≃L[R] M₂} (h : (f : M → M₂) = g) : f = g :=
begin
cases f; cases g,
simp only [],
ext x,
simp only [coe_fn_coe_base] at h,
induction h,
refl
end
/-- A continuous linear equivalence induces a homeomorphism. -/
def to_homeomorph (e : M ≃L[R] M₂) : M ≃ₜ M₂ := { ..e }
-- Make some straightforward lemmas available to `simp`.
@[simp] lemma map_zero (e : M ≃L[R] M₂) : e (0 : M) = 0 := (e : M →L[R] M₂).map_zero
@[simp] lemma map_add (e : M ≃L[R] M₂) (x y : M) : e (x + y) = e x + e y :=
(e : M →L[R] M₂).map_add x y
@[simp] lemma map_sub (e : M ≃L[R] M₂) (x y : M) : e (x - y) = e x - e y :=
(e : M →L[R] M₂).map_sub x y
@[simp] lemma map_smul (e : M ≃L[R] M₂) (c : R) (x : M) : e (c • x) = c • (e x) :=
(e : M →L[R] M₂).map_smul c x
@[simp] lemma map_neg (e : M ≃L[R] M₂) (x : M) : e (-x) = -e x := (e : M →L[R] M₂).map_neg x
@[simp] lemma map_eq_zero_iff (e : M ≃L[R] M₂) {x : M} : e x = 0 ↔ x = 0 :=
e.to_linear_equiv.map_eq_zero_iff
protected lemma continuous (e : M ≃L[R] M₂) : continuous (e : M → M₂) :=
e.continuous_to_fun
protected lemma continuous_on (e : M ≃L[R] M₂) {s : set M} : continuous_on (e : M → M₂) s :=
e.continuous.continuous_on
protected lemma continuous_at (e : M ≃L[R] M₂) {x : M} : continuous_at (e : M → M₂) x :=
e.continuous.continuous_at
protected lemma continuous_within_at (e : M ≃L[R] M₂) {s : set M} {x : M} :
continuous_within_at (e : M → M₂) s x :=
e.continuous.continuous_within_at
lemma comp_continuous_on_iff
{α : Type*} [topological_space α] (e : M ≃L[R] M₂) (f : α → M) (s : set α) :
continuous_on (e ∘ f) s ↔ continuous_on f s :=
e.to_homeomorph.comp_continuous_on_iff _ _
lemma comp_continuous_iff
{α : Type*} [topological_space α] (e : M ≃L[R] M₂) (f : α → M) :
continuous (e ∘ f) ↔ continuous f :=
e.to_homeomorph.comp_continuous_iff _
section
variable (M)
/-- The identity map as a continuous linear equivalence. -/
@[refl] protected def refl : M ≃L[R] M :=
{ continuous_to_fun := continuous_id,
continuous_inv_fun := continuous_id,
.. linear_equiv.refl R M }
end
/-- The inverse of a continuous linear equivalence as a continuous linear equivalence-/
@[symm] protected def symm (e : M ≃L[R] M₂) : M₂ ≃L[R] M :=
{ continuous_to_fun := e.continuous_inv_fun,
continuous_inv_fun := e.continuous_to_fun,
.. e.to_linear_equiv.symm }
@[simp] lemma symm_to_linear_equiv (e : M ≃L[R] M₂) :
e.symm.to_linear_equiv = e.to_linear_equiv.symm :=
by { ext, refl }
/-- The composition of two continuous linear equivalences as a continuous linear equivalence. -/
@[trans] protected def trans (e₁ : M ≃L[R] M₂) (e₂ : M₂ ≃L[R] M₃) : M ≃L[R] M₃ :=
{ continuous_to_fun := e₂.continuous_to_fun.comp e₁.continuous_to_fun,
continuous_inv_fun := e₁.continuous_inv_fun.comp e₂.continuous_inv_fun,
.. e₁.to_linear_equiv.trans e₂.to_linear_equiv }
@[simp] lemma trans_to_linear_equiv (e₁ : M ≃L[R] M₂) (e₂ : M₂ ≃L[R] M₃) :
(e₁.trans e₂).to_linear_equiv = e₁.to_linear_equiv.trans e₂.to_linear_equiv :=
by { ext, refl }
theorem bijective (e : M ≃L[R] M₂) : function.bijective e := e.to_linear_equiv.to_equiv.bijective
theorem injective (e : M ≃L[R] M₂) : function.injective e := e.to_linear_equiv.to_equiv.injective
theorem surjective (e : M ≃L[R] M₂) : function.surjective e := e.to_linear_equiv.to_equiv.surjective
@[simp] theorem apply_symm_apply (e : M ≃L[R] M₂) (c : M₂) : e (e.symm c) = c := e.1.6 c
@[simp] theorem symm_apply_apply (e : M ≃L[R] M₂) (b : M) : e.symm (e b) = b := e.1.5 b
@[simp] theorem coe_comp_coe_symm (e : M ≃L[R] M₂) :
(e : M →L[R] M₂).comp (e.symm : M₂ →L[R] M) = continuous_linear_map.id :=
continuous_linear_map.ext e.apply_symm_apply
@[simp] theorem coe_symm_comp_coe (e : M ≃L[R] M₂) :
(e.symm : M₂ →L[R] M).comp (e : M →L[R] M₂) = continuous_linear_map.id :=
continuous_linear_map.ext e.symm_apply_apply
lemma symm_comp_self (e : M ≃L[R] M₂) :
(e.symm : M₂ → M) ∘ (e : M → M₂) = id :=
by{ ext x, exact symm_apply_apply e x }
lemma self_comp_symm (e : M ≃L[R] M₂) :
(e : M → M₂) ∘ (e.symm : M₂ → M) = id :=
by{ ext x, exact apply_symm_apply e x }
@[simp] lemma symm_comp_self' (e : M ≃L[R] M₂) :
((e.symm : M₂ →L[R] M) : M₂ → M) ∘ ((e : M →L[R] M₂) : M → M₂) = id :=
symm_comp_self e
@[simp] lemma self_comp_symm' (e : M ≃L[R] M₂) :
((e : M →L[R] M₂) : M → M₂) ∘ ((e.symm : M₂ →L[R] M) : M₂ → M) = id :=
self_comp_symm e
@[simp] theorem symm_symm (e : M ≃L[R] M₂) : e.symm.symm = e :=
by { ext x, refl }
@[simp] theorem symm_symm_apply (e : M ≃L[R] M₂) (x : M) : e.symm.symm x = e x :=
rfl
end continuous_linear_equiv
|
8827d634df36f35ec39ac17bf22a04409f3643e8 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/analysis/normed_space/is_R_or_C.lean | 4143c1789b63c33db0677d7082a9e9bc12bdcbf9 | [
"Apache-2.0"
] | permissive | urkud/mathlib | eab80095e1b9f1513bfb7f25b4fa82fa4fd02989 | 6379d39e6b5b279df9715f8011369a301b634e41 | refs/heads/master | 1,658,425,342,662 | 1,658,078,703,000 | 1,658,078,703,000 | 186,910,338 | 0 | 0 | Apache-2.0 | 1,568,512,083,000 | 1,557,958,709,000 | Lean | UTF-8 | Lean | false | false | 4,105 | lean | /-
Copyright (c) 2021 Kalle Kytölä. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kalle Kytölä
-/
import data.complex.is_R_or_C
import analysis.normed_space.operator_norm
import analysis.normed_space.pointwise
/-!
# Normed spaces over R or C
This file is about results on normed spaces over the fields `ℝ` and `ℂ`.
## Main definitions
None.
## Main theorems
* `continuous_linear_map.op_norm_bound_of_ball_bound`: A bound on the norms of values of a linear
map in a ball yields a bound on the operator norm.
## Notes
This file exists mainly to avoid importing `is_R_or_C` in the main normed space theory files.
-/
open metric
@[simp, is_R_or_C_simps] lemma is_R_or_C.norm_coe_norm {𝕜 : Type*} [is_R_or_C 𝕜]
{E : Type*} [normed_group E] {z : E} : ∥(∥z∥ : 𝕜)∥ = ∥z∥ :=
by { unfold_coes, simp only [norm_algebra_map', ring_hom.to_fun_eq_coe, norm_norm], }
variables {𝕜 : Type*} [is_R_or_C 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E]
/-- Lemma to normalize a vector in a normed space `E` over either `ℂ` or `ℝ` to unit length. -/
@[simp] lemma norm_smul_inv_norm {x : E} (hx : x ≠ 0) : ∥(∥x∥⁻¹ : 𝕜) • x∥ = 1 :=
begin
have : ∥x∥ ≠ 0 := by simp [hx],
field_simp [norm_smul]
end
/-- Lemma to normalize a vector in a normed space `E` over either `ℂ` or `ℝ` to length `r`. -/
lemma norm_smul_inv_norm' {r : ℝ} (r_nonneg : 0 ≤ r) {x : E} (hx : x ≠ 0) :
∥(r * ∥x∥⁻¹ : 𝕜) • x∥ = r :=
begin
have : ∥x∥ ≠ 0 := by simp [hx],
field_simp [norm_smul, is_R_or_C.norm_eq_abs, r_nonneg] with is_R_or_C_simps
end
lemma linear_map.bound_of_sphere_bound
{r : ℝ} (r_pos : 0 < r) (c : ℝ) (f : E →ₗ[𝕜] 𝕜) (h : ∀ z ∈ sphere (0 : E) r, ∥f z∥ ≤ c) (z : E) :
∥f z∥ ≤ c / r * ∥z∥ :=
begin
by_cases z_zero : z = 0,
{ rw z_zero, simp only [linear_map.map_zero, norm_zero, mul_zero], },
set z₁ := (r * ∥z∥⁻¹ : 𝕜) • z with hz₁,
have norm_f_z₁ : ∥f z₁∥ ≤ c,
{ apply h,
rw mem_sphere_zero_iff_norm,
exact norm_smul_inv_norm' r_pos.le z_zero },
have r_ne_zero : (r : 𝕜) ≠ 0 := (algebra_map ℝ 𝕜).map_ne_zero.mpr r_pos.ne.symm,
have eq : f z = ∥z∥ / r * (f z₁),
{ rw [hz₁, linear_map.map_smul, smul_eq_mul],
rw [← mul_assoc, ← mul_assoc, div_mul_cancel _ r_ne_zero, mul_inv_cancel, one_mul],
simp only [z_zero, is_R_or_C.of_real_eq_zero, norm_eq_zero, ne.def, not_false_iff], },
rw [eq, norm_mul, norm_div, is_R_or_C.norm_coe_norm,
is_R_or_C.norm_of_nonneg r_pos.le, div_mul_eq_mul_div, div_mul_eq_mul_div, mul_comm],
apply div_le_div _ _ r_pos rfl.ge,
{ exact mul_nonneg ((norm_nonneg _).trans norm_f_z₁) (norm_nonneg z), },
apply mul_le_mul norm_f_z₁ rfl.le (norm_nonneg z) ((norm_nonneg _).trans norm_f_z₁),
end
/--
`linear_map.bound_of_ball_bound` is a version of this over arbitrary nondiscrete normed fields.
It produces a less precise bound so we keep both versions. -/
lemma linear_map.bound_of_ball_bound' {r : ℝ} (r_pos : 0 < r) (c : ℝ) (f : E →ₗ[𝕜] 𝕜)
(h : ∀ z ∈ closed_ball (0 : E) r, ∥f z∥ ≤ c) (z : E) :
∥f z∥ ≤ c / r * ∥z∥ :=
f.bound_of_sphere_bound r_pos c (λ z hz, h z hz.le) z
lemma continuous_linear_map.op_norm_bound_of_ball_bound
{r : ℝ} (r_pos : 0 < r) (c : ℝ) (f : E →L[𝕜] 𝕜) (h : ∀ z ∈ closed_ball (0 : E) r, ∥f z∥ ≤ c) :
∥f∥ ≤ c / r :=
begin
apply continuous_linear_map.op_norm_le_bound,
{ apply div_nonneg _ r_pos.le,
exact (norm_nonneg _).trans
(h 0 (by simp only [norm_zero, mem_closed_ball, dist_zero_left, r_pos.le])), },
apply linear_map.bound_of_ball_bound' r_pos,
exact λ z hz, h z hz,
end
variables (𝕜)
include 𝕜
lemma normed_space.sphere_nonempty_is_R_or_C [nontrivial E] {r : ℝ} (hr : 0 ≤ r) :
nonempty (sphere (0:E) r) :=
begin
letI : normed_space ℝ E := normed_space.restrict_scalars ℝ 𝕜 E,
exact set.nonempty_coe_sort.mpr (normed_space.sphere_nonempty.mpr hr),
end
|
fb02561c2b4ea4ddc5800a872ea7474579091ad1 | 9b9a16fa2cb737daee6b2785474678b6fa91d6d4 | /src/data/nat/basic.lean | 28690616aa64a7a4b9f0f33d25ecbcf14c04ce2e | [
"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 | 33,903 | 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, Leonardo de Moura, Jeremy Avigad, Mario Carneiro
Basic operations on the natural numbers.
-/
import logic.basic algebra.ordered_ring data.option.basic
universes u v
namespace nat
variables {m n k : ℕ}
attribute [simp] nat.add_sub_cancel nat.add_sub_cancel_left
attribute [simp] nat.sub_self
theorem succ_inj' {n m : ℕ} : succ n = succ m ↔ n = m :=
⟨succ_inj, congr_arg _⟩
theorem succ_le_succ_iff {m n : ℕ} : succ m ≤ succ n ↔ m ≤ n :=
⟨le_of_succ_le_succ, succ_le_succ⟩
theorem lt_succ_iff {m n : ℕ} : m < succ n ↔ m ≤ n :=
succ_le_succ_iff
lemma succ_le_iff {m n : ℕ} : succ m ≤ n ↔ m < n :=
⟨lt_of_succ_le, succ_le_of_lt⟩
theorem pred_eq_of_eq_succ {m n : ℕ} (H : m = n.succ) : m.pred = n := by simp [H]
theorem pred_sub (n m : ℕ) : pred n - m = pred (n - m) :=
by rw [← sub_one, nat.sub_sub, one_add]; refl
lemma pred_eq_sub_one (n : ℕ) : pred n = n - 1 := rfl
theorem pos_iff_ne_zero : n > 0 ↔ n ≠ 0 :=
⟨ne_of_gt, nat.pos_of_ne_zero⟩
theorem pos_iff_ne_zero' : 0 < n ↔ n ≠ 0 := pos_iff_ne_zero
lemma one_lt_iff_ne_zero_and_ne_one : ∀ {n : ℕ}, 1 < n ↔ n ≠ 0 ∧ n ≠ 1
| 0 := dec_trivial
| 1 := dec_trivial
| (n+2) := dec_trivial
theorem eq_of_lt_succ_of_not_lt {a b : ℕ} (h1 : a < b + 1) (h2 : ¬ a < b) : a = b :=
have h3 : a ≤ b, from le_of_lt_succ h1,
or.elim (eq_or_lt_of_not_lt h2) (λ h, h) (λ h, absurd h (not_lt_of_ge h3))
protected theorem le_sub_add (n m : ℕ) : n ≤ n - m + m :=
or.elim (le_total n m)
(assume : n ≤ m, begin rw [sub_eq_zero_of_le this, zero_add], exact this end)
(assume : m ≤ n, begin rw (nat.sub_add_cancel this) end)
theorem sub_add_eq_max (n m : ℕ) : n - m + m = max n m :=
eq_max (nat.le_sub_add _ _) (le_add_left _ _) $ λ k h₁ h₂,
by rw ← nat.sub_add_cancel h₂; exact
add_le_add_right (nat.sub_le_sub_right h₁ _) _
theorem sub_add_min (n m : ℕ) : n - m + min n m = n :=
(le_total n m).elim
(λ h, by rw [min_eq_left h, sub_eq_zero_of_le h, zero_add])
(λ h, by rw [min_eq_right h, nat.sub_add_cancel h])
protected theorem add_sub_cancel' {n m : ℕ} (h : n ≥ m) : m + (n - m) = n :=
by rw [add_comm, nat.sub_add_cancel h]
protected theorem sub_eq_of_eq_add (h : k = m + n) : k - m = n :=
begin rw [h, nat.add_sub_cancel_left] end
theorem sub_min (n m : ℕ) : n - min n m = n - m :=
nat.sub_eq_of_eq_add $ by rw [add_comm, sub_add_min]
protected theorem lt_of_sub_pos (h : n - m > 0) : m < n :=
lt_of_not_ge
(assume : m ≥ n,
have n - m = 0, from sub_eq_zero_of_le this,
begin rw this at h, exact lt_irrefl _ h end)
protected theorem lt_of_sub_lt_sub_right : m - k < n - k → m < n :=
lt_imp_lt_of_le_imp_le (λ h, nat.sub_le_sub_right h _)
protected theorem lt_of_sub_lt_sub_left : m - n < m - k → k < n :=
lt_imp_lt_of_le_imp_le (nat.sub_le_sub_left _)
protected theorem sub_lt_self (h₁ : m > 0) (h₂ : n > 0) : m - n < m :=
calc
m - n = succ (pred m) - succ (pred n) : by rw [succ_pred_eq_of_pos h₁, succ_pred_eq_of_pos h₂]
... = pred m - pred n : by rw succ_sub_succ
... ≤ pred m : sub_le _ _
... < succ (pred m) : lt_succ_self _
... = m : succ_pred_eq_of_pos h₁
protected theorem le_sub_right_of_add_le (h : m + k ≤ n) : m ≤ n - k :=
by rw ← nat.add_sub_cancel m k; exact nat.sub_le_sub_right h k
protected theorem le_sub_left_of_add_le (h : k + m ≤ n) : m ≤ n - k :=
nat.le_sub_right_of_add_le (by rwa add_comm at h)
protected theorem lt_sub_right_of_add_lt (h : m + k < n) : m < n - k :=
lt_of_succ_le $ nat.le_sub_right_of_add_le $
by rw succ_add; exact succ_le_of_lt h
protected theorem lt_sub_left_of_add_lt (h : k + m < n) : m < n - k :=
nat.lt_sub_right_of_add_lt (by rwa add_comm at h)
protected theorem add_lt_of_lt_sub_right (h : m < n - k) : m + k < n :=
@nat.lt_of_sub_lt_sub_right _ _ k (by rwa nat.add_sub_cancel)
protected theorem add_lt_of_lt_sub_left (h : m < n - k) : k + m < n :=
by rw add_comm; exact nat.add_lt_of_lt_sub_right h
protected theorem le_add_of_sub_le_right : n - k ≤ m → n ≤ m + k :=
le_imp_le_of_lt_imp_lt nat.lt_sub_right_of_add_lt
protected theorem le_add_of_sub_le_left : n - k ≤ m → n ≤ k + m :=
le_imp_le_of_lt_imp_lt nat.lt_sub_left_of_add_lt
protected theorem lt_add_of_sub_lt_right : n - k < m → n < m + k :=
lt_imp_lt_of_le_imp_le nat.le_sub_right_of_add_le
protected theorem lt_add_of_sub_lt_left : n - k < m → n < k + m :=
lt_imp_lt_of_le_imp_le nat.le_sub_left_of_add_le
protected theorem sub_le_left_of_le_add : n ≤ k + m → n - k ≤ m :=
le_imp_le_of_lt_imp_lt nat.add_lt_of_lt_sub_left
protected theorem sub_le_right_of_le_add : n ≤ m + k → n - k ≤ m :=
le_imp_le_of_lt_imp_lt nat.add_lt_of_lt_sub_right
protected theorem sub_lt_left_iff_lt_add (H : n ≤ k) : k - n < m ↔ k < n + m :=
⟨nat.lt_add_of_sub_lt_left,
λ h₁,
have succ k ≤ n + m, from succ_le_of_lt h₁,
have succ (k - n) ≤ m, from
calc succ (k - n) = succ k - n : by rw (succ_sub H)
... ≤ n + m - n : nat.sub_le_sub_right this n
... = m : by rw nat.add_sub_cancel_left,
lt_of_succ_le this⟩
protected theorem le_sub_left_iff_add_le (H : m ≤ k) : n ≤ k - m ↔ m + n ≤ k :=
le_iff_le_iff_lt_iff_lt.2 (nat.sub_lt_left_iff_lt_add H)
protected theorem le_sub_right_iff_add_le (H : n ≤ k) : m ≤ k - n ↔ m + n ≤ k :=
by rw [nat.le_sub_left_iff_add_le H, add_comm]
protected theorem lt_sub_left_iff_add_lt : n < k - m ↔ m + n < k :=
⟨nat.add_lt_of_lt_sub_left, nat.lt_sub_left_of_add_lt⟩
protected theorem lt_sub_right_iff_add_lt : m < k - n ↔ m + n < k :=
by rw [nat.lt_sub_left_iff_add_lt, add_comm]
theorem sub_le_left_iff_le_add : m - n ≤ k ↔ m ≤ n + k :=
le_iff_le_iff_lt_iff_lt.2 nat.lt_sub_left_iff_add_lt
theorem sub_le_right_iff_le_add : m - k ≤ n ↔ m ≤ n + k :=
by rw [nat.sub_le_left_iff_le_add, add_comm]
protected theorem sub_lt_right_iff_lt_add (H : k ≤ m) : m - k < n ↔ m < n + k :=
by rw [nat.sub_lt_left_iff_lt_add H, add_comm]
protected theorem sub_le_sub_left_iff (H : k ≤ m) : m - n ≤ m - k ↔ k ≤ n :=
⟨λ h,
have k + (m - k) - n ≤ m - k, by rwa nat.add_sub_cancel' H,
nat.le_of_add_le_add_right (nat.le_add_of_sub_le_left this),
nat.sub_le_sub_left _⟩
protected theorem sub_lt_sub_right_iff (H : k ≤ m) : m - k < n - k ↔ m < n :=
lt_iff_lt_of_le_iff_le (nat.sub_le_sub_right_iff _ _ _ H)
protected theorem sub_lt_sub_left_iff (H : n ≤ m) : m - n < m - k ↔ k < n :=
lt_iff_lt_of_le_iff_le (nat.sub_le_sub_left_iff H)
protected theorem sub_le_iff : m - n ≤ k ↔ m - k ≤ n :=
nat.sub_le_left_iff_le_add.trans nat.sub_le_right_iff_le_add.symm
protected lemma sub_le_self (n m : ℕ) : n - m ≤ n :=
nat.sub_le_left_of_le_add (nat.le_add_left _ _)
protected theorem sub_lt_iff (h₁ : n ≤ m) (h₂ : k ≤ m) : m - n < k ↔ m - k < n :=
(nat.sub_lt_left_iff_lt_add h₁).trans (nat.sub_lt_right_iff_lt_add h₂).symm
lemma pred_le_iff {n m : ℕ} : pred n ≤ m ↔ n ≤ succ m :=
@nat.sub_le_right_iff_le_add n m 1
lemma lt_pred_iff {n m : ℕ} : n < pred m ↔ succ n < m :=
@nat.lt_sub_right_iff_add_lt n 1 m
protected theorem mul_ne_zero {n m : ℕ} (n0 : n ≠ 0) (m0 : m ≠ 0) : n * m ≠ 0
| nm := (eq_zero_of_mul_eq_zero nm).elim n0 m0
@[simp] protected theorem mul_eq_zero {a b : ℕ} : a * b = 0 ↔ a = 0 ∨ b = 0 :=
iff.intro eq_zero_of_mul_eq_zero (by simp [or_imp_distrib] {contextual := tt})
@[simp] protected theorem zero_eq_mul {a b : ℕ} : 0 = a * b ↔ a = 0 ∨ b = 0 :=
by rw [eq_comm, nat.mul_eq_zero]
@[elab_as_eliminator]
protected def strong_rec' {p : ℕ → Sort u} (H : ∀ n, (∀ m, m < n → p m) → p n) : ∀ (n : ℕ), p n
| n := H n (λ m hm, strong_rec' m)
attribute [simp] nat.div_self
protected lemma div_le_of_le_mul' {m n : ℕ} {k} (h : m ≤ k * n) : m / k ≤ n :=
(eq_zero_or_pos k).elim
(λ k0, by rw [k0, nat.div_zero]; apply zero_le)
(λ k0, (decidable.mul_le_mul_left k0).1 $
calc k * (m / k)
≤ m % k + k * (m / k) : le_add_left _ _
... = m : mod_add_div _ _
... ≤ k * n : h)
protected lemma div_le_self' (m n : ℕ) : m / n ≤ m :=
(eq_zero_or_pos n).elim
(λ n0, by rw [n0, nat.div_zero]; apply zero_le)
(λ n0, nat.div_le_of_le_mul' $ calc
m = 1 * m : (one_mul _).symm
... ≤ n * m : mul_le_mul_right _ n0)
theorem le_div_iff_mul_le' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x ≤ y / k ↔ x * k ≤ y :=
begin
revert x, refine nat.strong_rec' _ y,
clear y, intros y IH x,
cases decidable.lt_or_le y k with h h,
{ rw [div_eq_of_lt h],
cases x with x,
{ simp [zero_mul, zero_le] },
{ rw succ_mul,
exact iff_of_false (not_succ_le_zero _)
(not_le_of_lt $ lt_of_lt_of_le h (le_add_left _ _)) } },
{ rw [div_eq_sub_div k0 h],
cases x with x,
{ simp [zero_mul, zero_le] },
{ rw [← add_one, nat.add_le_add_iff_le_right, succ_mul,
IH _ (sub_lt_of_pos_le _ _ k0 h), add_le_to_le_sub _ h] } }
end
theorem div_mul_le_self' (m n : ℕ) : m / n * n ≤ m :=
(nat.eq_zero_or_pos n).elim (λ n0, by simp [n0, zero_le]) $ λ n0,
(le_div_iff_mul_le' n0).1 (le_refl _)
theorem div_lt_iff_lt_mul' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x / k < y ↔ x < y * k :=
lt_iff_lt_of_le_iff_le $ le_div_iff_mul_le' k0
protected theorem div_le_div_right {n m : ℕ} (h : n ≤ m) {k : ℕ} : n / k ≤ m / k :=
(nat.eq_zero_or_pos k).elim (λ k0, by simp [k0]) $ λ hk,
(le_div_iff_mul_le' hk).2 $ le_trans (nat.div_mul_le_self' _ _) h
protected theorem eq_mul_of_div_eq_right {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) :
a = b * c :=
by rw [← H2, nat.mul_div_cancel' H1]
protected theorem div_eq_iff_eq_mul_right {a b c : ℕ} (H : b > 0) (H' : b ∣ a) :
a / b = c ↔ a = b * c :=
⟨nat.eq_mul_of_div_eq_right H', nat.div_eq_of_eq_mul_right H⟩
protected theorem div_eq_iff_eq_mul_left {a b c : ℕ} (H : b > 0) (H' : b ∣ a) :
a / b = c ↔ a = c * b :=
by rw mul_comm; exact nat.div_eq_iff_eq_mul_right H H'
protected theorem eq_mul_of_div_eq_left {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) :
a = c * b :=
by rw [mul_comm, nat.eq_mul_of_div_eq_right H1 H2]
protected theorem mul_div_cancel_left' {a b : ℕ} (Hd : a ∣ b) : a * (b / a) = b :=
by rw [mul_comm,nat.div_mul_cancel Hd]
protected theorem div_mod_unique {n k m d : ℕ} (h : 0 < k) :
n / k = d ∧ n % k = m ↔ m + k * d = n ∧ m < k :=
⟨λ ⟨e₁, e₂⟩, e₁ ▸ e₂ ▸ ⟨mod_add_div _ _, mod_lt _ h⟩,
λ ⟨h₁, h₂⟩, h₁ ▸ by rw [add_mul_div_left _ _ h, add_mul_mod_self_left];
simp [div_eq_of_lt, mod_eq_of_lt, h₂]⟩
lemma two_mul_odd_div_two {n : ℕ} (hn : n % 2 = 1) : 2 * (n / 2) = n - 1 :=
by conv {to_rhs, rw [← nat.mod_add_div n 2, hn, nat.add_sub_cancel_left]}
lemma div_dvd_of_dvd {a b : ℕ} (h : b ∣ a) : (a / b) ∣ a :=
⟨b, (nat.div_mul_cancel h).symm⟩
protected lemma div_pos {a b : ℕ} (hba : b ≤ a) (hb : 0 < b) : 0 < a / b :=
nat.pos_of_ne_zero (λ h, lt_irrefl a
(calc a = a % b : by simpa [h] using (mod_add_div a b).symm
... < b : nat.mod_lt a hb
... ≤ a : hba))
protected theorem mul_right_inj {a b c : ℕ} (ha : a > 0) : b * a = c * a ↔ b = c :=
⟨nat.eq_of_mul_eq_mul_right ha, λ e, e ▸ rfl⟩
protected theorem mul_left_inj {a b c : ℕ} (ha : a > 0) : a * b = a * c ↔ b = c :=
⟨nat.eq_of_mul_eq_mul_left ha, λ e, e ▸ rfl⟩
protected lemma div_div_self : ∀ {a b : ℕ}, b ∣ a → 0 < a → a / (a / b) = b
| a 0 h₁ h₂ := by rw eq_zero_of_zero_dvd h₁; refl
| 0 b h₁ h₂ := absurd h₂ dec_trivial
| (a+1) (b+1) h₁ h₂ :=
(nat.mul_right_inj (nat.div_pos (le_of_dvd (succ_pos a) h₁) (succ_pos b))).1 $
by rw [nat.div_mul_cancel (div_dvd_of_dvd h₁), nat.mul_div_cancel' h₁]
protected lemma div_lt_of_lt_mul {m n k : ℕ} (h : m < n * k) : m / n < k :=
lt_of_mul_lt_mul_left
(calc n * (m / n) ≤ m % n + n * (m / n) : nat.le_add_left _ _
... = m : mod_add_div _ _
... < n * k : h)
(nat.zero_le n)
protected lemma div_eq_zero_iff {a b : ℕ} (hb : 0 < b) : a / b = 0 ↔ a < b :=
⟨λ h, by rw [← mod_add_div a b, h, mul_zero, add_zero]; exact mod_lt _ hb,
λ h, by rw [← nat.mul_left_inj hb, ← @add_left_cancel_iff _ _ (a % b), mod_add_div,
mod_eq_of_lt h, mul_zero, add_zero]⟩
lemma mod_mul_right_div_self (a b c : ℕ) : a % (b * c) / b = (a / b) % c :=
if hb : b = 0 then by simp [hb] else if hc : c = 0 then by simp [hc]
else by conv {to_rhs, rw ← mod_add_div a (b * c)};
rw [mul_assoc, nat.add_mul_div_left _ _ (nat.pos_of_ne_zero hb), add_mul_mod_self_left,
mod_eq_of_lt (nat.div_lt_of_lt_mul (mod_lt _ (mul_pos (nat.pos_of_ne_zero hb) (nat.pos_of_ne_zero hc))))]
lemma mod_mul_left_div_self (a b c : ℕ) : a % (c * b) / b = (a / b) % c :=
by rw [mul_comm c, mod_mul_right_div_self]
@[simp] protected theorem dvd_one {n : ℕ} : n ∣ 1 ↔ n = 1 :=
⟨eq_one_of_dvd_one, λ e, e.symm ▸ dvd_refl _⟩
protected theorem dvd_add_left {k m n : ℕ} (h : k ∣ n) : k ∣ m + n ↔ k ∣ m :=
(nat.dvd_add_iff_left h).symm
protected theorem dvd_add_right {k m n : ℕ} (h : k ∣ m) : k ∣ m + n ↔ k ∣ n :=
(nat.dvd_add_iff_right h).symm
protected theorem mul_dvd_mul_iff_left {a b c : ℕ} (ha : a > 0) : a * b ∣ a * c ↔ b ∣ c :=
exists_congr $ λ d, by rw [mul_assoc, nat.mul_left_inj ha]
protected theorem mul_dvd_mul_iff_right {a b c : ℕ} (hc : c > 0) : a * c ∣ b * c ↔ a ∣ b :=
exists_congr $ λ d, by rw [mul_right_comm, nat.mul_right_inj hc]
@[simp] theorem mod_mod (a n : ℕ) : (a % n) % n = a % n :=
(eq_zero_or_pos n).elim
(λ n0, by simp [n0])
(λ npos, mod_eq_of_lt (mod_lt _ npos))
theorem add_pos_left {m : ℕ} (h : m > 0) (n : ℕ) : m + n > 0 :=
calc
m + n > 0 + n : nat.add_lt_add_right h n
... = n : nat.zero_add n
... ≥ 0 : zero_le n
theorem add_pos_right (m : ℕ) {n : ℕ} (h : n > 0) : m + n > 0 :=
begin rw add_comm, exact add_pos_left h m end
theorem add_pos_iff_pos_or_pos (m n : ℕ) : m + n > 0 ↔ m > 0 ∨ n > 0 :=
iff.intro
begin
intro h,
cases m with m,
{simp [zero_add] at h, exact or.inr h},
exact or.inl (succ_pos _)
end
begin
intro h, cases h with mpos npos,
{ apply add_pos_left mpos },
apply add_pos_right _ npos
end
lemma lt_succ_iff_lt_or_eq {n i : ℕ} : n < i.succ ↔ (n < i ∨ n = i) :=
lt_succ_iff.trans le_iff_lt_or_eq
theorem le_zero_iff {i : ℕ} : i ≤ 0 ↔ i = 0 :=
⟨nat.eq_zero_of_le_zero, assume h, h ▸ le_refl i⟩
theorem le_add_one_iff {i j : ℕ} : i ≤ j + 1 ↔ (i ≤ j ∨ i = j + 1) :=
⟨assume h,
match nat.eq_or_lt_of_le h with
| or.inl h := or.inr h
| or.inr h := or.inl $ nat.le_of_succ_le_succ h
end,
or.rec (assume h, le_trans h $ nat.le_add_right _ _) le_of_eq⟩
theorem mul_self_inj {n m : ℕ} : n * n = m * m ↔ n = m :=
le_antisymm_iff.trans (le_antisymm_iff.trans
(and_congr mul_self_le_mul_self_iff mul_self_le_mul_self_iff)).symm
instance decidable_ball_lt (n : nat) (P : Π k < n, Prop) :
∀ [H : ∀ n h, decidable (P n h)], decidable (∀ n h, P n h) :=
begin
induction n with n IH; intro; resetI,
{ exact is_true (λ n, dec_trivial) },
cases IH (λ k h, P k (lt_succ_of_lt h)) with h,
{ refine is_false (mt _ h), intros hn k h, apply hn },
by_cases p : P n (lt_succ_self n),
{ exact is_true (λ k h',
(lt_or_eq_of_le $ le_of_lt_succ h').elim (h _)
(λ e, match k, e, h' with _, rfl, h := p end)) },
{ exact is_false (mt (λ hn, hn _ _) p) }
end
instance decidable_forall_fin {n : ℕ} (P : fin n → Prop)
[H : decidable_pred P] : decidable (∀ i, P i) :=
decidable_of_iff (∀ k h, P ⟨k, h⟩) ⟨λ a ⟨k, h⟩, a k h, λ a k h, a ⟨k, h⟩⟩
instance decidable_ball_le (n : ℕ) (P : Π k ≤ n, Prop)
[H : ∀ n h, decidable (P n h)] : decidable (∀ n h, P n h) :=
decidable_of_iff (∀ k (h : k < succ n), P k (le_of_lt_succ h))
⟨λ a k h, a k (lt_succ_of_le h), λ a k h, a k _⟩
instance decidable_lo_hi (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x < hi → P x) :=
decidable_of_iff (∀ x < hi - lo, P (lo + x))
⟨λal x hl hh, by have := al (x - lo) (lt_of_not_ge $
(not_congr (nat.sub_le_sub_right_iff _ _ _ hl)).2 $ not_le_of_gt hh);
rwa [nat.add_sub_of_le hl] at this,
λal x h, al _ (nat.le_add_right _ _) (nat.add_lt_of_lt_sub_left h)⟩
instance decidable_lo_hi_le (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x ≤ hi → P x) :=
decidable_of_iff (∀x, lo ≤ x → x < hi + 1 → P x) $
ball_congr $ λ x hl, imp_congr lt_succ_iff iff.rfl
protected theorem bit0_le {n m : ℕ} (h : n ≤ m) : bit0 n ≤ bit0 m :=
add_le_add h h
protected theorem bit1_le {n m : ℕ} (h : n ≤ m) : bit1 n ≤ bit1 m :=
succ_le_succ (add_le_add h h)
theorem bit_le : ∀ (b : bool) {n m : ℕ}, n ≤ m → bit b n ≤ bit b m
| tt n m h := nat.bit1_le h
| ff n m h := nat.bit0_le h
theorem bit_ne_zero (b) {n} (h : n ≠ 0) : bit b n ≠ 0 :=
by cases b; [exact nat.bit0_ne_zero h, exact nat.bit1_ne_zero _]
theorem bit0_le_bit : ∀ (b) {m n : ℕ}, m ≤ n → bit0 m ≤ bit b n
| tt m n h := le_of_lt $ nat.bit0_lt_bit1 h
| ff m n h := nat.bit0_le h
theorem bit_le_bit1 : ∀ (b) {m n : ℕ}, m ≤ n → bit b m ≤ bit1 n
| ff m n h := le_of_lt $ nat.bit0_lt_bit1 h
| tt m n h := nat.bit1_le h
theorem bit_lt_bit0 : ∀ (b) {n m : ℕ}, n < m → bit b n < bit0 m
| tt n m h := nat.bit1_lt_bit0 h
| ff n m h := nat.bit0_lt h
theorem bit_lt_bit (a b) {n m : ℕ} (h : n < m) : bit a n < bit b m :=
lt_of_lt_of_le (bit_lt_bit0 _ h) (bit0_le_bit _ (le_refl _))
/- partial subtraction -/
/-- Partial predecessor operation. Returns `ppred n = some m`
if `n = m + 1`, otherwise `none`. -/
@[simp] def ppred : ℕ → option ℕ
| 0 := none
| (n+1) := some n
/-- Partial subtraction operation. Returns `psub m n = some k`
if `m = n + k`, otherwise `none`. -/
@[simp] def psub (m : ℕ) : ℕ → option ℕ
| 0 := some m
| (n+1) := psub n >>= ppred
theorem pred_eq_ppred (n : ℕ) : pred n = (ppred n).get_or_else 0 :=
by cases n; refl
theorem sub_eq_psub (m : ℕ) : ∀ n, m - n = (psub m n).get_or_else 0
| 0 := rfl
| (n+1) := (pred_eq_ppred (m-n)).trans $
by rw [sub_eq_psub, psub]; cases psub m n; refl
@[simp] theorem ppred_eq_some {m : ℕ} : ∀ {n}, ppred n = some m ↔ succ m = n
| 0 := by split; intro h; contradiction
| (n+1) := by dsimp; split; intro h; injection h; subst n
@[simp] theorem ppred_eq_none : ∀ {n : ℕ}, ppred n = none ↔ n = 0
| 0 := by simp
| (n+1) := by dsimp; split; contradiction
theorem psub_eq_some {m : ℕ} : ∀ {n k}, psub m n = some k ↔ k + n = m
| 0 k := by simp [eq_comm]
| (n+1) k := by dsimp; apply option.bind_eq_some.trans; simp [psub_eq_some]
theorem psub_eq_none (m n : ℕ) : psub m n = none ↔ m < n :=
begin
cases s : psub m n; simp [eq_comm],
{ show m < n, refine lt_of_not_ge (λ h, _),
cases le.dest h with k e,
injection s.symm.trans (psub_eq_some.2 $ (add_comm _ _).trans e) },
{ show n ≤ m, rw ← psub_eq_some.1 s, apply le_add_left }
end
theorem ppred_eq_pred {n} (h : 0 < n) : ppred n = some (pred n) :=
ppred_eq_some.2 $ succ_pred_eq_of_pos h
theorem psub_eq_sub {m n} (h : n ≤ m) : psub m n = some (m - n) :=
psub_eq_some.2 $ nat.sub_add_cancel h
theorem psub_add (m n k) : psub m (n + k) = do x ← psub m n, psub x k :=
by induction k; simp [*, add_succ, bind_assoc]
/- pow -/
attribute [simp] nat.pow_zero nat.pow_one
@[simp] lemma one_pow : ∀ n : ℕ, 1 ^ n = 1
| 0 := rfl
| (k+1) := show 1^k * 1 = 1, by rw [mul_one, one_pow]
theorem pow_add (a m n : ℕ) : a^(m + n) = a^m * a^n :=
by induction n; simp [*, pow_succ, mul_assoc]
theorem pow_two (a : ℕ) : a ^ 2 = a * a := show (1 * a) * a = _, by rw one_mul
theorem pow_dvd_pow (a : ℕ) {m n : ℕ} (h : m ≤ n) : a^m ∣ a^n :=
by rw [← nat.add_sub_cancel' h, pow_add]; apply dvd_mul_right
theorem pow_dvd_pow_of_dvd {a b : ℕ} (h : a ∣ b) : ∀ n:ℕ, a^n ∣ b^n
| 0 := dvd_refl _
| (n+1) := mul_dvd_mul (pow_dvd_pow_of_dvd n) h
theorem mul_pow (a b n : ℕ) : (a * b) ^ n = a ^ n * b ^ n :=
by induction n; simp [*, nat.pow_succ, mul_comm, mul_assoc, mul_left_comm]
protected theorem pow_mul (a b n : ℕ) : n ^ (a * b) = (n ^ a) ^ b :=
by induction b; simp [*, nat.succ_eq_add_one, nat.pow_add, mul_add, mul_comm]
theorem pow_pos {p : ℕ} (hp : p > 0) : ∀ n : ℕ, p ^ n > 0
| 0 := by simpa using zero_lt_one
| (k+1) := mul_pos (pow_pos _) hp
lemma pow_eq_mul_pow_sub (p : ℕ) {m n : ℕ} (h : m ≤ n) : p ^ m * p ^ (n - m) = p ^ n :=
by rw [←nat.pow_add, nat.add_sub_cancel' h]
lemma pow_lt_pow_succ {p : ℕ} (h : p > 1) (n : ℕ) : p^n < p^(n+1) :=
suffices p^n*1 < p^n*p, by simpa,
nat.mul_lt_mul_of_pos_left h (nat.pow_pos (lt_of_succ_lt h) n)
lemma lt_pow_self {p : ℕ} (h : p > 1) : ∀ n : ℕ, n < p ^ n
| 0 := by simp [zero_lt_one]
| (n+1) := calc
n + 1 < p^n + 1 : nat.add_lt_add_right (lt_pow_self _) _
... ≤ p ^ (n+1) : pow_lt_pow_succ h _
lemma not_pos_pow_dvd : ∀ {p k : ℕ} (hp : p > 1) (hk : k > 1), ¬ p^k ∣ p
| (succ p) (succ k) hp hk h :=
have (succ p)^k * succ p ∣ 1 * succ p, by simpa,
have (succ p) ^ k ∣ 1, from dvd_of_mul_dvd_mul_right (succ_pos _) this,
have he : (succ p) ^ k = 1, from eq_one_of_dvd_one this,
have k < (succ p) ^ k, from lt_pow_self hp k,
have k < 1, by rwa [he] at this,
have k = 0, from eq_zero_of_le_zero $ le_of_lt_succ this,
have 1 > 1, by rwa [this] at hk,
absurd this dec_trivial
@[simp] theorem bodd_div2_eq (n : ℕ) : bodd_div2 n = (bodd n, div2 n) :=
by unfold bodd div2; cases bodd_div2 n; refl
@[simp] lemma bodd_bit0 (n) : bodd (bit0 n) = ff := bodd_bit ff n
@[simp] lemma bodd_bit1 (n) : bodd (bit1 n) = tt := bodd_bit tt n
@[simp] lemma div2_bit0 (n) : div2 (bit0 n) = n := div2_bit ff n
@[simp] lemma div2_bit1 (n) : div2 (bit1 n) = n := div2_bit tt n
/- iterate -/
section
variables {α : Sort*} (op : α → α)
@[simp] theorem iterate_zero (a : α) : op^[0] a = a := rfl
@[simp] theorem iterate_succ (n : ℕ) (a : α) : op^[succ n] a = (op^[n]) (op a) := rfl
theorem iterate_add : ∀ (m n : ℕ) (a : α), op^[m + n] a = (op^[m]) (op^[n] a)
| m 0 a := rfl
| m (succ n) a := iterate_add m n _
theorem iterate_succ' (n : ℕ) (a : α) : op^[succ n] a = op (op^[n] a) :=
by rw [← one_add, iterate_add]; refl
theorem iterate₀ {α : Type u} {op : α → α} {x : α} (H : op x = x) {n : ℕ} :
op^[n] x = x :=
by induction n; [simp only [iterate_zero], simp only [iterate_succ', H, *]]
theorem iterate₁ {α : Type u} {β : Type v} {op : α → α} {op' : β → β} {op'' : α → β}
(H : ∀ x, op' (op'' x) = op'' (op x)) {n : ℕ} {x : α} :
op'^[n] (op'' x) = op'' (op^[n] x) :=
by induction n; [simp only [iterate_zero], simp only [iterate_succ', H, *]]
theorem iterate₂ {α : Type u} {op : α → α} {op' : α → α → α} (H : ∀ x y, op (op' x y) = op' (op x) (op y)) {n : ℕ} {x y : α} :
op^[n] (op' x y) = op' (op^[n] x) (op^[n] y) :=
by induction n; [simp only [iterate_zero], simp only [iterate_succ', H, *]]
theorem iterate_cancel {α : Type u} {op op' : α → α} (H : ∀ x, op (op' x) = x) {n : ℕ} {x : α} : op^[n] (op'^[n] x) = x :=
by induction n; [refl, rwa [iterate_succ, iterate_succ', H]]
theorem iterate_inj {α : Type u} {op : α → α} (Hinj : function.injective op) (n : ℕ) (x y : α)
(H : (op^[n] x) = (op^[n] y)) : x = y :=
by induction n with n ih; simp only [iterate_zero, iterate_succ'] at H;
[exact H, exact ih (Hinj H)]
end
/- size and shift -/
theorem shiftl'_ne_zero_left (b) {m} (h : m ≠ 0) (n) : shiftl' b m n ≠ 0 :=
by induction n; simp [shiftl', bit_ne_zero, *]
theorem shiftl'_tt_ne_zero (m) : ∀ {n} (h : n ≠ 0), shiftl' tt m n ≠ 0
| 0 h := absurd rfl h
| (succ n) _ := nat.bit1_ne_zero _
@[simp] theorem size_zero : size 0 = 0 := rfl
@[simp] theorem size_bit {b n} (h : bit b n ≠ 0) : size (bit b n) = succ (size n) :=
begin
rw size,
conv { to_lhs, rw [binary_rec], simp [h] },
rw div2_bit, refl
end
@[simp] theorem size_bit0 {n} (h : n ≠ 0) : size (bit0 n) = succ (size n) :=
@size_bit ff n (nat.bit0_ne_zero h)
@[simp] theorem size_bit1 (n) : size (bit1 n) = succ (size n) :=
@size_bit tt n (nat.bit1_ne_zero n)
@[simp] theorem size_one : size 1 = 1 := by apply size_bit1 0
@[simp] theorem size_shiftl' {b m n} (h : shiftl' b m n ≠ 0) :
size (shiftl' b m n) = size m + n :=
begin
induction n with n IH; simp [shiftl'] at h ⊢,
rw [size_bit h, nat.add_succ],
by_cases s0 : shiftl' b m n = 0; [skip, rw [IH s0]],
rw s0 at h ⊢,
cases b, {exact absurd rfl h},
have : shiftl' tt m n + 1 = 1 := congr_arg (+1) s0,
rw [shiftl'_tt_eq_mul_pow] at this,
have m0 := succ_inj (eq_one_of_dvd_one ⟨_, this.symm⟩),
subst m0,
simp at this,
have : n = 0 := eq_zero_of_le_zero (le_of_not_gt $ λ hn,
ne_of_gt (pow_lt_pow_of_lt_right dec_trivial hn) this),
subst n, refl
end
@[simp] theorem size_shiftl {m} (h : m ≠ 0) (n) :
size (shiftl m n) = size m + n :=
size_shiftl' (shiftl'_ne_zero_left _ h _)
theorem lt_size_self (n : ℕ) : n < 2^size n :=
begin
rw [← one_shiftl],
have : ∀ {n}, n = 0 → n < shiftl 1 (size n) :=
λ n e, by subst e; exact dec_trivial,
apply binary_rec _ _ n, {apply this rfl},
intros b n IH,
by_cases bit b n = 0, {apply this h},
rw [size_bit h, shiftl_succ],
exact bit_lt_bit0 _ IH
end
theorem size_le {m n : ℕ} : size m ≤ n ↔ m < 2^n :=
⟨λ h, lt_of_lt_of_le (lt_size_self _) (pow_le_pow_of_le_right dec_trivial h),
begin
rw [← one_shiftl], revert n,
apply binary_rec _ _ m,
{ intros n h, apply zero_le },
{ intros b m IH n h,
by_cases e : bit b m = 0, { rw e, apply zero_le },
rw [size_bit e],
cases n with n,
{ exact e.elim (eq_zero_of_le_zero (le_of_lt_succ h)) },
{ apply succ_le_succ (IH _),
apply lt_imp_lt_of_le_imp_le (λ h', bit0_le_bit _ h') h } }
end⟩
theorem lt_size {m n : ℕ} : m < size n ↔ 2^m ≤ n :=
by rw [← not_lt, iff_not_comm, not_lt, size_le]
theorem size_pos {n : ℕ} : 0 < size n ↔ 0 < n :=
by rw lt_size; refl
theorem size_eq_zero {n : ℕ} : size n = 0 ↔ n = 0 :=
by have := @size_pos n; simp [pos_iff_ne_zero'] at this;
exact not_iff_not.1 this
theorem size_pow {n : ℕ} : size (2^n) = n+1 :=
le_antisymm
(size_le.2 $ pow_lt_pow_of_lt_right dec_trivial (lt_succ_self _))
(lt_size.2 $ le_refl _)
theorem size_le_size {m n : ℕ} (h : m ≤ n) : size m ≤ size n :=
size_le.2 $ lt_of_le_of_lt h (lt_size_self _)
/- factorial -/
/-- `fact n` is the factorial of `n`. -/
@[simp] def fact : nat → nat
| 0 := 1
| (succ n) := succ n * fact n
@[simp] theorem fact_zero : fact 0 = 1 := rfl
@[simp] theorem fact_one : fact 1 = 1 := rfl
@[simp] theorem fact_succ (n) : fact (succ n) = succ n * fact n := rfl
theorem fact_pos : ∀ n, fact n > 0
| 0 := zero_lt_one
| (succ n) := mul_pos (succ_pos _) (fact_pos n)
theorem fact_ne_zero (n : ℕ) : fact n ≠ 0 := ne_of_gt (fact_pos _)
theorem fact_dvd_fact {m n} (h : m ≤ n) : fact m ∣ fact n :=
begin
induction n with n IH; simp,
{ have := eq_zero_of_le_zero h, subst m, simp },
{ cases eq_or_lt_of_le h with he hl,
{ subst m, simp },
{ apply dvd_mul_of_dvd_right (IH (le_of_lt_succ hl)) } }
end
theorem dvd_fact : ∀ {m n}, m > 0 → m ≤ n → m ∣ fact n
| (succ m) n _ h := dvd_of_mul_right_dvd (fact_dvd_fact h)
theorem fact_le {m n} (h : m ≤ n) : fact m ≤ fact n :=
le_of_dvd (fact_pos _) (fact_dvd_fact h)
lemma fact_mul_pow_le_fact : ∀ {m n : ℕ}, m.fact * m.succ ^ n ≤ (m + n).fact
| m 0 := by simp
| m (n+1) :=
by rw [← add_assoc, nat.fact_succ, mul_comm (nat.succ _), nat.pow_succ, ← mul_assoc];
exact mul_le_mul fact_mul_pow_le_fact
(nat.succ_le_succ (nat.le_add_right _ _)) (nat.zero_le _) (nat.zero_le _)
section find_greatest
/-- `find_greatest P b` is the largest `i ≤ bound` such that `P i` holds, or `0` if no such `i`
exists -/
protected def find_greatest (P : ℕ → Prop) [decidable_pred P] : ℕ → ℕ
| 0 := 0
| (n + 1) := if P (n + 1) then n + 1 else find_greatest n
variables {P : ℕ → Prop} [decidable_pred P]
@[simp] lemma find_greatest_zero : nat.find_greatest P 0 = 0 := rfl
@[simp] lemma find_greatest_eq : ∀{b}, P b → nat.find_greatest P b = b
| 0 h := rfl
| (n + 1) h := by simp [nat.find_greatest, h]
@[simp] lemma find_greatest_of_not {b} (h : ¬ P (b + 1)) :
nat.find_greatest P (b + 1) = nat.find_greatest P b :=
by simp [nat.find_greatest, h]
lemma find_greatest_spec_and_le :
∀{b m}, m ≤ b → P m → P (nat.find_greatest P b) ∧ m ≤ nat.find_greatest P b
| 0 m hm hP :=
have m = 0, from le_antisymm hm (nat.zero_le _),
show P 0 ∧ m ≤ 0, from this ▸ ⟨hP, le_refl _⟩
| (b + 1) m hm hP :=
begin
by_cases h : P (b + 1),
{ simp [h, hm] },
{ have : m ≠ b + 1 := assume this, h $ this ▸ hP,
have : m ≤ b := (le_of_not_gt $ assume h : b + 1 ≤ m, this $ le_antisymm hm h),
have : P (nat.find_greatest P b) ∧ m ≤ nat.find_greatest P b :=
find_greatest_spec_and_le this hP,
simp [h, this] }
end
lemma find_greatest_spec {b} : (∃m, m ≤ b ∧ P m) → P (nat.find_greatest P b)
| ⟨m, hmb, hm⟩ := (find_greatest_spec_and_le hmb hm).1
lemma find_greatest_le : ∀ {b}, nat.find_greatest P b ≤ b
| 0 := le_refl _
| (b + 1) :=
have nat.find_greatest P b ≤ b + 1, from le_trans find_greatest_le (nat.le_succ b),
by by_cases P (b + 1); simp [h, this]
lemma le_find_greatest {b m} (hmb : m ≤ b) (hm : P m) : m ≤ nat.find_greatest P b :=
(find_greatest_spec_and_le hmb hm).2
lemma find_greatest_is_greatest {P : ℕ → Prop} [decidable_pred P] {b} :
(∃ m, m ≤ b ∧ P m) → ∀ k, nat.find_greatest P b < k ∧ k ≤ b → ¬ P k
| ⟨m, hmb, hP⟩ k ⟨hk, hkb⟩ hPk := lt_irrefl k $ lt_of_le_of_lt (le_find_greatest hkb hPk) hk
end find_greatest
section div
lemma dvd_div_of_mul_dvd {a b c : ℕ} (h : a * b ∣ c) : b ∣ c / a :=
if ha : a = 0 then
by simp [ha]
else
have ha : a > 0, from nat.pos_of_ne_zero ha,
have h1 : ∃ d, c = a * b * d, from h,
let ⟨d, hd⟩ := h1 in
have hac : a ∣ c, from dvd_of_mul_right_dvd h,
have h2 : c / a = b * d, from nat.div_eq_of_eq_mul_right ha (by simpa [mul_assoc] using hd),
show ∃ d, c / a = b * d, from ⟨d, h2⟩
lemma mul_dvd_of_dvd_div {a b c : ℕ} (hab : c ∣ b) (h : a ∣ b / c) : c * a ∣ b :=
have h1 : ∃ d, b / c = a * d, from h,
have h2 : ∃ e, b = c * e, from hab,
let ⟨d, hd⟩ := h1, ⟨e, he⟩ := h2 in
have h3 : b = a * d * c, from
nat.eq_mul_of_div_eq_left hab hd,
show ∃ d, b = c * a * d, from ⟨d, by cc⟩
lemma div_mul_div {a b c d : ℕ} (hab : b ∣ a) (hcd : d ∣ c) :
(a / b) * (c / d) = (a * c) / (b * d) :=
have exi1 : ∃ x, a = b * x, from hab,
have exi2 : ∃ y, c = d * y, from hcd,
if hb : b = 0 then by simp [hb]
else have b > 0, from nat.pos_of_ne_zero hb,
if hd : d = 0 then by simp [hd]
else have d > 0, from nat.pos_of_ne_zero hd,
begin
cases exi1 with x hx, cases exi2 with y hy,
rw [hx, hy, nat.mul_div_cancel_left, nat.mul_div_cancel_left],
symmetry,
apply nat.div_eq_of_eq_mul_left,
apply mul_pos,
repeat {assumption},
cc
end
lemma pow_dvd_of_le_of_pow_dvd {p m n k : ℕ} (hmn : m ≤ n) (hdiv : p ^ n ∣ k) : p ^ m ∣ k :=
have p ^ m ∣ p ^ n, from pow_dvd_pow _ hmn,
dvd_trans this hdiv
lemma dvd_of_pow_dvd {p k m : ℕ} (hk : 1 ≤ k) (hpk : p^k ∣ m) : p ∣ m :=
by rw ←nat.pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk
end div
lemma exists_eq_add_of_le : ∀ {m n : ℕ}, m ≤ n → ∃ k : ℕ, n = m + k
| 0 0 h := ⟨0, by simp⟩
| 0 (n+1) h := ⟨n+1, by simp⟩
| (m+1) (n+1) h := let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in ⟨k, by simp [hk]⟩
lemma exists_eq_add_of_lt : ∀ {m n : ℕ}, m < n → ∃ k : ℕ, n = m + k + 1
| 0 0 h := false.elim $ lt_irrefl _ h
| 0 (n+1) h := ⟨n, by simp⟩
| (m+1) (n+1) h := let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in ⟨k, by simp [hk]⟩
lemma with_bot.add_eq_zero_iff : ∀ {n m : with_bot ℕ}, n + m = 0 ↔ n = 0 ∧ m = 0
| none m := iff_of_false dec_trivial (λ h, absurd h.1 dec_trivial)
| n none := iff_of_false (by cases n; exact dec_trivial)
(λ h, absurd h.2 dec_trivial)
| (some n) (some m) := show (n + m : with_bot ℕ) = (0 : ℕ) ↔ (n : with_bot ℕ) = (0 : ℕ) ∧
(m : with_bot ℕ) = (0 : ℕ),
by rw [← with_bot.coe_add, with_bot.coe_eq_coe, with_bot.coe_eq_coe,
with_bot.coe_eq_coe, add_eq_zero_iff' (nat.zero_le _) (nat.zero_le _)]
lemma with_bot.add_eq_one_iff : ∀ {n m : with_bot ℕ}, n + m = 1 ↔ (n = 0 ∧ m = 1) ∨ (n = 1 ∧ m = 0)
| none none := dec_trivial
| none (some m) := dec_trivial
| (some n) none := iff_of_false dec_trivial (λ h, h.elim (λ h, absurd h.2 dec_trivial)
(λ h, absurd h.2 dec_trivial))
| (some n) (some 0) := by erw [with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe,
with_bot.coe_eq_coe]; simp
| (some n) (some (m + 1)) := by erw [with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe,
with_bot.coe_eq_coe, with_bot.coe_eq_coe]; simp [nat.add_succ, nat.succ_inj', nat.succ_ne_zero]
-- induction
@[elab_as_eliminator] lemma le_induction {P : nat → Prop} {m} (h0 : P m) (h1 : ∀ n ≥ m, P n → P (n + 1)) :
∀ n ≥ m, P n :=
by apply nat.less_than_or_equal.rec h0; exact h1
end nat
|
aad508d56d38954daf87e36411904bcb8d81ed04 | d642a6b1261b2cbe691e53561ac777b924751b63 | /src/data/pfun.lean | ef901a8156410a6651c4836238ebac77717eaa2a | [
"Apache-2.0"
] | permissive | cipher1024/mathlib | fee56b9954e969721715e45fea8bcb95f9dc03fe | d077887141000fefa5a264e30fa57520e9f03522 | refs/heads/master | 1,651,806,490,504 | 1,573,508,694,000 | 1,573,508,694,000 | 107,216,176 | 0 | 0 | Apache-2.0 | 1,647,363,136,000 | 1,508,213,014,000 | Lean | UTF-8 | Lean | false | false | 22,514 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro, Jeremy Avigad
-/
import data.set.basic data.equiv.basic data.rel logic.relator
/-- `roption α` is the type of "partial values" of type `α`. It
is similar to `option α` except the domain condition can be an
arbitrary proposition, not necessarily decidable. -/
structure {u} roption (α : Type u) : Type u :=
(dom : Prop)
(get : dom → α)
namespace roption
variables {α : Type*} {β : Type*} {γ : Type*}
/-- Convert an `roption α` with a decidable domain to an option -/
def to_option (o : roption α) [decidable o.dom] : option α :=
if h : dom o then some (o.get h) else none
/-- `roption` extensionality -/
theorem ext' : ∀ {o p : roption α}
(H1 : o.dom ↔ p.dom)
(H2 : ∀h₁ h₂, o.get h₁ = p.get h₂), o = p
| ⟨od, o⟩ ⟨pd, p⟩ H1 H2 := have t : od = pd, from propext H1,
by cases t; rw [show o = p, from funext $ λp, H2 p p]
/-- `roption` eta expansion -/
@[simp] theorem eta : Π (o : roption α), (⟨o.dom, λ h, o.get h⟩ : roption α) = o
| ⟨h, f⟩ := rfl
/-- `a ∈ o` means that `o` is defined and equal to `a` -/
protected def mem (a : α) (o : roption α) : Prop := ∃ h, o.get h = a
instance : has_mem α (roption α) := ⟨roption.mem⟩
theorem mem_eq (a : α) (o : roption α) : (a ∈ o) = (∃ h, o.get h = a) :=
rfl
theorem dom_iff_mem : ∀ {o : roption α}, o.dom ↔ ∃y, y ∈ o
| ⟨p, f⟩ := ⟨λh, ⟨f h, h, rfl⟩, λ⟨_, h, rfl⟩, h⟩
theorem get_mem {o : roption α} (h) : get o h ∈ o := ⟨_, rfl⟩
/-- `roption` extensionality -/
theorem ext {o p : roption α} (H : ∀ a, a ∈ o ↔ a ∈ p) : o = p :=
ext' ⟨λ h, ((H _).1 ⟨h, rfl⟩).fst,
λ h, ((H _).2 ⟨h, rfl⟩).fst⟩ $
λ a b, ((H _).2 ⟨_, rfl⟩).snd
/-- The `none` value in `roption` has a `false` domain and an empty function. -/
def none : roption α := ⟨false, false.rec _⟩
@[simp] theorem not_mem_none (a : α) : a ∉ @none α := λ h, h.fst
/-- The `some a` value in `roption` has a `true` domain and the
function returns `a`. -/
def some (a : α) : roption α := ⟨true, λ_, a⟩
theorem mem_unique : relator.left_unique ((∈) : α → roption α → Prop)
| _ ⟨p, f⟩ _ ⟨h₁, rfl⟩ ⟨h₂, rfl⟩ := rfl
theorem get_eq_of_mem {o : roption α} {a} (h : a ∈ o) (h') : get o h' = a :=
mem_unique ⟨_, rfl⟩ h
@[simp] theorem get_some {a : α} (ha : (some a).dom) : get (some a) ha = a := rfl
theorem mem_some (a : α) : a ∈ some a := ⟨trivial, rfl⟩
@[simp] theorem mem_some_iff {a b} : b ∈ (some a : roption α) ↔ b = a :=
⟨λ⟨h, e⟩, e.symm, λ e, ⟨trivial, e.symm⟩⟩
theorem eq_some_iff {a : α} {o : roption α} : o = some a ↔ a ∈ o :=
⟨λ e, e.symm ▸ mem_some _,
λ ⟨h, e⟩, e ▸ ext' (iff_true_intro h) (λ _ _, rfl)⟩
theorem eq_none_iff {o : roption α} : o = none ↔ ∀ a, a ∉ o :=
⟨λ e, e.symm ▸ not_mem_none,
λ h, ext (by simpa [not_mem_none])⟩
theorem eq_none_iff' {o : roption α} : o = none ↔ ¬ o.dom :=
⟨λ e, e.symm ▸ id, λ h, eq_none_iff.2 (λ a h', h h'.fst)⟩
lemma some_ne_none (x : α) : some x ≠ none :=
by { intro h, change none.dom, rw [← h], trivial }
lemma ne_none_iff {o : roption α} : o ≠ none ↔ ∃x, o = some x :=
begin
split,
{ rw [ne, eq_none_iff], intro h, push_neg at h, cases h with x hx, use x, rwa [eq_some_iff] },
{ rintro ⟨x, rfl⟩, apply some_ne_none }
end
@[simp] lemma some_inj {a b : α} : roption.some a = some b ↔ a = b :=
function.injective.eq_iff (λ a b h, congr_fun (eq_of_heq (roption.mk.inj h).2) trivial)
@[simp] lemma some_get {a : roption α} (ha : a.dom) :
roption.some (roption.get a ha) = a :=
eq.symm (eq_some_iff.2 ⟨ha, rfl⟩)
lemma get_eq_iff_eq_some {a : roption α} {ha : a.dom} {b : α} :
a.get ha = b ↔ a = some b :=
⟨λ h, by simp [h.symm], λ h, by simp [h]⟩
instance none_decidable : decidable (@none α).dom := decidable.false
instance some_decidable (a : α) : decidable (some a).dom := decidable.true
def get_or_else (a : roption α) [decidable a.dom] (d : α) :=
if ha : a.dom then a.get ha else d
@[simp] lemma get_or_else_none (d : α) : get_or_else none d = d :=
dif_neg id
@[simp] lemma get_or_else_some (a : α) (d : α) : get_or_else (some a) d = a :=
dif_pos trivial
@[simp] theorem mem_to_option {o : roption α} [decidable o.dom] {a : α} :
a ∈ to_option o ↔ a ∈ o :=
begin
unfold to_option,
by_cases h : o.dom; simp [h],
{ exact ⟨λ h, ⟨_, h⟩, λ ⟨_, h⟩, h⟩ },
{ exact mt Exists.fst h }
end
/-- Convert an `option α` into an `roption α` -/
def of_option : option α → roption α
| option.none := none
| (option.some a) := some a
@[simp] theorem mem_of_option {a : α} : ∀ {o : option α}, a ∈ of_option o ↔ a ∈ o
| option.none := ⟨λ h, h.fst.elim, λ h, option.no_confusion h⟩
| (option.some b) := ⟨λ h, congr_arg option.some h.snd,
λ h, ⟨trivial, option.some.inj h⟩⟩
@[simp] theorem of_option_dom {α} : ∀ (o : option α), (of_option o).dom ↔ o.is_some
| option.none := by simp [of_option, none]
| (option.some a) := by simp [of_option]
theorem of_option_eq_get {α} (o : option α) : of_option o = ⟨_, @option.get _ o⟩ :=
roption.ext' (of_option_dom o) $ λ h₁ h₂, by cases o; [cases h₁, refl]
instance : has_coe (option α) (roption α) := ⟨of_option⟩
@[simp] theorem mem_coe {a : α} {o : option α} :
a ∈ (o : roption α) ↔ a ∈ o := mem_of_option
@[simp] theorem coe_none : (@option.none α : roption α) = none := rfl
@[simp] theorem coe_some (a : α) : (option.some a : roption α) = some a := rfl
@[elab_as_eliminator] protected lemma induction_on {P : roption α → Prop}
(a : roption α) (hnone : P none) (hsome : ∀ a : α, P (some a)) : P a :=
(classical.em a.dom).elim
(λ h, roption.some_get h ▸ hsome _)
(λ h, (eq_none_iff'.2 h).symm ▸ hnone)
instance of_option_decidable : ∀ o : option α, decidable (of_option o).dom
| option.none := roption.none_decidable
| (option.some a) := roption.some_decidable a
@[simp] theorem to_of_option (o : option α) : to_option (of_option o) = o :=
by cases o; refl
@[simp] theorem of_to_option (o : roption α) [decidable o.dom] : of_option (to_option o) = o :=
ext $ λ a, mem_of_option.trans mem_to_option
noncomputable def equiv_option : roption α ≃ option α :=
by haveI := classical.dec; exact
⟨λ o, to_option o, of_option, λ o, of_to_option o,
λ o, eq.trans (by dsimp; congr) (to_of_option o)⟩
/-- `assert p f` is a bind-like operation which appends an additional condition
`p` to the domain and uses `f` to produce the value. -/
def assert (p : Prop) (f : p → roption α) : roption α :=
⟨∃h : p, (f h).dom, λha, (f ha.fst).get ha.snd⟩
/-- The bind operation has value `g (f.get)`, and is defined when all the
parts are defined. -/
protected def bind (f : roption α) (g : α → roption β) : roption β :=
assert (dom f) (λb, g (f.get b))
/-- The map operation for `roption` just maps the value and maintains the same domain. -/
def map (f : α → β) (o : roption α) : roption β :=
⟨o.dom, f ∘ o.get⟩
theorem mem_map (f : α → β) {o : roption α} :
∀ {a}, a ∈ o → f a ∈ map f o
| _ ⟨h, rfl⟩ := ⟨_, rfl⟩
@[simp] theorem mem_map_iff (f : α → β) {o : roption α} {b} :
b ∈ map f o ↔ ∃ a ∈ o, f a = b :=
⟨match b with _, ⟨h, rfl⟩ := ⟨_, ⟨_, rfl⟩, rfl⟩ end,
λ ⟨a, h₁, h₂⟩, h₂ ▸ mem_map f h₁⟩
@[simp] theorem map_none (f : α → β) :
map f none = none := eq_none_iff.2 $ λ a, by simp
@[simp] theorem map_some (f : α → β) (a : α) : map f (some a) = some (f a) :=
eq_some_iff.2 $ mem_map f $ mem_some _
theorem mem_assert {p : Prop} {f : p → roption α}
: ∀ {a} (h : p), a ∈ f h → a ∈ assert p f
| _ _ ⟨h, rfl⟩ := ⟨⟨_, _⟩, rfl⟩
@[simp] theorem mem_assert_iff {p : Prop} {f : p → roption α} {a} :
a ∈ assert p f ↔ ∃ h : p, a ∈ f h :=
⟨match a with _, ⟨h, rfl⟩ := ⟨_, ⟨_, rfl⟩⟩ end,
λ ⟨a, h⟩, mem_assert _ h⟩
theorem mem_bind {f : roption α} {g : α → roption β} :
∀ {a b}, a ∈ f → b ∈ g a → b ∈ f.bind g
| _ _ ⟨h, rfl⟩ ⟨h₂, rfl⟩ := ⟨⟨_, _⟩, rfl⟩
@[simp] theorem mem_bind_iff {f : roption α} {g : α → roption β} {b} :
b ∈ f.bind g ↔ ∃ a ∈ f, b ∈ g a :=
⟨match b with _, ⟨⟨h₁, h₂⟩, rfl⟩ := ⟨_, ⟨_, rfl⟩, ⟨_, rfl⟩⟩ end,
λ ⟨a, h₁, h₂⟩, mem_bind h₁ h₂⟩
@[simp] theorem bind_none (f : α → roption β) :
none.bind f = none := eq_none_iff.2 $ λ a, by simp
@[simp] theorem bind_some (a : α) (f : α → roption β) :
(some a).bind f = f a := ext $ by simp
theorem bind_some_eq_map (f : α → β) (x : roption α) :
x.bind (some ∘ f) = map f x :=
ext $ by simp [eq_comm]
theorem bind_assoc {γ} (f : roption α) (g : α → roption β) (k : β → roption γ) :
(f.bind g).bind k = f.bind (λ x, (g x).bind k) :=
ext $ λ a, by simp; exact
⟨λ ⟨_, ⟨_, h₁, h₂⟩, h₃⟩, ⟨_, h₁, _, h₂, h₃⟩,
λ ⟨_, h₁, _, h₂, h₃⟩, ⟨_, ⟨_, h₁, h₂⟩, h₃⟩⟩
@[simp] theorem bind_map {γ} (f : α → β) (x) (g : β → roption γ) :
(map f x).bind g = x.bind (λ y, g (f y)) :=
by rw [← bind_some_eq_map, bind_assoc]; simp
@[simp] theorem map_bind {γ} (f : α → roption β) (x : roption α) (g : β → γ) :
map g (x.bind f) = x.bind (λ y, map g (f y)) :=
by rw [← bind_some_eq_map, bind_assoc]; simp [bind_some_eq_map]
theorem map_map (g : β → γ) (f : α → β) (o : roption α) :
map g (map f o) = map (g ∘ f) o :=
by rw [← bind_some_eq_map, bind_map, bind_some_eq_map]
instance : monad roption :=
{ pure := @some,
map := @map,
bind := @roption.bind }
instance : is_lawful_monad roption :=
{ bind_pure_comp_eq_map := @bind_some_eq_map,
id_map := λ β f, by cases f; refl,
pure_bind := @bind_some,
bind_assoc := @bind_assoc }
theorem map_id' {f : α → α} (H : ∀ (x : α), f x = x) (o) : map f o = o :=
by rw [show f = id, from funext H]; exact id_map o
@[simp] theorem bind_some_right (x : roption α) : x.bind some = x :=
by rw [bind_some_eq_map]; simp [map_id']
@[simp] theorem ret_eq_some (a : α) : return a = some a := rfl
@[simp] theorem map_eq_map {α β} (f : α → β) (o : roption α) :
f <$> o = map f o := rfl
@[simp] theorem bind_eq_bind {α β} (f : roption α) (g : α → roption β) :
f >>= g = f.bind g := rfl
instance : monad_fail roption :=
{ fail := λ_ _, none, ..roption.monad }
/- `restrict p o h` replaces the domain of `o` with `p`, and is well defined when
`p` implies `o` is defined. -/
def restrict (p : Prop) : ∀ (o : roption α), (p → o.dom) → roption α
| ⟨d, f⟩ H := ⟨p, λh, f (H h)⟩
@[simp]
theorem mem_restrict (p : Prop) (o : roption α) (h : p → o.dom) (a : α) :
a ∈ restrict p o h ↔ p ∧ a ∈ o :=
begin
cases o, dsimp [restrict, mem_eq], split,
{ rintro ⟨h₀, h₁⟩, exact ⟨h₀, ⟨_, h₁⟩⟩ },
rintro ⟨h₀, h₁, h₂⟩, exact ⟨h₀, h₂⟩
end
/-- `unwrap o` gets the value at `o`, ignoring the condition.
(This function is unsound.) -/
meta def unwrap (o : roption α) : α := o.get undefined
theorem assert_defined {p : Prop} {f : p → roption α} :
∀ (h : p), (f h).dom → (assert p f).dom := exists.intro
theorem bind_defined {f : roption α} {g : α → roption β} :
∀ (h : f.dom), (g (f.get h)).dom → (f.bind g).dom := assert_defined
@[simp] theorem bind_dom {f : roption α} {g : α → roption β} :
(f.bind g).dom ↔ ∃ h : f.dom, (g (f.get h)).dom := iff.rfl
end roption
/-- `pfun α β`, or `α →. β`, is the type of partial functions from
`α` to `β`. It is defined as `α → roption β`. -/
def pfun (α : Type*) (β : Type*) := α → roption β
infixr ` →. `:25 := pfun
namespace pfun
variables {α : Type*} {β : Type*} {γ : Type*}
/-- The domain of a partial function -/
def dom (f : α →. β) : set α := λ a, (f a).dom
theorem mem_dom (f : α →. β) (x : α) : x ∈ dom f ↔ ∃ y, y ∈ f x :=
by simp [dom, set.mem_def, roption.dom_iff_mem]
theorem dom_eq (f : α →. β) : dom f = {x | ∃ y, y ∈ f x} :=
set.ext (mem_dom f)
/-- Evaluate a partial function -/
def fn (f : α →. β) (x) (h : dom f x) : β := (f x).get h
/-- Evaluate a partial function to return an `option` -/
def eval_opt (f : α →. β) [D : decidable_pred (dom f)] (x : α) : option β :=
@roption.to_option _ _ (D x)
/-- Partial function extensionality -/
theorem ext' {f g : α →. β}
(H1 : ∀ a, a ∈ dom f ↔ a ∈ dom g)
(H2 : ∀ a p q, f.fn a p = g.fn a q) : f = g :=
funext $ λ a, roption.ext' (H1 a) (H2 a)
theorem ext {f g : α →. β} (H : ∀ a b, b ∈ f a ↔ b ∈ g a) : f = g :=
funext $ λ a, roption.ext (H a)
/-- Turn a partial function into a function out of a subtype -/
def as_subtype (f : α →. β) (s : {x // f.dom x}) : β := f.fn s.1 s.2
def equiv_subtype : (α →. β) ≃ (Σ p : α → Prop, subtype p → β) :=
⟨λ f, ⟨f.dom, as_subtype f⟩,
λ ⟨p, f⟩ x, ⟨p x, λ h, f ⟨x, h⟩⟩,
λ f, funext $ λ a, roption.eta _,
λ ⟨p, f⟩, by dsimp; congr; funext a; cases a; refl⟩
theorem as_subtype_eq_of_mem {f : α →. β} {x : α} {y : β} (fxy : y ∈ f x) (domx : x ∈ f.dom) :
f.as_subtype ⟨x, domx⟩ = y :=
roption.mem_unique (roption.get_mem _) fxy
/-- Turn a total function into a partial function -/
protected def lift (f : α → β) : α →. β := λ a, roption.some (f a)
instance : has_coe (α → β) (α →. β) := ⟨pfun.lift⟩
@[simp] theorem lift_eq_coe (f : α → β) : pfun.lift f = f := rfl
@[simp] theorem coe_val (f : α → β) (a : α) :
(f : α →. β) a = roption.some (f a) := rfl
/-- The graph of a partial function is the set of pairs
`(x, f x)` where `x` is in the domain of `f`. -/
def graph (f : α →. β) : set (α × β) := {p | p.2 ∈ f p.1}
def graph' (f : α →. β) : rel α β := λ x y, y ∈ f x
/-- The range of a partial function is the set of values
`f x` where `x` is in the domain of `f`. -/
def ran (f : α →. β) : set β := {b | ∃a, b ∈ f a}
/-- Restrict a partial function to a smaller domain. -/
def restrict (f : α →. β) {p : set α} (H : p ⊆ f.dom) : α →. β :=
λ x, roption.restrict (p x) (f x) (@H x)
@[simp]
theorem mem_restrict {f : α →. β} {s : set α} (h : s ⊆ f.dom) (a : α) (b : β) :
b ∈ restrict f h a ↔ a ∈ s ∧ b ∈ f a :=
by { simp [restrict], reflexivity }
def res (f : α → β) (s : set α) : α →. β :=
restrict (pfun.lift f) (set.subset_univ s)
theorem mem_res (f : α → β) (s : set α) (a : α) (b : β) :
b ∈ res f s a ↔ (a ∈ s ∧ f a = b) :=
by { simp [res], split; {intro h, simp [h]} }
theorem res_univ (f : α → β) : pfun.res f set.univ = f :=
rfl
theorem dom_iff_graph (f : α →. β) (x : α) : x ∈ f.dom ↔ ∃y, (x, y) ∈ f.graph :=
roption.dom_iff_mem
theorem lift_graph {f : α → β} {a b} : (a, b) ∈ (f : α →. β).graph ↔ f a = b :=
show (∃ (h : true), f a = b) ↔ f a = b, by simp
/-- The monad `pure` function, the total constant `x` function -/
protected def pure (x : β) : α →. β := λ_, roption.some x
/-- The monad `bind` function, pointwise `roption.bind` -/
def bind (f : α →. β) (g : β → α →. γ) : α →. γ :=
λa, roption.bind (f a) (λb, g b a)
/-- The monad `map` function, pointwise `roption.map` -/
def map (f : β → γ) (g : α →. β) : α →. γ :=
λa, roption.map f (g a)
instance : monad (pfun α) :=
{ pure := @pfun.pure _,
bind := @pfun.bind _,
map := @pfun.map _ }
instance : is_lawful_monad (pfun α) :=
{ bind_pure_comp_eq_map := λ β γ f x, funext $ λ a, roption.bind_some_eq_map _ _,
id_map := λ β f, by funext a; dsimp [functor.map, pfun.map]; cases f a; refl,
pure_bind := λ β γ x f, funext $ λ a, roption.bind_some.{u_1 u_2} _ (f x),
bind_assoc := λ β γ δ f g k,
funext $ λ a, roption.bind_assoc (f a) (λ b, g b a) (λ b, k b a) }
theorem pure_defined (p : set α) (x : β) : p ⊆ (@pfun.pure α _ x).dom := set.subset_univ p
theorem bind_defined {α β γ} (p : set α) {f : α →. β} {g : β → α →. γ}
(H1 : p ⊆ f.dom) (H2 : ∀x, p ⊆ (g x).dom) : p ⊆ (f >>= g).dom :=
λa ha, (⟨H1 ha, H2 _ ha⟩ : (f >>= g).dom a)
def fix (f : α →. β ⊕ α) : α →. β := λ a,
roption.assert (acc (λ x y, sum.inr x ∈ f y) a) $ λ h,
@well_founded.fix_F _ (λ x y, sum.inr x ∈ f y) _
(λ a IH, roption.assert (f a).dom $ λ hf,
by cases e : (f a).get hf with b a';
[exact roption.some b, exact IH _ ⟨hf, e⟩])
a h
theorem dom_of_mem_fix {f : α →. β ⊕ α} {a : α} {b : β}
(h : b ∈ fix f a) : (f a).dom :=
let ⟨h₁, h₂⟩ := roption.mem_assert_iff.1 h in
by rw well_founded.fix_F_eq at h₂; exact h₂.fst.fst
theorem mem_fix_iff {f : α →. β ⊕ α} {a : α} {b : β} :
b ∈ fix f a ↔ sum.inl b ∈ f a ∨ ∃ a', sum.inr a' ∈ f a ∧ b ∈ fix f a' :=
⟨λ h, let ⟨h₁, h₂⟩ := roption.mem_assert_iff.1 h in
begin
rw well_founded.fix_F_eq at h₂,
simp at h₂,
cases h₂ with h₂ h₃,
cases e : (f a).get h₂ with b' a'; simp [e] at h₃,
{ subst b', refine or.inl ⟨h₂, e⟩ },
{ exact or.inr ⟨a', ⟨_, e⟩, roption.mem_assert _ h₃⟩ }
end,
λ h, begin
simp [fix],
rcases h with ⟨h₁, h₂⟩ | ⟨a', h, h₃⟩,
{ refine ⟨⟨_, λ y h', _⟩, _⟩,
{ injection roption.mem_unique ⟨h₁, h₂⟩ h' },
{ rw well_founded.fix_F_eq, simp [h₁, h₂] } },
{ simp [fix] at h₃, cases h₃ with h₃ h₄,
refine ⟨⟨_, λ y h', _⟩, _⟩,
{ injection roption.mem_unique h h' with e,
exact e ▸ h₃ },
{ cases h with h₁ h₂,
rw well_founded.fix_F_eq, simp [h₁, h₂, h₄] } }
end⟩
@[elab_as_eliminator] def fix_induction
{f : α →. β ⊕ α} {b : β} {C : α → Sort*} {a : α} (h : b ∈ fix f a)
(H : ∀ a, b ∈ fix f a →
(∀ a', b ∈ fix f a' → sum.inr a' ∈ f a → C a') → C a) : C a :=
begin
replace h := roption.mem_assert_iff.1 h,
have := h.snd, revert this,
induction h.fst with a ha IH, intro h₂,
refine H a (roption.mem_assert_iff.2 ⟨⟨_, ha⟩, h₂⟩)
(λ a' ha' fa', _),
have := (roption.mem_assert_iff.1 ha').snd,
exact IH _ fa' ⟨ha _ fa', this⟩ this
end
end pfun
namespace pfun
variables {α : Type*} {β : Type*} (f : α →. β)
def image (s : set α) : set β := rel.image f.graph' s
lemma image_def (s : set α) : image f s = {y | ∃ x ∈ s, y ∈ f x} := rfl
lemma mem_image (y : β) (s : set α) : y ∈ image f s ↔ ∃ x ∈ s, y ∈ f x :=
iff.refl _
lemma image_mono {s t : set α} (h : s ⊆ t) : f.image s ⊆ f.image t :=
rel.image_mono _ h
lemma image_inter (s t : set α) : f.image (s ∩ t) ⊆ f.image s ∩ f.image t :=
rel.image_inter _ s t
lemma image_union (s t : set α) : f.image (s ∪ t) = f.image s ∪ f.image t :=
rel.image_union _ s t
def preimage (s : set β) : set α := rel.preimage (λ x y, y ∈ f x) s
lemma preimage_def (s : set β) : preimage f s = {x | ∃ y ∈ s, y ∈ f x} := rfl
lemma mem_preimage (s : set β) (x : α) : x ∈ preimage f s ↔ ∃ y ∈ s, y ∈ f x :=
iff.refl _
lemma preimage_subset_dom (s : set β) : f.preimage s ⊆ f.dom :=
assume x ⟨y, ys, fxy⟩, roption.dom_iff_mem.mpr ⟨y, fxy⟩
lemma preimage_mono {s t : set β} (h : s ⊆ t) : f.preimage s ⊆ f.preimage t :=
rel.preimage_mono _ h
lemma preimage_inter (s t : set β) : f.preimage (s ∩ t) ⊆ f.preimage s ∩ f.preimage t :=
rel.preimage_inter _ s t
lemma preimage_union (s t : set β) : f.preimage (s ∪ t) = f.preimage s ∪ f.preimage t :=
rel.preimage_union _ s t
lemma preimage_univ : f.preimage set.univ = f.dom :=
by ext; simp [mem_preimage, mem_dom]
def core (s : set β) : set α := rel.core f.graph' s
lemma core_def (s : set β) : core f s = {x | ∀ y, y ∈ f x → y ∈ s} := rfl
lemma mem_core (x : α) (s : set β) : x ∈ core f s ↔ (∀ y, y ∈ f x → y ∈ s) :=
iff.rfl
lemma compl_dom_subset_core (s : set β) : -f.dom ⊆ f.core s :=
assume x hx y fxy,
absurd ((mem_dom f x).mpr ⟨y, fxy⟩) hx
lemma core_mono {s t : set β} (h : s ⊆ t) : f.core s ⊆ f.core t :=
rel.core_mono _ h
lemma core_inter (s t : set β) : f.core (s ∩ t) = f.core s ∩ f.core t :=
rel.core_inter _ s t
lemma mem_core_res (f : α → β) (s : set α) (t : set β) (x : α) :
x ∈ core (res f s) t ↔ (x ∈ s → f x ∈ t) :=
begin
simp [mem_core, mem_res], split,
{ intros h h', apply h _ h', reflexivity },
intros h y xs fxeq, rw ←fxeq, exact h xs
end
section
open_locale classical
lemma core_res (f : α → β) (s : set α) (t : set β) : core (res f s) t = -s ∪ f ⁻¹' t :=
by { ext, rw mem_core_res, by_cases h : x ∈ s; simp [h] }
end
lemma core_restrict (f : α → β) (s : set β) : core (f : α →. β) s = set.preimage f s :=
by ext x; simp [core_def]
lemma preimage_subset_core (f : α →. β) (s : set β) : f.preimage s ⊆ f.core s :=
assume x ⟨y, ys, fxy⟩ y' fxy',
have y = y', from roption.mem_unique fxy fxy',
this ▸ ys
lemma preimage_eq (f : α →. β) (s : set β) : f.preimage s = f.core s ∩ f.dom :=
set.eq_of_subset_of_subset
(set.subset_inter (preimage_subset_core f s) (preimage_subset_dom f s))
(assume x ⟨xcore, xdom⟩,
let y := (f x).get xdom in
have ys : y ∈ s, from xcore _ (roption.get_mem _),
show x ∈ preimage f s, from ⟨(f x).get xdom, ys, roption.get_mem _⟩)
lemma core_eq (f : α →. β) (s : set β) : f.core s = f.preimage s ∪ -f.dom :=
by rw [preimage_eq, set.union_distrib_right, set.union_comm (dom f), set.compl_union_self,
set.inter_univ, set.union_eq_self_of_subset_right (compl_dom_subset_core f s)]
lemma preimage_as_subtype (f : α →. β) (s : set β) :
f.as_subtype ⁻¹' s = subtype.val ⁻¹' pfun.preimage f s :=
begin
ext x,
simp only [set.mem_preimage, set.mem_set_of_eq, pfun.as_subtype, pfun.mem_preimage],
show pfun.fn f (x.val) _ ∈ s ↔ ∃ y ∈ s, y ∈ f (x.val),
exact iff.intro
(assume h, ⟨_, h, roption.get_mem _⟩)
(assume ⟨y, ys, fxy⟩,
have f.fn x.val x.property ∈ f x.val := roption.get_mem _,
roption.mem_unique fxy this ▸ ys)
end
end pfun
|
0eb602ec18c6bba1404725c6f25d2005a04f3489 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/list/defs_auto.lean | 6e849a94554d0bd676bbe489792d80689ff6223f | [] | 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 | 31,534 | lean | /-
Copyright (c) 2014 Parikshit Khanna. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.option.defs
import Mathlib.logic.basic
import Mathlib.tactic.cache
import Mathlib.PostPort
universes u_1 u v w u_2
namespace Mathlib
/-!
## Definitions on lists
This file contains various definitions on lists. It does not contain
proofs about these definitions, those are contained in other files in `data/list`
-/
namespace list
/-- Returns whether a list is []. Returns a boolean even if `l = []` is not decidable. -/
def is_nil {α : Type u_1} : List α → Bool := sorry
protected instance has_sdiff {α : Type u} [DecidableEq α] : has_sdiff (List α) :=
has_sdiff.mk list.diff
/-- Split a list at an index.
split_at 2 [a, b, c] = ([a, b], [c]) -/
def split_at {α : Type u} : ℕ → List α → List α × List α := sorry
/-- An auxiliary function for `split_on_p`. -/
def split_on_p_aux {α : Type u} (P : α → Prop) [decidable_pred P] :
List α → (List α → List α) → List (List α) :=
sorry
/-- Split a list at every element satisfying a predicate. -/
def split_on_p {α : Type u} (P : α → Prop) [decidable_pred P] (l : List α) : List (List α) :=
split_on_p_aux P l id
/-- Split a list at every occurrence of an element.
[1,1,2,3,2,4,4].split_on 2 = [[1,1],[3],[4,4]] -/
def split_on {α : Type u} [DecidableEq α] (a : α) (as : List α) : List (List α) :=
split_on_p (fun (_x : α) => _x = a) as
/-- Concatenate an element at the end of a list.
concat [a, b] c = [a, b, c] -/
@[simp] def concat {α : Type u} : List α → α → List α := sorry
/-- `head' xs` returns the first element of `xs` if `xs` is non-empty;
it returns `none` otherwise -/
@[simp] def head' {α : Type u} : List α → Option α := sorry
/-- Convert a list into an array (whose length is the length of `l`). -/
def to_array {α : Type u} (l : List α) : array (length l) α :=
d_array.mk fun (v : fin (length l)) => nth_le l (subtype.val v) sorry
/-- "inhabited" `nth` function: returns `default` instead of `none` in the case
that the index is out of bounds. -/
@[simp] def inth {α : Type u} [h : Inhabited α] (l : List α) (n : ℕ) : α := option.iget (nth l n)
/-- Apply a function to the nth tail of `l`. Returns the input without
using `f` if the index is larger than the length of the list.
modify_nth_tail f 2 [a, b, c] = [a, b] ++ f [c] -/
@[simp] def modify_nth_tail {α : Type u} (f : List α → List α) : ℕ → List α → List α := sorry
/-- Apply `f` to the head of the list, if it exists. -/
@[simp] def modify_head {α : Type u} (f : α → α) : List α → List α := sorry
/-- Apply `f` to the nth element of the list, if it exists. -/
def modify_nth {α : Type u} (f : α → α) : ℕ → List α → List α := modify_nth_tail (modify_head f)
/-- Apply `f` to the last element of `l`, if it exists. -/
@[simp] def modify_last {α : Type u} (f : α → α) : List α → List α := sorry
/-- `insert_nth n a l` inserts `a` into the list `l` after the first `n` elements of `l`
`insert_nth 2 1 [1, 2, 3, 4] = [1, 2, 1, 3, 4]`-/
def insert_nth {α : Type u} (n : ℕ) (a : α) : List α → List α := modify_nth_tail (List.cons a) n
/-- Take `n` elements from a list `l`. If `l` has less than `n` elements, append `n - length l`
elements `default α`. -/
def take' {α : Type u} [Inhabited α] (n : ℕ) : List α → List α := sorry
/-- Get the longest initial segment of the list whose members all satisfy `p`.
take_while (λ x, x < 3) [0, 2, 5, 1] = [0, 2] -/
def take_while {α : Type u} (p : α → Prop) [decidable_pred p] : List α → List α := sorry
/-- Fold a function `f` over the list from the left, returning the list
of partial results.
scanl (+) 0 [1, 2, 3] = [0, 1, 3, 6] -/
def scanl {α : Type u} {β : Type v} (f : α → β → α) : α → List β → List α := sorry
/-- Auxiliary definition used to define `scanr`. If `scanr_aux f b l = (b', l')`
then `scanr f b l = b' :: l'` -/
def scanr_aux {α : Type u} {β : Type v} (f : α → β → β) (b : β) : List α → β × List β := sorry
/-- Fold a function `f` over the list from the right, returning the list
of partial results.
scanr (+) 0 [1, 2, 3] = [6, 5, 3, 0] -/
def scanr {α : Type u} {β : Type v} (f : α → β → β) (b : β) (l : List α) : List β := sorry
/-- Product of a list.
prod [a, b, c] = ((1 * a) * b) * c -/
def prod {α : Type u} [Mul α] [HasOne α] : List α → α := foldl Mul.mul 1
/-- Sum of a list.
sum [a, b, c] = ((0 + a) + b) + c -/
-- Later this will be tagged with `to_additive`, but this can't be done yet because of import
-- dependencies.
def sum {α : Type u} [Add α] [HasZero α] : List α → α := foldl Add.add 0
/-- The alternating sum of a list. -/
def alternating_sum {G : Type u_1} [HasZero G] [Add G] [Neg G] : List G → G := sorry
/-- The alternating product of a list. -/
def alternating_prod {G : Type u_1} [HasOne G] [Mul G] [has_inv G] : List G → G := sorry
/-- Given a function `f : α → β ⊕ γ`, `partition_map f l` maps the list by `f`
whilst partitioning the result it into a pair of lists, `list β × list γ`,
partitioning the `sum.inl _` into the left list, and the `sum.inr _` into the right list.
`partition_map (id : ℕ ⊕ ℕ → ℕ ⊕ ℕ) [inl 0, inr 1, inl 2] = ([0,2], [1])` -/
def partition_map {α : Type u} {β : Type v} {γ : Type w} (f : α → β ⊕ γ) :
List α → List β × List γ :=
sorry
/-- `find p l` is the first element of `l` satisfying `p`, or `none` if no such
element exists. -/
def find {α : Type u} (p : α → Prop) [decidable_pred p] : List α → Option α := sorry
/-- `mfind tac l` returns the first element of `l` on which `tac` succeeds, and
fails otherwise. -/
def mfind {α : Type u} {m : Type u → Type v} [Monad m] [alternative m] (tac : α → m PUnit) :
List α → m α :=
mfirst fun (a : α) => tac a $> a
/-- `mbfind' p l` returns the first element `a` of `l` for which `p a` returns
true. `mbfind'` short-circuits, so `p` is not necessarily run on every `a` in
`l`. This is a monadic version of `list.find`. -/
def mbfind' {m : Type u → Type v} [Monad m] {α : Type u} (p : α → m (ulift Bool)) :
List α → m (Option α) :=
sorry
/-- A variant of `mbfind'` with more restrictive universe levels. -/
def mbfind {m : Type → Type v} [Monad m] {α : Type} (p : α → m Bool) (xs : List α) : m (Option α) :=
mbfind' (Functor.map ulift.up ∘ p) xs
/-- `many p as` returns true iff `p` returns true for any element of `l`.
`many` short-circuits, so if `p` returns true for any element of `l`, later
elements are not checked. This is a monadic version of `list.any`. -/
-- Implementing this via `mbfind` would give us less universe polymorphism.
def many {m : Type → Type v} [Monad m] {α : Type u} (p : α → m Bool) : List α → m Bool := sorry
/-- `mall p as` returns true iff `p` returns true for all elements of `l`.
`mall` short-circuits, so if `p` returns false for any element of `l`, later
elements are not checked. This is a monadic version of `list.all`. -/
def mall {m : Type → Type v} [Monad m] {α : Type u} (p : α → m Bool) (as : List α) : m Bool :=
bnot <$> many (fun (a : α) => bnot <$> p a) as
/-- `mbor xs` runs the actions in `xs`, returning true if any of them returns
true. `mbor` short-circuits, so if an action returns true, later actions are
not run. This is a monadic version of `list.bor`. -/
def mbor {m : Type → Type v} [Monad m] : List (m Bool) → m Bool := many id
/-- `mband xs` runs the actions in `xs`, returning true if all of them return
true. `mband` short-circuits, so if an action returns false, later actions are
not run. This is a monadic version of `list.band`. -/
def mband {m : Type → Type v} [Monad m] : List (m Bool) → m Bool := mall id
/-- Auxiliary definition for `foldl_with_index`. -/
def foldl_with_index_aux {α : Type u} {β : Type v} (f : ℕ → α → β → α) : ℕ → α → List β → α := sorry
/-- Fold a list from left to right as with `foldl`, but the combining function
also receives each element's index. -/
def foldl_with_index {α : Type u} {β : Type v} (f : ℕ → α → β → α) (a : α) (l : List β) : α :=
foldl_with_index_aux f 0 a l
/-- Auxiliary definition for `foldr_with_index`. -/
def foldr_with_index_aux {α : Type u} {β : Type v} (f : ℕ → α → β → β) : ℕ → β → List α → β := sorry
/-- Fold a list from right to left as with `foldr`, but the combining function
also receives each element's index. -/
def foldr_with_index {α : Type u} {β : Type v} (f : ℕ → α → β → β) (b : β) (l : List α) : β :=
foldr_with_index_aux f 0 b l
/-- `find_indexes p l` is the list of indexes of elements of `l` that satisfy `p`. -/
def find_indexes {α : Type u} (p : α → Prop) [decidable_pred p] (l : List α) : List ℕ :=
foldr_with_index (fun (i : ℕ) (a : α) (is : List ℕ) => ite (p a) (i :: is) is) [] l
/-- Returns the elements of `l` that satisfy `p` together with their indexes in
`l`. The returned list is ordered by index. -/
def indexes_values {α : Type u} (p : α → Prop) [decidable_pred p] (l : List α) : List (ℕ × α) :=
foldr_with_index (fun (i : ℕ) (a : α) (l : List (ℕ × α)) => ite (p a) ((i, a) :: l) l) [] l
/-- `indexes_of a l` is the list of all indexes of `a` in `l`. For example:
```
indexes_of a [a, b, a, a] = [0, 2, 3]
```
-/
def indexes_of {α : Type u} [DecidableEq α] (a : α) : List α → List ℕ := find_indexes (Eq a)
/-- Monadic variant of `foldl_with_index`. -/
def mfoldl_with_index {m : Type v → Type w} [Monad m] {α : Type u_1} {β : Type v}
(f : ℕ → β → α → m β) (b : β) (as : List α) : m β :=
foldl_with_index
(fun (i : ℕ) (ma : m β) (b : α) =>
do
let a ← ma
f i a b)
(pure b) as
/-- Monadic variant of `foldr_with_index`. -/
def mfoldr_with_index {m : Type v → Type w} [Monad m] {α : Type u_1} {β : Type v}
(f : ℕ → α → β → m β) (b : β) (as : List α) : m β :=
foldr_with_index
(fun (i : ℕ) (a : α) (mb : m β) =>
do
let b ← mb
f i a b)
(pure b) as
/-- Auxiliary definition for `mmap_with_index`. -/
def mmap_with_index_aux {m : Type v → Type w} [Applicative m] {α : Type u_1} {β : Type v}
(f : ℕ → α → m β) : ℕ → List α → m (List β) :=
sorry
/-- Applicative variant of `map_with_index`. -/
def mmap_with_index {m : Type v → Type w} [Applicative m] {α : Type u_1} {β : Type v}
(f : ℕ → α → m β) (as : List α) : m (List β) :=
mmap_with_index_aux f 0 as
/-- Auxiliary definition for `mmap_with_index'`. -/
def mmap_with_index'_aux {m : Type v → Type w} [Applicative m] {α : Type u_1}
(f : ℕ → α → m PUnit) : ℕ → List α → m PUnit :=
sorry
/-- A variant of `mmap_with_index` specialised to applicative actions which
return `unit`. -/
def mmap_with_index' {m : Type v → Type w} [Applicative m] {α : Type u_1} (f : ℕ → α → m PUnit)
(as : List α) : m PUnit :=
mmap_with_index'_aux f 0 as
/-- `lookmap` is a combination of `lookup` and `filter_map`.
`lookmap f l` will apply `f : α → option α` to each element of the list,
replacing `a → b` at the first value `a` in the list such that `f a = some b`. -/
def lookmap {α : Type u} (f : α → Option α) : List α → List α := sorry
/-- `countp p l` is the number of elements of `l` that satisfy `p`. -/
def countp {α : Type u} (p : α → Prop) [decidable_pred p] : List α → ℕ := sorry
/-- `count a l` is the number of occurrences of `a` in `l`. -/
def count {α : Type u} [DecidableEq α] (a : α) : List α → ℕ := countp (Eq a)
/-- `is_prefix l₁ l₂`, or `l₁ <+: l₂`, means that `l₁` is a prefix of `l₂`,
that is, `l₂` has the form `l₁ ++ t` for some `t`. -/
def is_prefix {α : Type u} (l₁ : List α) (l₂ : List α) := ∃ (t : List α), l₁ ++ t = l₂
/-- `is_suffix l₁ l₂`, or `l₁ <:+ l₂`, means that `l₁` is a suffix of `l₂`,
that is, `l₂` has the form `t ++ l₁` for some `t`. -/
def is_suffix {α : Type u} (l₁ : List α) (l₂ : List α) := ∃ (t : List α), t ++ l₁ = l₂
/-- `is_infix l₁ l₂`, or `l₁ <:+: l₂`, means that `l₁` is a contiguous
substring of `l₂`, that is, `l₂` has the form `s ++ l₁ ++ t` for some `s, t`. -/
def is_infix {α : Type u} (l₁ : List α) (l₂ : List α) :=
∃ (s : List α), ∃ (t : List α), s ++ l₁ ++ t = l₂
infixl:50 " <+: " => Mathlib.list.is_prefix
infixl:50 " <:+ " => Mathlib.list.is_suffix
infixl:50 " <:+: " => Mathlib.list.is_infix
/-- `inits l` is the list of initial segments of `l`.
inits [1, 2, 3] = [[], [1], [1, 2], [1, 2, 3]] -/
@[simp] def inits {α : Type u} : List α → List (List α) := sorry
/-- `tails l` is the list of terminal segments of `l`.
tails [1, 2, 3] = [[1, 2, 3], [2, 3], [3], []] -/
@[simp] def tails {α : Type u} : List α → List (List α) := sorry
def sublists'_aux {α : Type u} {β : Type v} :
List α → (List α → List β) → List (List β) → List (List β) :=
sorry
/-- `sublists' l` is the list of all (non-contiguous) sublists of `l`.
It differs from `sublists` only in the order of appearance of the sublists;
`sublists'` uses the first element of the list as the MSB,
`sublists` uses the first element of the list as the LSB.
sublists' [1, 2, 3] = [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]] -/
def sublists' {α : Type u} (l : List α) : List (List α) := sublists'_aux l id []
def sublists_aux {α : Type u} {β : Type v} : List α → (List α → List β → List β) → List β := sorry
/-- `sublists l` is the list of all (non-contiguous) sublists of `l`; cf. `sublists'`
for a different ordering.
sublists [1, 2, 3] = [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] -/
def sublists {α : Type u} (l : List α) : List (List α) := [] :: sublists_aux l List.cons
def sublists_aux₁ {α : Type u} {β : Type v} : List α → (List α → List β) → List β := sorry
/-- `forall₂ R l₁ l₂` means that `l₁` and `l₂` have the same length,
and whenever `a` is the nth element of `l₁`, and `b` is the nth element of `l₂`,
then `R a b` is satisfied. -/
inductive forall₂ {α : Type u} {β : Type v} (R : α → β → Prop) : List α → List β → Prop where
| nil : forall₂ R [] []
| cons :
∀ {a : α} {b : β} {l₁ : List α} {l₂ : List β},
R a b → forall₂ R l₁ l₂ → forall₂ R (a :: l₁) (b :: l₂)
/-- Auxiliary definition used to define `transpose`.
`transpose_aux l L` takes each element of `l` and appends it to the start of
each element of `L`.
`transpose_aux [a, b, c] [l₁, l₂, l₃] = [a::l₁, b::l₂, c::l₃]` -/
def transpose_aux {α : Type u} : List α → List (List α) → List (List α) := sorry
/-- transpose of a list of lists, treated as a matrix.
transpose [[1, 2], [3, 4], [5, 6]] = [[1, 3, 5], [2, 4, 6]] -/
def transpose {α : Type u} : List (List α) → List (List α) := sorry
/-- List of all sections through a list of lists. A section
of `[L₁, L₂, ..., Lₙ]` is a list whose first element comes from
`L₁`, whose second element comes from `L₂`, and so on. -/
def sections {α : Type u} : List (List α) → List (List α) := sorry
def permutations_aux2 {α : Type u} {β : Type v} (t : α) (ts : List α) (r : List β) :
List α → (List α → β) → List α × List β :=
sorry
def permutations_aux.rec {α : Type u} {C : List α → List α → Sort v} (H0 : (is : List α) → C [] is)
(H1 : (t : α) → (ts is : List α) → C ts (t :: is) → C is [] → C (t :: ts) is) (l₁ : List α)
(l₂ : List α) : C l₁ l₂ :=
sorry
def permutations_aux {α : Type u} : List α → List α → List (List α) := sorry
/-- List of all permutations of `l`.
permutations [1, 2, 3] =
[[1, 2, 3], [2, 1, 3], [3, 2, 1],
[2, 3, 1], [3, 1, 2], [1, 3, 2]] -/
def permutations {α : Type u} (l : List α) : List (List α) := l :: permutations_aux l []
/-- `erasep p l` removes the first element of `l` satisfying the predicate `p`. -/
def erasep {α : Type u} (p : α → Prop) [decidable_pred p] : List α → List α := sorry
/-- `extractp p l` returns a pair of an element `a` of `l` satisfying the predicate
`p`, and `l`, with `a` removed. If there is no such element `a` it returns `(none, l)`. -/
def extractp {α : Type u} (p : α → Prop) [decidable_pred p] : List α → Option α × List α := sorry
/-- `revzip l` returns a list of pairs of the elements of `l` paired
with the elements of `l` in reverse order.
`revzip [1,2,3,4,5] = [(1, 5), (2, 4), (3, 3), (4, 2), (5, 1)]`
-/
def revzip {α : Type u} (l : List α) : List (α × α) := zip l (reverse l)
/-- `product l₁ l₂` is the list of pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂`.
product [1, 2] [5, 6] = [(1, 5), (1, 6), (2, 5), (2, 6)] -/
def product {α : Type u} {β : Type v} (l₁ : List α) (l₂ : List β) : List (α × β) :=
list.bind l₁ fun (a : α) => map (Prod.mk a) l₂
/-- `sigma l₁ l₂` is the list of dependent pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂ a`.
sigma [1, 2] (λ_, [(5 : ℕ), 6]) = [(1, 5), (1, 6), (2, 5), (2, 6)] -/
protected def sigma {α : Type u} {σ : α → Type u_1} (l₁ : List α) (l₂ : (a : α) → List (σ a)) :
List (sigma fun (a : α) => σ a) :=
list.bind l₁ fun (a : α) => map (sigma.mk a) (l₂ a)
/-- Auxliary definition used to define `of_fn`.
`of_fn_aux f m h l` returns the first `m` elements of `of_fn f`
appended to `l` -/
def of_fn_aux {α : Type u} {n : ℕ} (f : fin n → α) (m : ℕ) : m ≤ n → List α → List α := sorry
/-- `of_fn f` with `f : fin n → α` returns the list whose ith element is `f i`
`of_fun f = [f 0, f 1, ... , f(n - 1)]` -/
def of_fn {α : Type u} {n : ℕ} (f : fin n → α) : List α := of_fn_aux f n sorry []
/-- `of_fn_nth_val f i` returns `some (f i)` if `i < n` and `none` otherwise. -/
def of_fn_nth_val {α : Type u} {n : ℕ} (f : fin n → α) (i : ℕ) : Option α :=
dite (i < n) (fun (h : i < n) => some (f { val := i, property := h })) fun (h : ¬i < n) => none
/-- `disjoint l₁ l₂` means that `l₁` and `l₂` have no elements in common. -/
def disjoint {α : Type u} (l₁ : List α) (l₂ : List α) := ∀ {a : α}, a ∈ l₁ → a ∈ l₂ → False
/-- `pairwise R l` means that all the elements with earlier indexes are
`R`-related to all the elements with later indexes.
pairwise R [1, 2, 3] ↔ R 1 2 ∧ R 1 3 ∧ R 2 3
For example if `R = (≠)` then it asserts `l` has no duplicates,
and if `R = (<)` then it asserts that `l` is (strictly) sorted. -/
inductive pairwise {α : Type u} (R : α → α → Prop) : List α → Prop where
| nil : pairwise R []
| cons : ∀ {a : α} {l : List α}, (∀ (a' : α), a' ∈ l → R a a') → pairwise R l → pairwise R (a :: l)
@[simp] theorem pairwise_cons {α : Type u} {R : α → α → Prop} {a : α} {l : List α} :
pairwise R (a :: l) ↔ (∀ (a' : α), a' ∈ l → R a a') ∧ pairwise R l :=
sorry
protected instance decidable_pairwise {α : Type u} {R : α → α → Prop} [DecidableRel R]
(l : List α) : Decidable (pairwise R l) :=
List.rec (is_true pairwise.nil)
(fun (hd : α) (tl : List α) (ih : Decidable (pairwise R tl)) =>
decidable_of_iff' ((∀ (a' : α), a' ∈ tl → R hd a') ∧ pairwise R tl) pairwise_cons)
l
/-- `pw_filter R l` is a maximal sublist of `l` which is `pairwise R`.
`pw_filter (≠)` is the erase duplicates function (cf. `erase_dup`), and `pw_filter (<)` finds
a maximal increasing subsequence in `l`. For example,
pw_filter (<) [0, 1, 5, 2, 6, 3, 4] = [0, 1, 2, 3, 4] -/
def pw_filter {α : Type u} (R : α → α → Prop) [DecidableRel R] : List α → List α := sorry
/-- `chain R a l` means that `R` holds between adjacent elements of `a::l`.
chain R a [b, c, d] ↔ R a b ∧ R b c ∧ R c d -/
inductive chain {α : Type u} (R : α → α → Prop) : α → List α → Prop where
| nil : ∀ {a : α}, chain R a []
| cons : ∀ {a b : α} {l : List α}, R a b → chain R b l → chain R a (b :: l)
/-- `chain' R l` means that `R` holds between adjacent elements of `l`.
chain' R [a, b, c, d] ↔ R a b ∧ R b c ∧ R c d -/
def chain' {α : Type u} (R : α → α → Prop) : List α → Prop := sorry
@[simp] theorem chain_cons {α : Type u} {R : α → α → Prop} {a : α} {b : α} {l : List α} :
chain R a (b :: l) ↔ R a b ∧ chain R b l :=
sorry
protected instance decidable_chain {α : Type u} {R : α → α → Prop} [DecidableRel R] (a : α)
(l : List α) : Decidable (chain R a l) :=
List.rec (fun (a : α) => eq.mpr sorry decidable.true)
(fun (l_hd : α) (l_tl : List α) (l_ih : (a : α) → Decidable (chain R a l_tl)) (a : α) =>
eq.mpr sorry and.decidable)
l a
protected instance decidable_chain' {α : Type u} {R : α → α → Prop} [DecidableRel R] (l : List α) :
Decidable (chain' R l) :=
list.cases_on l (id decidable.true)
fun (l_hd : α) (l_tl : List α) => id (list.decidable_chain l_hd l_tl)
/-- `nodup l` means that `l` has no duplicates, that is, any element appears at most
once in the list. It is defined as `pairwise (≠)`. -/
def nodup {α : Type u} : List α → Prop := pairwise ne
protected instance nodup_decidable {α : Type u} [DecidableEq α] (l : List α) :
Decidable (nodup l) :=
list.decidable_pairwise
/-- `erase_dup l` removes duplicates from `l` (taking only the first occurrence).
Defined as `pw_filter (≠)`.
erase_dup [1, 0, 2, 2, 1] = [0, 2, 1] -/
def erase_dup {α : Type u} [DecidableEq α] : List α → List α := pw_filter ne
/-- `range' s n` is the list of numbers `[s, s+1, ..., s+n-1]`.
It is intended mainly for proving properties of `range` and `iota`. -/
@[simp] def range' : ℕ → ℕ → List ℕ := sorry
/-- Drop `none`s from a list, and replace each remaining `some a` with `a`. -/
def reduce_option {α : Type u_1} : List (Option α) → List α := filter_map id
/-- `ilast' x xs` returns the last element of `xs` if `xs` is non-empty;
it returns `x` otherwise -/
@[simp] def ilast' {α : Type u_1} : α → List α → α := sorry
/-- `last' xs` returns the last element of `xs` if `xs` is non-empty;
it returns `none` otherwise -/
@[simp] def last' {α : Type u_1} : List α → Option α := sorry
/-- `rotate l n` rotates the elements of `l` to the left by `n`
rotate [0, 1, 2, 3, 4, 5] 2 = [2, 3, 4, 5, 0, 1] -/
def rotate {α : Type u} (l : List α) (n : ℕ) : List α := sorry
/-- rotate' is the same as `rotate`, but slower. Used for proofs about `rotate`-/
def rotate' {α : Type u} : List α → ℕ → List α := sorry
/-- Given a decidable predicate `p` and a proof of existence of `a ∈ l` such that `p a`,
choose the first element with this property. This version returns both `a` and proofs
of `a ∈ l` and `p a`. -/
def choose_x {α : Type u} (p : α → Prop) [decidable_pred p] (l : List α)
(hp : ∃ (a : α), a ∈ l ∧ p a) : Subtype fun (a : α) => a ∈ l ∧ p a :=
sorry
/-- Given a decidable predicate `p` and a proof of existence of `a ∈ l` such that `p a`,
choose the first element with this property. This version returns `a : α`, and properties
are given by `choose_mem` and `choose_property`. -/
def choose {α : Type u} (p : α → Prop) [decidable_pred p] (l : List α)
(hp : ∃ (a : α), a ∈ l ∧ p a) : α :=
↑(choose_x p l hp)
/-- Filters and maps elements of a list -/
def mmap_filter {m : Type → Type v} [Monad m] {α : Type u_1} {β : Type} (f : α → m (Option β)) :
List α → m (List β) :=
sorry
/--
`mmap_upper_triangle f l` calls `f` on all elements in the upper triangular part of `l × l`.
That is, for each `e ∈ l`, it will run `f e e` and then `f e e'`
for each `e'` that appears after `e` in `l`.
Example: suppose `l = [1, 2, 3]`. `mmap_upper_triangle f l` will produce the list
`[f 1 1, f 1 2, f 1 3, f 2 2, f 2 3, f 3 3]`.
-/
def mmap_upper_triangle {m : Type u → Type u_1} [Monad m] {α : Type u} {β : Type u}
(f : α → α → m β) : List α → m (List β) :=
sorry
/--
`mmap'_diag f l` calls `f` on all elements in the upper triangular part of `l × l`.
That is, for each `e ∈ l`, it will run `f e e` and then `f e e'`
for each `e'` that appears after `e` in `l`.
Example: suppose `l = [1, 2, 3]`. `mmap'_diag f l` will evaluate, in this order,
`f 1 1`, `f 1 2`, `f 1 3`, `f 2 2`, `f 2 3`, `f 3 3`.
-/
def mmap'_diag {m : Type → Type u_1} [Monad m] {α : Type u_2} (f : α → α → m Unit) :
List α → m Unit :=
sorry
protected def traverse {F : Type u → Type v} [Applicative F] {α : Type u_1} {β : Type u}
(f : α → F β) : List α → F (List β) :=
sorry
/-- `get_rest l l₁` returns `some l₂` if `l = l₁ ++ l₂`.
If `l₁` is not a prefix of `l`, returns `none` -/
def get_rest {α : Type u} [DecidableEq α] : List α → List α → Option (List α) := sorry
/--
`list.slice n m xs` removes a slice of length `m` at index `n` in list `xs`.
-/
def slice {α : Type u_1} : ℕ → ℕ → List α → List α := sorry
/--
Left-biased version of `list.map₂`. `map₂_left' f as bs` applies `f` to each
pair of elements `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, `f` is
applied to `none` for the remaining `aᵢ`. Returns the results of the `f`
applications and the remaining `bs`.
```
map₂_left' prod.mk [1, 2] ['a'] = ([(1, some 'a'), (2, none)], [])
map₂_left' prod.mk [1] ['a', 'b'] = ([(1, some 'a')], ['b'])
```
-/
@[simp] def map₂_left' {α : Type u} {β : Type v} {γ : Type w} (f : α → Option β → γ) :
List α → List β → List γ × List β :=
sorry
/--
Right-biased version of `list.map₂`. `map₂_right' f as bs` applies `f` to each
pair of elements `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, `f` is
applied to `none` for the remaining `bᵢ`. Returns the results of the `f`
applications and the remaining `as`.
```
map₂_right' prod.mk [1] ['a', 'b'] = ([(some 1, 'a'), (none, 'b')], [])
map₂_right' prod.mk [1, 2] ['a'] = ([(some 1, 'a')], [2])
```
-/
def map₂_right' {α : Type u} {β : Type v} {γ : Type w} (f : Option α → β → γ) (as : List α)
(bs : List β) : List γ × List α :=
map₂_left' (flip f) bs as
/--
Left-biased version of `list.zip`. `zip_left' as bs` returns the list of
pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, the
remaining `aᵢ` are paired with `none`. Also returns the remaining `bs`.
```
zip_left' [1, 2] ['a'] = ([(1, some 'a'), (2, none)], [])
zip_left' [1] ['a', 'b'] = ([(1, some 'a')], ['b'])
zip_left' = map₂_left' prod.mk
```
-/
def zip_left' {α : Type u} {β : Type v} : List α → List β → List (α × Option β) × List β :=
map₂_left' Prod.mk
/--
Right-biased version of `list.zip`. `zip_right' as bs` returns the list of
pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, the
remaining `bᵢ` are paired with `none`. Also returns the remaining `as`.
```
zip_right' [1] ['a', 'b'] = ([(some 1, 'a'), (none, 'b')], [])
zip_right' [1, 2] ['a'] = ([(some 1, 'a')], [2])
zip_right' = map₂_right' prod.mk
```
-/
def zip_right' {α : Type u} {β : Type v} : List α → List β → List (Option α × β) × List α :=
map₂_right' Prod.mk
/--
Left-biased version of `list.map₂`. `map₂_left f as bs` applies `f` to each pair
`aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, `f` is applied to `none`
for the remaining `aᵢ`.
```
map₂_left prod.mk [1, 2] ['a'] = [(1, some 'a'), (2, none)]
map₂_left prod.mk [1] ['a', 'b'] = [(1, some 'a')]
map₂_left f as bs = (map₂_left' f as bs).fst
```
-/
@[simp] def map₂_left {α : Type u} {β : Type v} {γ : Type w} (f : α → Option β → γ) :
List α → List β → List γ :=
sorry
/--
Right-biased version of `list.map₂`. `map₂_right f as bs` applies `f` to each
pair `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, `f` is applied to
`none` for the remaining `bᵢ`.
```
map₂_right prod.mk [1, 2] ['a'] = [(some 1, 'a')]
map₂_right prod.mk [1] ['a', 'b'] = [(some 1, 'a'), (none, 'b')]
map₂_right f as bs = (map₂_right' f as bs).fst
```
-/
def map₂_right {α : Type u} {β : Type v} {γ : Type w} (f : Option α → β → γ) (as : List α)
(bs : List β) : List γ :=
map₂_left (flip f) bs as
/--
Left-biased version of `list.zip`. `zip_left as bs` returns the list of pairs
`(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, the
remaining `aᵢ` are paired with `none`.
```
zip_left [1, 2] ['a'] = [(1, some 'a'), (2, none)]
zip_left [1] ['a', 'b'] = [(1, some 'a')]
zip_left = map₂_left prod.mk
```
-/
def zip_left {α : Type u} {β : Type v} : List α → List β → List (α × Option β) := map₂_left Prod.mk
/--
Right-biased version of `list.zip`. `zip_right as bs` returns the list of pairs
`(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, the
remaining `bᵢ` are paired with `none`.
```
zip_right [1, 2] ['a'] = [(some 1, 'a')]
zip_right [1] ['a', 'b'] = [(some 1, 'a'), (none, 'b')]
zip_right = map₂_right prod.mk
```
-/
def zip_right {α : Type u} {β : Type v} : List α → List β → List (Option α × β) :=
map₂_right Prod.mk
/--
If all elements of `xs` are `some xᵢ`, `all_some xs` returns the `xᵢ`. Otherwise
it returns `none`.
```
all_some [some 1, some 2] = some [1, 2]
all_some [some 1, none ] = none
```
-/
def all_some {α : Type u} : List (Option α) → Option (List α) := sorry
/--
`fill_nones xs ys` replaces the `none`s in `xs` with elements of `ys`. If there
are not enough `ys` to replace all the `none`s, the remaining `none`s are
dropped from `xs`.
```
fill_nones [none, some 1, none, none] [2, 3] = [2, 1, 3]
```
-/
def fill_nones {α : Type u_1} : List (Option α) → List α → List α := sorry
/--
`take_list as ns` extracts successive sublists from `as`. For `ns = n₁ ... nₘ`,
it first takes the `n₁` initial elements from `as`, then the next `n₂` ones,
etc. It returns the sublists of `as` -- one for each `nᵢ` -- and the remaining
elements of `as`. If `as` does not have at least as many elements as the sum of
the `nᵢ`, the corresponding sublists will have less than `nᵢ` elements.
```
take_list ['a', 'b', 'c', 'd', 'e'] [2, 1, 1] = ([['a', 'b'], ['c'], ['d']], ['e'])
take_list ['a', 'b'] [3, 1] = ([['a', 'b'], []], [])
```
-/
def take_list {α : Type u_1} : List α → List ℕ → List (List α) × List α := sorry
/--
`to_rbmap as` is the map that associates each index `i` of `as` with the
corresponding element of `as`.
```
to_rbmap ['a', 'b', 'c'] = rbmap_of [(0, 'a'), (1, 'b'), (2, 'c')]
```
-/
def to_rbmap {α : Type u} : List α → rbmap ℕ α :=
foldl_with_index (fun (i : ℕ) (mapp : rbmap ℕ α) (a : α) => rbmap.insert mapp i a) (mk_rbmap ℕ α)
end Mathlib |
299aa743a424197e79d5371dcddcc6f5e9b78b18 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/control/equiv_functor/instances.lean | c21408022ba9c6d2b9873a5bc48e15e73e69c668 | [] | 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,336 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Scott Morrison
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.fintype.basic
import Mathlib.control.equiv_functor
import Mathlib.PostPort
universes u_1
namespace Mathlib
/-!
# `equiv_functor` instances
We derive some `equiv_functor` instances, to enable `equiv_rw` to rewrite under these functions.
-/
protected instance equiv_functor_unique : equiv_functor unique :=
equiv_functor.mk fun (α β : Type u_1) (e : α ≃ β) => ⇑(equiv.unique_congr e)
protected instance equiv_functor_perm : equiv_functor equiv.perm :=
equiv_functor.mk fun (α β : Type u_1) (e : α ≃ β) (p : equiv.perm α) => equiv.trans (equiv.trans (equiv.symm e) p) e
-- There is a classical instance of `is_lawful_functor finset` available,
-- but we provide this computable alternative separately.
protected instance equiv_functor_finset : equiv_functor finset :=
equiv_functor.mk fun (α β : Type u_1) (e : α ≃ β) (s : finset α) => finset.map (equiv.to_embedding e) s
protected instance equiv_functor_fintype : equiv_functor fintype :=
equiv_functor.mk fun (α β : Type u_1) (e : α ≃ β) (s : fintype α) => fintype.of_bijective (⇑e) (equiv.bijective e)
|
32908b5b965a48dbe72a7f50c692bdf458e46b05 | aa5a655c05e5359a70646b7154e7cac59f0b4132 | /stage0/src/Lean/Meta/Tactic/Assert.lean | 66eeb63ae95c3509213a92502f29ff2e33605392 | [
"Apache-2.0"
] | permissive | lambdaxymox/lean4 | ae943c960a42247e06eff25c35338268d07454cb | 278d47c77270664ef29715faab467feac8a0f446 | refs/heads/master | 1,677,891,867,340 | 1,612,500,005,000 | 1,612,500,005,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,046 | 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.Tactic.Util
import Lean.Meta.Tactic.FVarSubst
import Lean.Meta.Tactic.Intro
import Lean.Meta.Tactic.Revert
namespace Lean.Meta
/--
Convert the given goal `Ctx |- target` into `Ctx |- type -> target`.
It assumes `val` has type `type` -/
def assert (mvarId : MVarId) (name : Name) (type : Expr) (val : Expr) : MetaM MVarId :=
withMVarContext mvarId do
checkNotAssigned mvarId `assert
let tag ← getMVarTag mvarId
let target ← getMVarType mvarId
let newType := Lean.mkForall name BinderInfo.default type target
let newMVar ← mkFreshExprSyntheticOpaqueMVar newType tag
assignExprMVar mvarId (mkApp newMVar val)
pure newMVar.mvarId!
/--
Convert the given goal `Ctx |- target` into `Ctx |- let name : type := val; target`.
It assumes `val` has type `type` -/
def define (mvarId : MVarId) (name : Name) (type : Expr) (val : Expr) : MetaM MVarId := do
withMVarContext mvarId do
checkNotAssigned mvarId `define
let tag ← getMVarTag mvarId
let target ← getMVarType mvarId
let newType := Lean.mkLet name type val target
let newMVar ← mkFreshExprSyntheticOpaqueMVar newType tag
assignExprMVar mvarId newMVar
pure newMVar.mvarId!
/--
Convert the given goal `Ctx |- target` into `Ctx |- (hName : type) -> hName = val -> target`.
It assumes `val` has type `type` -/
def assertExt (mvarId : MVarId) (name : Name) (type : Expr) (val : Expr) (hName : Name := `h) : MetaM MVarId := do
withMVarContext mvarId do
checkNotAssigned mvarId `assert
let tag ← getMVarTag mvarId
let target ← getMVarType mvarId
let u ← getLevel type
let hType := mkApp3 (mkConst `Eq [u]) type (mkBVar 0) val
let newType := Lean.mkForall name BinderInfo.default type $ Lean.mkForall hName BinderInfo.default hType target
let newMVar ← mkFreshExprSyntheticOpaqueMVar newType tag
let rflPrf ← mkEqRefl val
assignExprMVar mvarId (mkApp2 newMVar val rflPrf)
pure newMVar.mvarId!
structure AssertAfterResult where
fvarId : FVarId
mvarId : MVarId
subst : FVarSubst
/--
Convert the given goal `Ctx |- target` into a goal containing `(userName : type)` after the local declaration with if `fvarId`.
It assumes `val` has type `type`, and that `type` is well-formed after `fvarId`.
Note that `val` does not need to be well-formed after `fvarId`. That is, it may contain variables that are defined after `fvarId`. -/
def assertAfter (mvarId : MVarId) (fvarId : FVarId) (userName : Name) (type : Expr) (val : Expr) : MetaM AssertAfterResult := do
withMVarContext mvarId do
checkNotAssigned mvarId `assertAfter
let tag ← getMVarTag mvarId
let target ← getMVarType mvarId
let localDecl ← getLocalDecl fvarId
let lctx ← getLCtx
let localInsts ← getLocalInstances
let fvarIds := lctx.foldl (init := #[]) (start := localDecl.index+1) fun fvarIds decl => fvarIds.push decl.fvarId
let xs := fvarIds.map mkFVar
let targetNew ← mkForallFVars xs target
let targetNew := Lean.mkForall userName BinderInfo.default type targetNew
let lctxNew := fvarIds.foldl (init := lctx) fun lctxNew fvarId => lctxNew.erase fvarId
let localInstsNew := localInsts.filter fun inst => !fvarIds.contains inst.fvar.fvarId!
let mvarNew ← mkFreshExprMVarAt lctxNew localInstsNew targetNew MetavarKind.syntheticOpaque tag
let args := (fvarIds.filter fun fvarId => !(lctx.get! fvarId).isLet).map mkFVar
let args := #[val] ++ args
assignExprMVar mvarId (mkAppN mvarNew args)
let (fvarIdNew, mvarIdNew) ← intro1P mvarNew.mvarId!
let (fvarIdsNew, mvarIdNew) ← introNP mvarIdNew fvarIds.size
let subst := fvarIds.size.fold (init := {}) fun i subst => subst.insert fvarIds[i] (mkFVar fvarIdsNew[i])
pure { fvarId := fvarIdNew, mvarId := mvarIdNew, subst := subst }
end Lean.Meta
|
0c7ccd998d036efe851cf3efa1aef4c88a8968ea | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Init/Data/Char.lean | dc2257bbfe08b2353210792c07dcb17bfdd5649c | [
"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 | 200 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Data.Char.Basic
|
eabd79d1916a6e5b58c72cc38ad51f002829b296 | fecda8e6b848337561d6467a1e30cf23176d6ad0 | /src/topology/sheaves/forget.lean | 69337c740148abe3ce93be36561220da08c17e83 | [
"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 | 8,035 | 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 topology.sheaves.sheaf
import category_theory.limits.preserves.shapes
import category_theory.limits.types
/-!
# Checking the sheaf condition on the underlying presheaf of types.
If `G : C ⥤ D` is a functor which reflects isomorphisms and preserves limits
(we assume all limits exist in both `C` and `D`),
then checking the sheaf condition for a presheaf `F : presheaf C X`
is equivalent to checking the sheaf condition for `F ⋙ G`.
The important special case is when
`C` is a concrete category with a forgetful functor
that preserves limits and reflects isomorphisms.
Then to check the sheaf condition it suffices
to check it on the underlying sheaf of types.
## References
* https://stacks.math.columbia.edu/tag/0073
-/
noncomputable theory
open category_theory
open category_theory.limits
open topological_space
open opposite
namespace Top
namespace sheaf_condition
universes v u₁ u₂
variables {C : Type u₁} [category.{v} C] [has_limits C]
variables {D : Type u₂} [category.{v} D] [has_limits D]
variables (G : C ⥤ D) [preserves_limits G]
variables {X : Top.{v}} (F : presheaf C X)
variables {ι : Type v} (U : ι → opens X)
local attribute [reducible] sheaf_condition.diagram
local attribute [reducible] sheaf_condition.left_res sheaf_condition.right_res
/--
When `G` preserves limits, the sheaf condition diagram for `F` composed with `G` is
naturally isomorphic to the sheaf condition diagram for `F ⋙ G`.
-/
def diagram_comp_preserves_limits :
sheaf_condition.diagram F U ⋙ G ≅ sheaf_condition.diagram (F ⋙ G) U :=
begin
fapply nat_iso.of_components,
rintro ⟨j⟩,
exact (preserves_products_iso _ _),
exact (preserves_products_iso _ _),
rintros ⟨⟩ ⟨⟩ ⟨⟩,
{ ext, simp, dsimp, simp, }, -- non-terminal `simp`, but `squeeze_simp` fails
{ ext,
simp only [limit.lift_π, functor.comp_map, parallel_pair_map_left, fan.mk_π_app,
map_lift_comp_preserves_products_iso_hom, functor.map_comp, category.assoc],
dsimp, simp, },
{ ext,
simp only [limit.lift_π, functor.comp_map, parallel_pair_map_right, fan.mk_π_app,
map_lift_comp_preserves_products_iso_hom, functor.map_comp, category.assoc],
dsimp, simp, },
{ ext, simp, dsimp, simp, },
end
local attribute [reducible] sheaf_condition.res
/--
When `G` preserves limits, the image under `G` of the sheaf condition fork for `F`
is the sheaf condition fork for `F ⋙ G`,
postcomposed with the inverse of the natural isomorphism `diagram_comp_preserves_limits`.
-/
def map_cone_fork : G.map_cone (sheaf_condition.fork F U) ≅
(cones.postcompose (diagram_comp_preserves_limits G F U).inv).obj
(sheaf_condition.fork (F ⋙ G) U) :=
cones.ext (iso.refl _) (λ j,
begin
dsimp, simp [diagram_comp_preserves_limits], cases j; dsimp,
{ rw iso.eq_comp_inv,
ext,
simp, dsimp, simp, },
{ rw iso.eq_comp_inv,
ext,
simp, -- non-terminal `simp`, but `squeeze_simp` fails
dsimp,
simp only [limit.lift_π, fan.mk_π_app, ←G.map_comp, limit.lift_π_assoc, fan.mk_π_app] }
end)
end sheaf_condition
universes v u₁ u₂
open sheaf_condition
variables {C : Type u₁} [category.{v} C] {D : Type u₂} [category.{v} D]
variables (G : C ⥤ D)
variables [reflects_isomorphisms G]
variables [has_limits C] [has_limits D] [preserves_limits G]
variables {X : Top.{v}} (F : presheaf C X)
/--
If `G : C ⥤ D` is a functor which reflects isomorphisms and preserves limits
(we assume all limits exist in both `C` and `D`),
then checking the sheaf condition for a presheaf `F : presheaf C X`
is equivalent to checking the sheaf condition for `F ⋙ G`.
The important special case is when
`C` is a concrete category with a forgetful functor
that preserves limits and reflects isomorphisms.
Then to check the sheaf condition it suffices to check it on the underlying sheaf of types.
Another useful example is the forgetful functor `TopCommRing ⥤ Top`.
See https://stacks.math.columbia.edu/tag/0073.
In fact we prove a stronger version with arbitrary complete target category.
-/
def sheaf_condition_equiv_sheaf_condition_comp :
sheaf_condition F ≃ sheaf_condition (F ⋙ G) :=
begin
apply equiv_of_subsingleton_of_subsingleton,
{ intros S ι U,
-- We have that the sheaf condition fork for `F` is a limit fork,
have t₁ := S U,
-- and since `G` preserves limits, the image under `G` of this fork is a limit fork too.
have t₂ := @preserves_limit.preserves _ _ _ _ _ _ _ G _ _ t₁,
-- As we established above, that image is just the sheaf condition fork
-- for `F ⋙ G` postcomposed with some natural isomorphism,
have t₃ := is_limit.of_iso_limit t₂ (map_cone_fork G F U),
-- and as postcomposing by a natural isomorphism preserves limit cones,
have t₄ := is_limit.postcompose_inv_equiv _ _ t₃,
-- we have our desired conclusion.
exact t₄, },
{ intros S ι U,
-- Let `f` be the universal morphism from `F.obj U` to the equalizer of the sheaf condition fork,
-- whatever it is. Our goal is to show that this is an isomorphism.
let f := equalizer.lift _ (w F U),
-- If we can do that,
suffices : is_iso (G.map f),
{ resetI,
-- we have that `f` itself is an isomorphism, since `G` reflects isomorphisms
haveI : is_iso f := is_iso_of_reflects_iso f G,
-- TODO package this up as a result elsewhere:
apply is_limit.of_iso_limit (limit.is_limit _),
apply iso.symm,
fapply cones.ext,
exact (as_iso f),
rintro ⟨_|_⟩; { dsimp [f], simp, }, },
{ -- Returning to the task of shwoing that `G.map f` is an isomorphism,
-- we note that `G.map f` is almost but not quite (see below) a morphism
-- from the sheaf condition cone for `F ⋙ G` to the
-- image under `G` of the equalizer cone for the sheaf condition diagram.
let c := sheaf_condition.fork (F ⋙ G) U,
have hc : is_limit c := S U,
let d := G.map_cone (equalizer.fork (left_res F U) (right_res F U)),
have hd : is_limit d := preserves_limit.preserves (limit.is_limit _),
-- Since both of these are limit cones
-- (`c` by our hypothesis `S`, and `d` because `G` preserves limits),
-- we hope to be able to conclude that `f` is an isomorphism.
-- We say "not quite" above because `c` and `d` don't quite have the same shape:
-- we need to postcompose by the natural isomorphism `diagram_comp_preserves_limits`
-- introduced above.
let d' := (cones.postcompose (diagram_comp_preserves_limits G F U).hom).obj d,
have hd' : is_limit d' :=
(is_limit.postcompose_hom_equiv (diagram_comp_preserves_limits G F U) d).symm hd,
-- Now everything works: we verify that `f` really is a morphism between these cones:
let f' : c ⟶ d' :=
fork.mk_hom (G.map f)
begin
dsimp only [c, d, d', f, diagram_comp_preserves_limits, res],
dunfold fork.ι,
ext1 j,
dsimp,
simp only [category.assoc, ←functor.map_comp_assoc, equalizer.lift_ι,
map_lift_comp_preserves_products_iso_hom_assoc],
dsimp [res], simp,
end,
-- conclude that it is an isomorphism,
-- just because it's a morphism between two limit cones.
haveI : is_iso f' := is_limit.hom_is_iso hc hd' f',
-- A cone morphism is an isomorphism exactly if the morphism between the cone points is,
-- so we're done!
exact { ..((cones.forget _).map_iso (as_iso f')) }, }, },
end
/-!
As an example, we now have everything we need to check the sheaf condition
for a presheaf of commutative rings, merely by checking the sheaf condition
for the underlying sheaf of types.
```
example (X : Top) (F : presheaf CommRing X) (h : sheaf_condition (F ⋙ (forget CommRing))) :
sheaf_condition F :=
(sheaf_condition_equiv_sheaf_condition_forget F).symm h
```
-/
end Top
|
5ff96a9da982d12d26830640b712004af38965ca | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /test/continuity.lean | ff2a2633c2acf1a966e64d8ba57cc92dc3705182 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 2,268 | lean | import topology.tactic
import topology.algebra.monoid
import topology.instances.real
import analysis.special_functions.trigonometric.basic
example {X Y : Type*} [topological_space X] [topological_space Y]
(f₁ f₂ : X → Y) (hf₁ : continuous f₁) (hf₂ : continuous f₂)
(g : Y → ℝ) (hg : continuous g) : continuous (λ x, (max (g (f₁ x)) (g (f₂ x))) + 1) :=
by guard_proof_term { continuity } ((hg.comp hf₁).max (hg.comp hf₂)).add continuous_const
example {κ ι : Type}
(K : κ → Type) [∀ k, topological_space (K k)] (I : ι → Type) [∀ i, topological_space (I i)]
(e : κ ≃ ι) (F : Π k, homeomorph (K k) (I (e k))) :
continuous (λ (f : Π k, K k) (i : ι), F (e.symm i) (f (e.symm i))) :=
by guard_proof_term { continuity }
@continuous_pi _ _ _ _ _ (λ (f : Π k, K k) i, (F (e.symm i)) (f (e.symm i)))
(λ (i : ι), ((F (e.symm i)).continuous).comp (continuous_apply (e.symm i)))
open real
local attribute [continuity] continuous_exp continuous_sin continuous_cos
example : continuous (λ x : ℝ, exp ((max x (-x)) + sin x)^2) :=
by guard_proof_term { continuity }
(continuous_exp.comp ((continuous_id.max continuous_id.neg).add continuous_sin)).pow 2
example : continuous (λ x : ℝ, exp ((max x (-x)) + sin (cos x))^2) :=
by guard_proof_term { continuity }
(continuous_exp.comp ((continuous_id'.max continuous_id'.neg).add (continuous_sin.comp continuous_cos))).pow 2
-- Without `md := semireducible` in the call to `apply_rules` in `continuity`,
-- this last example would have run off the rails:
-- ```
-- example : continuous (λ x : ℝ, exp ((max x (-x)) + sin (cos x))^2) :=
-- by show_term { continuity! }
-- ```
-- produces lots of subgoals, including many copies of
-- ⊢ continuous complex.re
-- ⊢ continuous complex.exp
-- ⊢ continuous coe
-- ⊢ continuous (λ (x : ℝ), ↑x)
/-! Some tests of the `comp_of_eq` lemmas -/
example {α β : Type*} [topological_space α] [topological_space β] {x₀ : α} (f : α → α → β)
(hf : continuous_at (function.uncurry f) (x₀, x₀)) :
continuous_at (λ x, f x x) x₀ :=
begin
success_if_fail { exact hf.comp x (continuous_at_id.prod continuous_at_id) },
exact hf.comp_of_eq (continuous_at_id.prod continuous_at_id) rfl
end
|
6d765d318a16fb232a1f4adb6a83f858e64c5011 | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /tests/lean/run/nat_bug6.lean | c5470bff9132a3ec2cd82ca39012e810e08e2d45 | [
"Apache-2.0"
] | permissive | codyroux/lean | 7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3 | 0cca265db19f7296531e339192e9b9bae4a31f8b | refs/heads/master | 1,610,909,964,159 | 1,407,084,399,000 | 1,416,857,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 475 | lean | import standard
using eq_proofs
inductive nat : Type :=
zero : nat,
succ : nat → nat
namespace nat
definition add (x y : nat) : nat := nat.rec x (λn r, succ r) y
infixl `+` := add
definition mul (n m : nat) := nat.rec zero (fun m x, x + n) m
infixl `*` := mul
axiom mul_zero_right (n : nat) : n * zero = zero
constant P : nat → Prop
print "==========================="
theorem tst (n : nat) (H : P (n * zero)) : P zero
:= eq.subst (mul_zero_right _) H
end nat
exit
|
956ecaceee4e36be264a7efc1ffbd6465fdbed97 | 704c0b4221e71a413a9270e3160af0813f426c91 | /scratch/LP_operations.lean | d26d8f2a4e7cf589e075e24cd125977f215a1da4 | [] | no_license | CohenCyril/LP | d39b766199d2176b592ff223f9c00cdcb4d5f76d | 4dca829aa0fe94c0627410b88d9dad54e6ed2c63 | refs/heads/master | 1,596,132,000,357 | 1,568,817,913,000 | 1,568,817,913,000 | 210,310,499 | 0 | 0 | null | 1,569,229,479,000 | 1,569,229,479,000 | null | UTF-8 | Lean | false | false | 43,162 | lean | import data.matrix.pequiv data.rat.basic tactic.fin_cases data.list.min_max .partition2
open matrix fintype finset function pequiv
local notation `rvec`:2000 n := matrix (fin 1) (fin n) ℚ
local notation `cvec`:2000 m := matrix (fin m) (fin 1) ℚ
local infix ` ⬝ `:70 := matrix.mul
local postfix `ᵀ` : 1500 := transpose
section
universes u v
variables {l m n o : Type u} [fintype l] [fintype m] [fintype n] [fintype o] {R : Type v}
/- Belongs in mathlib -/
lemma mul_right_eq_of_mul_eq [semiring R] {M : matrix l m R} {N : matrix m n R} {O : matrix l n R}
{P : matrix n o R} (h : M ⬝ N = O) : M ⬝ (N ⬝ P) = O ⬝ P :=
by rw [← matrix.mul_assoc, h]
end
variables {m n : ℕ}
/-- The tableau consists of a matrix and a constant `offset` column.
`to_partition` stores the indices of the current row and column variables.
`restricted` is the set of variables that are restricted to be nonnegative -/
structure tableau (m n : ℕ) :=
(to_matrix : matrix (fin m) (fin n) ℚ)
(offset : cvec m)
(to_partition : partition m n)
(restricted : finset (fin (m + n)))
namespace tableau
open partition
section predicates
variable (T : tableau m n)
/-- The affine subspace represented by the tableau ignoring nonnegativity restrictiions -/
def flat : set (cvec (m + n)) := { x | T.to_partition.rowp.to_matrix ⬝ x =
T.to_matrix ⬝ T.to_partition.colp.to_matrix ⬝ x + T.offset }
/-- The sol_set is the subset of ℚ^(m+n) that satisifies the tableau -/
def sol_set : set (cvec (m + n)) := flat T ∩ { x | ∀ i, i ∈ T.restricted → 0 ≤ x i 0 }
/-- Predicate for a variable being unbounded above in the `sol_set` -/
def is_unbounded_above (i : fin (m + n)) : Prop :=
∀ q : ℚ, ∃ x : cvec (m + n), x ∈ sol_set T ∧ q ≤ x i 0
/-- Predicate for a variable being unbounded below in the `sol_set` -/
def is_unbounded_below (i : fin (m + n)) : Prop :=
∀ q : ℚ, ∃ x : cvec (m + n), x ∈ sol_set T ∧ x i 0 ≤ q
def is_maximised (x : cvec (m + n)) (i : fin (m + n)) : Prop :=
∀ y : cvec (m + n), y ∈ sol_set T → y i 0 ≤ x i 0
/-- Is this equivalent to `∀ (x : cvec (m + n)), x ∈ sol_set T → x i 0 = x j 0`? No -/
def equal_in_flat (i j : fin (m + n)) : Prop :=
∀ (x : cvec (m + n)), x ∈ flat T → x i 0 = x j 0
/-- Returns an element of the `flat` after assigning values to the column variables -/
def of_col (T : tableau m n) (x : cvec n) : cvec (m + n) :=
T.to_partition.colp.to_matrixᵀ ⬝ x + T.to_partition.rowp.to_matrixᵀ ⬝
(T.to_matrix ⬝ x + T.offset)
/-- A `tableau` is feasible if its `offset` column is nonnegative in restricted rows -/
def feasible : Prop :=
∀ i, T.to_partition.rowg i ∈ T.restricted → 0 ≤ T.offset i 0
/-- Given a row index `r` and a column index `s` it returns a tableau with `r` and `s` switched,
but with the same `sol_set` -/
def pivot (r : fin m) (c : fin n) : tableau m n :=
let p := (T.to_matrix r c)⁻¹ in
{ to_matrix := λ i j,
if i = r
then if j = c
then p
else -T.to_matrix r j * p
else if j = c
then T.to_matrix i c * p
else T.to_matrix i j - T.to_matrix i c * T.to_matrix r j * p,
to_partition := T.to_partition.swap r c,
offset := λ i k,
if i = r
then -T.offset r k * p
else T.offset i k - T.to_matrix i c * T.offset r k * p,
restricted := T.restricted }
end predicates
section predicate_lemmas
variable {T : tableau m n}
lemma mem_flat_iff {x : cvec (m + n)} : x ∈ T.flat ↔
∀ r, x (T.to_partition.rowg r) 0 = univ.sum
(λ c : fin n, T.to_matrix r c * x (T.to_partition.colg c) 0) +
T.offset r 0 :=
have hx : x ∈ T.flat ↔ ∀ i, (T.to_partition.rowp.to_matrix ⬝ x) i 0 =
(T.to_matrix ⬝ T.to_partition.colp.to_matrix ⬝ x + T.offset) i 0,
by rw [flat, set.mem_set_of_eq, matrix.ext_iff.symm, forall_swap,
unique.forall_iff];
refl,
begin
rw hx,
refine forall_congr (λ i, _),
rw [mul_matrix_apply, add_val, rowp_eq_some_rowg, matrix.mul_assoc, matrix.mul],
conv in (T.to_matrix _ _ * (T.to_partition.colp.to_matrix ⬝ x) _ _)
{ rw [mul_matrix_apply, colp_eq_some_colg] },
end
variable (T)
@[simp] lemma colp_mul_of_col (x : cvec n) :
T.to_partition.colp.to_matrix ⬝ of_col T x = x :=
by simp [matrix.mul_assoc, matrix.mul_add, of_col, flat,
mul_right_eq_of_mul_eq (rowp_mul_colp_transpose _),
mul_right_eq_of_mul_eq (rowp_mul_rowp_transpose _),
mul_right_eq_of_mul_eq (colp_mul_colp_transpose _),
mul_right_eq_of_mul_eq (colp_mul_rowp_transpose _)]
@[simp] lemma rowp_mul_of_col (x : cvec n) :
T.to_partition.rowp.to_matrix ⬝ of_col T x = T.to_matrix ⬝ x + T.offset :=
by simp [matrix.mul_assoc, matrix.mul_add, of_col, flat,
mul_right_eq_of_mul_eq (rowp_mul_colp_transpose _),
mul_right_eq_of_mul_eq (rowp_mul_rowp_transpose _),
mul_right_eq_of_mul_eq (colp_mul_colp_transpose _),
mul_right_eq_of_mul_eq (colp_mul_rowp_transpose _)]
lemma of_col_mem_flat (x : cvec n) : T.of_col x ∈ T.flat :=
by simp [matrix.mul_assoc, matrix.mul_add, flat]
@[simp] lemma of_col_colg (x : cvec n) (c : fin n) :
of_col T x (T.to_partition.colg c) = x c :=
funext $ λ v,
calc of_col T x (T.to_partition.colg c) v =
(T.to_partition.colp.to_matrix ⬝ of_col T x) c v :
by rw [mul_matrix_apply, colp_eq_some_colg]
... = x c v : by rw [colp_mul_of_col]
@[simp] lemma of_col_rowg (c : cvec n) (r : fin m) :
of_col T c (T.to_partition.rowg r) = (T.to_matrix ⬝ c + T.offset) r :=
funext $ λ v,
calc of_col T c (T.to_partition.rowg r) v =
(T.to_partition.rowp.to_matrix ⬝ of_col T c) r v :
by rw [mul_matrix_apply, rowp_eq_some_rowg]
... = (T.to_matrix ⬝ c + T.offset) r v : by rw [rowp_mul_of_col]
variable {T}
/-- Condition for the solution given by setting column index `j` to `q` and all other columns to
zero being in the `sol_set` -/
lemma of_col_single_mem_sol_set {q : ℚ} {c : fin n} (hT : T.feasible)
(hi : ∀ i, T.to_partition.rowg i ∈ T.restricted → 0 ≤ q * T.to_matrix i c)
(hj : T.to_partition.colg c ∉ T.restricted ∨ 0 ≤ q) :
T.of_col (q • (single c 0).to_matrix) ∈ T.sol_set :=
⟨of_col_mem_flat _ _,
λ v, (T.to_partition.eq_rowg_or_colg v).elim
begin
rintros ⟨r, hr⟩ hres,
subst hr,
rw [of_col_rowg, add_val, matrix.mul_smul, smul_val, matrix_mul_apply,
symm_single, single_apply],
exact add_nonneg (hi _ hres) (hT _ hres)
end
begin
rintros ⟨j, hj⟩ hres,
subst hj,
simp [of_col_colg, smul_val, pequiv.single, pequiv.to_matrix],
by_cases hjc : j = c; simp [*, le_refl] at *
end⟩
lemma feasible_iff_of_col_zero_mem_sol_set : T.feasible ↔ T.of_col 0 ∈ T.sol_set :=
suffices (∀ i : fin m, T.to_partition.rowg i ∈ T.restricted → 0 ≤ T.offset i 0) ↔
∀ v : fin (m + n), v ∈ T.restricted → (0 : ℚ) ≤ T.of_col 0 v 0,
by simpa [sol_set, feasible, of_col_mem_flat],
⟨λ h v hv, (T.to_partition.eq_rowg_or_colg v).elim
(by rintros ⟨i, hi⟩; subst hi; simp; tauto)
(by rintros ⟨j, hj⟩; subst hj; simp),
λ h i hi, by simpa using h _ hi⟩
lemma is_unbounded_above_colg_aux {c : fin n} (hT : T.feasible)
(h : ∀ i : fin m, T.to_partition.rowg i ∈ T.restricted → 0 ≤ T.to_matrix i c) (q : ℚ):
of_col T (max q 0 • (single c 0).to_matrix) ∈ sol_set T ∧
q ≤ of_col T (max q 0 • (single c 0).to_matrix) (T.to_partition.colg c) 0 :=
⟨of_col_single_mem_sol_set hT (λ i hi, mul_nonneg (le_max_right _ _) (h _ hi))
(or.inr (le_max_right _ _)),
by simp [of_col_colg, smul_val, pequiv.single, pequiv.to_matrix, le_refl q]⟩
/-- A column variable is unbounded above if it is in a column where every negative entry is
in a row owned by an unrestricted variable -/
lemma is_unbounded_above_colg {c : fin n} (hT : T.feasible)
(h : ∀ i : fin m, T.to_partition.rowg i ∈ T.restricted → 0 ≤ T.to_matrix i c) :
T.is_unbounded_above (T.to_partition.colg c) :=
λ q, ⟨_, is_unbounded_above_colg_aux hT h q⟩
lemma is_unbounded_below_colg_aux {c : fin n} (hT : T.feasible)
(hres : T.to_partition.colg c ∉ T.restricted)
(h : ∀ i : fin m, T.to_partition.rowg i ∈ T.restricted → T.to_matrix i c ≤ 0) (q : ℚ) :
of_col T (min q 0 • (single c 0).to_matrix) ∈ sol_set T ∧
of_col T (min q 0 • (single c 0).to_matrix) (T.to_partition.colg c) 0 ≤ q :=
⟨of_col_single_mem_sol_set hT
(λ i hi, mul_nonneg_of_nonpos_of_nonpos (min_le_right _ _) (h _ hi))
(or.inl hres),
by simp [of_col_colg, smul_val, pequiv.single, pequiv.to_matrix, le_refl q]⟩
/-- A column variable is unbounded below if it is unrestricted and it is in a column where every
positive entry is in a row owned by an unrestricted variable -/
lemma is_unbounded_below_colg {c : fin n} (hT : T.feasible)
(hres : T.to_partition.colg c ∉ T.restricted)
(h : ∀ i : fin m, T.to_partition.rowg i ∈ T.restricted → T.to_matrix i c ≤ 0) :
T.is_unbounded_below (T.to_partition.colg c) :=
λ q, ⟨_, is_unbounded_below_colg_aux hT hres h q⟩
/-- A row variable `r` is unbounded above if it is unrestricted and there is a column `s`
where every restricted row variable has a nonpositive entry in that column, and
`r` has a negative entry in that column. -/
lemma is_unbounded_above_rowg_of_nonpos {r : fin m} (hT : T.feasible) (s : fin n)
(hres : T.to_partition.colg s ∉ T.restricted)
(h : ∀ i : fin m, T.to_partition.rowg i ∈ T.restricted → T.to_matrix i s ≤ 0)
(his : T.to_matrix r s < 0) : is_unbounded_above T (T.to_partition.rowg r) :=
λ q, ⟨T.of_col (min ((q - T.offset r 0) / T.to_matrix r s) 0 • (single s 0).to_matrix),
of_col_single_mem_sol_set hT
(λ i' hi', mul_nonneg_of_nonpos_of_nonpos (min_le_right _ _) (h _ hi'))
(or.inl hres),
begin
rw [of_col_rowg, add_val, matrix.mul_smul, smul_val, matrix_mul_apply,
symm_single_apply],
cases le_total 0 ((q - T.offset r 0) / T.to_matrix r s) with hq hq,
{ rw [min_eq_right hq],
rw [le_div_iff_of_neg his, zero_mul, sub_nonpos] at hq,
simpa },
{ rw [min_eq_left hq, div_mul_cancel _ (ne_of_lt his)],
simp }
end⟩
/-- A row variable `r` is unbounded above if there is a column `s`
where every restricted row variable has a nonpositive entry in that column, and
`r` has a positive entry in that column. -/
lemma is_unbounded_above_rowg_of_nonneg {r : fin m} (hT : T.feasible) (s : fin n)
(hs : ∀ i : fin m, T.to_partition.rowg i ∈ T.restricted → 0 ≤ T.to_matrix i s)
(his : 0 < T.to_matrix r s) : is_unbounded_above T (T.to_partition.rowg r) :=
λ q, ⟨T.of_col (max ((q - T.offset r 0) / T.to_matrix r s) 0 • (single s 0).to_matrix),
of_col_single_mem_sol_set hT
(λ i hi, mul_nonneg (le_max_right _ _) (hs i hi))
(or.inr (le_max_right _ _)),
begin
rw [of_col_rowg, add_val, matrix.mul_smul, smul_val, matrix_mul_apply,
symm_single_apply],
cases le_total ((q - T.offset r 0) / T.to_matrix r s) 0 with hq hq,
{ rw [max_eq_right hq],
rw [div_le_iff his, zero_mul, sub_nonpos] at hq,
simpa },
{ rw [max_eq_left hq, div_mul_cancel _ (ne_of_gt his)],
simp }
end⟩
/-- The sample solution of a feasible tableau maximises the variable in row `r`,
if every entry in that row is nonpositive and every entry in that row owned by a restricted
variable is `0` -/
lemma is_maximised_of_col_zero {r : fin m} (hf : T.feasible)
(h : ∀ j, T.to_matrix r j ≤ 0 ∧ (T.to_partition.colg j ∉ T.restricted → T.to_matrix r j = 0)) :
T.is_maximised (T.of_col 0) (T.to_partition.rowg r) :=
λ x hx, begin
rw [of_col_rowg, matrix.mul_zero, zero_add, mem_flat_iff.1 hx.1],
refine add_le_of_nonpos_of_le _ (le_refl _),
refine sum_nonpos (λ j _, _),
by_cases hj : (T.to_partition.colg j) ∈ T.restricted,
{ refine mul_nonpos_of_nonpos_of_nonneg (h _).1 (hx.2 _ hj) },
{ rw [(h _).2 hj, _root_.zero_mul] }
end
/-- Expression for the sum of all but one entries in the a row of a tableau. -/
lemma row_sum_erase_eq {x : cvec (m + n)} (hx : x ∈ T.flat) {r : fin m} {s : fin n} :
(univ.erase s).sum (λ j : fin n, T.to_matrix r j * x (T.to_partition.colg j) 0) =
x (T.to_partition.rowg r) 0 - T.offset r 0 - T.to_matrix r s * x (colg (T.to_partition) s) 0 :=
begin
rw [mem_flat_iff] at hx,
conv_rhs { rw [hx r, ← insert_erase (mem_univ s), sum_insert (not_mem_erase _ _)] },
simp
end
/-- An expression for a column variable in terms of row variables. -/
lemma colg_eq {x : cvec (m + n)} (hx : x ∈ T.flat) {r : fin m} {s : fin n}
(hrs : T.to_matrix r s ≠ 0) : x (T.to_partition.colg s) 0 =
(x (T.to_partition.rowg r) 0
-(univ.erase s).sum (λ j : fin n, T.to_matrix r j * x (T.to_partition.colg j) 0)
- T.offset r 0) * (T.to_matrix r s)⁻¹ :=
by simp [row_sum_erase_eq hx, mul_left_comm (T.to_matrix r s)⁻¹, mul_assoc,
mul_left_comm (T.to_matrix r s), mul_inv_cancel hrs]
/-- Another expression for a column variable in terms of row variables. -/
lemma colg_eq' {x : cvec (m + n)} (hx : x ∈ T.flat) {r : fin m} {s : fin n}
(hrs : T.to_matrix r s ≠ 0) : x (T.to_partition.colg s) 0 =
univ.sum (λ (j : fin n), (if j = s then (T.to_matrix r s)⁻¹
else (-(T.to_matrix r j * (T.to_matrix r s)⁻¹))) *
x (colg (swap (T.to_partition) r s) j) 0) -
(T.offset r 0) * (T.to_matrix r s)⁻¹ :=
have (univ.erase s).sum
(λ j : fin n, ite (j = s) (T.to_matrix r s)⁻¹ (-(T.to_matrix r j * (T.to_matrix r s)⁻¹)) *
x (colg (swap (T.to_partition) r s) j) 0) =
(univ.erase s).sum (λ j : fin n,
-T.to_matrix r j * x (T.to_partition.colg j) 0 * (T.to_matrix r s)⁻¹),
from finset.sum_congr rfl $ λ j hj,
by simp [if_neg (mem_erase.1 hj).1, colg_swap_of_ne _ (mem_erase.1 hj).1,
mul_comm, mul_assoc, mul_left_comm],
by rw [← finset.insert_erase (mem_univ s), finset.sum_insert (not_mem_erase _ _),
if_pos rfl, colg_swap, colg_eq hx hrs, this, ← finset.sum_mul];
simp [_root_.add_mul, mul_comm, _root_.mul_add]
/-- Pivoting twice in the same place does nothing -/
@[simp] lemma pivot_pivot {r : fin m} {s : fin n} (hrs : T.to_matrix r s ≠ 0) :
(T.pivot r s).pivot r s = T :=
begin
cases T,
simp [pivot, function.funext_iff],
split; intros; split_ifs;
simp [*, mul_assoc, mul_left_comm (T_to_matrix r s), mul_left_comm (T_to_matrix r s)⁻¹,
mul_comm (T_to_matrix r s), inv_mul_cancel hrs]
end
/- These two sets are equal_in_flat, the stronger lemma is `flat_pivot` -/
private lemma subset_flat_pivot {r : fin m} {s : fin n} (h : T.to_matrix r s ≠ 0) :
T.flat ⊆ (T.pivot r s).flat :=
λ x hx,
have ∀ i : fin m, (univ.erase s).sum (λ j : fin n,
ite (j = s) (T.to_matrix i s * (T.to_matrix r s)⁻¹)
(T.to_matrix i j + -(T.to_matrix i s * T.to_matrix r j * (T.to_matrix r s)⁻¹))
* x ((T.to_partition.swap r s).colg j) 0) =
(univ.erase s).sum (λ j : fin n, T.to_matrix i j * x (T.to_partition.colg j) 0 -
T.to_matrix r j *
x (T.to_partition.colg j) 0 * T.to_matrix i s * (T.to_matrix r s)⁻¹),
from λ i, finset.sum_congr rfl (λ j hj,
by rw [if_neg (mem_erase.1 hj).1, colg_swap_of_ne _ (mem_erase.1 hj).1];
simp [mul_add, add_mul, mul_comm, mul_assoc, mul_left_comm]),
begin
rw mem_flat_iff,
assume i,
by_cases hir : i = r,
{ rw eq_comm at hir,
subst hir,
dsimp [pivot],
simp [mul_inv_cancel h, neg_mul_eq_neg_mul_symm, if_true,
add_comm, mul_inv_cancel, rowg_swap, eq_self_iff_true, colg_eq' hx h],
congr, funext, congr },
{ dsimp [pivot],
simp only [if_neg hir],
rw [← insert_erase (mem_univ s), sum_insert (not_mem_erase _ _),
if_pos rfl, colg_swap, this, sum_sub_distrib, ← sum_mul, ← sum_mul,
row_sum_erase_eq hx, rowg_swap_of_ne _ hir],
simp [row_sum_erase_eq hx, mul_add, add_mul,
mul_comm, mul_left_comm, mul_assoc],
simp [mul_assoc, mul_left_comm (T.to_matrix r s), mul_left_comm (T.to_matrix r s)⁻¹,
mul_comm (T.to_matrix r s), inv_mul_cancel h] }
end
variable (T)
@[simp] lemma pivot_pivot_element (r : fin m) (s : fin n) :
(T.pivot r s).to_matrix r s = (T.to_matrix r s)⁻¹ :=
by simp [pivot, if_pos rfl]
@[simp] lemma pivot_pivot_row {r : fin m} {j s : fin n} (h : j ≠ s) :
(T.pivot r s).to_matrix r j = -T.to_matrix r j / T.to_matrix r s :=
by dsimp [pivot]; rw [if_pos rfl, if_neg h, div_eq_mul_inv]
@[simp] lemma pivot_pivot_column {i r : fin m} {s : fin n} (h : i ≠ r) :
(T.pivot r s).to_matrix i s = T.to_matrix i s / T.to_matrix r s :=
by dsimp [pivot]; rw [if_neg h, if_pos rfl, div_eq_mul_inv]
@[simp] lemma pivot_of_ne_of_ne {i r : fin m} {j s : fin n} (hir : i ≠ r)
(hjs : j ≠ s) : (T.pivot r s).to_matrix i j =
T.to_matrix i j - T.to_matrix i s * T.to_matrix r j / T.to_matrix r s :=
by dsimp [pivot]; rw [if_neg hir, if_neg hjs, div_eq_mul_inv]
@[simp] lemma offset_pivot_row {r : fin m} {s : fin n} : (T.pivot r s).offset r 0 =
-T.offset r 0 / T.to_matrix r s :=
by simp [pivot, if_pos rfl, div_eq_mul_inv]
@[simp] lemma offset_pivot_of_ne {i r : fin m} {s : fin n} (hir : i ≠ r) : (T.pivot r s).offset i 0
= T.offset i 0 - T.to_matrix i s * T.offset r 0 / T.to_matrix r s :=
by dsimp [pivot]; rw [if_neg hir, div_eq_mul_inv]
@[simp] lemma restricted_pivot (r s) : (T.pivot r s).restricted = T.restricted := rfl
@[simp] lemma to_partition_pivot (r s) : (T.pivot r s).to_partition = T.to_partition.swap r s := rfl
variable {T}
@[simp] lemma flat_pivot {r : fin m} {s : fin n} (hrs : T.to_matrix r s ≠ 0) :
(T.pivot r s).flat = T.flat :=
set.subset.antisymm
(by conv_rhs { rw ← pivot_pivot hrs };
exact subset_flat_pivot (by simp [hrs]))
(subset_flat_pivot hrs)
@[simp] lemma sol_set_pivot {r : fin m} {s : fin n} (hrs : T.to_matrix r s ≠ 0) :
(T.pivot r s).sol_set = T.sol_set :=
by rw [sol_set, flat_pivot hrs]; refl
lemma feasible_pivot (hTf : T.feasible) {r : fin m} {c : fin n}
(hc : T.offset r 0 / T.to_matrix r c ≤ 0)
(h : ∀ i : fin m, i ≠ r → T.to_partition.rowg i ∈ T.restricted →
0 ≤ T.offset i 0 - T.to_matrix i c * T.offset r 0 / T.to_matrix r c) :
(T.pivot r c).feasible :=
assume i hi,
if hir : i = r
then begin
subst hir,
rw [offset_pivot_row],
simpa [neg_div] using hc
end
else begin
rw [to_partition_pivot, rowg_swap_of_ne _ hir, restricted_pivot] at hi,
rw [offset_pivot_of_ne _ hir],
simpa [offset_pivot_of_ne _ hir] using h _ hir hi
end
/-- Two row variables are `equal_in_flat` iff the corresponding rows of the tableau are equal -/
lemma equal_in_flat_row_row {i i' : fin m} :
T.equal_in_flat (T.to_partition.rowg i) (T.to_partition.rowg i')
↔ (T.offset i 0 = T.offset i' 0 ∧ ∀ j : fin n, T.to_matrix i j = T.to_matrix i' j) :=
⟨λ h, have Hoffset : T.offset i 0 = T.offset i' 0,
by simpa [of_col_rowg] using h (T.of_col 0) (of_col_mem_flat _ _),
⟨Hoffset,
λ j, begin
have := h (T.of_col (single j (0 : fin 1)).to_matrix) (of_col_mem_flat _ _),
rwa [of_col_rowg, of_col_rowg, add_val, add_val, matrix_mul_apply, matrix_mul_apply,
symm_single_apply, Hoffset, add_right_cancel_iff] at this,
end⟩,
λ h x hx, by simp [mem_flat_iff.1 hx, h.1, h.2]⟩
/-- A row variable is equal_in_flat to a column variable iff its row has zeros, and a single
one in that column. -/
lemma equal_in_flat_row_col {i : fin m} {j : fin n} :
T.equal_in_flat (T.to_partition.rowg i) (T.to_partition.colg j)
↔ (∀ j', j' ≠ j → T.to_matrix i j' = 0) ∧ T.offset i 0 = 0 ∧ T.to_matrix i j = 1 :=
⟨λ h, have Hoffset : T.offset i 0 = 0,
by simpa using h (T.of_col 0) (of_col_mem_flat _ _),
⟨assume j' hj', begin
have := h (T.of_col (single j' (0 : fin 1)).to_matrix) (of_col_mem_flat _ _),
rwa [of_col_rowg, of_col_colg, add_val, Hoffset, add_zero, matrix_mul_apply,
symm_single_apply, pequiv.to_matrix, single_apply_of_ne hj',
if_neg (option.not_mem_none _)] at this
end,
Hoffset,
begin
have := h (T.of_col (single j (0 : fin 1)).to_matrix) (of_col_mem_flat _ _),
rwa [of_col_rowg, of_col_colg, add_val, Hoffset, add_zero, matrix_mul_apply,
symm_single_apply, pequiv.to_matrix, single_apply] at this
end⟩,
by rintros ⟨h₁, h₂, h₃⟩ x hx;
rw [mem_flat_iff.1 hx, h₂, sum_eq_single j]; simp *; tauto⟩
end predicate_lemmas
/-- definition used to define well-foundedness of a pivot rule -/
inductive rel_gen {α : Type*} (f : α → option α) : α → α → Prop
| of_mem : ∀ {x y}, x ∈ f y → rel_gen x y
| trans : ∀ {x y z}, rel_gen x y → rel_gen y z → rel_gen x z
/-- A pivot rule is a function that selects a nonzero pivot, given a tableau, such that
iterating using this pivot rule terminates. -/
structure pivot_rule (m n : ℕ) : Type :=
(pivot_indices : tableau m n → option (fin m × fin n))
(well_founded : well_founded (rel_gen (λ T, pivot_indices T >>= λ i, T.pivot i.1 i.2)))
(ne_zero : ∀ {T r s}, (r, s) ∈ pivot_indices T → T.to_matrix r s ≠ 0)
def pivot_rule.rel (p : pivot_rule m n) : tableau m n → tableau m n → Prop :=
rel_gen (λ T, p.pivot_indices T >>= λ i, T.pivot i.1 i.2)
lemma pivot_rule.rel_wf (p : pivot_rule m n) : well_founded p.rel := p.well_founded
def iterate (p : pivot_rule m n) : tableau m n → tableau m n
| T :=
have ∀ (r : fin m) (s : fin n), (r, s) ∈ p.pivot_indices T → p.rel (T.pivot r s) T,
from λ r s hrs, rel_gen.of_mem $ by rw option.mem_def.1 hrs; exact rfl,
option.cases_on (p.pivot_indices T) (λ _, T)
(λ i this,
have wf : p.rel (T.pivot i.1 i.2) T, from this _ _ (by cases i; exact rfl),
iterate (T.pivot i.1 i.2))
this
using_well_founded { rel_tac := λ _ _, `[exact ⟨_, p.rel_wf⟩],
dec_tac := tactic.assumption }
lemma iterate_pivot {p : pivot_rule m n} {T : tableau m n} {r : fin m} {s : fin n}
(hrs : (r, s) ∈ p.pivot_indices T) : (T.pivot r s).iterate p = T.iterate p :=
by conv_rhs {rw iterate}; simp [option.mem_def.1 hrs]
@[simp] lemma pivot_indices_iterate (p : pivot_rule m n) : ∀ (T : tableau m n),
p.pivot_indices (T.iterate p) = none
| T :=
have ∀ r s, (r, s) ∈ p.pivot_indices T → p.rel (T.pivot r s) T,
from λ r s hrs, rel_gen.of_mem $ by rw option.mem_def.1 hrs; exact rfl,
begin
rw iterate,
cases h : p.pivot_indices T with i,
{ simp [h] },
{ cases i with r s,
simp [h, pivot_indices_iterate (T.pivot r s)] }
end
using_well_founded { rel_tac := λ _ _, `[exact ⟨_, p.rel_wf⟩], dec_tac := `[tauto] }
/- Is there some nice elaborator attribute for this, to avoid `P` having to be explicit? -/
lemma iterate_induction_on (P : tableau m n → Prop) (p : pivot_rule m n) :
∀ T : tableau m n, P T → (∀ T' r s, P T' → (r, s) ∈ p.pivot_indices T'
→ P (T'.pivot r s)) → P (T.iterate p)
| T := λ hT ih,
have ∀ r s, (r, s) ∈ p.pivot_indices T → p.rel (T.pivot r s) T,
from λ r s hrs, rel_gen.of_mem $ by rw option.mem_def.1 hrs; exact rfl,
begin
rw iterate,
cases h : p.pivot_indices T with i,
{ simp [hT, h] },
{ cases i with r s,
simp [h, iterate_induction_on _ (ih _ _ _ hT h) ih] }
end
using_well_founded { rel_tac := λ _ _, `[exact ⟨_, p.rel_wf⟩], dec_tac := `[tauto] }
@[simp] lemma iterate_flat (p : pivot_rule m n) (T : tableau m n) :
(T.iterate p).flat = T.flat :=
iterate_induction_on (λ T', T'.flat = T.flat) p T rfl $
assume T' r s (hT' : T'.flat = T.flat) hrs, by rw [← hT', flat_pivot (p.ne_zero hrs)]
@[simp] lemma iterate_sol_set (p : pivot_rule m n) (T : tableau m n) :
(T.iterate p).sol_set = T.sol_set :=
iterate_induction_on (λ T', T'.sol_set = T.sol_set) p T rfl $
assume T' r s (hT' : T'.sol_set = T.sol_set) hrs,
by rw [← hT', sol_set_pivot (p.ne_zero hrs)]
namespace simplex
def find_pivot_column (T : tableau m n) (obj : fin m) : option (fin n) :=
option.cases_on (fin.find (λ c : fin n, T.to_matrix obj c ≠ 0 ∧ T.to_partition.colg c ∉ T.restricted))
(fin.find (λ c : fin n, 0 < T.to_matrix obj c))
some
def find_pivot_row (T : tableau m n) (obj: fin m) (c : fin n) : option (fin m) :=
let l := (list.fin_range m).filter (λ r : fin m, obj ≠ r ∧ T.to_partition.rowg r ∈ T.restricted
∧ T.to_matrix obj c / T.to_matrix r c < 0) in
l.argmin (λ r', abs (T.offset r' 0 / T.to_matrix r' c))
lemma find_pivot_column_spec {T : tableau m n} {obj : fin m} {s : fin n} :
s ∈ find_pivot_column T obj → (T.to_matrix obj s ≠ 0 ∧ T.to_partition.colg s ∉ T.restricted)
∨ (0 < T.to_matrix obj s ∧ T.to_partition.colg s ∈ T.restricted) :=
begin
simp [find_pivot_column],
cases h : fin.find (λ s : fin n, T.to_matrix obj s ≠ 0 ∧ T.to_partition.colg s ∉ T.restricted),
{ finish [h, fin.find_eq_some_iff, fin.find_eq_none_iff, lt_irrefl (0 : ℚ)] },
{ finish [fin.find_eq_some_iff] }
end
-- lemma find_pivot_column_eq_none_aux {T : tableau m n} {i : fin m} {s : fin n} :
-- find_pivot_column T i = none ↔ (∀ s, T.to_matrix i s ≤ 0) :=
-- begin
-- simp [find_pivot_column, fin.find_eq_none_iff],
-- cases h : fin.find (λ s : fin n, T.to_matrix i s ≠ 0 ∧ T.to_partition.colg s ∉ T.restricted),
-- { finish [fin.find_eq_none_iff] },
-- { simp [find_eq_some_iff] at *, }
-- end
lemma find_pivot_column_eq_none {T : tableau m n} {obj : fin m} (hT : T.feasible)
(h : find_pivot_column T obj = none) : T.is_maximised (T.of_col 0) (T.to_partition.rowg obj) :=
is_maximised_of_col_zero hT
begin
revert h,
simp [find_pivot_column],
cases h : fin.find (λ c : fin n, T.to_matrix obj c ≠ 0 ∧ T.to_partition.colg c ∉ T.restricted),
{ finish [fin.find_eq_none_iff] },
{ simp [h] }
end
lemma find_pivot_row_spec {T : tableau m n} {obj r : fin m} {c : fin n} :
r ∈ find_pivot_row T obj c →
obj ≠ r ∧ T.to_partition.rowg r ∈ T.restricted ∧
T.to_matrix obj c / T.to_matrix r c < 0 ∧
(∀ r' : fin m, obj ≠ r' → T.to_partition.rowg r' ∈ T.restricted →
T.to_matrix obj c / T.to_matrix r' c < 0 →
abs (T.offset r 0 / T.to_matrix r c) ≤ abs (T.offset r' 0 / T.to_matrix r' c)) :=
by simp only [list.mem_argmin_iff, list.mem_filter, find_pivot_row,
list.mem_fin_range, true_and, and_imp]; tauto
lemma find_pivot_row_eq_none_aux {T : tableau m n} {obj : fin m} {c : fin n}
(hrow : find_pivot_row T obj c = none) (hs : c ∈ find_pivot_column T obj) :
∀ r, obj ≠ r → T.to_partition.rowg r ∈ T.restricted → 0 ≤ T.to_matrix obj c / T.to_matrix r c :=
by simpa [find_pivot_row, list.filter_eq_nil] using hrow
lemma find_pivot_row_eq_none {T : tableau m n} {obj : fin m} {c : fin n} (hT : T.feasible)
(hrow : find_pivot_row T obj c = none) (hs : c ∈ find_pivot_column T obj) :
T.is_unbounded_above (T.to_partition.rowg obj) :=
have hrow : ∀ r, obj ≠ r → T.to_partition.rowg r ∈ T.restricted →
0 ≤ T.to_matrix obj c / T.to_matrix r c,
from find_pivot_row_eq_none_aux hrow hs,
have hc : (T.to_matrix obj c ≠ 0 ∧ T.to_partition.colg c ∉ T.restricted)
∨ (0 < T.to_matrix obj c ∧ T.to_partition.colg c ∈ T.restricted),
from find_pivot_column_spec hs,
have hToc : T.to_matrix obj c ≠ 0, from λ h, by simpa [h, lt_irrefl] using hc,
(lt_or_gt_of_ne hToc).elim
(λ hToc : T.to_matrix obj c < 0, is_unbounded_above_rowg_of_nonpos hT c
(hc.elim and.right (λ h, (not_lt_of_gt hToc h.1).elim))
(λ i hi, classical.by_cases
(λ hoi : obj = i, le_of_lt (hoi ▸ hToc))
(λ hoi : obj ≠ i, inv_nonpos.1 $ nonpos_of_mul_nonneg_right (hrow _ hoi hi) hToc))
hToc)
(λ hToc : 0 < T.to_matrix obj c, is_unbounded_above_rowg_of_nonneg hT c
(λ i hi, classical.by_cases
(λ hoi : obj = i, le_of_lt (hoi ▸ hToc))
(λ hoi : obj ≠ i, inv_nonneg.1 $ nonneg_of_mul_nonneg_left (hrow _ hoi hi) hToc))
hToc)
/-- This `pivot_rule` maximises the sample value of `i` -/
def simplex_pivot_rule (i : fin m) : pivot_rule m n :=
{ pivot_indices := λ T, find_pivot_column T i >>= λ s,
find_pivot_row T i s >>= λ r, some (r, s),
well_founded := sorry,
ne_zero := λ T r s, begin
simp only [option.mem_def, option.bind_eq_some,
find_pivot_row, list.argmin_eq_some_iff, and_imp,
exists_imp_distrib, prod.mk.inj_iff, list.mem_filter],
intros,
substs x r,
assume h,
simp [h, lt_irrefl, *] at *
end }
end simplex
def simplex (T : tableau m n) (i : fin m) : tableau m n :=
T.iterate (simplex.simplex_pivot_rule i)
namespace simplex
/-- The simplex algorithm does not pivot the variable it is trying to optimise -/
lemma simplex_pivot_indices_ne {T : tableau m n} {i : fin m} {r s} :
(r, s) ∈ (simplex_pivot_rule i).pivot_indices T → i ≠ r :=
by simp only [simplex_pivot_rule, find_pivot_row, fin.find_eq_some_iff, option.mem_def, list.mem_filter,
option.bind_eq_some, prod.mk.inj_iff, exists_imp_distrib, and_imp, list.argmin_eq_some_iff,
@forall_swap _ (_ = r), @forall_swap (_ ≠ r), imp_self, forall_true_iff] {contextual := tt}
/-- `simplex` does not move the row variable it is trying to maximise. -/
lemma rowg_simplex (T : tableau m n) (i : fin m) :
(T.simplex i).to_partition.rowg i = T.to_partition.rowg i :=
iterate_induction_on (λ T', T'.to_partition.rowg i = T.to_partition.rowg i) _ _ rfl $
assume T' r s (hT' : T'.to_partition.rowg i = T.to_partition.rowg i) hrs,
by rw [to_partition_pivot, rowg_swap_of_ne _ (simplex_pivot_indices_ne hrs), hT']
lemma simplex_pivot_rule_eq_none {T : tableau m n} {i : fin m} (hT : T.feasible)
(h : (simplex_pivot_rule i).pivot_indices T = none) :
is_maximised T (T.of_col 0) (T.to_partition.rowg i) ∨
is_unbounded_above T (T.to_partition.rowg i) :=
begin
cases hs : find_pivot_column T i with s,
{ exact or.inl (find_pivot_column_eq_none hT hs) },
{ dsimp [simplex_pivot_rule] at h,
rw [hs, option.some_bind, option.bind_eq_none] at h,
have : find_pivot_row T i s = none,
{ exact option.eq_none_iff_forall_not_mem.2 (λ r, by simpa using h (r, s) r) },
exact or.inr (find_pivot_row_eq_none hT this hs) }
end
@[simp] lemma mem_simplex_pivot_rule_indices {T : tableau m n} {i : fin m} {r s} :
(r, s) ∈ (simplex_pivot_rule i).pivot_indices T ↔
s ∈ find_pivot_column T i ∧ r ∈ find_pivot_row T i s :=
begin
simp only [simplex_pivot_rule, option.mem_def, option.bind_eq_some,
prod.mk.inj_iff, and_comm _ (_ = r), @and.left_comm _ (_ = r), exists_eq_left, and.assoc],
simp only [and_comm _ (_ = s), @and.left_comm _ (_ = s), exists_eq_left]
end
lemma simplex_pivot_rule_feasible {T : tableau m n} {i : fin m} (hT : T.feasible)
{r s} (hrs : (r, s) ∈ (simplex_pivot_rule i).pivot_indices T) : (T.pivot r s).feasible :=
λ i' hi', begin
rw [mem_simplex_pivot_rule_indices] at hrs,
have hs := find_pivot_column_spec hrs.1,
have hr := find_pivot_row_spec hrs.2,
dsimp only [pivot],
by_cases hir : i' = r,
{ subst i',
rw [if_pos rfl, neg_mul_eq_neg_mul_symm, neg_nonneg],
exact mul_nonpos_of_nonneg_of_nonpos (hT _ hr.2.1)
(le_of_lt (neg_of_mul_neg_left hr.2.2.1 (le_of_lt (by simp * at *)))) },
{ rw if_neg hir,
rw [to_partition_pivot, rowg_swap_of_ne _ hir, restricted_pivot] at hi',
by_cases hii : i = i',
{ subst i',
refine add_nonneg (hT _ hi') (neg_nonneg.2 _),
rw [mul_assoc, mul_left_comm],
exact mul_nonpos_of_nonneg_of_nonpos (hT _ hr.2.1) (le_of_lt hr.2.2.1) },
{ by_cases hTi'r : 0 < T.to_matrix i' s / T.to_matrix r s,
{ have hTi's0 : T.to_matrix i' s ≠ 0, from λ h, by simpa [h, lt_irrefl] using hTi'r,
have hTrs0 : T.to_matrix r s ≠ 0, from λ h, by simpa [h, lt_irrefl] using hTi'r,
have hTii' : T.to_matrix i s / T.to_matrix i' s < 0,
{ suffices : (T.to_matrix i s / T.to_matrix r s) / (T.to_matrix i' s / T.to_matrix r s) < 0,
{ simp only [div_eq_mul_inv, mul_assoc, mul_inv', inv_inv',
mul_left_comm (T.to_matrix r s), mul_left_comm (T.to_matrix r s)⁻¹,
mul_comm (T.to_matrix r s), inv_mul_cancel hTrs0, mul_one] at this,
simpa [mul_comm, div_eq_mul_inv] },
{ exact div_neg_of_neg_of_pos hr.2.2.1 hTi'r } },
have := hr.2.2.2 _ hii hi' hTii',
rwa [abs_div, abs_div, abs_of_nonneg (hT _ hr.2.1), abs_of_nonneg (hT _ hi'),
le_div_iff (abs_pos_iff.2 hTi's0), div_eq_mul_inv, mul_right_comm, ← abs_inv, mul_assoc,
← abs_mul, ← div_eq_mul_inv, abs_of_nonneg (le_of_lt hTi'r), ← sub_nonneg,
← mul_div_assoc, div_eq_mul_inv, mul_comm (T.offset r 0)] at this },
{ refine add_nonneg (hT _ hi') (neg_nonneg.2 _),
rw [mul_assoc, mul_left_comm],
exact mul_nonpos_of_nonneg_of_nonpos (hT _ hr.2.1) (le_of_not_gt hTi'r) } } }
end
lemma simplex_feasible {T : tableau m n} (hT : T.feasible) (i : fin m) : (simplex T i).feasible :=
iterate_induction_on feasible _ _ hT (λ _ _ _ hT, simplex_pivot_rule_feasible hT)
lemma simplex_unbounded_or_maximised {T : tableau m n} (hT : T.feasible) (i : fin m) :
is_maximised (simplex T i) ((simplex T i).of_col 0) (T.to_partition.rowg i) ∨
is_unbounded_above (simplex T i) (T.to_partition.rowg i) :=
by rw ← rowg_simplex;
exact simplex_pivot_rule_eq_none (simplex_feasible hT i) (pivot_indices_iterate _ _)
@[simp] lemma simplex_flat {T : tableau m n} (i : fin m) : flat (T.simplex i) = T.flat :=
iterate_flat _ _
@[simp] lemma simplex_sol_set {T : tableau m n} (i : fin m) : sol_set (T.simplex i) = T.sol_set :=
iterate_sol_set _ _
end simplex
section add_row
/-- adds a new row without making it a restricted variable. -/
def add_row (T : tableau m n) (fac : rvec (m + n)) (const : ℚ) : tableau (m + 1) n :=
{ to_matrix := λ i j, if hm : i.1 < m
then T.to_matrix (fin.cast_lt i hm) j
else fac 0 (T.to_partition.colg j) +
univ.sum (λ i' : fin m, fac 0 (T.to_partition.rowg i') * T.to_matrix i' j),
offset := λ i j, if hm : i.1 < m
then T.offset (fin.cast_lt i hm) j
else const +
univ.sum (λ i' : fin m, fac 0 (T.to_partition.rowg i') * T.offset i' 0),
to_partition := T.to_partition.add_row,
restricted := T.restricted.map ⟨fin.castp,
λ ⟨_, _⟩ ⟨_, _⟩ h, fin.eq_of_veq (fin.veq_of_eq h : _)⟩ }
@[simp] lemma add_row_to_partition (T : tableau m n) (fac : rvec (m + n)) (const : ℚ) :
(T.add_row fac const).to_partition = T.to_partition.add_row := rfl
lemma add_row_to_matrix (T : tableau m n) (fac : rvec (m + n)) (const : ℚ) :
(T.add_row fac const).to_matrix = λ i j, if hm : i.1 < m
then T.to_matrix (fin.cast_lt i hm) j else fac 0 (T.to_partition.colg j) +
univ.sum (λ i' : fin m, fac 0 (T.to_partition.rowg i') * T.to_matrix i' j) := rfl
lemma add_row_offset (T : tableau m n) (fac : rvec (m + n)) (const : ℚ) :
(T.add_row fac const).offset = λ i j, if hm : i.1 < m
then T.offset (fin.cast_lt i hm) j else const +
univ.sum (λ i' : fin m, fac 0 (T.to_partition.rowg i') * T.offset i' 0) := rfl
lemma add_row_restricted (T : tableau m n) (fac : rvec (m + n)) (const : ℚ) :
(T.add_row fac const).restricted = T.restricted.image fin.castp :=
by simp [add_row, map_eq_image]
@[simp] lemma fin.cast_lt_cast_succ {n : ℕ} (a : fin n) (h : a.1 < n) :
a.cast_succ.cast_lt h = a := by cases a; refl
lemma minor_mem_flat_of_mem_add_row_flat {T : tableau m n} {fac : rvec (m + n)} {const : ℚ}
{x : cvec (m + 1 + n)} : x ∈ (T.add_row fac const).flat → minor x fin.castp id ∈ T.flat :=
begin
rw [mem_flat_iff, mem_flat_iff],
intros h r,
have := h (fin.cast_succ r),
simp [add_row_rowg_cast_succ, add_row_offset, add_row_to_matrix,
(show (fin.cast_succ r).val < m, from r.2), add_row_colg] at this,
simpa
end
lemma minor_mem_sol_set_of_mem_add_row_sol_set {T : tableau m n} {fac : rvec (m + n)} {const : ℚ}
{x : cvec (m + 1 + n)} : x ∈ (T.add_row fac const).sol_set → minor x fin.castp id ∈ T.sol_set :=
and_implies minor_mem_flat_of_mem_add_row_flat begin
assume h v,
simp only [set.mem_set_of_eq, add_row_restricted, mem_image, exists_imp_distrib] at h,
simpa [add_row_restricted, matrix.minor, id.def] using h (fin.castp v) v
end
lemma add_row_new_eq_sum_fac (T : tableau m n) (fac : rvec (m + n)) (const : ℚ)
(x : cvec (m + 1 + n)) (hx : x ∈ (T.add_row fac const).flat) :
x fin.lastp 0 = univ.sum (λ v : fin (m + n), fac 0 v * x (fin.castp v) 0) + const :=
calc x fin.lastp 0 = x ((T.add_row fac const).to_partition.rowg (fin.last _)) 0 :
by simp [add_row_rowg_last]
... = univ.sum (λ j : fin n, _) + (T.add_row fac const).offset _ _ : mem_flat_iff.1 hx _
... = const +
univ.sum (λ j, (fac 0 (T.to_partition.colg j) * x (T.to_partition.add_row.colg j) 0)) +
(univ.sum (λ j, univ.sum (λ i, fac 0 (T.to_partition.rowg i) * T.to_matrix i j *
x (T.to_partition.add_row.colg j) 0))
+ univ.sum (λ i, fac 0 (T.to_partition.rowg i) * T.offset i 0)) :
by simp [add_row_to_matrix, add_row_offset, fin.last, add_mul, sum_add_distrib, sum_mul]
... = const +
univ.sum (λ j, (fac 0 (T.to_partition.colg j) * x (T.to_partition.add_row.colg j) 0)) +
(univ.sum (λ i, univ.sum (λ j, fac 0 (T.to_partition.rowg i) * T.to_matrix i j *
x (T.to_partition.add_row.colg j) 0))
+ univ.sum (λ i, fac 0 (T.to_partition.rowg i) * T.offset i 0)) : by rw [sum_comm]
... = const +
univ.sum (λ j, (fac 0 (T.to_partition.colg j) * x (T.to_partition.add_row.colg j) 0)) +
univ.sum (λ i : fin m, (fac 0 (T.to_partition.rowg i) * x (fin.castp (T.to_partition.rowg i)) 0)) :
begin
rw [← sum_add_distrib],
have : ∀ r : fin m, x (fin.castp (T.to_partition.rowg r)) 0 =
sum univ (λ (c : fin n), T.to_matrix r c * x (fin.castp (T.to_partition.colg c)) 0) +
T.offset r 0, from mem_flat_iff.1 (minor_mem_flat_of_mem_add_row_flat hx),
simp [this, mul_add, add_row_colg, mul_sum, mul_assoc]
end
... = ((univ.image T.to_partition.colg).sum (λ v, (fac 0 v * x (fin.castp v) 0)) +
(univ.image T.to_partition.rowg).sum (λ v, (fac 0 v * x (fin.castp v) 0))) + const :
by rw [sum_image, sum_image];
simp [add_row_rowg_cast_succ, add_row_colg, T.to_partition.injective_rowg.eq_iff,
T.to_partition.injective_colg.eq_iff]
... = _ : begin
rw [← sum_union],
congr,
simpa [finset.ext, eq_comm] using T.to_partition.eq_rowg_or_colg,
{ simp [finset.ext, eq_comm, T.to_partition.rowg_ne_colg] {contextual := tt} }
end
end add_row
open tableau.simplex
/-- Boolean returning whether -/
def max_nonneg (T : tableau m n) (i : fin m) : bool :=
0 ≤ (simplex T i).offset i 0
lemma max_nonneg_iff (T : tableau m n) (hT : T.feasible) (i : fin m) :
T.max_nonneg i ↔ ∃ x : cvec (m + n), x ∈ T.sol_set ∧ 0 ≤ x (T.to_partition.rowg i) 0 :=
by simp [max_nonneg, bool.of_to_bool_iff]; exact
⟨λ h, ⟨(T.simplex i).of_col 0, by rw [← simplex_sol_set i,
← feasible_iff_of_col_zero_mem_sol_set]; exact simplex_feasible hT _,
_⟩ ,
_⟩
section assertge
end assertge
end tableau
section test
open tableau tableau.simplex
def list.to_matrix (m :ℕ) (n : ℕ) (l : list (list ℚ)) : matrix (fin m) (fin n) ℚ :=
λ i j, (l.nth_le i sorry).nth_le j sorry
instance has_repr_fin_fun {n : ℕ} {α : Type*} [has_repr α] : has_repr (fin n → α) :=
⟨λ f, repr (vector.of_fn f).to_list⟩
instance {m n} : has_repr (matrix (fin m) (fin n) ℚ) := has_repr_fin_fun
-- def T : tableau 4 5 :=
-- { to_matrix := list.to_matrix 4 5 [[1, 3/4, -20, 1/2, -6], [0, 1/4, -8, -1, 9],
-- [0, 1/2, -12, 1/2, 3], [0,0,0,1,0]],
-- offset := (list.to_matrix 1 4 [[-3,0,0,1]])ᵀ,
-- to_partition := default _,
-- restricted := univ.erase 6 }
def T : tableau 25 10 :=
{ to_matrix := list.to_matrix 25 10
[[0, 0, 0, 0, 1, 0, 1, 0, 1, -1], [-1, 1, 0, -1, 1, 0, 1, -1, 0, 0],
[0, -1, 1, 1, 1, 0, 0, 0, 1, 0], [1, 1, 1, 0, 1, -1, 1, -1, 1, -1],
[0, 1, 1, -1, -1, 1, -1, 1, -1, 1], [0, -1, 1, -1, 1, 1, 0, 1, 0, -1],
[-1, 0, 0, -1, -1, 1, 1, 0, -1, -1], [-1, 0, 0, -1, 0, -1, 0, 0, -1, 1],
[-1, 0, 0, 1, -1, 1, -1, -1, 1, 0], [1, 0, 0, 0, 1, -1, 1, 0, -1, 1],
[0, -1, 1, 0, 0, 1, 0, -1, 0, 0], [-1, 1, -1, 1, 1, 0, 1, 0, 1, 0],
[1, 1, 1, 1, -1, 0, 0, 0, -1, 0], [-1, -1, 0, 0, 1, 0, 1, 1, -1, 0],
[0, 0, -1, 1, -1, 0, 0, 1, 0, -1], [-1, 0, -1, 1, 1, 1, 0, 0, 0, 0], [
1, 0, -1, 1, 0, -1, -1, 1, -1, 1], [-1, 1, -1, 1, -1, -1, -1, 1, -1, 1],
[-1, 0, 0, 0, 1, -1, 1, -1, -1, 1], [-1, -1, -1, 1, 0, 1, -1, 1, 0, 0],
[-1, 0, 0, 0, -1, -1, 1, -1, 0, 1], [-1, 0, 0, -1, 1, 1, 1, -1, 1, 0],
[0, -1, 0, 0, 0, -1, 0, 1, 0, -1], [1, -1, 1, 0, 0, 1, 0, 1, 0, -1],
[0, -1, -1, 0, 0, 0, -1, 0, 1, 0]],
offset := λ i _, if i.1 < 8 then 0 else 1,
to_partition := default _,
restricted := univ }
def Beale : tableau 4 4 :=
{ to_matrix := list.to_matrix 4 4
[[3/4, -150, 1/50, -6],
[-1/4, 60,1/25,-9],
[-1/2,90,1/50,-3],
[0,0,-1,0]],
offset := λ i k, if i = 3 then 1 else 0,
to_partition := default _,
restricted := univ }
def Yudin_golstein : tableau 4 4 :=
{ to_matrix := list.to_matrix 4 4
[[1,-1,1,-1],
[-2,3,5,-6],
[-6,5,3,-2],
[-3,-1,-2,-4]],
offset := λ i k, if i = 3 then 1 else 0,
to_partition := default _,
restricted := univ }
def Kuhn : tableau 4 4 :=
{ to_matrix := list.to_matrix 4 4
[[2,3,-1,-12],
[2,9,-1,-9],
[-1/3,-1,1/3,2],
[-2,-3,1,12]],
offset := λ i k, if i = 3 then 2 else 0,
to_partition := default _,
restricted := univ }
def me : tableau 3 2 :=
{ to_matrix := list.to_matrix 3 2
[[1/2, 1], [1, 1], [-1, 1]],
offset := 0,
to_partition := default _,
restricted := univ }
def tableau.flip_up : tableau m n → tableau m n :=
λ T,
{ to_matrix := λ i j, T.to_matrix ⟨(-i-1 : ℤ).nat_mod m, sorry⟩ j,
offset := λ i j, T.offset ⟨(-i - 1 : ℤ).nat_mod m, sorry⟩ j,
to_partition := T.to_partition,
restricted := univ }
#eval let A := me in
((A.simplex 0).to_matrix, (A.flip_up.simplex 3).to_matrix)
-- def T : tableau 4 5 :=
-- { to_matrix := list.to_matrix 4 5 [[1, 3/5, 20, 1/2, -6], [19, 1, -8, -1, 9],
-- [5, 1/2, -12, 1/2, 3], [13,0.1,11,21,0]],
-- offset := (list.to_matrix 1 4 [[3,1,51,1]])ᵀ,
-- to_partition := default _,
-- restricted := univ }
--set_option profiler true
#print algebra.sub
-- def T : tableau 25 10 :=
-- { to_matrix := list.to_matrix 25 10
-- [[1,0,1,-1,-1,-1,1,-1,1,1],[0,1,-1,1,1,1,-1,1,-1,1],[0,1,-1,1,-1,0,-1,-1,-1,0],[1,1,-1,-1,-1,-1,-1,1,-1,-1],[0,-1,1,1,0,-1,1,-1,1,-1],[0,1,1,0,1,1,0,1,0,1],[0,1,0,1,0,1,1,0,-1,-1],[0,0,-1,1,1,0,0,0,1,-1],[0,0,1,0,1,-1,-1,0,1,1],[0,-1,0,0,1,-1,-1,1,0,0],[0,-1,1,0,0,1,0,-1,1,0],[1,1,1,-1,1,-1,-1,0,-1,1],[1,1,-1,-1,-1,1,-1,1,-1,-1],[-1,-1,-1,1,1,1,1,1,-1,-1],[0,1,0,0,1,-1,0,0,-1,1],[-1,-1,-1,-1,1,1,1,0,-1,1],[0,0,-1,-1,0,1,1,-1,1,1],[1,0,1,0,0,0,1,0,0,1],[-1,0,-1,0,1,1,-1,1,1,-1],[0,1,-1,1,-1,0,0,-1,-1,-1],[1,1,0,1,1,0,1,1,-1,1],[0,0,0,0,0,1,-1,1,0,-1],[1,1,0,0,-1,1,0,0,1,0],[0,0,-1,1,-1,1,-1,1,-1,-1],[0,0,0,0,1,-1,1,1,-1,-1]],
-- offset := λ i _, 1,
-- to_partition := default _,
-- restricted := univ }
#print random_gen
#print tc.rec
#print nat
#eval let s := T.simplex 0 in (s.to_partition.row_indices).1
end test
|
5be54336056f939be55204f1545f905257ce4a4c | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/data/finsupp/basic.lean | 4c7a35bcdfdfa787528efce99b30fa9898c60da5 | [
"Apache-2.0"
] | permissive | ayush1801/mathlib | 78949b9f789f488148142221606bf15c02b960d2 | ce164e28f262acbb3de6281b3b03660a9f744e3c | refs/heads/master | 1,692,886,907,941 | 1,635,270,866,000 | 1,635,270,866,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 109,289 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Scott Morrison
-/
import data.finset.preimage
import algebra.indicator_function
import algebra.group_action_hom
/-!
# Type of functions with finite support
For any type `α` and a type `M` with zero, we define the type `finsupp α M` (notation: `α →₀ M`)
of finitely supported functions from `α` to `M`, i.e. the functions which are zero everywhere
on `α` except on a finite set.
Functions with finite support are used (at least) in the following parts of the library:
* `monoid_algebra R M` and `add_monoid_algebra R M` are defined as `M →₀ R`;
* polynomials and multivariate polynomials are defined as `add_monoid_algebra`s, hence they use
`finsupp` under the hood;
* the linear combination of a family of vectors `v i` with coefficients `f i` (as used, e.g., to
define linearly independent family `linear_independent`) is defined as a map
`finsupp.total : (ι → M) → (ι →₀ R) →ₗ[R] M`.
Some other constructions are naturally equivalent to `α →₀ M` with some `α` and `M` but are defined
in a different way in the library:
* `multiset α ≃+ α →₀ ℕ`;
* `free_abelian_group α ≃+ α →₀ ℤ`.
Most of the theory assumes that the range is a commutative additive monoid. This gives us the big
sum operator as a powerful way to construct `finsupp` elements.
Many constructions based on `α →₀ M` use `semireducible` type tags to avoid reusing unwanted type
instances. E.g., `monoid_algebra`, `add_monoid_algebra`, and types based on these two have
non-pointwise multiplication.
## Notations
This file adds `α →₀ M` as a global notation for `finsupp α M`. We also use the following convention
for `Type*` variables in this file
* `α`, `β`, `γ`: types with no additional structure that appear as the first argument to `finsupp`
somewhere in the statement;
* `ι` : an auxiliary index type;
* `M`, `M'`, `N`, `P`: types with `has_zero` or `(add_)(comm_)monoid` structure; `M` is also used
for a (semi)module over a (semi)ring.
* `G`, `H`: groups (commutative or not, multiplicative or additive);
* `R`, `S`: (semi)rings.
## TODO
* This file is currently ~2K lines long, so possibly it should be splitted into smaller chunks;
* Add the list of definitions and important lemmas to the module docstring.
## Implementation notes
This file is a `noncomputable theory` and uses classical logic throughout.
## Notation
This file defines `α →₀ β` as notation for `finsupp α β`.
-/
noncomputable theory
open_locale classical big_operators
open finset
variables {α β γ ι M M' N P G H R S : Type*}
/-- `finsupp α M`, denoted `α →₀ M`, is the type of functions `f : α → M` such that
`f x = 0` for all but finitely many `x`. -/
structure finsupp (α : Type*) (M : Type*) [has_zero M] :=
(support : finset α)
(to_fun : α → M)
(mem_support_to_fun : ∀a, a ∈ support ↔ to_fun a ≠ 0)
infixr ` →₀ `:25 := finsupp
namespace finsupp
/-! ### Basic declarations about `finsupp` -/
section basic
variable [has_zero M]
instance : has_coe_to_fun (α →₀ M) (λ _, α → M) := ⟨to_fun⟩
@[simp] lemma coe_mk (f : α → M) (s : finset α) (h : ∀ a, a ∈ s ↔ f a ≠ 0) :
⇑(⟨s, f, h⟩ : α →₀ M) = f := rfl
instance : has_zero (α →₀ M) := ⟨⟨∅, 0, λ _, ⟨false.elim, λ H, H rfl⟩⟩⟩
@[simp] lemma coe_zero : ⇑(0 : α →₀ M) = 0 := rfl
lemma zero_apply {a : α} : (0 : α →₀ M) a = 0 := rfl
@[simp] lemma support_zero : (0 : α →₀ M).support = ∅ := rfl
instance : inhabited (α →₀ M) := ⟨0⟩
@[simp] lemma mem_support_iff {f : α →₀ M} : ∀{a:α}, a ∈ f.support ↔ f a ≠ 0 :=
f.mem_support_to_fun
@[simp, norm_cast] lemma fun_support_eq (f : α →₀ M) : function.support f = f.support :=
set.ext $ λ x, mem_support_iff.symm
lemma not_mem_support_iff {f : α →₀ M} {a} : a ∉ f.support ↔ f a = 0 :=
not_iff_comm.1 mem_support_iff.symm
lemma coe_fn_injective : @function.injective (α →₀ M) (α → M) coe_fn
| ⟨s, f, hf⟩ ⟨t, g, hg⟩ h :=
begin
change f = g at h, subst h,
have : s = t, { ext a, exact (hf a).trans (hg a).symm },
subst this
end
@[simp, norm_cast] lemma coe_fn_inj {f g : α →₀ M} : (f : α → M) = g ↔ f = g :=
coe_fn_injective.eq_iff
@[simp, norm_cast] lemma coe_eq_zero {f : α →₀ M} : (f : α → M) = 0 ↔ f = 0 :=
by rw [← coe_zero, coe_fn_inj]
@[ext] lemma ext {f g : α →₀ M} (h : ∀a, f a = g a) : f = g := coe_fn_injective (funext h)
lemma ext_iff {f g : α →₀ M} : f = g ↔ (∀a:α, f a = g a) :=
⟨by rintros rfl a; refl, ext⟩
lemma ext_iff' {f g : α →₀ M} : f = g ↔ f.support = g.support ∧ ∀ x ∈ f.support, f x = g x :=
⟨λ h, h ▸ ⟨rfl, λ _ _, rfl⟩, λ ⟨h₁, h₂⟩, ext $ λ a,
if h : a ∈ f.support then h₂ a h else
have hf : f a = 0, from not_mem_support_iff.1 h,
have hg : g a = 0, by rwa [h₁, not_mem_support_iff] at h,
by rw [hf, hg]⟩
lemma congr_fun {f g : α →₀ M} (h : f = g) (a : α) : f a = g a :=
congr_fun (congr_arg finsupp.to_fun h) a
@[simp] lemma support_eq_empty {f : α →₀ M} : f.support = ∅ ↔ f = 0 :=
by exact_mod_cast @function.support_eq_empty_iff _ _ _ f
lemma support_nonempty_iff {f : α →₀ M} : f.support.nonempty ↔ f ≠ 0 :=
by simp only [finsupp.support_eq_empty, finset.nonempty_iff_ne_empty, ne.def]
lemma nonzero_iff_exists {f : α →₀ M} : f ≠ 0 ↔ ∃ a : α, f a ≠ 0 :=
by simp [← finsupp.support_eq_empty, finset.eq_empty_iff_forall_not_mem]
lemma card_support_eq_zero {f : α →₀ M} : card f.support = 0 ↔ f = 0 :=
by simp
instance [decidable_eq α] [decidable_eq M] : decidable_eq (α →₀ M) :=
assume f g, decidable_of_iff (f.support = g.support ∧ (∀a∈f.support, f a = g a)) ext_iff'.symm
lemma finite_support (f : α →₀ M) : set.finite (function.support f) :=
f.fun_support_eq.symm ▸ f.support.finite_to_set
lemma support_subset_iff {s : set α} {f : α →₀ M} :
↑f.support ⊆ s ↔ (∀a∉s, f a = 0) :=
by simp only [set.subset_def, mem_coe, mem_support_iff];
exact forall_congr (assume a, not_imp_comm)
/-- Given `fintype α`, `equiv_fun_on_fintype` is the `equiv` between `α →₀ β` and `α → β`.
(All functions on a finite type are finitely supported.) -/
@[simps] def equiv_fun_on_fintype [fintype α] : (α →₀ M) ≃ (α → M) :=
⟨λf a, f a, λf, mk (finset.univ.filter $ λa, f a ≠ 0) f (by simp only [true_and, finset.mem_univ,
iff_self, finset.mem_filter, finset.filter_congr_decidable, forall_true_iff]),
begin intro f, ext a, refl end,
begin intro f, ext a, refl end⟩
@[simp] lemma equiv_fun_on_fintype_symm_coe {α} [fintype α] (f : α →₀ M) :
equiv_fun_on_fintype.symm f = f :=
by { ext, simp [equiv_fun_on_fintype], }
end basic
/-! ### Declarations about `single` -/
section single
variables [has_zero M] {a a' : α} {b : M}
/-- `single a b` is the finitely supported function which has
value `b` at `a` and zero otherwise. -/
def single (a : α) (b : M) : α →₀ M :=
⟨if b = 0 then ∅ else {a}, λ a', if a = a' then b else 0, λ a', begin
by_cases hb : b = 0; by_cases a = a';
simp only [hb, h, if_pos, if_false, mem_singleton],
{ exact ⟨false.elim, λ H, H rfl⟩ },
{ exact ⟨false.elim, λ H, H rfl⟩ },
{ exact ⟨λ _, hb, λ _, rfl⟩ },
{ exact ⟨λ H _, h H.symm, λ H, (H rfl).elim⟩ }
end⟩
lemma single_apply [decidable (a = a')] : single a b a' = if a = a' then b else 0 :=
by convert rfl
lemma single_eq_indicator : ⇑(single a b) = set.indicator {a} (λ _, b) :=
by { ext, simp [single_apply, set.indicator, @eq_comm _ a] }
@[simp] lemma single_eq_same : (single a b : α →₀ M) a = b :=
if_pos rfl
@[simp] lemma single_eq_of_ne (h : a ≠ a') : (single a b : α →₀ M) a' = 0 :=
if_neg h
lemma single_eq_update : ⇑(single a b) = function.update 0 a b :=
by rw [single_eq_indicator, ← set.piecewise_eq_indicator, set.piecewise_singleton]
lemma single_eq_pi_single : ⇑(single a b) = pi.single a b :=
single_eq_update
@[simp] lemma single_zero : (single a 0 : α →₀ M) = 0 :=
coe_fn_injective $ by simpa only [single_eq_update, coe_zero]
using function.update_eq_self a (0 : α → M)
lemma single_of_single_apply (a a' : α) (b : M) :
single a ((single a' b) a) = single a' (single a' b) a :=
begin
rw [single_apply, single_apply],
ext,
split_ifs,
{ rw h, },
{ rw [zero_apply, single_apply, if_t_t], },
end
lemma support_single_ne_zero (hb : b ≠ 0) : (single a b).support = {a} :=
if_neg hb
lemma support_single_subset : (single a b).support ⊆ {a} :=
show ite _ _ _ ⊆ _, by split_ifs; [exact empty_subset _, exact subset.refl _]
lemma single_apply_mem (x) : single a b x ∈ ({0, b} : set M) :=
by rcases em (a = x) with (rfl|hx); [simp, simp [single_eq_of_ne hx]]
lemma range_single_subset : set.range (single a b) ⊆ {0, b} :=
set.range_subset_iff.2 single_apply_mem
/-- `finsupp.single a b` is injective in `b`. For the statement that it is injective in `a`, see
`finsupp.single_left_injective` -/
lemma single_injective (a : α) : function.injective (single a : M → α →₀ M) :=
assume b₁ b₂ eq,
have (single a b₁ : α →₀ M) a = (single a b₂ : α →₀ M) a, by rw eq,
by rwa [single_eq_same, single_eq_same] at this
lemma single_apply_eq_zero {a x : α} {b : M} : single a b x = 0 ↔ (x = a → b = 0) :=
by simp [single_eq_indicator]
lemma mem_support_single (a a' : α) (b : M) :
a ∈ (single a' b).support ↔ a = a' ∧ b ≠ 0 :=
by simp [single_apply_eq_zero, not_or_distrib]
lemma eq_single_iff {f : α →₀ M} {a b} : f = single a b ↔ f.support ⊆ {a} ∧ f a = b :=
begin
refine ⟨λ h, h.symm ▸ ⟨support_single_subset, single_eq_same⟩, _⟩,
rintro ⟨h, rfl⟩,
ext x,
by_cases hx : a = x; simp only [hx, single_eq_same, single_eq_of_ne, ne.def, not_false_iff],
exact not_mem_support_iff.1 (mt (λ hx, (mem_singleton.1 (h hx)).symm) hx)
end
lemma single_eq_single_iff (a₁ a₂ : α) (b₁ b₂ : M) :
single a₁ b₁ = single a₂ b₂ ↔ ((a₁ = a₂ ∧ b₁ = b₂) ∨ (b₁ = 0 ∧ b₂ = 0)) :=
begin
split,
{ assume eq,
by_cases a₁ = a₂,
{ refine or.inl ⟨h, _⟩,
rwa [h, (single_injective a₂).eq_iff] at eq },
{ rw [ext_iff] at eq,
have h₁ := eq a₁,
have h₂ := eq a₂,
simp only [single_eq_same, single_eq_of_ne h, single_eq_of_ne (ne.symm h)] at h₁ h₂,
exact or.inr ⟨h₁, h₂.symm⟩ } },
{ rintros (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩),
{ refl },
{ rw [single_zero, single_zero] } }
end
/-- `finsupp.single a b` is injective in `a`. For the statement that it is injective in `b`, see
`finsupp.single_injective` -/
lemma single_left_injective (h : b ≠ 0) : function.injective (λ a : α, single a b) :=
λ a a' H, (((single_eq_single_iff _ _ _ _).mp H).resolve_right $ λ hb, h hb.1).left
lemma single_left_inj (h : b ≠ 0) : single a b = single a' b ↔ a = a' :=
(single_left_injective h).eq_iff
lemma support_single_ne_bot (i : α) (h : b ≠ 0) :
(single i b).support ≠ ⊥ :=
begin
have : i ∈ (single i b).support := by simpa using h,
intro H,
simpa [H]
end
lemma support_single_disjoint {b' : M} (hb : b ≠ 0) (hb' : b' ≠ 0) {i j : α} :
disjoint (single i b).support (single j b').support ↔ i ≠ j :=
by rw [support_single_ne_zero hb, support_single_ne_zero hb', disjoint_singleton]
@[simp] lemma single_eq_zero : single a b = 0 ↔ b = 0 :=
by simp [ext_iff, single_eq_indicator]
lemma single_swap (a₁ a₂ : α) (b : M) : single a₁ b a₂ = single a₂ b a₁ :=
by simp only [single_apply]; ac_refl
instance [nonempty α] [nontrivial M] : nontrivial (α →₀ M) :=
begin
inhabit α,
rcases exists_ne (0 : M) with ⟨x, hx⟩,
exact nontrivial_of_ne (single (default α) x) 0 (mt single_eq_zero.1 hx)
end
lemma unique_single [unique α] (x : α →₀ M) : x = single (default α) (x (default α)) :=
ext $ unique.forall_iff.2 single_eq_same.symm
lemma unique_ext [unique α] {f g : α →₀ M} (h : f (default α) = g (default α)) : f = g :=
ext $ λ a, by rwa [unique.eq_default a]
lemma unique_ext_iff [unique α] {f g : α →₀ M} : f = g ↔ f (default α) = g (default α) :=
⟨λ h, h ▸ rfl, unique_ext⟩
@[simp] lemma unique_single_eq_iff [unique α] {b' : M} :
single a b = single a' b' ↔ b = b' :=
by rw [unique_ext_iff, unique.eq_default a, unique.eq_default a', single_eq_same, single_eq_same]
lemma support_eq_singleton {f : α →₀ M} {a : α} :
f.support = {a} ↔ f a ≠ 0 ∧ f = single a (f a) :=
⟨λ h, ⟨mem_support_iff.1 $ h.symm ▸ finset.mem_singleton_self a,
eq_single_iff.2 ⟨subset_of_eq h, rfl⟩⟩, λ h, h.2.symm ▸ support_single_ne_zero h.1⟩
lemma support_eq_singleton' {f : α →₀ M} {a : α} :
f.support = {a} ↔ ∃ b ≠ 0, f = single a b :=
⟨λ h, let h := support_eq_singleton.1 h in ⟨_, h.1, h.2⟩,
λ ⟨b, hb, hf⟩, hf.symm ▸ support_single_ne_zero hb⟩
lemma card_support_eq_one {f : α →₀ M} : card f.support = 1 ↔ ∃ a, f a ≠ 0 ∧ f = single a (f a) :=
by simp only [card_eq_one, support_eq_singleton]
lemma card_support_eq_one' {f : α →₀ M} : card f.support = 1 ↔ ∃ a (b ≠ 0), f = single a b :=
by simp only [card_eq_one, support_eq_singleton']
lemma support_subset_singleton {f : α →₀ M} {a : α} :
f.support ⊆ {a} ↔ f = single a (f a) :=
⟨λ h, eq_single_iff.mpr ⟨h, rfl⟩, λ h, (eq_single_iff.mp h).left⟩
lemma support_subset_singleton' {f : α →₀ M} {a : α} :
f.support ⊆ {a} ↔ ∃ b, f = single a b :=
⟨λ h, ⟨f a, support_subset_singleton.mp h⟩,
λ ⟨b, hb⟩, by rw [hb, support_subset_singleton, single_eq_same]⟩
lemma card_support_le_one [nonempty α] {f : α →₀ M} :
card f.support ≤ 1 ↔ ∃ a, f = single a (f a) :=
by simp only [card_le_one_iff_subset_singleton, support_subset_singleton]
lemma card_support_le_one' [nonempty α] {f : α →₀ M} :
card f.support ≤ 1 ↔ ∃ a b, f = single a b :=
by simp only [card_le_one_iff_subset_singleton, support_subset_singleton']
@[simp] lemma equiv_fun_on_fintype_single [fintype α] (x : α) (m : M) :
(@finsupp.equiv_fun_on_fintype α M _ _) (finsupp.single x m) = pi.single x m :=
by { ext, simp [finsupp.single_eq_pi_single, finsupp.equiv_fun_on_fintype], }
@[simp] lemma equiv_fun_on_fintype_symm_single [fintype α] (x : α) (m : M) :
(@finsupp.equiv_fun_on_fintype α M _ _).symm (pi.single x m) = finsupp.single x m :=
by { ext, simp [finsupp.single_eq_pi_single, finsupp.equiv_fun_on_fintype], }
end single
/-! ### Declarations about `update` -/
section update
variables [has_zero M] (f : α →₀ M) (a : α) (b : M) (i : α)
/-- Replace the value of a `α →₀ M` at a given point `a : α` by a given value `b : M`.
If `b = 0`, this amounts to removing `a` from the `finsupp.support`.
Otherwise, if `a` was not in the `finsupp.support`, it is added to it.
This is the finitely-supported version of `function.update`. -/
def update : α →₀ M :=
⟨if b = 0 then f.support.erase a else insert a f.support,
function.update f a b,
λ i, begin
simp only [function.update_apply, ne.def],
split_ifs with hb ha ha hb;
simp [ha, hb]
end⟩
@[simp] lemma coe_update : (f.update a b : α → M) = function.update f a b := rfl
@[simp] lemma update_self : f.update a (f a) = f :=
by { ext, simp }
lemma support_update : support (f.update a b) =
if b = 0 then f.support.erase a else insert a f.support := rfl
@[simp] lemma support_update_zero : support (f.update a 0) = f.support.erase a := if_pos rfl
variables {b}
lemma support_update_ne_zero (h : b ≠ 0) : support (f.update a b) = insert a f.support := if_neg h
end update
/-! ### Declarations about `on_finset` -/
section on_finset
variables [has_zero M]
/-- `on_finset s f hf` is the finsupp function representing `f` restricted to the finset `s`.
The function needs to be `0` outside of `s`. Use this when the set needs to be filtered anyways,
otherwise a better set representation is often available. -/
def on_finset (s : finset α) (f : α → M) (hf : ∀a, f a ≠ 0 → a ∈ s) : α →₀ M :=
⟨s.filter (λa, f a ≠ 0), f, by simpa⟩
@[simp] lemma on_finset_apply {s : finset α} {f : α → M} {hf a} :
(on_finset s f hf : α →₀ M) a = f a :=
rfl
@[simp] lemma support_on_finset_subset {s : finset α} {f : α → M} {hf} :
(on_finset s f hf).support ⊆ s :=
filter_subset _ _
@[simp] lemma mem_support_on_finset
{s : finset α} {f : α → M} (hf : ∀ (a : α), f a ≠ 0 → a ∈ s) {a : α} :
a ∈ (finsupp.on_finset s f hf).support ↔ f a ≠ 0 :=
by rw [finsupp.mem_support_iff, finsupp.on_finset_apply]
lemma support_on_finset
{s : finset α} {f : α → M} (hf : ∀ (a : α), f a ≠ 0 → a ∈ s) :
(finsupp.on_finset s f hf).support = s.filter (λ a, f a ≠ 0) :=
rfl
end on_finset
section of_support_finite
variables [has_zero M]
/-- The natural `finsupp` induced by the function `f` given that it has finite support. -/
noncomputable def of_support_finite
(f : α → M) (hf : (function.support f).finite) : α →₀ M :=
{ support := hf.to_finset,
to_fun := f,
mem_support_to_fun := λ _, hf.mem_to_finset }
lemma of_support_finite_coe {f : α → M} {hf : (function.support f).finite} :
(of_support_finite f hf : α → M) = f := rfl
instance : can_lift (α → M) (α →₀ M) :=
{ coe := coe_fn,
cond := λ f, (function.support f).finite,
prf := λ f hf, ⟨of_support_finite f hf, rfl⟩ }
end of_support_finite
/-! ### Declarations about `map_range` -/
section map_range
variables [has_zero M] [has_zero N] [has_zero P]
/-- The composition of `f : M → N` and `g : α →₀ M` is
`map_range f hf g : α →₀ N`, well-defined when `f 0 = 0`.
This preserves the structure on `f`, and exists in various bundled forms for when `f` is itself
bundled:
* `finsupp.map_range.equiv`
* `finsupp.map_range.zero_hom`
* `finsupp.map_range.add_monoid_hom`
* `finsupp.map_range.add_equiv`
* `finsupp.map_range.linear_map`
* `finsupp.map_range.linear_equiv`
-/
def map_range (f : M → N) (hf : f 0 = 0) (g : α →₀ M) : α →₀ N :=
on_finset g.support (f ∘ g) $
assume a, by rw [mem_support_iff, not_imp_not]; exact λ H, (congr_arg f H).trans hf
@[simp] lemma map_range_apply {f : M → N} {hf : f 0 = 0} {g : α →₀ M} {a : α} :
map_range f hf g a = f (g a) :=
rfl
@[simp] lemma map_range_zero {f : M → N} {hf : f 0 = 0} : map_range f hf (0 : α →₀ M) = 0 :=
ext $ λ a, by simp only [hf, zero_apply, map_range_apply]
@[simp] lemma map_range_id (g : α →₀ M) : map_range id rfl g = g :=
ext $ λ _, rfl
lemma map_range_comp
(f : N → P) (hf : f 0 = 0) (f₂ : M → N) (hf₂ : f₂ 0 = 0) (h : (f ∘ f₂) 0 = 0) (g : α →₀ M) :
map_range (f ∘ f₂) h g = map_range f hf (map_range f₂ hf₂ g) :=
ext $ λ _, rfl
lemma support_map_range {f : M → N} {hf : f 0 = 0} {g : α →₀ M} :
(map_range f hf g).support ⊆ g.support :=
support_on_finset_subset
@[simp] lemma map_range_single {f : M → N} {hf : f 0 = 0} {a : α} {b : M} :
map_range f hf (single a b) = single a (f b) :=
ext $ λ a', show f (ite _ _ _) = ite _ _ _, by split_ifs; [refl, exact hf]
end map_range
/-! ### Declarations about `emb_domain` -/
section emb_domain
variables [has_zero M] [has_zero N]
/-- Given `f : α ↪ β` and `v : α →₀ M`, `emb_domain f v : β →₀ M`
is the finitely supported function whose value at `f a : β` is `v a`.
For a `b : β` outside the range of `f`, it is zero. -/
def emb_domain (f : α ↪ β) (v : α →₀ M) : β →₀ M :=
begin
refine ⟨v.support.map f, λa₂,
if h : a₂ ∈ v.support.map f then v (v.support.choose (λa₁, f a₁ = a₂) _) else 0, _⟩,
{ rcases finset.mem_map.1 h with ⟨a, ha, rfl⟩,
exact exists_unique.intro a ⟨ha, rfl⟩ (assume b ⟨_, hb⟩, f.injective hb) },
{ assume a₂,
split_ifs,
{ simp only [h, true_iff, ne.def],
rw [← not_mem_support_iff, not_not],
apply finset.choose_mem },
{ simp only [h, ne.def, ne_self_iff_false] } }
end
@[simp] lemma support_emb_domain (f : α ↪ β) (v : α →₀ M) :
(emb_domain f v).support = v.support.map f :=
rfl
@[simp] lemma emb_domain_zero (f : α ↪ β) : (emb_domain f 0 : β →₀ M) = 0 :=
rfl
@[simp] lemma emb_domain_apply (f : α ↪ β) (v : α →₀ M) (a : α) :
emb_domain f v (f a) = v a :=
begin
change dite _ _ _ = _,
split_ifs; rw [finset.mem_map' f] at h,
{ refine congr_arg (v : α → M) (f.inj' _),
exact finset.choose_property (λa₁, f a₁ = f a) _ _ },
{ exact (not_mem_support_iff.1 h).symm }
end
lemma emb_domain_notin_range (f : α ↪ β) (v : α →₀ M) (a : β) (h : a ∉ set.range f) :
emb_domain f v a = 0 :=
begin
refine dif_neg (mt (assume h, _) h),
rcases finset.mem_map.1 h with ⟨a, h, rfl⟩,
exact set.mem_range_self a
end
lemma emb_domain_injective (f : α ↪ β) :
function.injective (emb_domain f : (α →₀ M) → (β →₀ M)) :=
λ l₁ l₂ h, ext $ λ a, by simpa only [emb_domain_apply] using ext_iff.1 h (f a)
@[simp] lemma emb_domain_inj {f : α ↪ β} {l₁ l₂ : α →₀ M} :
emb_domain f l₁ = emb_domain f l₂ ↔ l₁ = l₂ :=
(emb_domain_injective f).eq_iff
@[simp] lemma emb_domain_eq_zero {f : α ↪ β} {l : α →₀ M} :
emb_domain f l = 0 ↔ l = 0 :=
(emb_domain_injective f).eq_iff' $ emb_domain_zero f
lemma emb_domain_map_range
(f : α ↪ β) (g : M → N) (p : α →₀ M) (hg : g 0 = 0) :
emb_domain f (map_range g hg p) = map_range g hg (emb_domain f p) :=
begin
ext a,
by_cases a ∈ set.range f,
{ rcases h with ⟨a', rfl⟩,
rw [map_range_apply, emb_domain_apply, emb_domain_apply, map_range_apply] },
{ rw [map_range_apply, emb_domain_notin_range, emb_domain_notin_range, ← hg]; assumption }
end
lemma single_of_emb_domain_single
(l : α →₀ M) (f : α ↪ β) (a : β) (b : M) (hb : b ≠ 0)
(h : l.emb_domain f = single a b) :
∃ x, l = single x b ∧ f x = a :=
begin
have h_map_support : finset.map f (l.support) = {a},
by rw [←support_emb_domain, h, support_single_ne_zero hb]; refl,
have ha : a ∈ finset.map f (l.support),
by simp only [h_map_support, finset.mem_singleton],
rcases finset.mem_map.1 ha with ⟨c, hc₁, hc₂⟩,
use c,
split,
{ ext d,
rw [← emb_domain_apply f l, h],
by_cases h_cases : c = d,
{ simp only [eq.symm h_cases, hc₂, single_eq_same] },
{ rw [single_apply, single_apply, if_neg, if_neg h_cases],
by_contra hfd,
exact h_cases (f.injective (hc₂.trans hfd)) } },
{ exact hc₂ }
end
@[simp] lemma emb_domain_single (f : α ↪ β) (a : α) (m : M) :
emb_domain f (single a m) = single (f a) m :=
begin
ext b,
by_cases h : b ∈ set.range f,
{ rcases h with ⟨a', rfl⟩,
simp [single_apply], },
{ simp only [emb_domain_notin_range, h, single_apply, not_false_iff],
rw if_neg,
rintro rfl,
simpa using h, },
end
end emb_domain
/-! ### Declarations about `zip_with` -/
section zip_with
variables [has_zero M] [has_zero N] [has_zero P]
/-- `zip_with f hf g₁ g₂` is the finitely supported function satisfying
`zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, and it is well-defined when `f 0 0 = 0`. -/
def zip_with (f : M → N → P) (hf : f 0 0 = 0) (g₁ : α →₀ M) (g₂ : α →₀ N) : (α →₀ P) :=
on_finset (g₁.support ∪ g₂.support) (λa, f (g₁ a) (g₂ a)) $ λ a H,
begin
simp only [mem_union, mem_support_iff, ne], rw [← not_and_distrib],
rintro ⟨h₁, h₂⟩, rw [h₁, h₂] at H, exact H hf
end
@[simp] lemma zip_with_apply
{f : M → N → P} {hf : f 0 0 = 0} {g₁ : α →₀ M} {g₂ : α →₀ N} {a : α} :
zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a) :=
rfl
lemma support_zip_with [D : decidable_eq α] {f : M → N → P} {hf : f 0 0 = 0}
{g₁ : α →₀ M} {g₂ : α →₀ N} : (zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support :=
by rw subsingleton.elim D; exact support_on_finset_subset
end zip_with
/-! ### Declarations about `erase` -/
section erase
variables [has_zero M]
/-- `erase a f` is the finitely supported function equal to `f` except at `a` where it is equal to
`0`. -/
def erase (a : α) (f : α →₀ M) : α →₀ M :=
⟨f.support.erase a, (λa', if a' = a then 0 else f a'),
assume a', by rw [mem_erase, mem_support_iff]; split_ifs;
[exact ⟨λ H _, H.1 h, λ H, (H rfl).elim⟩,
exact and_iff_right h]⟩
@[simp] lemma support_erase {a : α} {f : α →₀ M} :
(f.erase a).support = f.support.erase a :=
rfl
@[simp] lemma erase_same {a : α} {f : α →₀ M} : (f.erase a) a = 0 :=
if_pos rfl
@[simp] lemma erase_ne {a a' : α} {f : α →₀ M} (h : a' ≠ a) : (f.erase a) a' = f a' :=
if_neg h
@[simp] lemma erase_single {a : α} {b : M} : (erase a (single a b)) = 0 :=
begin
ext s, by_cases hs : s = a,
{ rw [hs, erase_same], refl },
{ rw [erase_ne hs], exact single_eq_of_ne (ne.symm hs) }
end
lemma erase_single_ne {a a' : α} {b : M} (h : a ≠ a') : (erase a (single a' b)) = single a' b :=
begin
ext s, by_cases hs : s = a,
{ rw [hs, erase_same, single_eq_of_ne (h.symm)] },
{ rw [erase_ne hs] }
end
@[simp] lemma erase_zero (a : α) : erase a (0 : α →₀ M) = 0 :=
by rw [← support_eq_empty, support_erase, support_zero, erase_empty]
end erase
/-!
### Declarations about `sum` and `prod`
In most of this section, the domain `β` is assumed to be an `add_monoid`.
-/
section sum_prod
/-- `prod f g` is the product of `g a (f a)` over the support of `f`. -/
@[to_additive "`sum f g` is the sum of `g a (f a)` over the support of `f`. "]
def prod [has_zero M] [comm_monoid N] (f : α →₀ M) (g : α → M → N) : N :=
∏ a in f.support, g a (f a)
variables [has_zero M] [has_zero M'] [comm_monoid N]
@[to_additive]
lemma prod_of_support_subset (f : α →₀ M) {s : finset α}
(hs : f.support ⊆ s) (g : α → M → N) (h : ∀ i ∈ s, g i 0 = 1) :
f.prod g = ∏ x in s, g x (f x) :=
finset.prod_subset hs $ λ x hxs hx, h x hxs ▸ congr_arg (g x) $ not_mem_support_iff.1 hx
@[to_additive]
lemma prod_fintype [fintype α] (f : α →₀ M) (g : α → M → N) (h : ∀ i, g i 0 = 1) :
f.prod g = ∏ i, g i (f i) :=
f.prod_of_support_subset (subset_univ _) g (λ x _, h x)
@[simp, to_additive]
lemma prod_single_index {a : α} {b : M} {h : α → M → N} (h_zero : h a 0 = 1) :
(single a b).prod h = h a b :=
calc (single a b).prod h = ∏ x in {a}, h x (single a b x) :
prod_of_support_subset _ support_single_subset h $ λ x hx, (mem_singleton.1 hx).symm ▸ h_zero
... = h a b : by simp
@[to_additive]
lemma prod_map_range_index {f : M → M'} {hf : f 0 = 0} {g : α →₀ M} {h : α → M' → N}
(h0 : ∀a, h a 0 = 1) : (map_range f hf g).prod h = g.prod (λa b, h a (f b)) :=
finset.prod_subset support_map_range $ λ _ _ H,
by rw [not_mem_support_iff.1 H, h0]
@[simp, to_additive]
lemma prod_zero_index {h : α → M → N} : (0 : α →₀ M).prod h = 1 := rfl
@[to_additive]
lemma prod_comm (f : α →₀ M) (g : β →₀ M') (h : α → M → β → M' → N) :
f.prod (λ x v, g.prod (λ x' v', h x v x' v')) = g.prod (λ x' v', f.prod (λ x v, h x v x' v')) :=
finset.prod_comm
@[simp, to_additive]
lemma prod_ite_eq [decidable_eq α] (f : α →₀ M) (a : α) (b : α → M → N) :
f.prod (λ x v, ite (a = x) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 :=
by { dsimp [finsupp.prod], rw f.support.prod_ite_eq, }
@[simp] lemma sum_ite_self_eq
[decidable_eq α] {N : Type*} [add_comm_monoid N] (f : α →₀ N) (a : α) :
f.sum (λ x v, ite (a = x) v 0) = f a :=
by { convert f.sum_ite_eq a (λ x, id), simp [ite_eq_right_iff.2 eq.symm] }
/-- A restatement of `prod_ite_eq` with the equality test reversed. -/
@[simp, to_additive "A restatement of `sum_ite_eq` with the equality test reversed."]
lemma prod_ite_eq' [decidable_eq α] (f : α →₀ M) (a : α) (b : α → M → N) :
f.prod (λ x v, ite (x = a) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 :=
by { dsimp [finsupp.prod], rw f.support.prod_ite_eq', }
@[simp] lemma sum_ite_self_eq'
[decidable_eq α] {N : Type*} [add_comm_monoid N] (f : α →₀ N) (a : α) :
f.sum (λ x v, ite (x = a) v 0) = f a :=
by { convert f.sum_ite_eq' a (λ x, id), simp [ite_eq_right_iff.2 eq.symm] }
@[simp] lemma prod_pow [fintype α] (f : α →₀ ℕ) (g : α → N) :
f.prod (λ a b, g a ^ b) = ∏ a, g a ^ (f a) :=
f.prod_fintype _ $ λ a, pow_zero _
/-- If `g` maps a second argument of 0 to 1, then multiplying it over the
result of `on_finset` is the same as multiplying it over the original
`finset`. -/
@[to_additive "If `g` maps a second argument of 0 to 0, summing it over the
result of `on_finset` is the same as summing it over the original
`finset`."]
lemma on_finset_prod {s : finset α} {f : α → M} {g : α → M → N}
(hf : ∀a, f a ≠ 0 → a ∈ s) (hg : ∀ a, g a 0 = 1) :
(on_finset s f hf).prod g = ∏ a in s, g a (f a) :=
finset.prod_subset support_on_finset_subset $ by simp [*] { contextual := tt }
@[to_additive]
lemma _root_.submonoid.finsupp_prod_mem (S : submonoid N) (f : α →₀ M) (g : α → M → N)
(h : ∀ c, f c ≠ 0 → g c (f c) ∈ S) : f.prod g ∈ S :=
S.prod_mem $ λ i hi, h _ (finsupp.mem_support_iff.mp hi)
end sum_prod
/-!
### Additive monoid structure on `α →₀ M`
-/
section add_zero_class
variables [add_zero_class M]
instance : has_add (α →₀ M) := ⟨zip_with (+) (add_zero 0)⟩
@[simp] lemma coe_add (f g : α →₀ M) : ⇑(f + g) = f + g := rfl
lemma add_apply (g₁ g₂ : α →₀ M) (a : α) : (g₁ + g₂) a = g₁ a + g₂ a := rfl
lemma support_add [decidable_eq α] {g₁ g₂ : α →₀ M} :
(g₁ + g₂).support ⊆ g₁.support ∪ g₂.support :=
support_zip_with
lemma support_add_eq [decidable_eq α] {g₁ g₂ : α →₀ M} (h : disjoint g₁.support g₂.support) :
(g₁ + g₂).support = g₁.support ∪ g₂.support :=
le_antisymm support_zip_with $ assume a ha,
(finset.mem_union.1 ha).elim
(assume ha, have a ∉ g₂.support, from disjoint_left.1 h ha,
by simp only [mem_support_iff, not_not] at *;
simpa only [add_apply, this, add_zero])
(assume ha, have a ∉ g₁.support, from disjoint_right.1 h ha,
by simp only [mem_support_iff, not_not] at *;
simpa only [add_apply, this, zero_add])
@[simp] lemma single_add {a : α} {b₁ b₂ : M} : single a (b₁ + b₂) = single a b₁ + single a b₂ :=
ext $ assume a',
begin
by_cases h : a = a',
{ rw [h, add_apply, single_eq_same, single_eq_same, single_eq_same] },
{ rw [add_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, zero_add] }
end
instance : add_zero_class (α →₀ M) :=
{ zero := 0,
add := (+),
zero_add := assume ⟨s, f, hf⟩, ext $ assume a, zero_add _,
add_zero := assume ⟨s, f, hf⟩, ext $ assume a, add_zero _ }
/-- `finsupp.single` as an `add_monoid_hom`.
See `finsupp.lsingle` for the stronger version as a linear map.
-/
@[simps] def single_add_hom (a : α) : M →+ α →₀ M :=
⟨single a, single_zero, λ _ _, single_add⟩
/-- Evaluation of a function `f : α →₀ M` at a point as an additive monoid homomorphism.
See `finsupp.lapply` for the stronger version as a linear map. -/
@[simps apply]
def apply_add_hom (a : α) : (α →₀ M) →+ M := ⟨λ g, g a, zero_apply, λ _ _, add_apply _ _ _⟩
lemma update_eq_single_add_erase (f : α →₀ M) (a : α) (b : M) :
f.update a b = single a b + f.erase a :=
begin
ext j,
rcases eq_or_ne a j with rfl|h,
{ simp },
{ simp [function.update_noteq h.symm, single_apply, h, erase_ne, h.symm] }
end
lemma update_eq_erase_add_single (f : α →₀ M) (a : α) (b : M) :
f.update a b = f.erase a + single a b :=
begin
ext j,
rcases eq_or_ne a j with rfl|h,
{ simp },
{ simp [function.update_noteq h.symm, single_apply, h, erase_ne, h.symm] }
end
lemma single_add_erase (a : α) (f : α →₀ M) : single a (f a) + f.erase a = f :=
by rw [←update_eq_single_add_erase, update_self]
lemma erase_add_single (a : α) (f : α →₀ M) : f.erase a + single a (f a) = f :=
by rw [←update_eq_erase_add_single, update_self]
@[simp] lemma erase_add (a : α) (f f' : α →₀ M) : erase a (f + f') = erase a f + erase a f' :=
begin
ext s, by_cases hs : s = a,
{ rw [hs, add_apply, erase_same, erase_same, erase_same, add_zero] },
rw [add_apply, erase_ne hs, erase_ne hs, erase_ne hs, add_apply],
end
/-- `finsupp.erase` as an `add_monoid_hom`. -/
@[simps]
def erase_add_hom (a : α) : (α →₀ M) →+ (α →₀ M) :=
{ to_fun := erase a, map_zero' := erase_zero a, map_add' := erase_add a }
@[elab_as_eliminator]
protected theorem induction {p : (α →₀ M) → Prop} (f : α →₀ M)
(h0 : p 0) (ha : ∀a b (f : α →₀ M), a ∉ f.support → b ≠ 0 → p f → p (single a b + f)) :
p f :=
suffices ∀s (f : α →₀ M), f.support = s → p f, from this _ _ rfl,
assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $
assume a s has ih f hf,
suffices p (single a (f a) + f.erase a), by rwa [single_add_erase] at this,
begin
apply ha,
{ rw [support_erase, mem_erase], exact λ H, H.1 rfl },
{ rw [← mem_support_iff, hf], exact mem_insert_self _ _ },
{ apply ih _ _,
rw [support_erase, hf, finset.erase_insert has] }
end
lemma induction₂ {p : (α →₀ M) → Prop} (f : α →₀ M)
(h0 : p 0) (ha : ∀a b (f : α →₀ M), a ∉ f.support → b ≠ 0 → p f → p (f + single a b)) :
p f :=
suffices ∀s (f : α →₀ M), f.support = s → p f, from this _ _ rfl,
assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $
assume a s has ih f hf,
suffices p (f.erase a + single a (f a)), by rwa [erase_add_single] at this,
begin
apply ha,
{ rw [support_erase, mem_erase], exact λ H, H.1 rfl },
{ rw [← mem_support_iff, hf], exact mem_insert_self _ _ },
{ apply ih _ _,
rw [support_erase, hf, finset.erase_insert has] }
end
lemma induction_linear {p : (α →₀ M) → Prop} (f : α →₀ M)
(h0 : p 0) (hadd : ∀ f g : α →₀ M, p f → p g → p (f + g)) (hsingle : ∀ a b, p (single a b)) :
p f :=
induction₂ f h0 (λ a b f _ _ w, hadd _ _ w (hsingle _ _))
@[simp] lemma add_closure_Union_range_single :
add_submonoid.closure (⋃ a : α, set.range (single a : M → α →₀ M)) = ⊤ :=
top_unique $ λ x hx, finsupp.induction x (add_submonoid.zero_mem _) $
λ a b f ha hb hf, add_submonoid.add_mem _
(add_submonoid.subset_closure $ set.mem_Union.2 ⟨a, set.mem_range_self _⟩) hf
/-- If two additive homomorphisms from `α →₀ M` are equal on each `single a b`, then
they are equal. -/
lemma add_hom_ext [add_zero_class N] ⦃f g : (α →₀ M) →+ N⦄
(H : ∀ x y, f (single x y) = g (single x y)) :
f = g :=
begin
refine add_monoid_hom.eq_of_eq_on_mdense add_closure_Union_range_single (λ f hf, _),
simp only [set.mem_Union, set.mem_range] at hf,
rcases hf with ⟨x, y, rfl⟩,
apply H
end
/-- If two additive homomorphisms from `α →₀ M` are equal on each `single a b`, then
they are equal.
We formulate this using equality of `add_monoid_hom`s so that `ext` tactic can apply a type-specific
extensionality lemma after this one. E.g., if the fiber `M` is `ℕ` or `ℤ`, then it suffices to
verify `f (single a 1) = g (single a 1)`. -/
@[ext] lemma add_hom_ext' [add_zero_class N] ⦃f g : (α →₀ M) →+ N⦄
(H : ∀ x, f.comp (single_add_hom x) = g.comp (single_add_hom x)) :
f = g :=
add_hom_ext $ λ x, add_monoid_hom.congr_fun (H x)
lemma mul_hom_ext [mul_one_class N] ⦃f g : multiplicative (α →₀ M) →* N⦄
(H : ∀ x y, f (multiplicative.of_add $ single x y) = g (multiplicative.of_add $ single x y)) :
f = g :=
monoid_hom.ext $ add_monoid_hom.congr_fun $
@add_hom_ext α M (additive N) _ _ f.to_additive'' g.to_additive'' H
@[ext] lemma mul_hom_ext' [mul_one_class N] {f g : multiplicative (α →₀ M) →* N}
(H : ∀ x, f.comp (single_add_hom x).to_multiplicative =
g.comp (single_add_hom x).to_multiplicative) :
f = g :=
mul_hom_ext $ λ x, monoid_hom.congr_fun (H x)
lemma map_range_add [add_zero_class N]
{f : M → N} {hf : f 0 = 0} (hf' : ∀ x y, f (x + y) = f x + f y) (v₁ v₂ : α →₀ M) :
map_range f hf (v₁ + v₂) = map_range f hf v₁ + map_range f hf v₂ :=
ext $ λ a, by simp only [hf', add_apply, map_range_apply]
/-- Bundle `emb_domain f` as an additive map from `α →₀ M` to `β →₀ M`. -/
@[simps] def emb_domain.add_monoid_hom (f : α ↪ β) : (α →₀ M) →+ (β →₀ M) :=
{ to_fun := λ v, emb_domain f v,
map_zero' := by simp,
map_add' := λ v w,
begin
ext b,
by_cases h : b ∈ set.range f,
{ rcases h with ⟨a, rfl⟩,
simp, },
{ simp [emb_domain_notin_range, h], },
end, }
@[simp] lemma emb_domain_add (f : α ↪ β) (v w : α →₀ M) :
emb_domain f (v + w) = emb_domain f v + emb_domain f w :=
(emb_domain.add_monoid_hom f).map_add v w
end add_zero_class
section add_monoid
variables [add_monoid M]
instance : add_monoid (α →₀ M) :=
{ add_monoid .
zero := 0,
add := (+),
add_assoc := assume ⟨s, f, hf⟩ ⟨t, g, hg⟩ ⟨u, h, hh⟩, ext $ assume a, add_assoc _ _ _,
nsmul := λ n v, v.map_range ((•) n) (nsmul_zero _),
nsmul_zero' := λ v, by { ext i, simp },
nsmul_succ' := λ n v, by { ext i, simp [nat.succ_eq_one_add, add_nsmul] },
.. finsupp.add_zero_class }
end add_monoid
end finsupp
@[to_additive]
lemma mul_equiv.map_finsupp_prod [has_zero M] [comm_monoid N] [comm_monoid P]
(h : N ≃* P) (f : α →₀ M) (g : α → M → N) : h (f.prod g) = f.prod (λ a b, h (g a b)) :=
h.map_prod _ _
@[to_additive]
lemma monoid_hom.map_finsupp_prod [has_zero M] [comm_monoid N] [comm_monoid P]
(h : N →* P) (f : α →₀ M) (g : α → M → N) : h (f.prod g) = f.prod (λ a b, h (g a b)) :=
h.map_prod _ _
lemma ring_hom.map_finsupp_sum [has_zero M] [semiring R] [semiring S]
(h : R →+* S) (f : α →₀ M) (g : α → M → R) : h (f.sum g) = f.sum (λ a b, h (g a b)) :=
h.map_sum _ _
lemma ring_hom.map_finsupp_prod [has_zero M] [comm_semiring R] [comm_semiring S]
(h : R →+* S) (f : α →₀ M) (g : α → M → R) : h (f.prod g) = f.prod (λ a b, h (g a b)) :=
h.map_prod _ _
@[to_additive]
lemma monoid_hom.coe_finsupp_prod [has_zero β] [monoid N] [comm_monoid P]
(f : α →₀ β) (g : α → β → N →* P) :
⇑(f.prod g) = f.prod (λ i fi, g i fi) :=
monoid_hom.coe_prod _ _
@[simp, to_additive]
lemma monoid_hom.finsupp_prod_apply [has_zero β] [monoid N] [comm_monoid P]
(f : α →₀ β) (g : α → β → N →* P) (x : N) :
f.prod g x = f.prod (λ i fi, g i fi x) :=
monoid_hom.finset_prod_apply _ _ _
namespace finsupp
instance [add_comm_monoid M] : add_comm_monoid (α →₀ M) :=
{ add_comm := assume ⟨s, f, _⟩ ⟨t, g, _⟩, ext $ assume a, add_comm _ _,
.. finsupp.add_monoid }
instance [add_group G] : has_sub (α →₀ G) := ⟨zip_with has_sub.sub (sub_zero _)⟩
instance [add_group G] : add_group (α →₀ G) :=
{ neg := map_range (has_neg.neg) neg_zero,
sub := has_sub.sub,
sub_eq_add_neg := λ x y, ext (λ i, sub_eq_add_neg _ _),
add_left_neg := assume ⟨s, f, _⟩, ext $ assume x, add_left_neg _,
gsmul := λ n v, v.map_range ((•) n) (gsmul_zero _),
gsmul_zero' := λ v, by { ext i, simp },
gsmul_succ' := λ n v, by { ext i, simp [nat.succ_eq_one_add, add_gsmul] },
gsmul_neg' := λ n v, by { ext i, simp only [nat.succ_eq_add_one, map_range_apply,
gsmul_neg_succ_of_nat, int.coe_nat_succ, neg_inj,
add_gsmul, add_nsmul, one_gsmul, gsmul_coe_nat, one_nsmul] },
.. finsupp.add_monoid }
instance [add_comm_group G] : add_comm_group (α →₀ G) :=
{ add_comm := add_comm, ..finsupp.add_group }
lemma single_multiset_sum [add_comm_monoid M] (s : multiset M) (a : α) :
single a s.sum = (s.map (single a)).sum :=
multiset.induction_on s single_zero $ λ a s ih,
by rw [multiset.sum_cons, single_add, ih, multiset.map_cons, multiset.sum_cons]
lemma single_finset_sum [add_comm_monoid M] (s : finset ι) (f : ι → M) (a : α) :
single a (∑ b in s, f b) = ∑ b in s, single a (f b) :=
begin
transitivity,
apply single_multiset_sum,
rw [multiset.map_map],
refl
end
lemma single_sum [has_zero M] [add_comm_monoid N] (s : ι →₀ M) (f : ι → M → N) (a : α) :
single a (s.sum f) = s.sum (λd c, single a (f d c)) :=
single_finset_sum _ _ _
@[to_additive]
lemma prod_neg_index [add_group G] [comm_monoid M] {g : α →₀ G} {h : α → G → M}
(h0 : ∀a, h a 0 = 1) :
(-g).prod h = g.prod (λa b, h a (- b)) :=
prod_map_range_index h0
@[simp] lemma coe_neg [add_group G] (g : α →₀ G) : ⇑(-g) = -g := rfl
lemma neg_apply [add_group G] (g : α →₀ G) (a : α) : (- g) a = - g a := rfl
@[simp] lemma coe_sub [add_group G] (g₁ g₂ : α →₀ G) : ⇑(g₁ - g₂) = g₁ - g₂ := rfl
lemma sub_apply [add_group G] (g₁ g₂ : α →₀ G) (a : α) : (g₁ - g₂) a = g₁ a - g₂ a := rfl
@[simp] lemma support_neg [add_group G] {f : α →₀ G} : support (-f) = support f :=
finset.subset.antisymm
support_map_range
(calc support f = support (- (- f)) : congr_arg support (neg_neg _).symm
... ⊆ support (- f) : support_map_range)
lemma erase_eq_sub_single [add_group G] (f : α →₀ G) (a : α) :
f.erase a = f - single a (f a) :=
begin
ext a',
rcases eq_or_ne a a' with rfl|h,
{ simp },
{ simp [erase_ne h.symm, single_eq_of_ne h] }
end
lemma update_eq_sub_add_single [add_group G] (f : α →₀ G) (a : α) (b : G) :
f.update a b = f - single a (f a) + single a b :=
by rw [update_eq_erase_add_single, erase_eq_sub_single]
@[simp] lemma sum_apply [has_zero M] [add_comm_monoid N]
{f : α →₀ M} {g : α → M → β →₀ N} {a₂ : β} :
(f.sum g) a₂ = f.sum (λa₁ b, g a₁ b a₂) :=
(apply_add_hom a₂ : (β →₀ N) →+ _).map_sum _ _
lemma support_sum [decidable_eq β] [has_zero M] [add_comm_monoid N]
{f : α →₀ M} {g : α → M → (β →₀ N)} :
(f.sum g).support ⊆ f.support.bUnion (λa, (g a (f a)).support) :=
have ∀ c, f.sum (λ a b, g a b c) ≠ 0 → (∃ a, f a ≠ 0 ∧ ¬ (g a (f a)) c = 0),
from assume a₁ h,
let ⟨a, ha, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in
⟨a, mem_support_iff.mp ha, ne⟩,
by simpa only [finset.subset_iff, mem_support_iff, finset.mem_bUnion, sum_apply, exists_prop]
@[simp] lemma sum_zero [has_zero M] [add_comm_monoid N] {f : α →₀ M} :
f.sum (λa b, (0 : N)) = 0 :=
finset.sum_const_zero
@[simp, to_additive]
lemma prod_mul [has_zero M] [comm_monoid N] {f : α →₀ M} {h₁ h₂ : α → M → N} :
f.prod (λa b, h₁ a b * h₂ a b) = f.prod h₁ * f.prod h₂ :=
finset.prod_mul_distrib
@[simp, to_additive]
lemma prod_inv [has_zero M] [comm_group G] {f : α →₀ M}
{h : α → M → G} : f.prod (λa b, (h a b)⁻¹) = (f.prod h)⁻¹ :=
(((monoid_hom.id G)⁻¹).map_prod _ _).symm
@[simp] lemma sum_sub [has_zero M] [add_comm_group G] {f : α →₀ M}
{h₁ h₂ : α → M → G} :
f.sum (λa b, h₁ a b - h₂ a b) = f.sum h₁ - f.sum h₂ :=
finset.sum_sub_distrib
@[to_additive]
lemma prod_add_index [add_comm_monoid M] [comm_monoid N] {f g : α →₀ M}
{h : α → M → N} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
(f + g).prod h = f.prod h * g.prod h :=
have hf : f.prod h = ∏ a in f.support ∪ g.support, h a (f a),
from f.prod_of_support_subset (subset_union_left _ _) _ $ λ a ha, h_zero a,
have hg : g.prod h = ∏ a in f.support ∪ g.support, h a (g a),
from g.prod_of_support_subset (subset_union_right _ _) _ $ λ a ha, h_zero a,
have hfg : (f + g).prod h = ∏ a in f.support ∪ g.support, h a ((f + g) a),
from (f + g).prod_of_support_subset support_add _ $ λ a ha, h_zero a,
by simp only [*, add_apply, prod_mul_distrib]
@[simp]
lemma sum_add_index' [add_comm_monoid M] [add_comm_monoid N] {f g : α →₀ M} (h : α → M →+ N) :
(f + g).sum (λ x, h x) = f.sum (λ x, h x) + g.sum (λ x, h x) :=
sum_add_index (λ a, (h a).map_zero) (λ a, (h a).map_add)
@[simp]
lemma prod_add_index' [add_comm_monoid M] [comm_monoid N] {f g : α →₀ M}
(h : α → multiplicative M →* N) :
(f + g).prod (λ a b, h a (multiplicative.of_add b)) =
f.prod (λ a b, h a (multiplicative.of_add b)) * g.prod (λ a b, h a (multiplicative.of_add b)) :=
prod_add_index (λ a, (h a).map_one) (λ a, (h a).map_mul)
/-- The canonical isomorphism between families of additive monoid homomorphisms `α → (M →+ N)`
and monoid homomorphisms `(α →₀ M) →+ N`. -/
def lift_add_hom [add_comm_monoid M] [add_comm_monoid N] : (α → M →+ N) ≃+ ((α →₀ M) →+ N) :=
{ to_fun := λ F,
{ to_fun := λ f, f.sum (λ x, F x),
map_zero' := finset.sum_empty,
map_add' := λ _ _, sum_add_index (λ x, (F x).map_zero) (λ x, (F x).map_add) },
inv_fun := λ F x, F.comp $ single_add_hom x,
left_inv := λ F, by { ext, simp },
right_inv := λ F, by { ext, simp },
map_add' := λ F G, by { ext, simp } }
@[simp] lemma lift_add_hom_apply [add_comm_monoid M] [add_comm_monoid N]
(F : α → M →+ N) (f : α →₀ M) :
lift_add_hom F f = f.sum (λ x, F x) :=
rfl
@[simp] lemma lift_add_hom_symm_apply [add_comm_monoid M] [add_comm_monoid N]
(F : (α →₀ M) →+ N) (x : α) :
lift_add_hom.symm F x = F.comp (single_add_hom x) :=
rfl
lemma lift_add_hom_symm_apply_apply [add_comm_monoid M] [add_comm_monoid N]
(F : (α →₀ M) →+ N) (x : α) (y : M) :
lift_add_hom.symm F x y = F (single x y) :=
rfl
@[simp] lemma lift_add_hom_single_add_hom [add_comm_monoid M] :
lift_add_hom (single_add_hom : α → M →+ α →₀ M) = add_monoid_hom.id _ :=
lift_add_hom.to_equiv.apply_eq_iff_eq_symm_apply.2 rfl
@[simp] lemma sum_single [add_comm_monoid M] (f : α →₀ M) :
f.sum single = f :=
add_monoid_hom.congr_fun lift_add_hom_single_add_hom f
@[simp] lemma lift_add_hom_apply_single [add_comm_monoid M] [add_comm_monoid N]
(f : α → M →+ N) (a : α) (b : M) :
lift_add_hom f (single a b) = f a b :=
sum_single_index (f a).map_zero
@[simp] lemma lift_add_hom_comp_single [add_comm_monoid M] [add_comm_monoid N] (f : α → M →+ N)
(a : α) :
(lift_add_hom f).comp (single_add_hom a) = f a :=
add_monoid_hom.ext $ λ b, lift_add_hom_apply_single f a b
lemma comp_lift_add_hom [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P]
(g : N →+ P) (f : α → M →+ N) :
g.comp (lift_add_hom f) = lift_add_hom (λ a, g.comp (f a)) :=
lift_add_hom.symm_apply_eq.1 $ funext $ λ a,
by rw [lift_add_hom_symm_apply, add_monoid_hom.comp_assoc, lift_add_hom_comp_single]
lemma sum_sub_index [add_comm_group β] [add_comm_group γ] {f g : α →₀ β}
{h : α → β → γ} (h_sub : ∀a b₁ b₂, h a (b₁ - b₂) = h a b₁ - h a b₂) :
(f - g).sum h = f.sum h - g.sum h :=
(lift_add_hom (λ a, add_monoid_hom.of_map_sub (h a) (h_sub a))).map_sub f g
@[to_additive]
lemma prod_emb_domain [has_zero M] [comm_monoid N] {v : α →₀ M} {f : α ↪ β} {g : β → M → N} :
(v.emb_domain f).prod g = v.prod (λ a b, g (f a) b) :=
begin
rw [prod, prod, support_emb_domain, finset.prod_map],
simp_rw emb_domain_apply,
end
@[to_additive]
lemma prod_finset_sum_index [add_comm_monoid M] [comm_monoid N]
{s : finset ι} {g : ι → α →₀ M}
{h : α → M → N} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
∏ i in s, (g i).prod h = (∑ i in s, g i).prod h :=
finset.induction_on s rfl $ λ a s has ih,
by rw [prod_insert has, ih, sum_insert has, prod_add_index h_zero h_add]
@[to_additive]
lemma prod_sum_index
[add_comm_monoid M] [add_comm_monoid N] [comm_monoid P]
{f : α →₀ M} {g : α → M → β →₀ N}
{h : β → N → P} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
(f.sum g).prod h = f.prod (λa b, (g a b).prod h) :=
(prod_finset_sum_index h_zero h_add).symm
lemma multiset_sum_sum_index
[add_comm_monoid M] [add_comm_monoid N]
(f : multiset (α →₀ M)) (h : α → M → N)
(h₀ : ∀a, h a 0 = 0) (h₁ : ∀ (a : α) (b₁ b₂ : M), h a (b₁ + b₂) = h a b₁ + h a b₂) :
(f.sum.sum h) = (f.map $ λg:α →₀ M, g.sum h).sum :=
multiset.induction_on f rfl $ assume a s ih,
by rw [multiset.sum_cons, multiset.map_cons, multiset.sum_cons, sum_add_index h₀ h₁, ih]
lemma support_sum_eq_bUnion {α : Type*} {ι : Type*} {M : Type*} [add_comm_monoid M]
{g : ι → α →₀ M} (s : finset ι) (h : ∀ i₁ i₂, i₁ ≠ i₂ → disjoint (g i₁).support (g i₂).support) :
(∑ i in s, g i).support = s.bUnion (λ i, (g i).support) :=
begin
apply finset.induction_on s,
{ simp },
{ intros i s hi,
simp only [hi, sum_insert, not_false_iff, bUnion_insert],
intro hs,
rw [finsupp.support_add_eq, hs],
rw [hs],
intros x hx,
simp only [mem_bUnion, exists_prop, inf_eq_inter, ne.def, mem_inter] at hx,
obtain ⟨hxi, j, hj, hxj⟩ := hx,
have hn : i ≠ j := λ H, hi (H.symm ▸ hj),
apply h _ _ hn,
simp [hxi, hxj] }
end
lemma multiset_map_sum [has_zero M] {f : α →₀ M} {m : β → γ} {h : α → M → multiset β} :
multiset.map m (f.sum h) = f.sum (λa b, (h a b).map m) :=
(multiset.map_add_monoid_hom m).map_sum _ f.support
lemma multiset_sum_sum [has_zero M] [add_comm_monoid N] {f : α →₀ M} {h : α → M → multiset N} :
multiset.sum (f.sum h) = f.sum (λa b, multiset.sum (h a b)) :=
(multiset.sum_add_monoid_hom : multiset N →+ N).map_sum _ f.support
section map_range
section equiv
variables [has_zero M] [has_zero N] [has_zero P]
/-- `finsupp.map_range` as an equiv. -/
@[simps apply]
def map_range.equiv (f : M ≃ N) (hf : f 0 = 0) (hf' : f.symm 0 = 0) : (α →₀ M) ≃ (α →₀ N) :=
{ to_fun := (map_range f hf : (α →₀ M) → (α →₀ N)),
inv_fun := (map_range f.symm hf' : (α →₀ N) → (α →₀ M)),
left_inv := λ x, begin
rw ←map_range_comp _ _ _ _; simp_rw equiv.symm_comp_self,
{ exact map_range_id _ },
{ refl },
end,
right_inv := λ x, begin
rw ←map_range_comp _ _ _ _; simp_rw equiv.self_comp_symm,
{ exact map_range_id _ },
{ refl },
end }
@[simp]
lemma map_range.equiv_refl :
map_range.equiv (equiv.refl M) rfl rfl = equiv.refl (α →₀ M) :=
equiv.ext map_range_id
lemma map_range.equiv_trans
(f : M ≃ N) (hf : f 0 = 0) (hf') (f₂ : N ≃ P) (hf₂ : f₂ 0 = 0) (hf₂') :
(map_range.equiv (f.trans f₂) (by rw [equiv.trans_apply, hf, hf₂])
(by rw [equiv.symm_trans_apply, hf₂', hf']) : (α →₀ _) ≃ _) =
(map_range.equiv f hf hf').trans (map_range.equiv f₂ hf₂ hf₂') :=
equiv.ext $ map_range_comp _ _ _ _ _
@[simp] lemma map_range.equiv_symm (f : M ≃ N) (hf hf') :
((map_range.equiv f hf hf').symm : (α →₀ _) ≃ _) = map_range.equiv f.symm hf' hf :=
equiv.ext $ λ x, rfl
end equiv
section zero_hom
variables [has_zero M] [has_zero N] [has_zero P]
/-- Composition with a fixed zero-preserving homomorphism is itself an zero-preserving homomorphism
on functions. -/
@[simps]
def map_range.zero_hom (f : zero_hom M N) : zero_hom (α →₀ M) (α →₀ N) :=
{ to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)),
map_zero' := map_range_zero }
@[simp]
lemma map_range.zero_hom_id :
map_range.zero_hom (zero_hom.id M) = zero_hom.id (α →₀ M) := zero_hom.ext map_range_id
lemma map_range.zero_hom_comp (f : zero_hom N P) (f₂ : zero_hom M N) :
(map_range.zero_hom (f.comp f₂) : zero_hom (α →₀ _) _) =
(map_range.zero_hom f).comp (map_range.zero_hom f₂) :=
zero_hom.ext $ map_range_comp _ _ _ _ _
end zero_hom
section add_monoid_hom
variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P]
/--
Composition with a fixed additive homomorphism is itself an additive homomorphism on functions.
-/
@[simps]
def map_range.add_monoid_hom (f : M →+ N) : (α →₀ M) →+ (α →₀ N) :=
{ to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)),
map_zero' := map_range_zero,
map_add' := λ a b, map_range_add f.map_add _ _ }
@[simp]
lemma map_range.add_monoid_hom_id :
map_range.add_monoid_hom (add_monoid_hom.id M) = add_monoid_hom.id (α →₀ M) :=
add_monoid_hom.ext map_range_id
lemma map_range.add_monoid_hom_comp (f : N →+ P) (f₂ : M →+ N) :
(map_range.add_monoid_hom (f.comp f₂) : (α →₀ _) →+ _) =
(map_range.add_monoid_hom f).comp (map_range.add_monoid_hom f₂) :=
add_monoid_hom.ext $ map_range_comp _ _ _ _ _
@[simp]
lemma map_range.add_monoid_hom_to_zero_hom (f : M →+ N) :
(map_range.add_monoid_hom f).to_zero_hom =
(map_range.zero_hom f.to_zero_hom : zero_hom (α →₀ _) _) :=
zero_hom.ext $ λ _, rfl
lemma map_range_multiset_sum (f : M →+ N) (m : multiset (α →₀ M)) :
map_range f f.map_zero m.sum = (m.map $ λx, map_range f f.map_zero x).sum :=
(map_range.add_monoid_hom f : (α →₀ _) →+ _).map_multiset_sum _
lemma map_range_finset_sum (f : M →+ N) (s : finset ι) (g : ι → (α →₀ M)) :
map_range f f.map_zero (∑ x in s, g x) = ∑ x in s, map_range f f.map_zero (g x) :=
(map_range.add_monoid_hom f : (α →₀ _) →+ _).map_sum _ _
/-- `finsupp.map_range.add_monoid_hom` as an equiv. -/
@[simps apply]
def map_range.add_equiv (f : M ≃+ N) : (α →₀ M) ≃+ (α →₀ N) :=
{ to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)),
inv_fun := (map_range f.symm f.symm.map_zero : (α →₀ N) → (α →₀ M)),
left_inv := λ x, begin
rw ←map_range_comp _ _ _ _; simp_rw add_equiv.symm_comp_self,
{ exact map_range_id _ },
{ refl },
end,
right_inv := λ x, begin
rw ←map_range_comp _ _ _ _; simp_rw add_equiv.self_comp_symm,
{ exact map_range_id _ },
{ refl },
end,
..(map_range.add_monoid_hom f.to_add_monoid_hom) }
@[simp]
lemma map_range.add_equiv_refl :
map_range.add_equiv (add_equiv.refl M) = add_equiv.refl (α →₀ M) :=
add_equiv.ext map_range_id
lemma map_range.add_equiv_trans (f : M ≃+ N) (f₂ : N ≃+ P) :
(map_range.add_equiv (f.trans f₂) : (α →₀ _) ≃+ _) =
(map_range.add_equiv f).trans (map_range.add_equiv f₂) :=
add_equiv.ext $ map_range_comp _ _ _ _ _
@[simp] lemma map_range.add_equiv_symm (f : M ≃+ N) :
((map_range.add_equiv f).symm : (α →₀ _) ≃+ _) = map_range.add_equiv f.symm :=
add_equiv.ext $ λ x, rfl
@[simp]
lemma map_range.add_equiv_to_add_monoid_hom (f : M ≃+ N) :
(map_range.add_equiv f : (α →₀ _) ≃+ _).to_add_monoid_hom =
(map_range.add_monoid_hom f.to_add_monoid_hom : (α →₀ _) →+ _) :=
add_monoid_hom.ext $ λ _, rfl
@[simp]
lemma map_range.add_equiv_to_equiv (f : M ≃+ N) :
(map_range.add_equiv f).to_equiv =
(map_range.equiv f.to_equiv f.map_zero f.symm.map_zero : (α →₀ _) ≃ _) :=
equiv.ext $ λ _, rfl
end add_monoid_hom
end map_range
/-! ### Declarations about `map_domain` -/
section map_domain
variables [add_comm_monoid M] {v v₁ v₂ : α →₀ M}
/-- Given `f : α → β` and `v : α →₀ M`, `map_domain f v : β →₀ M`
is the finitely supported function whose value at `a : β` is the sum
of `v x` over all `x` such that `f x = a`. -/
def map_domain (f : α → β) (v : α →₀ M) : β →₀ M :=
v.sum $ λa, single (f a)
lemma map_domain_apply {f : α → β} (hf : function.injective f) (x : α →₀ M) (a : α) :
map_domain f x (f a) = x a :=
begin
rw [map_domain, sum_apply, sum, finset.sum_eq_single a, single_eq_same],
{ assume b _ hba, exact single_eq_of_ne (hf.ne hba) },
{ assume h, rw [not_mem_support_iff.1 h, single_zero, zero_apply] }
end
lemma map_domain_notin_range {f : α → β} (x : α →₀ M) (a : β) (h : a ∉ set.range f) :
map_domain f x a = 0 :=
begin
rw [map_domain, sum_apply, sum],
exact finset.sum_eq_zero
(assume a' h', single_eq_of_ne $ assume eq, h $ eq ▸ set.mem_range_self _)
end
@[simp]
lemma map_domain_id : map_domain id v = v :=
sum_single _
lemma map_domain_comp {f : α → β} {g : β → γ} :
map_domain (g ∘ f) v = map_domain g (map_domain f v) :=
begin
refine ((sum_sum_index _ _).trans _).symm,
{ intros, exact single_zero },
{ intros, exact single_add },
refine sum_congr rfl (λ _ _, sum_single_index _),
{ exact single_zero }
end
@[simp]
lemma map_domain_single {f : α → β} {a : α} {b : M} : map_domain f (single a b) = single (f a) b :=
sum_single_index single_zero
@[simp] lemma map_domain_zero {f : α → β} : map_domain f (0 : α →₀ M) = (0 : β →₀ M) :=
sum_zero_index
lemma map_domain_congr {f g : α → β} (h : ∀x∈v.support, f x = g x) :
v.map_domain f = v.map_domain g :=
finset.sum_congr rfl $ λ _ H, by simp only [h _ H]
lemma map_domain_add {f : α → β} : map_domain f (v₁ + v₂) = map_domain f v₁ + map_domain f v₂ :=
sum_add_index (λ _, single_zero) (λ _ _ _, single_add)
@[simp] lemma map_domain_equiv_apply {f : α ≃ β} (x : α →₀ M) (a : β) :
map_domain f x a = x (f.symm a) :=
begin
conv_lhs { rw ←f.apply_symm_apply a },
exact map_domain_apply f.injective _ _,
end
/-- `finsupp.map_domain` is an `add_monoid_hom`. -/
@[simps]
def map_domain.add_monoid_hom (f : α → β) : (α →₀ M) →+ (β →₀ M) :=
{ to_fun := map_domain f,
map_zero' := map_domain_zero,
map_add' := λ _ _, map_domain_add}
@[simp]
lemma map_domain.add_monoid_hom_id : map_domain.add_monoid_hom id = add_monoid_hom.id (α →₀ M) :=
add_monoid_hom.ext $ λ _, map_domain_id
lemma map_domain.add_monoid_hom_comp (f : β → γ) (g : α → β) :
(map_domain.add_monoid_hom (f ∘ g) : (α →₀ M) →+ (γ →₀ M)) =
(map_domain.add_monoid_hom f).comp (map_domain.add_monoid_hom g) :=
add_monoid_hom.ext $ λ _, map_domain_comp
lemma map_domain_finset_sum {f : α → β} {s : finset ι} {v : ι → α →₀ M} :
map_domain f (∑ i in s, v i) = ∑ i in s, map_domain f (v i) :=
(map_domain.add_monoid_hom f : (α →₀ M) →+ β →₀ M).map_sum _ _
lemma map_domain_sum [has_zero N] {f : α → β} {s : α →₀ N} {v : α → N → α →₀ M} :
map_domain f (s.sum v) = s.sum (λa b, map_domain f (v a b)) :=
(map_domain.add_monoid_hom f : (α →₀ M) →+ β →₀ M).map_finsupp_sum _ _
lemma map_domain_support [decidable_eq β] {f : α → β} {s : α →₀ M} :
(s.map_domain f).support ⊆ s.support.image f :=
finset.subset.trans support_sum $
finset.subset.trans (finset.bUnion_mono $ assume a ha, support_single_subset) $
by rw [finset.bUnion_singleton]; exact subset.refl _
@[to_additive]
lemma prod_map_domain_index [comm_monoid N] {f : α → β} {s : α →₀ M}
{h : β → M → N} (h_zero : ∀b, h b 0 = 1) (h_add : ∀b m₁ m₂, h b (m₁ + m₂) = h b m₁ * h b m₂) :
(map_domain f s).prod h = s.prod (λa m, h (f a) m) :=
(prod_sum_index h_zero h_add).trans $ prod_congr rfl $ λ _ _, prod_single_index (h_zero _)
/--
A version of `sum_map_domain_index` that takes a bundled `add_monoid_hom`,
rather than separate linearity hypotheses.
-/
-- Note that in `prod_map_domain_index`, `M` is still an additive monoid,
-- so there is no analogous version in terms of `monoid_hom`.
@[simp]
lemma sum_map_domain_index_add_monoid_hom [add_comm_monoid N] {f : α → β}
{s : α →₀ M} (h : β → M →+ N) :
(map_domain f s).sum (λ b m, h b m) = s.sum (λ a m, h (f a) m) :=
@sum_map_domain_index _ _ _ _ _ _ _ _
(λ b m, h b m)
(λ b, (h b).map_zero)
(λ b m₁ m₂, (h b).map_add _ _)
lemma emb_domain_eq_map_domain (f : α ↪ β) (v : α →₀ M) :
emb_domain f v = map_domain f v :=
begin
ext a,
by_cases a ∈ set.range f,
{ rcases h with ⟨a, rfl⟩,
rw [map_domain_apply f.injective, emb_domain_apply] },
{ rw [map_domain_notin_range, emb_domain_notin_range]; assumption }
end
@[to_additive]
lemma prod_map_domain_index_inj [comm_monoid N] {f : α → β} {s : α →₀ M}
{h : β → M → N} (hf : function.injective f) :
(s.map_domain f).prod h = s.prod (λa b, h (f a) b) :=
by rw [←function.embedding.coe_fn_mk f hf, ←emb_domain_eq_map_domain, prod_emb_domain]
lemma map_domain_injective {f : α → β} (hf : function.injective f) :
function.injective (map_domain f : (α →₀ M) → (β →₀ M)) :=
begin
assume v₁ v₂ eq, ext a,
have : map_domain f v₁ (f a) = map_domain f v₂ (f a), { rw eq },
rwa [map_domain_apply hf, map_domain_apply hf] at this,
end
lemma map_domain.add_monoid_hom_comp_map_range [add_comm_monoid N] (f : α → β) (g : M →+ N) :
(map_domain.add_monoid_hom f).comp (map_range.add_monoid_hom g) =
(map_range.add_monoid_hom g).comp (map_domain.add_monoid_hom f) :=
by { ext, simp }
/-- When `g` preserves addition, `map_range` and `map_domain` commute. -/
lemma map_domain_map_range [add_comm_monoid N] (f : α → β) (v : α →₀ M) (g : M → N)
(h0 : g 0 = 0) (hadd : ∀ x y, g (x + y) = g x + g y) :
map_domain f (map_range g h0 v) = map_range g h0 (map_domain f v) :=
let g' : M →+ N := { to_fun := g, map_zero' := h0, map_add' := hadd} in
add_monoid_hom.congr_fun (map_domain.add_monoid_hom_comp_map_range f g') v
end map_domain
/-! ### Declarations about `comap_domain` -/
section comap_domain
/-- Given `f : α → β`, `l : β →₀ M` and a proof `hf` that `f` is injective on
the preimage of `l.support`, `comap_domain f l hf` is the finitely supported function
from `α` to `M` given by composing `l` with `f`. -/
def comap_domain [has_zero M] (f : α → β) (l : β →₀ M) (hf : set.inj_on f (f ⁻¹' ↑l.support)) :
α →₀ M :=
{ support := l.support.preimage f hf,
to_fun := (λ a, l (f a)),
mem_support_to_fun :=
begin
intros a,
simp only [finset.mem_def.symm, finset.mem_preimage],
exact l.mem_support_to_fun (f a),
end }
@[simp]
lemma comap_domain_apply [has_zero M] (f : α → β) (l : β →₀ M)
(hf : set.inj_on f (f ⁻¹' ↑l.support)) (a : α) :
comap_domain f l hf a = l (f a) :=
rfl
lemma sum_comap_domain [has_zero M] [add_comm_monoid N]
(f : α → β) (l : β →₀ M) (g : β → M → N)
(hf : set.bij_on f (f ⁻¹' ↑l.support) ↑l.support) :
(comap_domain f l hf.inj_on).sum (g ∘ f) = l.sum g :=
begin
simp only [sum, comap_domain_apply, (∘)],
simp [comap_domain, finset.sum_preimage_of_bij f _ _ (λ x, g x (l x))],
end
lemma eq_zero_of_comap_domain_eq_zero [add_comm_monoid M]
(f : α → β) (l : β →₀ M) (hf : set.bij_on f (f ⁻¹' ↑l.support) ↑l.support) :
comap_domain f l hf.inj_on = 0 → l = 0 :=
begin
rw [← support_eq_empty, ← support_eq_empty, comap_domain],
simp only [finset.ext_iff, finset.not_mem_empty, iff_false, mem_preimage],
assume h a ha,
cases hf.2.2 ha with b hb,
exact h b (hb.2.symm ▸ ha)
end
lemma map_domain_comap_domain [add_comm_monoid M] (f : α → β) (l : β →₀ M)
(hf : function.injective f) (hl : ↑l.support ⊆ set.range f):
map_domain f (comap_domain f l (hf.inj_on _)) = l :=
begin
ext a,
by_cases h_cases: a ∈ set.range f,
{ rcases set.mem_range.1 h_cases with ⟨b, hb⟩,
rw [hb.symm, map_domain_apply hf, comap_domain_apply] },
{ rw map_domain_notin_range _ _ h_cases,
by_contra h_contr,
apply h_cases (hl $ finset.mem_coe.2 $ mem_support_iff.2 $ λ h, h_contr h.symm) }
end
end comap_domain
section option
/-- Restrict a finitely supported function on `option α` to a finitely supported function on `α`. -/
def some [has_zero M] (f : option α →₀ M) : α →₀ M :=
f.comap_domain option.some (λ _, by simp)
@[simp] lemma some_apply [has_zero M] (f : option α →₀ M) (a : α) :
f.some a = f (option.some a) := rfl
@[simp] lemma some_zero [has_zero M] : (0 : option α →₀ M).some = 0 :=
by { ext, simp, }
@[simp] lemma some_add [add_comm_monoid M] (f g : option α →₀ M) : (f + g).some = f.some + g.some :=
by { ext, simp, }
@[simp] lemma some_single_none [has_zero M] (m : M) : (single none m : option α →₀ M).some = 0 :=
by { ext, simp, }
@[simp] lemma some_single_some [has_zero M] (a : α) (m : M) :
(single (option.some a) m : option α →₀ M).some = single a m :=
by { ext b, simp [single_apply], }
@[to_additive]
lemma prod_option_index [add_comm_monoid M] [comm_monoid N]
(f : option α →₀ M) (b : option α → M → N) (h_zero : ∀ o, b o 0 = 1)
(h_add : ∀ o m₁ m₂, b o (m₁ + m₂) = b o m₁ * b o m₂) :
f.prod b = b none (f none) * f.some.prod (λ a, b (option.some a)) :=
begin
apply induction_linear f,
{ simp [h_zero], },
{ intros f₁ f₂ h₁ h₂,
rw [finsupp.prod_add_index, h₁, h₂, some_add, finsupp.prod_add_index],
simp only [h_add, pi.add_apply, finsupp.coe_add],
rw mul_mul_mul_comm,
all_goals { simp [h_zero, h_add], }, },
{ rintros (_|a) m; simp [h_zero, h_add], }
end
lemma sum_option_index_smul [semiring R] [add_comm_monoid M] [module R M]
(f : option α →₀ R) (b : option α → M) :
f.sum (λ o r, r • b o) =
f none • b none + f.some.sum (λ a r, r • b (option.some a)) :=
f.sum_option_index _ (λ _, zero_smul _ _) (λ _ _ _, add_smul _ _ _)
end option
/-! ### Declarations about `equiv_congr_left` -/
section equiv_congr_left
variable [has_zero M]
/-- Given `f : α ≃ β`, we can map `l : α →₀ M` to `equiv_map_domain f l : β →₀ M` (computably)
by mapping the support forwards and the function backwards. -/
def equiv_map_domain (f : α ≃ β) (l : α →₀ M) : β →₀ M :=
{ support := l.support.map f.to_embedding,
to_fun := λ a, l (f.symm a),
mem_support_to_fun := λ a, by simp only [finset.mem_map_equiv, mem_support_to_fun]; refl }
@[simp] lemma equiv_map_domain_apply (f : α ≃ β) (l : α →₀ M) (b : β) :
equiv_map_domain f l b = l (f.symm b) := rfl
lemma equiv_map_domain_symm_apply (f : α ≃ β) (l : β →₀ M) (a : α) :
equiv_map_domain f.symm l a = l (f a) := rfl
@[simp] lemma equiv_map_domain_refl (l : α →₀ M) : equiv_map_domain (equiv.refl _) l = l :=
by ext x; refl
lemma equiv_map_domain_refl' : equiv_map_domain (equiv.refl _) = @id (α →₀ M) :=
by ext x; refl
lemma equiv_map_domain_trans (f : α ≃ β) (g : β ≃ γ) (l : α →₀ M) :
equiv_map_domain (f.trans g) l = equiv_map_domain g (equiv_map_domain f l) := by ext x; refl
lemma equiv_map_domain_trans' (f : α ≃ β) (g : β ≃ γ) :
@equiv_map_domain _ _ M _ (f.trans g) = equiv_map_domain g ∘ equiv_map_domain f := by ext x; refl
@[simp] lemma equiv_map_domain_single (f : α ≃ β) (a : α) (b : M) :
equiv_map_domain f (single a b) = single (f a) b :=
by ext x; simp only [single_apply, equiv.apply_eq_iff_eq_symm_apply, equiv_map_domain_apply]; congr
@[simp] lemma equiv_map_domain_zero {f : α ≃ β} : equiv_map_domain f (0 : α →₀ M) = (0 : β →₀ M) :=
by ext x; simp only [equiv_map_domain_apply, coe_zero, pi.zero_apply]
lemma equiv_map_domain_eq_map_domain {M} [add_comm_monoid M] (f : α ≃ β) (l : α →₀ M) :
equiv_map_domain f l = map_domain f l := by ext x; simp [map_domain_equiv_apply]
/-- Given `f : α ≃ β`, the finitely supported function spaces are also in bijection:
`(α →₀ M) ≃ (β →₀ M)`.
This is the finitely-supported version of `equiv.Pi_congr_left`. -/
def equiv_congr_left (f : α ≃ β) : (α →₀ M) ≃ (β →₀ M) :=
by refine ⟨equiv_map_domain f, equiv_map_domain f.symm, λ f, _, λ f, _⟩;
ext x; simp only [equiv_map_domain_apply, equiv.symm_symm,
equiv.symm_apply_apply, equiv.apply_symm_apply]
@[simp] lemma equiv_congr_left_apply (f : α ≃ β) (l : α →₀ M) :
equiv_congr_left f l = equiv_map_domain f l := rfl
@[simp] lemma equiv_congr_left_symm (f : α ≃ β) :
(@equiv_congr_left _ _ M _ f).symm = equiv_congr_left f.symm := rfl
end equiv_congr_left
/-! ### Declarations about `filter` -/
section filter
section has_zero
variables [has_zero M] (p : α → Prop) (f : α →₀ M)
/-- `filter p f` is the function which is `f a` if `p a` is true and 0 otherwise. -/
def filter (p : α → Prop) (f : α →₀ M) : α →₀ M :=
{ to_fun := λ a, if p a then f a else 0,
support := f.support.filter (λ a, p a),
mem_support_to_fun := λ a, by split_ifs; { simp only [h, mem_filter, mem_support_iff], tauto } }
lemma filter_apply (a : α) [D : decidable (p a)] : f.filter p a = if p a then f a else 0 :=
by rw subsingleton.elim D; refl
lemma filter_eq_indicator : ⇑(f.filter p) = set.indicator {x | p x} f := rfl
@[simp] lemma filter_apply_pos {a : α} (h : p a) : f.filter p a = f a :=
if_pos h
@[simp] lemma filter_apply_neg {a : α} (h : ¬ p a) : f.filter p a = 0 :=
if_neg h
@[simp] lemma support_filter [D : decidable_pred p] : (f.filter p).support = f.support.filter p :=
by rw subsingleton.elim D; refl
lemma filter_zero : (0 : α →₀ M).filter p = 0 :=
by rw [← support_eq_empty, support_filter, support_zero, finset.filter_empty]
@[simp] lemma filter_single_of_pos
{a : α} {b : M} (h : p a) : (single a b).filter p = single a b :=
coe_fn_injective $ by simp [filter_eq_indicator, set.subset_def, mem_support_single, h]
@[simp] lemma filter_single_of_neg
{a : α} {b : M} (h : ¬ p a) : (single a b).filter p = 0 :=
ext $ by simp [filter_eq_indicator, single_apply_eq_zero, @imp.swap (p _), h]
end has_zero
lemma filter_pos_add_filter_neg [add_zero_class M] (f : α →₀ M) (p : α → Prop) :
f.filter p + f.filter (λa, ¬ p a) = f :=
coe_fn_injective $ set.indicator_self_add_compl {x | p x} f
end filter
/-! ### Declarations about `frange` -/
section frange
variables [has_zero M]
/-- `frange f` is the image of `f` on the support of `f`. -/
def frange (f : α →₀ M) : finset M := finset.image f f.support
theorem mem_frange {f : α →₀ M} {y : M} :
y ∈ f.frange ↔ y ≠ 0 ∧ ∃ x, f x = y :=
finset.mem_image.trans
⟨λ ⟨x, hx1, hx2⟩, ⟨hx2 ▸ mem_support_iff.1 hx1, x, hx2⟩,
λ ⟨hy, x, hx⟩, ⟨x, mem_support_iff.2 (hx.symm ▸ hy), hx⟩⟩
theorem zero_not_mem_frange {f : α →₀ M} : (0:M) ∉ f.frange :=
λ H, (mem_frange.1 H).1 rfl
theorem frange_single {x : α} {y : M} : frange (single x y) ⊆ {y} :=
λ r hr, let ⟨t, ht1, ht2⟩ := mem_frange.1 hr in ht2 ▸
(by rw single_apply at ht2 ⊢; split_ifs at ht2 ⊢; [exact finset.mem_singleton_self _, cc])
end frange
/-! ### Declarations about `subtype_domain` -/
section subtype_domain
section zero
variables [has_zero M] {p : α → Prop}
/-- `subtype_domain p f` is the restriction of the finitely supported function
`f` to the subtype `p`. -/
def subtype_domain (p : α → Prop) (f : α →₀ M) : (subtype p →₀ M) :=
⟨f.support.subtype p, f ∘ coe, λ a, by simp only [mem_subtype, mem_support_iff]⟩
@[simp] lemma support_subtype_domain [D : decidable_pred p] {f : α →₀ M} :
(subtype_domain p f).support = f.support.subtype p :=
by rw subsingleton.elim D; refl
@[simp] lemma subtype_domain_apply {a : subtype p} {v : α →₀ M} :
(subtype_domain p v) a = v (a.val) :=
rfl
@[simp] lemma subtype_domain_zero : subtype_domain p (0 : α →₀ M) = 0 :=
rfl
lemma subtype_domain_eq_zero_iff' {f : α →₀ M} :
f.subtype_domain p = 0 ↔ ∀ x, p x → f x = 0 :=
by simp_rw [← support_eq_empty, support_subtype_domain, subtype_eq_empty, not_mem_support_iff]
lemma subtype_domain_eq_zero_iff {f : α →₀ M} (hf : ∀ x ∈ f.support , p x) :
f.subtype_domain p = 0 ↔ f = 0 :=
subtype_domain_eq_zero_iff'.trans ⟨λ H, ext $ λ x,
if hx : p x then H x hx else not_mem_support_iff.1 $ mt (hf x) hx, λ H x _, by simp [H]⟩
@[to_additive]
lemma prod_subtype_domain_index [comm_monoid N] {v : α →₀ M}
{h : α → M → N} (hp : ∀x∈v.support, p x) :
(v.subtype_domain p).prod (λa b, h a b) = v.prod h :=
prod_bij (λp _, p.val)
(λ _, mem_subtype.1)
(λ _ _, rfl)
(λ _ _ _ _, subtype.eq)
(λ b hb, ⟨⟨b, hp b hb⟩, mem_subtype.2 hb, rfl⟩)
end zero
section add_zero_class
variables [add_zero_class M] {p : α → Prop} {v v' : α →₀ M}
@[simp] lemma subtype_domain_add {v v' : α →₀ M} :
(v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p :=
ext $ λ _, rfl
/-- `subtype_domain` but as an `add_monoid_hom`. -/
def subtype_domain_add_monoid_hom : (α →₀ M) →+ subtype p →₀ M :=
{ to_fun := subtype_domain p,
map_zero' := subtype_domain_zero,
map_add' := λ _ _, subtype_domain_add }
/-- `finsupp.filter` as an `add_monoid_hom`. -/
def filter_add_hom (p : α → Prop) : (α →₀ M) →+ (α →₀ M) :=
{ to_fun := filter p,
map_zero' := filter_zero p,
map_add' := λ f g, coe_fn_injective $ set.indicator_add {x | p x} f g }
@[simp] lemma filter_add {v v' : α →₀ M} : (v + v').filter p = v.filter p + v'.filter p :=
(filter_add_hom p).map_add v v'
end add_zero_class
section comm_monoid
variables [add_comm_monoid M] {p : α → Prop}
lemma subtype_domain_sum {s : finset ι} {h : ι → α →₀ M} :
(∑ c in s, h c).subtype_domain p = ∑ c in s, (h c).subtype_domain p :=
(subtype_domain_add_monoid_hom : _ →+ subtype p →₀ M).map_sum _ s
lemma subtype_domain_finsupp_sum [has_zero N] {s : β →₀ N} {h : β → N → α →₀ M} :
(s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) :=
subtype_domain_sum
lemma filter_sum (s : finset ι) (f : ι → α →₀ M) :
(∑ a in s, f a).filter p = ∑ a in s, filter p (f a) :=
(filter_add_hom p : (α →₀ M) →+ _).map_sum f s
lemma filter_eq_sum (p : α → Prop) [D : decidable_pred p] (f : α →₀ M) :
f.filter p = ∑ i in f.support.filter p, single i (f i) :=
(f.filter p).sum_single.symm.trans $ finset.sum_congr (by rw subsingleton.elim D; refl) $
λ x hx, by rw [filter_apply_pos _ _ (mem_filter.1 hx).2]
end comm_monoid
section group
variables [add_group G] {p : α → Prop} {v v' : α →₀ G}
@[simp] lemma subtype_domain_neg : (- v).subtype_domain p = - v.subtype_domain p :=
ext $ λ _, rfl
@[simp] lemma subtype_domain_sub :
(v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p :=
ext $ λ _, rfl
@[simp] lemma single_neg {a : α} {b : G} : single a (-b) = -single a b :=
(single_add_hom a : G →+ _).map_neg b
@[simp] lemma single_sub {a : α} {b₁ b₂ : G} : single a (b₁ - b₂) = single a b₁ - single a b₂ :=
(single_add_hom a : G →+ _).map_sub b₁ b₂
@[simp] lemma erase_neg (a : α) (f : α →₀ G) : erase a (-f) = -erase a f :=
(erase_add_hom a : (_ →₀ G) →+ _).map_neg f
@[simp] lemma erase_sub (a : α) (f₁ f₂ : α →₀ G) : erase a (f₁ - f₂) = erase a f₁ - erase a f₂ :=
(erase_add_hom a : (_ →₀ G) →+ _).map_sub f₁ f₂
@[simp] lemma filter_neg (p : α → Prop) (f : α →₀ G) : filter p (-f) = -filter p f :=
(filter_add_hom p : (_ →₀ G) →+ _).map_neg f
@[simp] lemma filter_sub (p : α → Prop) (f₁ f₂ : α →₀ G) :
filter p (f₁ - f₂) = filter p f₁ - filter p f₂ :=
(filter_add_hom p : (_ →₀ G) →+ _).map_sub f₁ f₂
end group
end subtype_domain
/-! ### Declarations relating `finsupp` to `multiset` -/
section multiset
/-- Given `f : α →₀ ℕ`, `f.to_multiset` is the multiset with multiplicities given by the values of
`f` on the elements of `α`. We define this function as an `add_equiv`. -/
def to_multiset : (α →₀ ℕ) ≃+ multiset α :=
{ to_fun := λ f, f.sum (λa n, n • {a}),
inv_fun := λ s, ⟨s.to_finset, λ a, s.count a, λ a, by simp⟩,
left_inv := λ f, ext $ λ a, by {
simp only [sum, multiset.count_sum', multiset.count_singleton, mul_boole, coe_mk,
multiset.mem_to_finset, iff_self, not_not, mem_support_iff, ite_eq_left_iff, ne.def,
multiset.count_eq_zero, multiset.count_nsmul, finset.sum_ite_eq, ite_not],
exact eq.symm },
right_inv := λ s, by simp only [sum, coe_mk, multiset.to_finset_sum_count_nsmul_eq],
map_add' := λ f g, sum_add_index (λ a, zero_nsmul _) (λ a, add_nsmul _) }
lemma to_multiset_zero : (0 : α →₀ ℕ).to_multiset = 0 :=
rfl
lemma to_multiset_add (m n : α →₀ ℕ) :
(m + n).to_multiset = m.to_multiset + n.to_multiset :=
to_multiset.map_add m n
lemma to_multiset_apply (f : α →₀ ℕ) : f.to_multiset = f.sum (λ a n, n • {a}) := rfl
@[simp]
lemma to_multiset_symm_apply (s : multiset α) (x : α) :
finsupp.to_multiset.symm s x = s.count x :=
rfl
@[simp] lemma to_multiset_single (a : α) (n : ℕ) : to_multiset (single a n) = n • {a} :=
by rw [to_multiset_apply, sum_single_index]; apply zero_nsmul
lemma to_multiset_sum {ι : Type*} {f : ι → α →₀ ℕ} (s : finset ι) :
finsupp.to_multiset (∑ i in s, f i) = ∑ i in s, finsupp.to_multiset (f i) :=
add_equiv.map_sum _ _ _
lemma to_multiset_sum_single {ι : Type*} (s : finset ι) (n : ℕ) :
finsupp.to_multiset (∑ i in s, single i n) = n • s.val :=
by simp_rw [to_multiset_sum, finsupp.to_multiset_single, sum_nsmul, sum_multiset_singleton]
lemma card_to_multiset (f : α →₀ ℕ) : f.to_multiset.card = f.sum (λa, id) :=
by simp [to_multiset_apply, add_monoid_hom.map_finsupp_sum, function.id_def]
lemma to_multiset_map (f : α →₀ ℕ) (g : α → β) :
f.to_multiset.map g = (f.map_domain g).to_multiset :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.map_zero, map_domain_zero, to_multiset_zero] },
{ assume a n f _ _ ih,
rw [to_multiset_add, multiset.map_add, ih, map_domain_add, map_domain_single,
to_multiset_single, to_multiset_add, to_multiset_single,
← multiset.coe_map_add_monoid_hom, (multiset.map_add_monoid_hom g).map_nsmul],
refl }
end
@[simp] lemma prod_to_multiset [comm_monoid M] (f : M →₀ ℕ) :
f.to_multiset.prod = f.prod (λa n, a ^ n) :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.prod_zero, finsupp.prod_zero_index] },
{ assume a n f _ _ ih,
rw [to_multiset_add, multiset.prod_add, ih, to_multiset_single, finsupp.prod_add_index,
finsupp.prod_single_index, multiset.prod_nsmul, multiset.prod_singleton],
{ exact pow_zero a },
{ exact pow_zero },
{ exact pow_add } }
end
@[simp] lemma to_finset_to_multiset [decidable_eq α] (f : α →₀ ℕ) :
f.to_multiset.to_finset = f.support :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.to_finset_zero, support_zero] },
{ assume a n f ha hn ih,
rw [to_multiset_add, multiset.to_finset_add, ih, to_multiset_single, support_add_eq,
support_single_ne_zero hn, multiset.to_finset_nsmul _ _ hn, multiset.to_finset_singleton],
refine disjoint.mono_left support_single_subset _,
rwa [finset.disjoint_singleton_left] }
end
@[simp] lemma count_to_multiset [decidable_eq α] (f : α →₀ ℕ) (a : α) :
f.to_multiset.count a = f a :=
calc f.to_multiset.count a = f.sum (λx n, (n • {x} : multiset α).count a) :
(multiset.count_add_monoid_hom a).map_sum _ f.support
... = f.sum (λx n, n * ({x} : multiset α).count a) : by simp only [multiset.count_nsmul]
... = f a * ({a} : multiset α).count a : sum_eq_single _
(λ a' _ H, by simp only [multiset.count_singleton, if_false, H.symm, mul_zero])
(λ H, by simp only [not_mem_support_iff.1 H, zero_mul])
... = f a : by rw [multiset.count_singleton_self, mul_one]
lemma mem_support_multiset_sum [add_comm_monoid M]
{s : multiset (α →₀ M)} (a : α) :
a ∈ s.sum.support → ∃f∈s, a ∈ (f : α →₀ M).support :=
multiset.induction_on s false.elim
begin
assume f s ih ha,
by_cases a ∈ f.support,
{ exact ⟨f, multiset.mem_cons_self _ _, h⟩ },
{ simp only [multiset.sum_cons, mem_support_iff, add_apply,
not_mem_support_iff.1 h, zero_add] at ha,
rcases ih (mem_support_iff.2 ha) with ⟨f', h₀, h₁⟩,
exact ⟨f', multiset.mem_cons_of_mem h₀, h₁⟩ }
end
lemma mem_support_finset_sum [add_comm_monoid M]
{s : finset ι} {h : ι → α →₀ M} (a : α) (ha : a ∈ (∑ c in s, h c).support) :
∃ c ∈ s, a ∈ (h c).support :=
let ⟨f, hf, hfa⟩ := mem_support_multiset_sum a ha in
let ⟨c, hc, eq⟩ := multiset.mem_map.1 hf in
⟨c, hc, eq.symm ▸ hfa⟩
@[simp] lemma mem_to_multiset (f : α →₀ ℕ) (i : α) :
i ∈ f.to_multiset ↔ i ∈ f.support :=
by rw [← multiset.count_ne_zero, finsupp.count_to_multiset, finsupp.mem_support_iff]
end multiset
/-! ### Declarations about `curry` and `uncurry` -/
section curry_uncurry
variables [add_comm_monoid M] [add_comm_monoid N]
/-- Given a finitely supported function `f` from a product type `α × β` to `γ`,
`curry f` is the "curried" finitely supported function from `α` to the type of
finitely supported functions from `β` to `γ`. -/
protected def curry (f : (α × β) →₀ M) : α →₀ (β →₀ M) :=
f.sum $ λp c, single p.1 (single p.2 c)
@[simp] lemma curry_apply (f : (α × β) →₀ M) (x : α) (y : β) :
f.curry x y = f (x, y) :=
begin
have : ∀ (b : α × β), single b.fst (single b.snd (f b)) x y = if b = (x, y) then f b else 0,
{ rintros ⟨b₁, b₂⟩,
simp [single_apply, ite_apply, prod.ext_iff, ite_and],
split_ifs; simp [single_apply, *] },
rw [finsupp.curry, sum_apply, sum_apply, finsupp.sum, finset.sum_eq_single, this, if_pos rfl],
{ intros b hb b_ne, rw [this b, if_neg b_ne] },
{ intros hxy, rw [this (x, y), if_pos rfl, not_mem_support_iff.mp hxy] }
end
lemma sum_curry_index (f : (α × β) →₀ M) (g : α → β → M → N)
(hg₀ : ∀ a b, g a b 0 = 0) (hg₁ : ∀a b c₀ c₁, g a b (c₀ + c₁) = g a b c₀ + g a b c₁) :
f.curry.sum (λa f, f.sum (g a)) = f.sum (λp c, g p.1 p.2 c) :=
begin
rw [finsupp.curry],
transitivity,
{ exact sum_sum_index (assume a, sum_zero_index)
(assume a b₀ b₁, sum_add_index (assume a, hg₀ _ _) (assume c d₀ d₁, hg₁ _ _ _ _)) },
congr, funext p c,
transitivity,
{ exact sum_single_index sum_zero_index },
exact sum_single_index (hg₀ _ _)
end
/-- Given a finitely supported function `f` from `α` to the type of
finitely supported functions from `β` to `M`,
`uncurry f` is the "uncurried" finitely supported function from `α × β` to `M`. -/
protected def uncurry (f : α →₀ (β →₀ M)) : (α × β) →₀ M :=
f.sum $ λa g, g.sum $ λb c, single (a, b) c
/-- `finsupp_prod_equiv` defines the `equiv` between `((α × β) →₀ M)` and `(α →₀ (β →₀ M))` given by
currying and uncurrying. -/
def finsupp_prod_equiv : ((α × β) →₀ M) ≃ (α →₀ (β →₀ M)) :=
by refine ⟨finsupp.curry, finsupp.uncurry, λ f, _, λ f, _⟩; simp only [
finsupp.curry, finsupp.uncurry, sum_sum_index, sum_zero_index, sum_add_index,
sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff,
forall_3_true_iff, prod.mk.eta, (single_sum _ _ _).symm, sum_single]
lemma filter_curry (f : α × β →₀ M) (p : α → Prop) :
(f.filter (λa:α×β, p a.1)).curry = f.curry.filter p :=
begin
rw [finsupp.curry, finsupp.curry, finsupp.sum, finsupp.sum, filter_sum, support_filter,
sum_filter],
refine finset.sum_congr rfl _,
rintros ⟨a₁, a₂⟩ ha,
dsimp only,
split_ifs,
{ rw [filter_apply_pos, filter_single_of_pos]; exact h },
{ rwa [filter_single_of_neg] }
end
lemma support_curry [decidable_eq α] (f : α × β →₀ M) :
f.curry.support ⊆ f.support.image prod.fst :=
begin
rw ← finset.bUnion_singleton,
refine finset.subset.trans support_sum _,
refine finset.bUnion_mono (assume a _, support_single_subset)
end
end curry_uncurry
section sum
/-- `finsupp.sum_elim f g` maps `inl x` to `f x` and `inr y` to `g y`. -/
def sum_elim {α β γ : Type*} [has_zero γ]
(f : α →₀ γ) (g : β →₀ γ) : α ⊕ β →₀ γ :=
on_finset
((f.support.map ⟨_, sum.inl_injective⟩) ∪ g.support.map ⟨_, sum.inr_injective⟩)
(sum.elim f g)
(λ ab h, by { cases ab with a b; simp only [sum.elim_inl, sum.elim_inr] at h; simpa })
@[simp] lemma coe_sum_elim {α β γ : Type*} [has_zero γ]
(f : α →₀ γ) (g : β →₀ γ) : ⇑(sum_elim f g) = sum.elim f g := rfl
lemma sum_elim_apply {α β γ : Type*} [has_zero γ]
(f : α →₀ γ) (g : β →₀ γ) (x : α ⊕ β) : sum_elim f g x = sum.elim f g x := rfl
lemma sum_elim_inl {α β γ : Type*} [has_zero γ]
(f : α →₀ γ) (g : β →₀ γ) (x : α) : sum_elim f g (sum.inl x) = f x := rfl
lemma sum_elim_inr {α β γ : Type*} [has_zero γ]
(f : α →₀ γ) (g : β →₀ γ) (x : β) : sum_elim f g (sum.inr x) = g x := rfl
/-- The equivalence between `(α ⊕ β) →₀ γ` and `(α →₀ γ) × (β →₀ γ)`.
This is the `finsupp` version of `equiv.sum_arrow_equiv_prod_arrow`. -/
@[simps apply symm_apply]
def sum_finsupp_equiv_prod_finsupp {α β γ : Type*} [has_zero γ] :
((α ⊕ β) →₀ γ) ≃ (α →₀ γ) × (β →₀ γ) :=
{ to_fun := λ f,
⟨f.comap_domain sum.inl (sum.inl_injective.inj_on _),
f.comap_domain sum.inr (sum.inr_injective.inj_on _)⟩,
inv_fun := λ fg, sum_elim fg.1 fg.2,
left_inv := λ f, by { ext ab, cases ab with a b; simp },
right_inv := λ fg, by { ext; simp } }
lemma fst_sum_finsupp_equiv_prod_finsupp {α β γ : Type*} [has_zero γ]
(f : (α ⊕ β) →₀ γ) (x : α) :
(sum_finsupp_equiv_prod_finsupp f).1 x = f (sum.inl x) :=
rfl
lemma snd_sum_finsupp_equiv_prod_finsupp {α β γ : Type*} [has_zero γ]
(f : (α ⊕ β) →₀ γ) (y : β) :
(sum_finsupp_equiv_prod_finsupp f).2 y = f (sum.inr y) :=
rfl
lemma sum_finsupp_equiv_prod_finsupp_symm_inl {α β γ : Type*} [has_zero γ]
(fg : (α →₀ γ) × (β →₀ γ)) (x : α) :
(sum_finsupp_equiv_prod_finsupp.symm fg) (sum.inl x) = fg.1 x :=
rfl
lemma sum_finsupp_equiv_prod_finsupp_symm_inr {α β γ : Type*} [has_zero γ]
(fg : (α →₀ γ) × (β →₀ γ)) (y : β) :
(sum_finsupp_equiv_prod_finsupp.symm fg) (sum.inr y) = fg.2 y :=
rfl
variables [add_monoid M]
/-- The additive equivalence between `(α ⊕ β) →₀ M` and `(α →₀ M) × (β →₀ M)`.
This is the `finsupp` version of `equiv.sum_arrow_equiv_prod_arrow`. -/
@[simps apply symm_apply] def sum_finsupp_add_equiv_prod_finsupp {α β : Type*} :
((α ⊕ β) →₀ M) ≃+ (α →₀ M) × (β →₀ M) :=
{ map_add' :=
by { intros, ext;
simp only [equiv.to_fun_as_coe, prod.fst_add, prod.snd_add, add_apply,
snd_sum_finsupp_equiv_prod_finsupp, fst_sum_finsupp_equiv_prod_finsupp] },
.. sum_finsupp_equiv_prod_finsupp }
lemma fst_sum_finsupp_add_equiv_prod_finsupp {α β : Type*}
(f : (α ⊕ β) →₀ M) (x : α) :
(sum_finsupp_add_equiv_prod_finsupp f).1 x = f (sum.inl x) :=
rfl
lemma snd_sum_finsupp_add_equiv_prod_finsupp {α β : Type*}
(f : (α ⊕ β) →₀ M) (y : β) :
(sum_finsupp_add_equiv_prod_finsupp f).2 y = f (sum.inr y) :=
rfl
lemma sum_finsupp_add_equiv_prod_finsupp_symm_inl {α β : Type*}
(fg : (α →₀ M) × (β →₀ M)) (x : α) :
(sum_finsupp_add_equiv_prod_finsupp.symm fg) (sum.inl x) = fg.1 x :=
rfl
lemma sum_finsupp_add_equiv_prod_finsupp_symm_inr {α β : Type*}
(fg : (α →₀ M) × (β →₀ M)) (y : β) :
(sum_finsupp_add_equiv_prod_finsupp.symm fg) (sum.inr y) = fg.2 y :=
rfl
end sum
section
variables [group G] [mul_action G α] [add_comm_monoid M]
/--
Scalar multiplication by a group element g,
given by precomposition with the action of g⁻¹ on the domain.
-/
def comap_has_scalar : has_scalar G (α →₀ M) :=
{ smul := λ g f, f.comap_domain (λ a, g⁻¹ • a)
(λ a a' m m' h, by simpa [←mul_smul] using (congr_arg (λ a, g • a) h)) }
local attribute [instance] comap_has_scalar
/--
Scalar multiplication by a group element,
given by precomposition with the action of g⁻¹ on the domain,
is multiplicative in g.
-/
def comap_mul_action : mul_action G (α →₀ M) :=
{ one_smul := λ f, by { ext, dsimp [(•)], simp, },
mul_smul := λ g g' f, by { ext, dsimp [(•)], simp [mul_smul], }, }
local attribute [instance] comap_mul_action
/--
Scalar multiplication by a group element,
given by precomposition with the action of g⁻¹ on the domain,
is additive in the second argument.
-/
def comap_distrib_mul_action :
distrib_mul_action G (α →₀ M) :=
{ smul_zero := λ g, by { ext, dsimp [(•)], simp, },
smul_add := λ g f f', by { ext, dsimp [(•)], simp, }, }
/--
Scalar multiplication by a group element on finitely supported functions on a group,
given by precomposition with the action of g⁻¹. -/
def comap_distrib_mul_action_self :
distrib_mul_action G (G →₀ M) :=
@finsupp.comap_distrib_mul_action G M G _ (monoid.to_mul_action G) _
@[simp]
lemma comap_smul_single (g : G) (a : α) (b : M) :
g • single a b = single (g • a) b :=
begin
ext a',
dsimp [(•)],
by_cases h : g • a = a',
{ subst h, simp [←mul_smul], },
{ simp [single_eq_of_ne h], rw [single_eq_of_ne],
rintro rfl, simpa [←mul_smul] using h, }
end
@[simp]
lemma comap_smul_apply (g : G) (f : α →₀ M) (a : α) :
(g • f) a = f (g⁻¹ • a) := rfl
end
section
instance [monoid R] [add_monoid M] [distrib_mul_action R M] : has_scalar R (α →₀ M) :=
⟨λa v, v.map_range ((•) a) (smul_zero _)⟩
/-!
Throughout this section, some `monoid` and `semiring` arguments are specified with `{}` instead of
`[]`. See note [implicit instance arguments].
-/
@[simp] lemma coe_smul {_ : monoid R} [add_monoid M] [distrib_mul_action R M]
(b : R) (v : α →₀ M) : ⇑(b • v) = b • v := rfl
lemma smul_apply {_ : monoid R} [add_monoid M] [distrib_mul_action R M]
(b : R) (v : α →₀ M) (a : α) : (b • v) a = b • (v a) := rfl
lemma _root_.is_smul_regular.finsupp {_ : monoid R} [add_monoid M] [distrib_mul_action R M] {k : R}
(hk : is_smul_regular M k) : is_smul_regular (α →₀ M) k :=
λ _ _ h, ext $ λ i, hk (congr_fun h i)
instance [monoid R] [nonempty α] [add_monoid M] [distrib_mul_action R M] [has_faithful_scalar R M] :
has_faithful_scalar R (α →₀ M) :=
{ eq_of_smul_eq_smul := λ r₁ r₂ h, let ⟨a⟩ := ‹nonempty α› in eq_of_smul_eq_smul $ λ m : M,
by simpa using congr_fun (h (single a m)) a }
variables (α M)
instance [monoid R] [add_monoid M] [distrib_mul_action R M] : distrib_mul_action R (α →₀ M) :=
{ smul := (•),
smul_add := λ a x y, ext $ λ _, smul_add _ _ _,
one_smul := λ x, ext $ λ _, one_smul _ _,
mul_smul := λ r s x, ext $ λ _, mul_smul _ _ _,
smul_zero := λ x, ext $ λ _, smul_zero _ }
instance [monoid R] [monoid S] [add_monoid M] [distrib_mul_action R M] [distrib_mul_action S M]
[has_scalar R S] [is_scalar_tower R S M] :
is_scalar_tower R S (α →₀ M) :=
{ smul_assoc := λ r s a, ext $ λ _, smul_assoc _ _ _ }
instance [monoid R] [monoid S] [add_monoid M] [distrib_mul_action R M] [distrib_mul_action S M]
[smul_comm_class R S M] :
smul_comm_class R S (α →₀ M) :=
{ smul_comm := λ r s a, ext $ λ _, smul_comm _ _ _ }
instance [semiring R] [add_comm_monoid M] [module R M] : module R (α →₀ M) :=
{ smul := (•),
zero_smul := λ x, ext $ λ _, zero_smul _ _,
add_smul := λ a x y, ext $ λ _, add_smul _ _ _,
.. finsupp.distrib_mul_action α M }
variables {α M} {R}
lemma support_smul {_ : monoid R} [add_monoid M] [distrib_mul_action R M] {b : R} {g : α →₀ M} :
(b • g).support ⊆ g.support :=
λ a, by { simp only [smul_apply, mem_support_iff, ne.def], exact mt (λ h, h.symm ▸ smul_zero _) }
section
variables {p : α → Prop}
@[simp] lemma filter_smul {_ : monoid R} [add_monoid M] [distrib_mul_action R M]
{b : R} {v : α →₀ M} : (b • v).filter p = b • v.filter p :=
coe_fn_injective $ set.indicator_smul {x | p x} b v
end
lemma map_domain_smul {_ : monoid R} [add_comm_monoid M] [distrib_mul_action R M]
{f : α → β} (b : R) (v : α →₀ M) : map_domain f (b • v) = b • map_domain f v :=
begin
change map_domain f (map_range _ _ _) = map_range _ _ _,
apply finsupp.induction v, { simp only [map_domain_zero, map_range_zero] },
intros a b v' hv₁ hv₂ IH,
rw [map_range_add, map_domain_add, IH, map_domain_add, map_range_add,
map_range_single, map_domain_single, map_domain_single, map_range_single];
apply smul_add
end
@[simp] lemma smul_single {_ : monoid R} [add_monoid M] [distrib_mul_action R M]
(c : R) (a : α) (b : M) : c • finsupp.single a b = finsupp.single a (c • b) :=
map_range_single
@[simp] lemma smul_single' {_ : semiring R}
(c : R) (a : α) (b : R) : c • finsupp.single a b = finsupp.single a (c * b) :=
smul_single _ _ _
lemma map_range_smul {_ : monoid R} [add_monoid M] [distrib_mul_action R M]
[add_monoid N] [distrib_mul_action R N]
{f : M → N} {hf : f 0 = 0} (c : R) (v : α →₀ M) (hsmul : ∀ x, f (c • x) = c • f x) :
map_range f hf (c • v) = c • map_range f hf v :=
begin
erw ←map_range_comp,
have : (f ∘ (•) c) = ((•) c ∘ f) := funext hsmul,
simp_rw this,
apply map_range_comp,
rw [function.comp_apply, smul_zero, hf],
end
lemma smul_single_one [semiring R] (a : α) (b : R) : b • single a 1 = single a b :=
by rw [smul_single, smul_eq_mul, mul_one]
end
lemma sum_smul_index [semiring R] [add_comm_monoid M] {g : α →₀ R} {b : R} {h : α → R → M}
(h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi a, h i (b * a)) :=
finsupp.sum_map_range_index h0
lemma sum_smul_index' [monoid R] [add_monoid M] [distrib_mul_action R M] [add_comm_monoid N]
{g : α →₀ M} {b : R} {h : α → M → N} (h0 : ∀i, h i 0 = 0) :
(b • g).sum h = g.sum (λi c, h i (b • c)) :=
finsupp.sum_map_range_index h0
/-- A version of `finsupp.sum_smul_index'` for bundled additive maps. -/
lemma sum_smul_index_add_monoid_hom
[monoid R] [add_monoid M] [add_comm_monoid N] [distrib_mul_action R M]
{g : α →₀ M} {b : R} {h : α → M →+ N} :
(b • g).sum (λ a, h a) = g.sum (λ i c, h i (b • c)) :=
sum_map_range_index (λ i, (h i).map_zero)
instance [semiring R] [add_comm_monoid M] [module R M] {ι : Type*}
[no_zero_smul_divisors R M] : no_zero_smul_divisors R (ι →₀ M) :=
⟨λ c f h, or_iff_not_imp_left.mpr (λ hc, finsupp.ext
(λ i, (smul_eq_zero.mp (finsupp.ext_iff.mp h i)).resolve_left hc))⟩
section distrib_mul_action_hom
variables [semiring R]
variables [add_comm_monoid M] [add_comm_monoid N] [distrib_mul_action R M] [distrib_mul_action R N]
/-- `finsupp.single` as a `distrib_mul_action_hom`.
See also `finsupp.lsingle` for the version as a linear map. -/
def distrib_mul_action_hom.single (a : α) : M →+[R] (α →₀ M) :=
{ map_smul' :=
λ k m, by simp only [add_monoid_hom.to_fun_eq_coe, single_add_hom_apply, smul_single],
.. single_add_hom a }
lemma distrib_mul_action_hom_ext {f g : (α →₀ M) →+[R] N}
(h : ∀ (a : α) (m : M), f (single a m) = g (single a m)) :
f = g :=
distrib_mul_action_hom.to_add_monoid_hom_injective $ add_hom_ext h
/-- See note [partially-applied ext lemmas]. -/
@[ext] lemma distrib_mul_action_hom_ext' {f g : (α →₀ M) →+[R] N}
(h : ∀ (a : α), f.comp (distrib_mul_action_hom.single a) =
g.comp (distrib_mul_action_hom.single a)) :
f = g :=
distrib_mul_action_hom_ext $ λ a, distrib_mul_action_hom.congr_fun (h a)
end distrib_mul_action_hom
section
variables [has_zero R]
/-- The `finsupp` version of `pi.unique`. -/
instance unique_of_right [subsingleton R] : unique (α →₀ R) :=
{ uniq := λ l, ext $ λ i, subsingleton.elim _ _,
.. finsupp.inhabited }
/-- The `finsupp` version of `pi.unique_of_is_empty`. -/
instance unique_of_left [is_empty α] : unique (α →₀ R) :=
{ uniq := λ l, ext is_empty_elim,
.. finsupp.inhabited }
end
/-- Given an `add_comm_monoid M` and `s : set α`, `restrict_support_equiv s M` is the `equiv`
between the subtype of finitely supported functions with support contained in `s` and
the type of finitely supported functions from `s`. -/
def restrict_support_equiv (s : set α) (M : Type*) [add_comm_monoid M] :
{f : α →₀ M // ↑f.support ⊆ s } ≃ (s →₀ M) :=
begin
refine ⟨λf, subtype_domain (λx, x ∈ s) f.1, λ f, ⟨f.map_domain subtype.val, _⟩, _, _⟩,
{ refine set.subset.trans (finset.coe_subset.2 map_domain_support) _,
rw [finset.coe_image, set.image_subset_iff],
exact assume x hx, x.2 },
{ rintros ⟨f, hf⟩,
apply subtype.eq,
ext a,
dsimp only,
refine classical.by_cases (assume h : a ∈ set.range (subtype.val : s → α), _) (assume h, _),
{ rcases h with ⟨x, rfl⟩,
rw [map_domain_apply subtype.val_injective, subtype_domain_apply] },
{ convert map_domain_notin_range _ _ h,
rw [← not_mem_support_iff],
refine mt _ h,
exact assume ha, ⟨⟨a, hf ha⟩, rfl⟩ } },
{ assume f,
ext ⟨a, ha⟩,
dsimp only,
rw [subtype_domain_apply, map_domain_apply subtype.val_injective] }
end
/-- Given `add_comm_monoid M` and `e : α ≃ β`, `dom_congr e` is the corresponding `equiv` between
`α →₀ M` and `β →₀ M`.
This is `finsupp.equiv_congr_left` as an `add_equiv`. -/
@[simps apply]
protected def dom_congr [add_comm_monoid M] (e : α ≃ β) : (α →₀ M) ≃+ (β →₀ M) :=
{ to_fun := equiv_map_domain e,
inv_fun := equiv_map_domain e.symm,
left_inv := λ v, begin
simp only [← equiv_map_domain_trans, equiv.trans_symm],
exact equiv_map_domain_refl _
end,
right_inv := begin
assume v,
simp only [← equiv_map_domain_trans, equiv.symm_trans],
exact equiv_map_domain_refl _
end,
map_add' := λ a b, by simp only [equiv_map_domain_eq_map_domain]; exact map_domain_add }
@[simp] lemma dom_congr_refl [add_comm_monoid M] :
finsupp.dom_congr (equiv.refl α) = add_equiv.refl (α →₀ M) :=
add_equiv.ext $ λ _, equiv_map_domain_refl _
@[simp] lemma dom_congr_symm [add_comm_monoid M] (e : α ≃ β) :
(finsupp.dom_congr e).symm = (finsupp.dom_congr e.symm : (β →₀ M) ≃+ (α →₀ M)):=
add_equiv.ext $ λ _, rfl
@[simp] lemma dom_congr_trans [add_comm_monoid M] (e : α ≃ β) (f : β ≃ γ) :
(finsupp.dom_congr e).trans (finsupp.dom_congr f) =
(finsupp.dom_congr (e.trans f) : (α →₀ M) ≃+ _) :=
add_equiv.ext $ λ _, (equiv_map_domain_trans _ _ _).symm
end finsupp
namespace finsupp
/-! ### Declarations about sigma types -/
section sigma
variables {αs : ι → Type*} [has_zero M] (l : (Σ i, αs i) →₀ M)
/-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `M` and
an index element `i : ι`, `split l i` is the `i`th component of `l`,
a finitely supported function from `as i` to `M`.
This is the `finsupp` version of `sigma.curry`.
-/
def split (i : ι) : αs i →₀ M :=
l.comap_domain (sigma.mk i) (λ x1 x2 _ _ hx, heq_iff_eq.1 (sigma.mk.inj hx).2)
lemma split_apply (i : ι) (x : αs i) : split l i x = l ⟨i, x⟩ :=
begin
dunfold split,
rw comap_domain_apply
end
/-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `β`,
`split_support l` is the finset of indices in `ι` that appear in the support of `l`. -/
def split_support : finset ι := l.support.image sigma.fst
lemma mem_split_support_iff_nonzero (i : ι) :
i ∈ split_support l ↔ split l i ≠ 0 :=
begin
rw [split_support, mem_image, ne.def, ← support_eq_empty, ← ne.def,
← finset.nonempty_iff_ne_empty, split, comap_domain, finset.nonempty],
simp only [exists_prop, finset.mem_preimage, exists_and_distrib_right, exists_eq_right,
mem_support_iff, sigma.exists, ne.def]
end
/-- Given `l`, a finitely supported function from the sigma type `Σ i, αs i` to `β` and
an `ι`-indexed family `g` of functions from `(αs i →₀ β)` to `γ`, `split_comp` defines a
finitely supported function from the index type `ι` to `γ` given by composing `g i` with
`split l i`. -/
def split_comp [has_zero N] (g : Π i, (αs i →₀ M) → N)
(hg : ∀ i x, x = 0 ↔ g i x = 0) : ι →₀ N :=
{ support := split_support l,
to_fun := λ i, g i (split l i),
mem_support_to_fun :=
begin
intros i,
rw [mem_split_support_iff_nonzero, not_iff_not, hg],
end }
lemma sigma_support : l.support = l.split_support.sigma (λ i, (l.split i).support) :=
by simp only [finset.ext_iff, split_support, split, comap_domain, mem_image,
mem_preimage, sigma.forall, mem_sigma]; tauto
lemma sigma_sum [add_comm_monoid N] (f : (Σ (i : ι), αs i) → M → N) :
l.sum f = ∑ i in split_support l, (split l i).sum (λ (a : αs i) b, f ⟨i, a⟩ b) :=
by simp only [sum, sigma_support, sum_sigma, split_apply]
variables {η : Type*} [fintype η] {ιs : η → Type*} [has_zero α]
/-- On a `fintype η`, `finsupp.split` is an equivalence between `(Σ (j : η), ιs j) →₀ α`
and `Π j, (ιs j →₀ α)`.
This is the `finsupp` version of `equiv.Pi_curry`. -/
noncomputable def sigma_finsupp_equiv_pi_finsupp :
((Σ j, ιs j) →₀ α) ≃ Π j, (ιs j →₀ α) :=
{ to_fun := split,
inv_fun := λ f, on_finset
(finset.univ.sigma (λ j, (f j).support))
(λ ji, f ji.1 ji.2)
(λ g hg, finset.mem_sigma.mpr ⟨finset.mem_univ _, mem_support_iff.mpr hg⟩),
left_inv := λ f, by { ext, simp [split] },
right_inv := λ f, by { ext, simp [split] } }
@[simp] lemma sigma_finsupp_equiv_pi_finsupp_apply
(f : (Σ j, ιs j) →₀ α) (j i) :
sigma_finsupp_equiv_pi_finsupp f j i = f ⟨j, i⟩ := rfl
/-- On a `fintype η`, `finsupp.split` is an additive equivalence between
`(Σ (j : η), ιs j) →₀ α` and `Π j, (ιs j →₀ α)`.
This is the `add_equiv` version of `finsupp.sigma_finsupp_equiv_pi_finsupp`.
-/
noncomputable def sigma_finsupp_add_equiv_pi_finsupp
{α : Type*} {ιs : η → Type*} [add_monoid α] :
((Σ j, ιs j) →₀ α) ≃+ Π j, (ιs j →₀ α) :=
{ map_add' := λ f g, by { ext, simp },
.. sigma_finsupp_equiv_pi_finsupp }
@[simp] lemma sigma_finsupp_add_equiv_pi_finsupp_apply
{α : Type*} {ιs : η → Type*} [add_monoid α] (f : (Σ j, ιs j) →₀ α) (j i) :
sigma_finsupp_add_equiv_pi_finsupp f j i = f ⟨j, i⟩ := rfl
end sigma
end finsupp
/-! ### Declarations relating `multiset` to `finsupp` -/
namespace multiset
/-- Given a multiset `s`, `s.to_finsupp` returns the finitely supported function on `ℕ` given by
the multiplicities of the elements of `s`. -/
def to_finsupp : multiset α ≃+ (α →₀ ℕ) := finsupp.to_multiset.symm
@[simp] lemma to_finsupp_support [D : decidable_eq α] (s : multiset α) :
s.to_finsupp.support = s.to_finset :=
by rw subsingleton.elim D; refl
@[simp] lemma to_finsupp_apply [D : decidable_eq α] (s : multiset α) (a : α) :
to_finsupp s a = s.count a :=
by rw subsingleton.elim D; refl
lemma to_finsupp_zero : to_finsupp (0 : multiset α) = 0 := add_equiv.map_zero _
lemma to_finsupp_add (s t : multiset α) :
to_finsupp (s + t) = to_finsupp s + to_finsupp t :=
to_finsupp.map_add s t
@[simp] lemma to_finsupp_singleton (a : α) : to_finsupp ({a} : multiset α) = finsupp.single a 1 :=
finsupp.to_multiset.symm_apply_eq.2 $ by simp
@[simp] lemma to_finsupp_to_multiset (s : multiset α) :
s.to_finsupp.to_multiset = s :=
finsupp.to_multiset.apply_symm_apply s
lemma to_finsupp_eq_iff {s : multiset α} {f : α →₀ ℕ} : s.to_finsupp = f ↔ s = f.to_multiset :=
finsupp.to_multiset.symm_apply_eq
end multiset
@[simp] lemma finsupp.to_multiset_to_finsupp (f : α →₀ ℕ) :
f.to_multiset.to_finsupp = f :=
finsupp.to_multiset.symm_apply_apply f
/-! ### Declarations about order(ed) instances on `finsupp` -/
namespace finsupp
instance [preorder M] [has_zero M] : preorder (α →₀ M) :=
{ le := λ f g, ∀ s, f s ≤ g s,
le_refl := λ f s, le_refl _,
le_trans := λ f g h Hfg Hgh s, le_trans (Hfg s) (Hgh s) }
instance [partial_order M] [has_zero M] : partial_order (α →₀ M) :=
{ le_antisymm := λ f g hfg hgf, ext $ λ s, le_antisymm (hfg s) (hgf s),
.. finsupp.preorder }
instance [ordered_add_comm_monoid M] : ordered_add_comm_monoid (α →₀ M) :=
{ add_le_add_left := λ a b h c s, add_le_add_left (h s) (c s),
.. finsupp.add_comm_monoid, .. finsupp.partial_order }
instance [ordered_cancel_add_comm_monoid M] : ordered_cancel_add_comm_monoid (α →₀ M) :=
{ add_le_add_left := λ a b h c s, add_le_add_left (h s) (c s),
le_of_add_le_add_left := λ a b c h s, le_of_add_le_add_left (h s),
add_left_cancel := λ a b c h, ext $ λ s, add_left_cancel (ext_iff.1 h s),
.. finsupp.add_comm_monoid, .. finsupp.partial_order }
instance [ordered_add_comm_monoid M] [contravariant_class M M (+) (≤)] :
contravariant_class (α →₀ M) (α →₀ M) (+) (≤) :=
⟨λ f g h H x, le_of_add_le_add_left $ H x⟩
lemma le_def [preorder M] [has_zero M] {f g : α →₀ M} : f ≤ g ↔ ∀ x, f x ≤ g x := iff.rfl
lemma le_iff' [canonically_ordered_add_monoid M] (f g : α →₀ M)
{t : finset α} (hf : f.support ⊆ t) :
f ≤ g ↔ ∀ s ∈ t, f s ≤ g s :=
⟨λ 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 [canonically_ordered_add_monoid M] (f g : α →₀ M) :
f ≤ g ↔ ∀ s ∈ f.support, f s ≤ g s :=
le_iff' f g (subset.refl _)
instance decidable_le [canonically_ordered_add_monoid M] [decidable_rel (@has_le.le M _)] :
decidable_rel (@has_le.le (α →₀ M) _) :=
λ f g, decidable_of_iff _ (le_iff f g).symm
@[simp] lemma single_le_iff [canonically_ordered_add_monoid M] {i : α} {x : M} {f : α →₀ M} :
single i x ≤ f ↔ x ≤ f i :=
(le_iff' _ _ support_single_subset).trans $ by simp
@[simp] lemma add_eq_zero_iff [canonically_ordered_add_monoid M] (f g : α →₀ M) :
f + g = 0 ↔ f = 0 ∧ g = 0 :=
by simp [ext_iff, forall_and_distrib]
/-- `finsupp.to_multiset` as an order isomorphism. -/
def order_iso_multiset : (α →₀ ℕ) ≃o multiset α :=
{ to_equiv := to_multiset.to_equiv,
map_rel_iff' := λ f g, by simp [multiset.le_iff_count, le_def] }
@[simp] lemma coe_order_iso_multiset : ⇑(@order_iso_multiset α) = to_multiset := rfl
@[simp] lemma coe_order_iso_multiset_symm :
⇑(@order_iso_multiset α).symm = multiset.to_finsupp := rfl
lemma to_multiset_strict_mono : strict_mono (@to_multiset α) :=
order_iso_multiset.strict_mono
lemma sum_id_lt_of_lt (m n : α →₀ ℕ) (h : m < n) :
m.sum (λ _, id) < n.sum (λ _, id) :=
begin
rw [← card_to_multiset, ← card_to_multiset],
apply multiset.card_lt_of_lt,
exact to_multiset_strict_mono h
end
variable (α)
/-- The order on `σ →₀ ℕ` is well-founded.-/
lemma lt_wf : well_founded (@has_lt.lt (α →₀ ℕ) _) :=
subrelation.wf (sum_id_lt_of_lt) $ inv_image.wf _ nat.lt_wf
variable {α}
/-! Declarations about subtraction on `finsupp` with codomain a `canonically_ordered_add_monoid`.
Some of these lemmas are used to develop the partial derivative on `mv_polynomial`. -/
section nat_sub
section canonically_ordered_monoid
variables [canonically_ordered_add_monoid M] [has_sub M] [has_ordered_sub M]
/-- This is called `tsub` for truncated subtraction, to distinguish it with subtraction in an
additive group. -/
instance tsub : has_sub (α →₀ M) :=
⟨zip_with (λ m n, m - n) (tsub_self 0)⟩
@[simp] lemma coe_tsub (g₁ g₂ : α →₀ M) : ⇑(g₁ - g₂) = g₁ - g₂ := rfl
lemma tsub_apply (g₁ g₂ : α →₀ M) (a : α) : (g₁ - g₂) a = g₁ a - g₂ a := rfl
instance : canonically_ordered_add_monoid (α →₀ M) :=
{ bot := 0,
bot_le := λ f s, zero_le (f s),
le_iff_exists_add := begin
intros f g,
split,
{ intro H, use g - f, ext x, symmetry, exact add_tsub_cancel_of_le (H x) },
{ rintro ⟨g, rfl⟩ x, exact self_le_add_right (f x) (g x) }
end,
..(by apply_instance : ordered_add_comm_monoid (α →₀ M)) }
instance : has_ordered_sub (α →₀ M) :=
⟨λ n m k, forall_congr $ λ x, tsub_le_iff_right⟩
@[simp] lemma single_tsub {a : α} {n₁ n₂ : M} : single a (n₁ - n₂) = single a n₁ - single a n₂ :=
begin
ext f,
by_cases h : (a = f),
{ rw [h, 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
end canonically_ordered_monoid
/-! Some lemmas specifically about `ℕ`. -/
lemma sub_single_one_add {a : α} {u u' : α →₀ ℕ} (h : u a ≠ 0) :
u - single a 1 + u' = u + u' - single a 1 :=
tsub_add_eq_add_tsub $ single_le_iff.mpr $ nat.one_le_iff_ne_zero.mpr h
lemma add_sub_single_one {a : α} {u u' : α →₀ ℕ} (h : u' a ≠ 0) :
u + (u' - single a 1) = u + u' - single a 1 :=
(add_tsub_assoc_of_le (single_le_iff.mpr $ nat.one_le_iff_ne_zero.mpr h) _).symm
end nat_sub
end finsupp
namespace multiset
lemma to_finsuppstrict_mono : strict_mono (@to_finsupp α) :=
finsupp.order_iso_multiset.symm.strict_mono
end multiset
|
b9793cd5fc9c2bd619ef60a07d7c76541b89234a | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/ring_theory/localization/num_denom.lean | 2da5967b481dd240e6deda5dae1a107e3253a2dc | [
"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 | 3,975 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston, Anne Baanen
-/
import ring_theory.localization.fraction_ring
import ring_theory.localization.integer
import ring_theory.unique_factorization_domain
/-!
# Numerator and denominator in a localization
## Implementation notes
See `src/ring_theory/localization/basic.lean` for a design overview.
## Tags
localization, ring localization, commutative ring localization, characteristic predicate,
commutative ring, field of fractions
-/
variables {R : Type*} [comm_ring R] (M : submonoid R) {S : Type*} [comm_ring S]
variables [algebra R S] {P : Type*} [comm_ring P]
namespace is_fraction_ring
open is_localization
section num_denom
variables (A : Type*) [comm_ring A] [is_domain A] [unique_factorization_monoid A]
variables {K : Type*} [field K] [algebra A K] [is_fraction_ring A K]
lemma exists_reduced_fraction (x : K) :
∃ (a : A) (b : non_zero_divisors A),
(∀ {d}, d ∣ a → d ∣ b → is_unit d) ∧ mk' K a b = x :=
begin
obtain ⟨⟨b, b_nonzero⟩, a, hab⟩ := exists_integer_multiple (non_zero_divisors A) x,
obtain ⟨a', b', c', no_factor, rfl, rfl⟩ :=
unique_factorization_monoid.exists_reduced_factors' a b
(mem_non_zero_divisors_iff_ne_zero.mp b_nonzero),
obtain ⟨c'_nonzero, b'_nonzero⟩ := mul_mem_non_zero_divisors.mp b_nonzero,
refine ⟨a', ⟨b', b'_nonzero⟩, @no_factor, _⟩,
refine mul_left_cancel₀
(is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors b_nonzero) _,
simp only [subtype.coe_mk, ring_hom.map_mul, algebra.smul_def] at *,
erw [←hab, mul_assoc, mk'_spec' _ a' ⟨b', b'_nonzero⟩],
end
/-- `f.num x` is the numerator of `x : f.codomain` as a reduced fraction. -/
noncomputable def num (x : K) : A :=
classical.some (exists_reduced_fraction A x)
/-- `f.num x` is the denominator of `x : f.codomain` as a reduced fraction. -/
noncomputable def denom (x : K) : non_zero_divisors A :=
classical.some (classical.some_spec (exists_reduced_fraction A x))
lemma num_denom_reduced (x : K) :
∀ {d}, d ∣ num A x → d ∣ denom A x → is_unit d :=
(classical.some_spec (classical.some_spec (exists_reduced_fraction A x))).1
@[simp] lemma mk'_num_denom (x : K) : mk' K (num A x) (denom A x) = x :=
(classical.some_spec (classical.some_spec (exists_reduced_fraction A x))).2
variables {A}
lemma num_mul_denom_eq_num_iff_eq {x y : K} :
x * algebra_map A K (denom A y) = algebra_map A K (num A y) ↔ x = y :=
⟨λ h, by simpa only [mk'_num_denom] using eq_mk'_iff_mul_eq.mpr h,
λ h, eq_mk'_iff_mul_eq.mp (by rw [h, mk'_num_denom])⟩
lemma num_mul_denom_eq_num_iff_eq' {x y : K} :
y * algebra_map A K (denom A x) = algebra_map A K (num A x) ↔ x = y :=
⟨λ h, by simpa only [eq_comm, mk'_num_denom] using eq_mk'_iff_mul_eq.mpr h,
λ h, eq_mk'_iff_mul_eq.mp (by rw [h, mk'_num_denom])⟩
lemma num_mul_denom_eq_num_mul_denom_iff_eq {x y : K} :
num A y * denom A x = num A x * denom A y ↔ x = y :=
⟨λ h, by simpa only [mk'_num_denom] using mk'_eq_of_eq h,
λ h, by rw h⟩
lemma eq_zero_of_num_eq_zero {x : K} (h : num A x = 0) : x = 0 :=
num_mul_denom_eq_num_iff_eq'.mp (by rw [zero_mul, h, ring_hom.map_zero])
lemma is_integer_of_is_unit_denom {x : K} (h : is_unit (denom A x : A)) : is_integer A x :=
begin
cases h with d hd,
have d_ne_zero : algebra_map A K (denom A x) ≠ 0 :=
is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors (denom A x).2,
use ↑d⁻¹ * num A x,
refine trans _ (mk'_num_denom A x),
rw [map_mul, map_units_inv, hd],
apply mul_left_cancel₀ d_ne_zero,
rw [←mul_assoc, mul_inv_cancel d_ne_zero, one_mul, mk'_spec']
end
lemma is_unit_denom_of_num_eq_zero {x : K} (h : num A x = 0) : is_unit (denom A x : A) :=
num_denom_reduced A x (h.symm ▸ dvd_zero _) dvd_rfl
end num_denom
variables (S)
end is_fraction_ring
|
7168d77d4da9ca636ea0bd865951049cc32b0508 | 737dc4b96c97368cb66b925eeea3ab633ec3d702 | /stage0/src/Lean/Data/Json/FromToJson.lean | 0bba89ba93692eecfe3f393d424e23335c5ae46a | [
"Apache-2.0"
] | permissive | Bioye97/lean4 | 1ace34638efd9913dc5991443777b01a08983289 | bc3900cbb9adda83eed7e6affeaade7cfd07716d | refs/heads/master | 1,690,589,820,211 | 1,631,051,000,000 | 1,631,067,598,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,886 | lean | /-
Copyright (c) 2019 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner, Marc Huisinga
-/
import Lean.Data.Json.Basic
import Lean.Data.Json.Printer
namespace Lean
universe u
class FromJson (α : Type u) where
fromJson? : Json → Except String α
export FromJson (fromJson?)
class ToJson (α : Type u) where
toJson : α → Json
export ToJson (toJson)
instance : FromJson Json := ⟨Except.ok⟩
instance : ToJson Json := ⟨id⟩
instance : FromJson JsonNumber := ⟨Json.getNum?⟩
instance : ToJson JsonNumber := ⟨Json.num⟩
-- looks like id, but there are coercions happening
instance : FromJson Bool := ⟨Json.getBool?⟩
instance : ToJson Bool := ⟨fun b => b⟩
instance : FromJson Nat := ⟨Json.getNat?⟩
instance : ToJson Nat := ⟨fun n => n⟩
instance : FromJson Int := ⟨Json.getInt?⟩
instance : ToJson Int := ⟨fun n => Json.num n⟩
instance : FromJson String := ⟨Json.getStr?⟩
instance : ToJson String := ⟨fun s => s⟩
instance [FromJson α] : FromJson (Array α) where
fromJson?
| Json.arr a => a.mapM fromJson?
| j => throw s!"expected JSON array, got '{j}'"
instance [ToJson α] : ToJson (Array α) :=
⟨fun a => Json.arr (a.map toJson)⟩
instance [FromJson α] : FromJson (Option α) where
fromJson?
| Json.null => Except.ok none
| j => some <$> fromJson? j
instance [ToJson α] : ToJson (Option α) :=
⟨fun
| none => Json.null
| some a => toJson a⟩
instance [FromJson α] [FromJson β] : FromJson (α × β) where
fromJson?
| Json.arr #[ja, jb] => do
let a ← fromJson? ja
let b ← fromJson? jb
return (a, b)
| j => throw s!"expected pair, got '{j}'"
instance [ToJson α] [ToJson β] : ToJson (α × β) where
toJson := fun (a, b) => Json.arr #[toJson a, toJson b]
instance : FromJson Name where
fromJson? j := do
let s ← j.getStr?
let some n ← Syntax.decodeNameLit ("`" ++ s)
| throw s!"expected a `Name`, got '{j}'"
return n
instance : ToJson Name where
toJson n := toString n
/- Note that `USize`s and `UInt64`s are stored as strings because JavaScript
cannot represent 64-bit numbers. -/
def bignumFromJson? (j : Json) : Except String Nat := do
let s ← j.getStr?
let some v ← Syntax.decodeNatLitVal? s -- TODO maybe this should be in Std
| throw s!"expected a string-encoded number, got '{j}'"
return v
def bignumToJson (n : Nat) : Json :=
toString n
instance : FromJson USize where
fromJson? j := do
let n ← bignumFromJson? j
if n ≥ USize.size then
throw "value '{j}' is too large for `USize`"
return USize.ofNat n
instance : ToJson USize where
toJson v := bignumToJson (USize.toNat v)
instance : FromJson UInt64 where
fromJson? j := do
let n ← bignumFromJson? j
if n ≥ UInt64.size then
throw "value '{j}' is too large for `UInt64`"
return UInt64.ofNat n
instance : ToJson UInt64 where
toJson v := bignumToJson (UInt64.toNat v)
namespace Json
instance : FromJson Structured := ⟨fun
| arr a => Structured.arr a
| obj o => Structured.obj o
| j => throw s!"expected structured object, got '{j}'"⟩
instance : ToJson Structured := ⟨fun
| Structured.arr a => arr a
| Structured.obj o => obj o⟩
def toStructured? [ToJson α] (v : α) : Except String Structured :=
fromJson? (toJson v)
def getObjValAs? (j : Json) (α : Type u) [FromJson α] (k : String) : Except String α :=
fromJson? <| j.getObjValD k
def opt [ToJson α] (k : String) : Option α → List (String × Json)
| none => []
| some o => [⟨k, toJson o⟩]
/-- Parses a JSON-encoded `structure` or `inductive` constructor. Used mostly by `deriving FromJson`. -/
def parseTagged
(json : Json)
(tag : String)
(nFields : Nat)
(fieldNames? : Option (Array Name)) : Except String (Array Json) :=
if nFields == 0 then
match getStr? json with
| Except.ok s => if s == tag then Except.ok #[] else throw s!"incorrect tag: {s} ≟ {tag}"
| Except.error err => Except.error err
else
match getObjVal? json tag with
| Except.ok payload =>
match fieldNames? with
| some fieldNames =>
do
let mut fields := #[]
for fieldName in fieldNames do
fields := fields.push (←getObjVal? payload fieldName.getString!)
Except.ok fields
| none =>
if nFields == 1 then
Except.ok #[payload]
else
match getArr? payload with
| Except.ok fields =>
if fields.size == nFields then
Except.ok fields
else
Except.error s!"incorrect number of fields: {fields.size} ≟ {nFields}"
| Except.error err => Except.error err
| Except.error err => Except.error err
end Json
end Lean
|
74cf6b451e17d4d3add88f35ab6b79bb0fa43c71 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/init/control/default_auto.lean | 8dfeda5399620785d305bf4219535047f1ab884a | [] | 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 | 705 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.control.applicative
import Mathlib.Lean3Lib.init.control.functor
import Mathlib.Lean3Lib.init.control.alternative
import Mathlib.Lean3Lib.init.control.monad
import Mathlib.Lean3Lib.init.control.lift
import Mathlib.Lean3Lib.init.control.lawful
import Mathlib.Lean3Lib.init.control.state
import Mathlib.Lean3Lib.init.control.id
import Mathlib.Lean3Lib.init.control.except
import Mathlib.Lean3Lib.init.control.reader
import Mathlib.Lean3Lib.init.control.option
namespace Mathlib
end Mathlib |
bba3b19a4144792ed5c4b4e9815bc773747b31ad | 08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4 | /src/Lean/Syntax.lean | 1a38855bd7be339188193929b1566ace005f901c | [
"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 | 21,050 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Sebastian Ullrich, Leonardo de Moura
-/
import Lean.Data.Name
import Lean.Data.Format
/--
A position range inside a string. This type is mostly in combination with syntax trees,
as there might not be a single underlying string in this case that could be used for a `Substring`.
-/
protected structure String.Range where
start : String.Pos
stop : String.Pos
deriving Inhabited, Repr, BEq, Hashable
def String.Range.contains (r : String.Range) (pos : String.Pos) (includeStop := false) : Bool :=
r.start <= pos && (if includeStop then pos <= r.stop else pos < r.stop)
def String.Range.includes (super sub : String.Range) : Bool :=
super.start <= sub.start && super.stop >= sub.stop
namespace Lean
def SourceInfo.updateTrailing (trailing : Substring) : SourceInfo → SourceInfo
| SourceInfo.original leading pos _ endPos => SourceInfo.original leading pos trailing endPos
| info => info
/-! # Syntax AST -/
inductive IsNode : Syntax → Prop where
| mk (info : SourceInfo) (kind : SyntaxNodeKind) (args : Array Syntax) : IsNode (Syntax.node info kind args)
def SyntaxNode : Type := {s : Syntax // IsNode s }
def unreachIsNodeMissing {β} (h : IsNode Syntax.missing) : β := False.elim (nomatch h)
def unreachIsNodeAtom {β} {info val} (h : IsNode (Syntax.atom info val)) : β := False.elim (nomatch h)
def unreachIsNodeIdent {β info rawVal val preresolved} (h : IsNode (Syntax.ident info rawVal val preresolved)) : β := False.elim (nomatch h)
def isLitKind (k : SyntaxNodeKind) : Bool :=
k == strLitKind || k == numLitKind || k == charLitKind || k == nameLitKind || k == scientificLitKind
namespace SyntaxNode
@[inline] def getKind (n : SyntaxNode) : SyntaxNodeKind :=
match n with
| ⟨Syntax.node _ k _, _⟩ => k
| ⟨Syntax.missing, h⟩ => unreachIsNodeMissing h
| ⟨Syntax.atom .., h⟩ => unreachIsNodeAtom h
| ⟨Syntax.ident .., h⟩ => unreachIsNodeIdent h
@[inline] def withArgs {β} (n : SyntaxNode) (fn : Array Syntax → β) : β :=
match n with
| ⟨Syntax.node _ _ args, _⟩ => fn args
| ⟨Syntax.missing, h⟩ => unreachIsNodeMissing h
| ⟨Syntax.atom _ _, h⟩ => unreachIsNodeAtom h
| ⟨Syntax.ident _ _ _ _, h⟩ => unreachIsNodeIdent h
@[inline] def getNumArgs (n : SyntaxNode) : Nat :=
withArgs n fun args => args.size
@[inline] def getArg (n : SyntaxNode) (i : Nat) : Syntax :=
withArgs n fun args => args.get! i
@[inline] def getArgs (n : SyntaxNode) : Array Syntax :=
withArgs n fun args => args
@[inline] def modifyArgs (n : SyntaxNode) (fn : Array Syntax → Array Syntax) : Syntax :=
match n with
| ⟨Syntax.node i k args, _⟩ => Syntax.node i k (fn args)
| ⟨Syntax.missing, h⟩ => unreachIsNodeMissing h
| ⟨Syntax.atom _ _, h⟩ => unreachIsNodeAtom h
| ⟨Syntax.ident _ _ _ _, h⟩ => unreachIsNodeIdent h
end SyntaxNode
namespace Syntax
def getAtomVal : Syntax → String
| atom _ val => val
| _ => ""
def setAtomVal : Syntax → String → Syntax
| atom info _, v => (atom info v)
| stx, _ => stx
@[inline] def ifNode {β} (stx : Syntax) (hyes : SyntaxNode → β) (hno : Unit → β) : β :=
match stx with
| Syntax.node i k args => hyes ⟨Syntax.node i k args, IsNode.mk i k args⟩
| _ => hno ()
@[inline] def ifNodeKind {β} (stx : Syntax) (kind : SyntaxNodeKind) (hyes : SyntaxNode → β) (hno : Unit → β) : β :=
match stx with
| Syntax.node i k args => if k == kind then hyes ⟨Syntax.node i k args, IsNode.mk i k args⟩ else hno ()
| _ => hno ()
def asNode : Syntax → SyntaxNode
| Syntax.node info kind args => ⟨Syntax.node info kind args, IsNode.mk info kind args⟩
| _ => ⟨mkNullNode, IsNode.mk _ _ _⟩
def getIdAt (stx : Syntax) (i : Nat) : Name :=
(stx.getArg i).getId
@[inline] def modifyArgs (stx : Syntax) (fn : Array Syntax → Array Syntax) : Syntax :=
match stx with
| node i k args => node i k (fn args)
| stx => stx
@[inline] def modifyArg (stx : Syntax) (i : Nat) (fn : Syntax → Syntax) : Syntax :=
match stx with
| node info k args => node info k (args.modify i fn)
| stx => stx
@[specialize] partial def replaceM {m : Type → Type} [Monad m] (fn : Syntax → m (Option Syntax)) : Syntax → m (Syntax)
| stx@(node info kind args) => do
match (← fn stx) with
| some stx => return stx
| none => return node info kind (← args.mapM (replaceM fn))
| stx => do
let o ← fn stx
return o.getD stx
@[specialize] partial def rewriteBottomUpM {m : Type → Type} [Monad m] (fn : Syntax → m (Syntax)) : Syntax → m (Syntax)
| node info kind args => do
let args ← args.mapM (rewriteBottomUpM fn)
fn (node info kind args)
| stx => fn stx
@[inline] def rewriteBottomUp (fn : Syntax → Syntax) (stx : Syntax) : Syntax :=
Id.run <| stx.rewriteBottomUpM fn
private def updateInfo : SourceInfo → String.Pos → String.Pos → SourceInfo
| SourceInfo.original lead pos trail endPos, leadStart, trailStop =>
SourceInfo.original { lead with startPos := leadStart } pos { trail with stopPos := trailStop } endPos
| info, _, _ => info
private def chooseNiceTrailStop (trail : Substring) : String.Pos :=
trail.startPos + trail.posOf '\n'
/-- Remark: the State `String.Pos` is the `SourceInfo.trailing.stopPos` of the previous token,
or the beginning of the String. -/
@[inline]
private def updateLeadingAux : Syntax → StateM String.Pos (Option Syntax)
| atom info@(SourceInfo.original _ _ trail _) val => do
let trailStop := chooseNiceTrailStop trail
let newInfo := updateInfo info (← get) trailStop
set trailStop
return some (atom newInfo val)
| ident info@(SourceInfo.original _ _ trail _) rawVal val pre => do
let trailStop := chooseNiceTrailStop trail
let newInfo := updateInfo info (← get) trailStop
set trailStop
return some (ident newInfo rawVal val pre)
| _ => pure none
/-- Set `SourceInfo.leading` according to the trailing stop of the preceding token.
The result is a round-tripping syntax tree IF, in the input syntax tree,
* all leading stops, atom contents, and trailing starts are correct
* trailing stops are between the trailing start and the next leading stop.
Remark: after parsing, all `SourceInfo.leading` fields are empty.
The `Syntax` argument is the output produced by the parser for `source`.
This function "fixes" the `source.leading` field.
Additionally, we try to choose "nicer" splits between leading and trailing stops
according to some heuristics so that e.g. comments are associated to the (intuitively)
correct token.
Note that the `SourceInfo.trailing` fields must be correct.
The implementation of this Function relies on this property. -/
def updateLeading : Syntax → Syntax :=
fun stx => (replaceM updateLeadingAux stx).run' 0
partial def updateTrailing (trailing : Substring) : Syntax → Syntax
| Syntax.atom info val => Syntax.atom (info.updateTrailing trailing) val
| Syntax.ident info rawVal val pre => Syntax.ident (info.updateTrailing trailing) rawVal val pre
| n@(Syntax.node info k args) =>
if args.size == 0 then n
else
let i := args.size - 1
let last := updateTrailing trailing args[i]!
let args := args.set! i last;
Syntax.node info k args
| s => s
partial def getTailWithPos : Syntax → Option Syntax
| stx@(atom info _) => info.getPos?.map fun _ => stx
| stx@(ident info ..) => info.getPos?.map fun _ => stx
| node SourceInfo.none _ args => args.findSomeRev? getTailWithPos
| stx@(node ..) => stx
| _ => none
open SourceInfo in
/-- Split an `ident` into its dot-separated components while preserving source info.
Macro scopes are first erased. For example, `` `foo.bla.boo._@._hyg.4 `` ↦ `` [`foo, `bla, `boo] ``.
If `nFields` is set, we take that many fields from the end and keep the remaining components
as one name. For example, `` `foo.bla.boo `` with `(nFields := 1)` ↦ `` [`foo.bla, `boo] ``. -/
def identComponents (stx : Syntax) (nFields? : Option Nat := none) : List Syntax :=
match stx with
| ident (SourceInfo.original lead pos trail _) rawStr val _ =>
let val := val.eraseMacroScopes
-- With original info, we assume that `rawStr` represents `val`.
let nameComps := nameComps val nFields?
let rawComps := splitNameLit rawStr
let rawComps :=
if let some nFields := nFields? then
let nPrefix := rawComps.length - nFields
let prefixSz := rawComps.take nPrefix |>.foldl (init := 0) fun acc (ss : Substring) => acc + ss.bsize + 1
let prefixSz := prefixSz - 1 -- The last component has no dot
rawStr.extract 0 ⟨prefixSz⟩ :: rawComps.drop nPrefix
else
rawComps
assert! nameComps.length == rawComps.length
nameComps.zip rawComps |>.map fun (id, ss) =>
let off := ss.startPos - rawStr.startPos
let lead := if off == 0 then lead else "".toSubstring
let trail := if ss.stopPos == rawStr.stopPos then trail else "".toSubstring
let info := original lead (pos + off) trail (pos + off + ⟨ss.bsize⟩)
ident info ss id []
| ident si _ val _ =>
let val := val.eraseMacroScopes
/- With non-original info:
- `rawStr` can take all kinds of forms so we only use `val`.
- there is no source extent to offset, so we pass it as-is. -/
nameComps val nFields? |>.map fun n => ident si n.toString.toSubstring n []
| _ => unreachable!
where
nameComps (n : Name) (nFields? : Option Nat) : List Name :=
if let some nFields := nFields? then
let nameComps := n.components
let nPrefix := nameComps.length - nFields
let namePrefix := nameComps.take nPrefix |>.foldl (init := Name.anonymous) fun acc n => acc ++ n
namePrefix :: nameComps.drop nPrefix
else
n.components
structure TopDown where
firstChoiceOnly : Bool
stx : Syntax
/--
`for _ in stx.topDown` iterates through each node and leaf in `stx` top-down, left-to-right.
If `firstChoiceOnly` is `true`, only visit the first argument of each choice node.
-/
def topDown (stx : Syntax) (firstChoiceOnly := false) : TopDown := ⟨firstChoiceOnly, stx⟩
partial instance : ForIn m TopDown Syntax where
forIn := fun ⟨firstChoiceOnly, stx⟩ init f => do
let rec @[specialize] loop stx b [Inhabited (type_of% b)] := do
match (← f stx b) with
| ForInStep.yield b' =>
let mut b := b'
if let Syntax.node _ k args := stx then
if firstChoiceOnly && k == choiceKind then
return ← loop args[0]! b
else
for arg in args do
match (← loop arg b) with
| ForInStep.yield b' => b := b'
| ForInStep.done b' => return ForInStep.done b'
return ForInStep.yield b
| ForInStep.done b => return ForInStep.done b
match (← @loop stx init ⟨init⟩) with
| ForInStep.yield b => return b
| ForInStep.done b => return b
partial def reprint (stx : Syntax) : Option String := do
let mut s := ""
for stx in stx.topDown (firstChoiceOnly := true) do
match stx with
| atom info val => s := s ++ reprintLeaf info val
| ident info rawVal _ _ => s := s ++ reprintLeaf info rawVal.toString
| node _ kind args =>
if kind == choiceKind then
-- this visit the first arg twice, but that should hardly be a problem
-- given that choice nodes are quite rare and small
let s0 ← reprint args[0]!
for arg in args[1:] do
let s' ← reprint arg
guard (s0 == s')
| _ => pure ()
return s
where
reprintLeaf (info : SourceInfo) (val : String) : String :=
match info with
| SourceInfo.original lead _ trail _ => s!"{lead}{val}{trail}"
-- no source info => add gracious amounts of whitespace to definitely separate tokens
-- Note that the proper pretty printer does not use this function.
-- The parser as well always produces source info, so round-tripping is still
-- guaranteed.
| _ => s!" {val} "
def hasMissing (stx : Syntax) : Bool := Id.run do
for stx in stx.topDown do
if stx.isMissing then
return true
return false
def getRange? (stx : Syntax) (canonicalOnly := false) : Option String.Range :=
match stx.getPos? canonicalOnly, stx.getTailPos? canonicalOnly with
| some start, some stop => some { start, stop }
| _, _ => none
/--
Represents a cursor into a syntax tree that can be read, written, and advanced down/up/left/right.
Indices are allowed to be out-of-bound, in which case `cur` is `Syntax.missing`.
If the `Traverser` is used linearly, updates are linear in the `Syntax` object as well.
-/
structure Traverser where
cur : Syntax
parents : Array Syntax
idxs : Array Nat
namespace Traverser
def fromSyntax (stx : Syntax) : Traverser :=
⟨stx, #[], #[]⟩
def setCur (t : Traverser) (stx : Syntax) : Traverser :=
{ t with cur := stx }
/-- Advance to the `idx`-th child of the current node. -/
def down (t : Traverser) (idx : Nat) : Traverser :=
if idx < t.cur.getNumArgs then
{ cur := t.cur.getArg idx, parents := t.parents.push <| t.cur.setArg idx default, idxs := t.idxs.push idx }
else
{ cur := Syntax.missing, parents := t.parents.push t.cur, idxs := t.idxs.push idx }
/-- Advance to the parent of the current node, if any. -/
def up (t : Traverser) : Traverser :=
if t.parents.size > 0 then
let cur := if t.idxs.back < t.parents.back.getNumArgs then t.parents.back.setArg t.idxs.back t.cur else t.parents.back
{ cur := cur, parents := t.parents.pop, idxs := t.idxs.pop }
else
t
/-- Advance to the left sibling of the current node, if any. -/
def left (t : Traverser) : Traverser :=
if t.parents.size > 0 then
t.up.down (t.idxs.back - 1)
else
t
/-- Advance to the right sibling of the current node, if any. -/
def right (t : Traverser) : Traverser :=
if t.parents.size > 0 then
t.up.down (t.idxs.back + 1)
else
t
end Traverser
/-- Monad class that gives read/write access to a `Traverser`. -/
class MonadTraverser (m : Type → Type) where
st : MonadState Traverser m
namespace MonadTraverser
variable {m : Type → Type} [Monad m] [t : MonadTraverser m]
def getCur : m Syntax := Traverser.cur <$> t.st.get
def setCur (stx : Syntax) : m Unit := @modify _ _ t.st (fun t => t.setCur stx)
def goDown (idx : Nat) : m Unit := @modify _ _ t.st (fun t => t.down idx)
def goUp : m Unit := @modify _ _ t.st (fun t => t.up)
def goLeft : m Unit := @modify _ _ t.st (fun t => t.left)
def goRight : m Unit := @modify _ _ t.st (fun t => t.right)
def getIdx : m Nat := do
let st ← t.st.get
return st.idxs.back?.getD 0
end MonadTraverser
end Syntax
namespace SyntaxNode
@[inline] def getIdAt (n : SyntaxNode) (i : Nat) : Name :=
(n.getArg i).getId
end SyntaxNode
def mkListNode (args : Array Syntax) : Syntax :=
mkNullNode args
namespace Syntax
-- quotation node kinds are formed from a unique quotation name plus "quot"
def isQuot : Syntax → Bool
| Syntax.node _ (Name.str _ "quot") _ => true
| Syntax.node _ `Lean.Parser.Term.dynamicQuot _ => true
| _ => false
def getQuotContent (stx : Syntax) : Syntax :=
let stx := if stx.getNumArgs == 1 then stx[0] else stx
if stx.isOfKind `Lean.Parser.Term.dynamicQuot then
stx[3]
else
stx[1]
-- antiquotation node kinds are formed from the original node kind (if any) plus "antiquot"
def isAntiquot : Syntax → Bool
| .node _ (.str _ "antiquot") _ => true
| _ => false
def isAntiquots (stx : Syntax) : Bool :=
stx.isAntiquot || (stx.isOfKind choiceKind && stx.getNumArgs > 0 && stx.getArgs.all isAntiquot)
def getCanonicalAntiquot (stx : Syntax) : Syntax :=
if stx.isOfKind choiceKind then
stx[0]
else
stx
def mkAntiquotNode (kind : Name) (term : Syntax) (nesting := 0) (name : Option String := none) (isPseudoKind := false) : Syntax :=
let nesting := mkNullNode (mkArray nesting (mkAtom "$"))
let term :=
if term.isIdent then term
else if term.isOfKind `Lean.Parser.Term.hole then term[0]
else mkNode `antiquotNestedExpr #[mkAtom "(", term, mkAtom ")"]
let name := match name with
| some name => mkNode `antiquotName #[mkAtom ":", mkAtom name]
| none => mkNullNode
mkNode (kind ++ (if isPseudoKind then `pseudo else Name.anonymous) ++ `antiquot) #[mkAtom "$", nesting, term, name]
-- Antiquotations can be escaped as in `$$x`, which is useful for nesting macros. Also works for antiquotation splices.
def isEscapedAntiquot (stx : Syntax) : Bool :=
!stx[1].getArgs.isEmpty
-- Also works for antiquotation splices.
def unescapeAntiquot (stx : Syntax) : Syntax :=
if isAntiquot stx then
stx.setArg 1 <| mkNullNode stx[1].getArgs.pop
else
stx
-- Also works for token antiquotations.
def getAntiquotTerm (stx : Syntax) : Syntax :=
let e := if stx.isAntiquot then stx[2] else stx[3]
if e.isIdent then e
else if e.isAtom then mkNode `Lean.Parser.Term.hole #[e]
else
-- `e` is from `"(" >> termParser >> ")"`
e[1]
/-- Return kind of parser expected at this antiquotation, and whether it is a "pseudo" kind (see `mkAntiquot`). -/
def antiquotKind? : Syntax → Option (SyntaxNodeKind × Bool)
| .node _ (.str (.str k "pseudo") "antiquot") _ => (k, true)
| .node _ (.str k "antiquot") _ => (k, false)
| _ => none
def antiquotKinds (stx : Syntax) : List (SyntaxNodeKind × Bool) :=
if stx.isOfKind choiceKind then
stx.getArgs.filterMap antiquotKind? |>.toList
else
match antiquotKind? stx with
| some stx => [stx]
| none => []
-- An "antiquotation splice" is something like `$[...]?` or `$[...]*`.
def antiquotSpliceKind? : Syntax → Option SyntaxNodeKind
| .node _ (.str k "antiquot_scope") _ => some k
| _ => none
def isAntiquotSplice (stx : Syntax) : Bool :=
antiquotSpliceKind? stx |>.isSome
def getAntiquotSpliceContents (stx : Syntax) : Array Syntax :=
stx[3].getArgs
-- `$[..],*` or `$x,*` ~> `,*`
def getAntiquotSpliceSuffix (stx : Syntax) : Syntax :=
if stx.isAntiquotSplice then
stx[5]
else
stx[1]
def mkAntiquotSpliceNode (kind : SyntaxNodeKind) (contents : Array Syntax) (suffix : String) (nesting := 0) : Syntax :=
let nesting := mkNullNode (mkArray nesting (mkAtom "$"))
mkNode (kind ++ `antiquot_splice) #[mkAtom "$", nesting, mkAtom "[", mkNullNode contents, mkAtom "]", mkAtom suffix]
-- `$x,*` etc.
def antiquotSuffixSplice? : Syntax → Option SyntaxNodeKind
| .node _ (.str k "antiquot_suffix_splice") _ => some k
| _ => none
def isAntiquotSuffixSplice (stx : Syntax) : Bool :=
antiquotSuffixSplice? stx |>.isSome
-- `$x` in the example above
def getAntiquotSuffixSpliceInner (stx : Syntax) : Syntax :=
stx[0]
def mkAntiquotSuffixSpliceNode (kind : SyntaxNodeKind) (inner : Syntax) (suffix : String) : Syntax :=
mkNode (kind ++ `antiquot_suffix_splice) #[inner, mkAtom suffix]
def isTokenAntiquot (stx : Syntax) : Bool :=
stx.isOfKind `token_antiquot
def isAnyAntiquot (stx : Syntax) : Bool :=
stx.isAntiquot || stx.isAntiquotSplice || stx.isAntiquotSuffixSplice || stx.isTokenAntiquot
/-- List of `Syntax` nodes in which each succeeding element is the parent of
the current. The associated index is the index of the preceding element in the
list of children of the current element. -/
protected abbrev Stack := List (Syntax × Nat)
/-- Return stack of syntax nodes satisfying `visit`, starting with such a node that also fulfills `accept` (default "is leaf"), and ending with the root. -/
partial def findStack? (root : Syntax) (visit : Syntax → Bool) (accept : Syntax → Bool := fun stx => !stx.hasArgs) : Option Syntax.Stack :=
if visit root then go [] root else none
where
go (stack : Syntax.Stack) (stx : Syntax) : Option Syntax.Stack := Id.run do
if accept stx then
return (stx, 0) :: stack -- the first index is arbitrary as there is no preceding element
for i in [0:stx.getNumArgs] do
if visit stx[i] then
if let some stack := go ((stx, i) :: stack) stx[i] then
return stack
return none
/-- Compare the `SyntaxNodeKind`s in `pattern` to those of the `Syntax`
elements in `stack`. Return `false` if `stack` is shorter than `pattern`. -/
def Stack.matches (stack : Syntax.Stack) (pattern : List $ Option SyntaxNodeKind) : Bool :=
stack.length >= pattern.length &&
(stack
|>.zipWith (fun (s, _) p => p |>.map (s.isOfKind ·) |>.getD true) pattern
|>.all id)
end Syntax
end Lean
|
0b9846eed8eb60126a351bee91bcfec291706a42 | 3dd1b66af77106badae6edb1c4dea91a146ead30 | /tests/lean/run/coe3.lean | 7b8a7ab5562f46bb66d09cc3d93b4e3332066b89 | [
"Apache-2.0"
] | permissive | silky/lean | 79c20c15c93feef47bb659a2cc139b26f3614642 | df8b88dca2f8da1a422cb618cd476ef5be730546 | refs/heads/master | 1,610,737,587,697 | 1,406,574,534,000 | 1,406,574,534,000 | 22,362,176 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 770 | lean | import standard
namespace setoid
inductive setoid : Type :=
| mk_setoid: Π (A : Type), (A → A → Prop) → setoid
definition carrier (s : setoid)
:= setoid_rec (λ a eq, a) s
definition eqv {s : setoid} : carrier s → carrier s → Prop
:= setoid_rec (λ a eqv, eqv) s
infix `≈`:50 := eqv
coercion carrier
inductive morphism (s1 s2 : setoid) : Type :=
| mk_morphism : Π (f : s1 → s2), (∀ x y, x ≈ y → f x ≈ f y) → morphism s1 s2
set_option pp.universes true
check mk_morphism
check λ (s1 s2 : setoid), s1
check λ (s1 s2 : Type), s1
inductive morphism2 (s1 : setoid) (s2 : setoid) : Type :=
| mk_morphism2 : Π (f : s1 → s2), (∀ x y, x ≈ y → f x ≈ f y) → morphism2 s1 s2
check mk_morphism2
end |
5fa18dd9cfde7cd7cf9fabf2cff45a694e90fc71 | 5d76f062116fa5bd22eda20d6fd74da58dba65bb | /src/snarks/groth16/vars.lean | 8c9cf6c9b6af4c44516a37311080a44d377f7d2f | [] | no_license | brando90/formal_baby_snark | 59e4732dfb43f97776a3643f2731262f58d2bb81 | 4732da237784bd461ff949729cc011db83917907 | refs/heads/master | 1,682,650,246,414 | 1,621,103,975,000 | 1,621,103,975,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 227 | lean |
section
/-- An inductive type from which to index the variables of the 3-variable polynomials the proof manages -/
@[derive decidable_eq]
inductive vars : Type
| α : vars
| β : vars
| γ : vars
| δ : vars
| x : vars
end |
1b7515ba7b05926c1a12817865f36e4d14d50f4b | 4fa161becb8ce7378a709f5992a594764699e268 | /src/tactic/generalizes.lean | e9e88377df5c15984336fe238de421c1b9945a3e | [
"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 | 9,946 | lean | /-
Copyright (c) 2020 Jannis Limperg. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jannis Limperg
-/
import tactic.core
/-!
# The `generalizes` tactic
This module defines the `tactic.generalizes'` tactic and its interactive version
`tactic.interactive.generalizes`. These work like `generalize`, but they can
generalize over multiple expressions at once. This is particularly handy when
there are dependencies between the expressions, in which case `generalize` will
usually fail but `generalizes` may succeed.
## Implementation notes
To generalize the target `T` over expressions `a₁ : T₁, ..., aₙ : Tₙ`, we first
create the new target type
T' = ∀ (j₁ : T₁) (j₁_eq : j₁ == a₁) ..., T''
where `T''` is `T` with any occurrences of the `aᵢ` replaced by the
corresponding `jᵢ`. Creating this expression is a bit difficult because we must
be careful when there are dependencies between the `aᵢ`. Suppose that `a₁ : T₁`
and `a₂ : P a₁`. Then we want to end up with the target
T' = ∀ (j₁ : T₁) (j₁_eq : j₁ == a₁) (j₂ : P j₁) (j₂_eq : @heq (P j₁) j₂ (P a₁) a₂), ...
Note the type of the heterogeneous equation `j₂_eq`: When abstracting over `a₁`,
we want to replace `a₁` by `j₁` in the left-hand side to get the correct type
for `j₂`, but not in the right-hand side. This construction is performed by
`generalizes'_aux₁` and `generalizes'_aux₂`.
Having constructed `T'`, we can `assert` it and use it to construct a proof of
the original target by instantiating the binders with `a₁`, `heq.refl a₁`, `a₂`,
`heq.refl a₂` etc. This leaves us with a generalized goal.
-/
universes u v w
namespace tactic
open expr
/--
`generalizes'_aux₁ md unify e [] args` iterates through the `args` from left to
right. In each step of the iteration, any occurrences of the expression from
`args` in `e` is replaced by a new local constant. The local constant's pretty
name is the name given in `args`. The `args` must be given in reverse dependency
order: `[fin n, n]` is okay, but `[n, fin n]` won't work.
The result of `generalizes'_aux₁` is `e` with all the `args` replaced and the
list of new local constants, one for each element of `args`. Note that the local
constants are not added to the local context.
`md` and `unify` control how subterms of `e` are matched against the expressions
in `args`; see `kabstract`.
-/
private meta def generalizes'_aux₁ (md : transparency) (unify : bool)
: expr → list expr → list (name × expr) → tactic (expr × list expr)
| e cnsts [] := pure (e, cnsts.reverse)
| e cnsts ((n, x) :: xs) := do
x_type ← infer_type x,
c ← mk_local' n binder_info.default x_type,
e ← kreplace e x c md unify,
cnsts ← cnsts.mmap $ λ c', kreplace c' x c md unify,
generalizes'_aux₁ e (c :: cnsts) xs
/--
`generalizes'_aux₂ md []` takes as input the expression `e` produced by
`generalizes'_aux₁` and a list containing, for each argument to be generalized:
- A name for the generalisation equation. If this is `none`, no equation is
generated.
- The local constant produced by `generalizes'_aux₁`.
- The argument itself.
From this information, it generates a type of the form
∀ (j₁ : T₁) (j₁_eq : j₁ = a₁) (j₂ : T₂) (j₂_eq : j₂ == a₂), e
where the `aᵢ` are the arguments and the `jᵢ` correspond to the local constants.
It also returns, for each argument, whether an equation was generated for the
argument and if so, whether the equation is homogeneous (`tt`) or heterogeneous
(`ff`).
The transparency `md` is used when determining whether the types of an argument
and its associated constant are definitionally equal (and thus whether to
generate a homogeneous or a heterogeneous equation).
-/
private meta def generalizes'_aux₂ (md : transparency)
: list (option bool) → expr → list (option name × expr × expr)
→ tactic (expr × list (option bool))
| eq_kinds e [] := pure (e, eq_kinds.reverse)
| eq_kinds e ((eq_name, cnst, arg) :: cs) := do
cnst_type ← infer_type cnst,
arg_type ← infer_type arg,
sort u ← infer_type arg_type,
⟨eq_binder, eq_kind⟩ ← do {
match eq_name with
| none := pure ((id : expr → expr), none)
| some eq_name := do
homogeneous ← succeeds $ is_def_eq cnst_type arg_type,
let eq_type :=
if homogeneous
then ((const `eq [u]) cnst_type (var 0) arg)
else ((const `heq [u]) cnst_type (var 0) arg_type arg),
let eq_binder : expr → expr := λ e,
pi eq_name binder_info.default eq_type (e.lift_vars 0 1),
pure (eq_binder, some homogeneous )
end
},
let e :=
pi cnst.local_pp_name binder_info.default cnst_type $
eq_binder $
e.abstract cnst,
generalizes'_aux₂ (eq_kind :: eq_kinds) e cs
/--
Generalizes the target over each of the expressions in `args`. Given
`args = [(a₁, h₁, arg₁), ...]`, this changes the target to
∀ (a₁ : T₁) (h₁ : a₁ == arg₁) ..., U
where `U` is the current target with every occurrence of `argᵢ` replaced by
`aᵢ`. A similar effect can be achieved by using `generalize` once for each of
the `args`, but if there are dependencies between the `args`, this may fail to
perform some generalizations.
The replacement is performed using keyed matching/unification with transparency
`md`. `unify` determines whether matching or unification is used. See
`kabstract`.
The `args` must be given in dependency order, so `[n, fin n]` is okay but
`[fin n, n]` will result in an error.
After generalizing the `args`, the target type may no longer type check.
`generalizes'` will then raise an error.
-/
meta def generalizes' (args : list (name × option name × expr))
(md := semireducible) (unify := tt) : tactic unit :=
focus1 $ do
tgt ← target,
let args_rev := args.reverse,
(tgt, cnsts) ← generalizes'_aux₁ md unify tgt []
(args_rev.map (λ ⟨e_name, _, e⟩, (e_name, e))),
let args' :=
@list.map₂ (name × option name × expr) expr _
(λ ⟨_, eq_name, x⟩ cnst, (eq_name, cnst, x)) args_rev cnsts,
⟨tgt, eq_kinds⟩ ← generalizes'_aux₂ md [] tgt args',
let eq_kinds := eq_kinds.reverse,
type_check tgt <|> fail!
"generalizes: unable to generalize the target because the generalized target type does not type check:\n{tgt}",
n ← mk_fresh_name,
h ← assert n tgt,
swap,
let args' :=
@list.map₂ (name × option name × expr) (option bool) _
(λ ⟨_, _, x⟩ eq_kind, (x, eq_kind)) args eq_kinds,
apps ← args'.mmap $ λ ⟨x, eq_kind⟩, do {
match eq_kind with
| none := pure [x]
| some eq_is_homogeneous := do
x_type ← infer_type x,
sort u ← infer_type x_type,
let eq_proof :=
if eq_is_homogeneous
then (const `eq.refl [u]) x_type x
else (const `heq.refl [u]) x_type x,
pure [x, eq_proof]
end
},
exact $ h.mk_app apps.join
/--
Like `generalizes'`, but also introduces the generalized constants and their
associated equations into the context.
-/
meta def generalizes_intro (args : list (name × option name × expr))
(md := semireducible) (unify := tt) : tactic (list expr) := do
generalizes' args md unify,
let binder_nos := args.map (λ ⟨_, hyp, _⟩, 1 + if hyp.is_some then 1 else 0),
intron' binder_nos.sum
namespace interactive
open interactive
open lean.parser
private meta def generalizes_arg_parser_eq : pexpr → lean.parser (pexpr × name)
| (app (app (macro _ [const `eq _ ]) e) (local_const x _ _ _)) := pure (e, x)
| (app (app (macro _ [const `heq _ ]) e) (local_const x _ _ _)) := pure (e, x)
| _ := failure
private meta def generalizes_arg_parser : lean.parser (name × option name × pexpr) :=
with_desc "(id :)? expr = id" $ do
lhs ← lean.parser.pexpr 0,
(tk ":" >> match lhs with
| local_const hyp_name _ _ _ := do
(arg, arg_name) ← lean.parser.pexpr 0 >>= generalizes_arg_parser_eq,
pure (arg_name, some hyp_name, arg)
| _ := failure
end) <|>
(do
(arg, arg_name) ← generalizes_arg_parser_eq lhs,
pure (arg_name, none, arg))
private meta def generalizes_args_parser
: lean.parser (list (name × option name × pexpr)) :=
with_desc "[(id :)? expr = id, ...]" $
tk "[" *> sep_by (tk ",") generalizes_arg_parser <* tk "]"
/--
Generalizes the target over multiple expressions. For example, given the goal
P : ∀ n, fin n → Prop
n : ℕ
f : fin n
⊢ P (nat.succ n) (fin.succ f)
you can use `generalizes [n'_eq : nat.succ n = n', f'_eq : fin.succ f == f']` to
get
P : ∀ n, fin n → Prop
n : ℕ
f : fin n
n' : ℕ
n'_eq : n' = nat.succ n
f' : fin n'
f'_eq : f' == fin.succ f
⊢ P n' f'
The expressions must be given in dependency order, so
`[f'_eq : fin.succ f == f', n'_eq : nat.succ n = n']` would fail since the type
of `fin.succ f` is `nat.succ n`.
You can choose to omit some or all of the generated equations. For the above
example, `generalizes [(nat.succ n = n'), (fin.succ f == f')]` gets you
P : ∀ n, fin n → Prop
n : ℕ
f : fin n
n' : ℕ
f' : fin n'
⊢ P n' f'
Note the parentheses; these are necessary to avoid parsing issues.
After generalization, the target type may no longer type check. `generalizes`
will then raise an error.
-/
meta def generalizes (args : parse generalizes_args_parser) : tactic unit :=
propagate_tags $ do
args ← args.mmap $ λ ⟨arg_name, hyp_name, arg⟩, do {
arg ← to_expr arg,
pure (arg_name, hyp_name, arg)
},
generalizes_intro args,
pure ()
add_tactic_doc
{ name := "generalizes",
category := doc_category.tactic,
decl_names := [`tactic.interactive.generalizes],
tags := ["context management"],
inherit_description_from := `tactic.interactive.generalizes }
end interactive
end tactic
|
5337e3df6b61a5d28040a60b193d3c22665593b8 | 390c7d44c0470f935f1ff06637607521791400da | /test3.lean | 3ecd2516f106a0d85c9e912f69e295818c9b368f | [] | no_license | avigad/auto | 32baee2744dd3ae53f1cffd3f04523b953e5a9eb | 1aa4ebf60f900e8d61bb423105592a4010fa6ec5 | refs/heads/master | 1,594,791,920,875 | 1,475,608,824,000 | 1,475,608,824,000 | 67,415,120 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,791 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
Examples from the tutorial.
-/
import .auto
open tactic
section
variables p q r s : Prop
-- commutativity of ∧ and ∨
example : p ∧ q ↔ q ∧ p := by safe'
example : p ∨ q ↔ q ∨ p := by safe'
-- associativity of ∧ and ∨
example : (p ∧ q) ∧ r ↔ p ∧ (q ∧ r) := by safe'
example : (p ∨ q) ∨ r ↔ p ∨ (q ∨ r) := by safe'
-- distributivity
example : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) := by safe'
example : p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (p ∨ r) := by safe'
-- other properties
example : (p → (q → r)) ↔ (p ∧ q → r) := by safe'
example : ((p ∨ q) → r) ↔ (p → r) ∧ (q → r) := by safe'
example : ¬(p ∨ q) ↔ ¬p ∧ ¬q := by safe'
example : ¬p ∨ ¬q → ¬(p ∧ q) := by safe'
example : ¬(p ∧ ¬ p) := by safe'
example : p ∧ ¬q → ¬(p → q) := by safe'
example : ¬p → (p → q) := by safe'
example : (¬p ∨ q) → (p → q) := by safe'
example : p ∨ false ↔ p := by safe'
example : p ∧ false ↔ false := by safe'
example : ¬(p ↔ ¬p) := by safe'
example : (p → q) → (¬q → ¬p) := by safe'
-- these require classical reasoning
example : (p → r ∨ s) → ((p → r) ∨ (p → s)) := by safe'
example : ¬(p ∧ q) → ¬p ∨ ¬q := by safe'
example : ¬(p → q) → p ∧ ¬q := by safe'
example : (p → q) → (¬p ∨ q) := by safe'
example : (¬q → ¬p) → (p → q) := by safe'
example : p ∨ ¬p := by safe'
example : (((p → q) → p) → p) := by safe'
end
/- to get the ones that are sorried, we need to find an element in the environment
to instantiate a metavariable -/
section
variables (A : Type) (p q : A → Prop)
variable a : A
variable r : Prop
example : (∃ x : A, r) → r := by auto'
--example : r → (∃ x : A, r) := by auto'
example : (∃ x, p x ∧ r) ↔ (∃ x, p x) ∧ r := by auto'
example : (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) := by auto'
example (h : ∀ x, ¬ ¬ p x) : p a := by force'
example (h : ∀ x, ¬ ¬ p x) : ∀ x, p x := by auto'
example : (∀ x, p x) ↔ ¬ (∃ x, ¬ p x) := by auto'
example : (∃ x, p x) ↔ ¬ (∀ x, ¬ p x) := sorry
example : (¬ ∃ x, p x) ↔ (∀ x, ¬ p x) := by auto'
example : (¬ ∀ x, p x) ↔ (∃ x, ¬ p x) := sorry
example : (∃ x, ¬ p x) → (¬ ∀ x, p x) := by auto'
example : (∀ x, p x → r) ↔ (∃ x, p x) → r := by auto'
example : (∃ x, p x → r) ↔ (∀ x, p x) → r := sorry
example : (∃ x, r → p x) ↔ (r → ∃ x, p x) := sorry
example : (∃ x, p x → r) → (∀ x, p x) → r := by auto'
example : (∃ x, r → p x) → (r → ∃ x, p x) := by auto'
end
|
6ba5d0785c1cc9ee66c64d4ff146d279d860f0ba | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/group_theory/subgroup/finite.lean | a5ab6c826172fa318009b7071ad62349cb5bff65 | [
"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 | 8,815 | lean | /-
Copyright (c) 2020 Kexing Ying. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kexing Ying
-/
import data.set.finite
import group_theory.subgroup.basic
import group_theory.submonoid.membership
/-!
# Subgroups
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file provides some result on multiplicative and additive subgroups in the finite context.
## Tags
subgroup, subgroups
-/
open_locale big_operators
variables {G : Type*} [group G]
variables {A : Type*} [add_group A]
namespace subgroup
@[to_additive]
instance (K : subgroup G) [d : decidable_pred (∈ K)] [fintype G] : fintype K :=
show fintype {g : G // g ∈ K}, from infer_instance
@[to_additive]
instance (K : subgroup G) [finite G] : finite K :=
subtype.finite
end subgroup
/-!
### Conversion to/from `additive`/`multiplicative`
-/
namespace subgroup
variables (H K : subgroup G)
/-- Product of a list of elements in a subgroup is in the subgroup. -/
@[to_additive "Sum of a list of elements in an `add_subgroup` is in the `add_subgroup`."]
protected lemma list_prod_mem {l : list G} : (∀ x ∈ l, x ∈ K) → l.prod ∈ K :=
list_prod_mem
/-- Product of a multiset of elements in a subgroup of a `comm_group` is in the subgroup. -/
@[to_additive "Sum of a multiset of elements in an `add_subgroup` of an `add_comm_group`
is in the `add_subgroup`."]
protected lemma multiset_prod_mem {G} [comm_group G] (K : subgroup G) (g : multiset G) :
(∀ a ∈ g, a ∈ K) → g.prod ∈ K := multiset_prod_mem g
@[to_additive]
lemma multiset_noncomm_prod_mem (K : subgroup G) (g : multiset G) (comm) :
(∀ a ∈ g, a ∈ K) → g.noncomm_prod comm ∈ K :=
K.to_submonoid.multiset_noncomm_prod_mem g comm
/-- Product of elements of a subgroup of a `comm_group` indexed by a `finset` is in the
subgroup. -/
@[to_additive "Sum of elements in an `add_subgroup` of an `add_comm_group` indexed by a `finset`
is in the `add_subgroup`."]
protected lemma prod_mem {G : Type*} [comm_group G] (K : subgroup G)
{ι : Type*} {t : finset ι} {f : ι → G} (h : ∀ c ∈ t, f c ∈ K) :
∏ c in t, f c ∈ K :=
prod_mem h
@[to_additive]
lemma noncomm_prod_mem (K : subgroup G) {ι : Type*} {t : finset ι} {f : ι → G} (comm) :
(∀ c ∈ t, f c ∈ K) → t.noncomm_prod f comm ∈ K :=
K.to_submonoid.noncomm_prod_mem t f comm
@[simp, norm_cast, to_additive] theorem coe_list_prod (l : list H) :
(l.prod : G) = (l.map coe).prod :=
submonoid_class.coe_list_prod l
@[simp, norm_cast, to_additive] theorem coe_multiset_prod {G} [comm_group G] (H : subgroup G)
(m : multiset H) : (m.prod : G) = (m.map coe).prod :=
submonoid_class.coe_multiset_prod m
@[simp, norm_cast, to_additive] theorem coe_finset_prod {ι G} [comm_group G] (H : subgroup G)
(f : ι → H) (s : finset ι) :
↑(∏ i in s, f i) = (∏ i in s, f i : G) :=
submonoid_class.coe_finset_prod f s
@[to_additive] instance fintype_bot : fintype (⊥ : subgroup G) := ⟨{1},
by {rintro ⟨x, ⟨hx⟩⟩, exact finset.mem_singleton_self _}⟩
/- curly brackets `{}` are used here instead of instance brackets `[]` because
the instance in a goal is often not the same as the one inferred by type class inference. -/
@[simp, to_additive] lemma card_bot {_ : fintype ↥(⊥ : subgroup G)} :
fintype.card (⊥ : subgroup G) = 1 :=
fintype.card_eq_one_iff.2
⟨⟨(1 : G), set.mem_singleton 1⟩, λ ⟨y, hy⟩, subtype.eq $ subgroup.mem_bot.1 hy⟩
@[to_additive] lemma eq_top_of_card_eq [fintype H] [fintype G]
(h : fintype.card H = fintype.card G) : H = ⊤ :=
begin
haveI : fintype (H : set G) := ‹fintype H›,
rw [set_like.ext'_iff, coe_top, ← finset.coe_univ, ← (H : set G).coe_to_finset, finset.coe_inj,
← finset.card_eq_iff_eq_univ, ← h, set.to_finset_card],
congr
end
@[to_additive] lemma eq_top_of_le_card [fintype H] [fintype G]
(h : fintype.card G ≤ fintype.card H) : H = ⊤ :=
eq_top_of_card_eq H (le_antisymm (fintype.card_le_of_injective coe subtype.coe_injective) h)
@[to_additive] lemma eq_bot_of_card_le [fintype H] (h : fintype.card H ≤ 1) : H = ⊥ :=
let _ := fintype.card_le_one_iff_subsingleton.mp h in by exactI eq_bot_of_subsingleton H
@[to_additive] lemma eq_bot_of_card_eq [fintype H] (h : fintype.card H = 1) : H = ⊥ :=
H.eq_bot_of_card_le (le_of_eq h)
@[to_additive] lemma card_le_one_iff_eq_bot [fintype H] : fintype.card H ≤ 1 ↔ H = ⊥ :=
⟨λ h, (eq_bot_iff_forall _).2
(λ x hx, by simpa [subtype.ext_iff] using fintype.card_le_one_iff.1 h ⟨x, hx⟩ 1),
λ h, by simp [h]⟩
@[to_additive] lemma one_lt_card_iff_ne_bot [fintype H] : 1 < fintype.card H ↔ H ≠ ⊥ :=
lt_iff_not_le.trans H.card_le_one_iff_eq_bot.not
end subgroup
namespace subgroup
section pi
open set
variables {η : Type*} {f : η → Type*} [∀ i, group (f i)]
@[to_additive]
lemma pi_mem_of_mul_single_mem_aux [decidable_eq η] (I : finset η) {H : subgroup (Π i, f i) }
(x : Π i, f i) (h1 : ∀ i, i ∉ I → x i = 1) (h2 : ∀ i, i ∈ I → pi.mul_single i (x i) ∈ H ) :
x ∈ H :=
begin
induction I using finset.induction_on with i I hnmem ih generalizing x,
{ convert one_mem H,
ext i,
exact (h1 i (not_mem_empty i)) },
{ have : x = function.update x i 1 * pi.mul_single i (x i),
{ ext j,
by_cases heq : j = i,
{ subst heq, simp, },
{ simp [heq], }, },
rw this, clear this,
apply mul_mem,
{ apply ih; clear ih,
{ intros j hj,
by_cases heq : j = i,
{ subst heq, simp, },
{ simp [heq], apply h1 j, simpa [heq] using hj, } },
{ intros j hj,
have : j ≠ i, by { rintro rfl, contradiction },
simp [this],
exact h2 _ (finset.mem_insert_of_mem hj), }, },
{ apply h2, simp, } }
end
@[to_additive]
lemma pi_mem_of_mul_single_mem [finite η] [decidable_eq η] {H : subgroup (Π i, f i)}
(x : Π i, f i) (h : ∀ i, pi.mul_single i (x i) ∈ H) : x ∈ H :=
by { casesI nonempty_fintype η,
exact pi_mem_of_mul_single_mem_aux finset.univ x (by simp) (λ i _, h i) }
/-- For finite index types, the `subgroup.pi` is generated by the embeddings of the groups. -/
@[to_additive "For finite index types, the `subgroup.pi` is generated by the embeddings of the
additive groups."]
lemma pi_le_iff [decidable_eq η] [finite η] {H : Π i, subgroup (f i)} {J : subgroup (Π i, f i)} :
pi univ H ≤ J ↔ ∀ i : η, map (monoid_hom.single f i) (H i) ≤ J :=
begin
split,
{ rintros h i _ ⟨x, hx, rfl⟩, apply h, simpa using hx },
{ exact λ h x hx, pi_mem_of_mul_single_mem x (λ i, h i (mem_map_of_mem _ (hx i trivial))), }
end
end pi
end subgroup
namespace subgroup
section normalizer
lemma mem_normalizer_fintype {S : set G} [finite S] {x : G}
(h : ∀ n, n ∈ S → x * n * x⁻¹ ∈ S) : x ∈ subgroup.set_normalizer S :=
by haveI := classical.prop_decidable; casesI nonempty_fintype S;
haveI := set.fintype_image S (λ n, x * n * x⁻¹); exact
λ n, ⟨h n, λ h₁,
have heq : (λ n, x * n * x⁻¹) '' S = S := set.eq_of_subset_of_card_le
(λ n ⟨y, hy⟩, hy.2 ▸ h y hy.1) (by rw set.card_image_of_injective S conj_injective),
have x * n * x⁻¹ ∈ (λ n, x * n * x⁻¹) '' S := heq.symm ▸ h₁,
let ⟨y, hy⟩ := this in conj_injective hy.2 ▸ hy.1⟩
end normalizer
end subgroup
namespace monoid_hom
variables {N : Type*} [group N]
open subgroup
@[to_additive]
instance decidable_mem_range (f : G →* N) [fintype G] [decidable_eq N] :
decidable_pred (∈ f.range) :=
λ x, fintype.decidable_exists_fintype
-- this instance can't go just after the definition of `mrange` because `fintype` is
-- not imported at that stage
/-- The range of a finite monoid under a monoid homomorphism is finite.
Note: this instance can form a diamond with `subtype.fintype` in the
presence of `fintype N`. -/
@[to_additive "The range of a finite additive monoid under an additive monoid homomorphism is
finite.
Note: this instance can form a diamond with `subtype.fintype` or `subgroup.fintype` in the
presence of `fintype N`."]
instance fintype_mrange {M N : Type*} [monoid M] [monoid N] [fintype M] [decidable_eq N]
(f : M →* N) : fintype (mrange f) :=
set.fintype_range f
/-- The range of a finite group under a group homomorphism is finite.
Note: this instance can form a diamond with `subtype.fintype` or `subgroup.fintype` in the
presence of `fintype N`. -/
@[to_additive "The range of a finite additive group under an additive group homomorphism is finite.
Note: this instance can form a diamond with `subtype.fintype` or `subgroup.fintype` in the
presence of `fintype N`."]
instance fintype_range [fintype G] [decidable_eq N] (f : G →* N) : fintype (range f) :=
set.fintype_range f
end monoid_hom
|
2e904dfd9be7132fd7d68b041c4ae0274a4beb26 | 367134ba5a65885e863bdc4507601606690974c1 | /test/linarith.lean | f2f8d078d63ca3ac966bbac718d3c08c295a1124 | [
"Apache-2.0"
] | permissive | kodyvajjha/mathlib | 9bead00e90f68269a313f45f5561766cfd8d5cad | b98af5dd79e13a38d84438b850a2e8858ec21284 | refs/heads/master | 1,624,350,366,310 | 1,615,563,062,000 | 1,615,563,062,000 | 162,666,963 | 0 | 0 | Apache-2.0 | 1,545,367,651,000 | 1,545,367,651,000 | null | UTF-8 | Lean | false | false | 10,534 | lean | import tactic.linarith
import algebra.field_power
example {α : Type} (_inst : Π (a : Prop), decidable a)
[linear_ordered_field α]
{a b c : α}
(ha : a < 0)
(hb : ¬b = 0)
(hc' : c = 0)
(h : (1 - a) * (b * b) ≤ 0)
(hc : 0 ≤ 0)
(this : -(a * -b * -b + b * -b + 0) = (1 - a) * (b * b))
(h : (1 - a) * (b * b) ≤ 0) :
0 < 1 - a :=
begin
linarith
end
example (e b c a v0 v1 : ℚ) (h1 : v0 = 5*a) (h2 : v1 = 3*b) (h3 : v0 + v1 + c = 10) :
v0 + 5 + (v1 - 3) + (c - 2) = 10 :=
by linarith
example (u v r s t : ℚ) (h : 0 < u*(t*v + t*r + s)) : 0 < (t*(r + v) + s)*3*u :=
by linarith
example (A B : ℚ) (h : 0 < A * B) : 0 < 8*A*B :=
begin
linarith
end
example (A B : ℚ) (h : 0 < A * B) : 0 < A*8*B :=
begin
linarith
end
example (A B : ℚ) (h : 0 < A * B) : 0 < A*B/8 :=
begin
linarith
end
example (A B : ℚ) (h : 0 < A * B) : 0 < A/8*B :=
begin
linarith
end
example (ε : ℚ) (h1 : ε > 0) : ε / 2 + ε / 3 + ε / 7 < ε :=
by linarith
example (x y z : ℚ) (h1 : 2*x < 3*y) (h2 : -4*x + z/2 < 0)
(h3 : 12*y - z < 0) : false :=
by linarith
example (ε : ℚ) (h1 : ε > 0) : ε / 2 < ε :=
by linarith
example (ε : ℚ) (h1 : ε > 0) : ε / 3 + ε / 3 + ε / 3 = ε :=
by linarith
example (a b c : ℚ) (h2 : b + 2 > 3 + b) : false :=
by linarith {discharger := `[ring SOP]}
example (a b c : ℚ) (h2 : b + 2 > 3 + b) : false :=
by linarith
example (a b c : ℚ) (x y : ℤ) (h1 : x ≤ 3*y) (h2 : b + 2 > 3 + b) : false :=
by linarith {restrict_type := ℚ}
example (g v V c h : ℚ) (h1 : h = 0) (h2 : v = V) (h3 : V > 0) (h4 : g > 0)
(h5 : 0 ≤ c) (h6 : c < 1) :
v ≤ V :=
by linarith
constant nat.prime : ℕ → Prop
example (x y z : ℚ) (h1 : 2*x + ((-3)*y) < 0) (h2 : (-4)*x + 2*z < 0)
(h3 : 12*y + (-4)* z < 0) (h4 : nat.prime 7) : false :=
by linarith
example (x y z : ℚ) (h1 : 2*1*x + (3)*(y*(-1)) < 0) (h2 : (-2)*x*2 < -(z + z))
(h3 : 12*y + (-4)* z < 0) (h4 : nat.prime 7) : false :=
by linarith
example (x y z : ℤ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0)
(h3 : 12*y - 4* z < 0) : false :=
by linarith
example (x y z : ℤ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : x*y < 5)
(h3 : 12*y - 4* z < 0) : false :=
by linarith
example (x y z : ℤ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : x*y < 5) :
¬ 12*y - 4* z < 0 :=
by linarith
example (w x y z : ℤ) (h1 : 4*x + (-3)*y + 6*w ≤ 0) (h2 : (-1)*x < 0)
(h3 : y < 0) (h4 : w ≥ 0) (h5 : nat.prime x.nat_abs) : false :=
by linarith
example (a b c : ℚ) (h1 : a > 0) (h2 : b > 5) (h3 : c < -10)
(h4 : a + b - c < 3) : false :=
by linarith
example (a b c : ℚ) (h2 : b > 0) (h3 : ¬ b ≥ 0) : false :=
by linarith
example (a b c : ℚ) (h2 : (2 : ℚ) > 3) : a + b - c ≥ 3 :=
by linarith {exfalso := ff}
example (x : ℚ) (hx : x > 0) (h : x.num < 0) : false :=
by linarith [rat.num_pos_iff_pos.mpr hx, h]
example (x : ℚ) (hx : x > 0) (h : x.num < 0) : false :=
by linarith only [rat.num_pos_iff_pos.mpr hx, h]
example (x y z : ℚ) (hx : x ≤ 3*y) (h2 : y ≤ 2*z) (h3 : x ≥ 6*z) : x = 3*y :=
by linarith
example (x y z : ℕ) (hx : x ≤ 3*y) (h2 : y ≤ 2*z) (h3 : x ≥ 6*z) : x = 3*y :=
by linarith
example (x y z : ℚ) (hx : ¬ x > 3*y) (h2 : ¬ y > 2*z) (h3 : x ≥ 6*z) : x = 3*y :=
by linarith
example (h1 : (1 : ℕ) < 1) : false :=
by linarith
example (a b c : ℚ) (h2 : b > 0) (h3 : b < 0) : nat.prime 10 :=
by linarith
example (a b c : ℕ) : a + b ≥ a :=
by linarith
example (a b c : ℕ) : ¬ a + b < a :=
by linarith
example (x y : ℚ) (h : 6 + ((x + 4) * x + (6 + 3 * y) * y) = 3) (h' : (x + 4) * x ≥ 0)
(h'' : (6 + 3 * y) * y ≥ 0) : false :=
by linarith
example (x y : ℚ)
(h : 6 + ((x + 4) * x + (6 + 3 * y) * y) = 3 ∧ (x + 4) * x ≥ 0 ∧ (6 + 3 * y) * y ≥ 0) : false :=
by linarith
example (a b i : ℕ) (h1 : ¬ a < i) (h2 : b < i) (h3 : a ≤ b) : false :=
by linarith
example (n : ℕ) (h1 : n ≤ 3) (h2 : n > 2) : n = 3 := by linarith
example (z : ℕ) (hz : ¬ z ≥ 2) (h2 : ¬ z + 1 ≤ 2) : false :=
by linarith
example (z : ℕ) (hz : ¬ z ≥ 2) : z + 1 ≤ 2 :=
by linarith
example (a b c : ℚ) (h1 : 1 / a < b) (h2 : b < c) : 1 / a < c :=
by linarith
example
(N : ℕ) (n : ℕ) (Hirrelevant : n > N)
(A : ℚ) (l : ℚ) (h : A - l ≤ -(A - l)) (h_1 : ¬A ≤ -A) (h_2 : ¬l ≤ -l)
(h_3 : -(A - l) < 1) : A < l + 1 := by linarith
example (d : ℚ) (q n : ℕ) (h1 : ((q : ℚ) - 1)*n ≥ 0) (h2 : d = 2/3*(((q : ℚ) - 1)*n)) :
d ≤ ((q : ℚ) - 1)*n :=
by linarith
example (d : ℚ) (q n : ℕ) (h1 : ((q : ℚ) - 1)*n ≥ 0) (h2 : d = 2/3*(((q : ℚ) - 1)*n)) :
((q : ℚ) - 1)*n - d = 1/3 * (((q : ℚ) - 1)*n) :=
by linarith
example (a : ℚ) (ha : 0 ≤ a) : 0 * 0 ≤ 2 * a :=
by linarith
example (x : ℚ) : id x ≥ x :=
by success_if_fail {linarith}; linarith!
example (x y z : ℚ) (hx : x < 5) (hx2 : x > 5) (hy : y < 5000000000) (hz : z > 34*y) : false :=
by linarith only [hx, hx2]
example (x y z : ℚ) (hx : x < 5) (hy : y < 5000000000) (hz : z > 34*y) : x ≤ 5 :=
by linarith only [hx]
example (x y : ℚ) (h : x < y) : x ≠ y := by linarith
example (x y : ℚ) (h : x < y) : ¬ x = y := by linarith
example (u v x y A B : ℚ)
(a : 0 < A)
(a_1 : 0 <= 1 - A)
(a_2 : 0 <= B - 1)
(a_3 : 0 <= B - x)
(a_4 : 0 <= B - y)
(a_5 : 0 <= u)
(a_6 : 0 <= v)
(a_7 : 0 < A - u)
(a_8 : 0 < A - v) :
u * y + v * x + u * v < 3 * A * B :=
by nlinarith
example (u v x y A B : ℚ) : (0 < A) → (A ≤ 1) → (1 ≤ B)
→ (x ≤ B) → ( y ≤ B)
→ (0 ≤ u ) → (0 ≤ v )
→ (u < A) → ( v < A)
→ (u * y + v * x + u * v < 3 * A * B) :=
begin
intros,
nlinarith
end
example (u v x y A B : ℚ)
(a : 0 < A)
(a_1 : 0 <= 1 - A)
(a_2 : 0 <= B - 1)
(a_3 : 0 <= B - x)
(a_4 : 0 <= B - y)
(a_5 : 0 <= u)
(a_6 : 0 <= v)
(a_7 : 0 < A - u)
(a_8 : 0 < A - v) :
(0 < A * A)
-> (0 <= A * (1 - A))
-> (0 <= A * (B - 1))
-> (0 <= A * (B - x))
-> (0 <= A * (B - y))
-> (0 <= A * u)
-> (0 <= A * v)
-> (0 < A * (A - u))
-> (0 < A * (A - v))
-> (0 <= (1 - A) * A)
-> (0 <= (1 - A) * (1 - A))
-> (0 <= (1 - A) * (B - 1))
-> (0 <= (1 - A) * (B - x))
-> (0 <= (1 - A) * (B - y))
-> (0 <= (1 - A) * u)
-> (0 <= (1 - A) * v)
-> (0 <= (1 - A) * (A - u))
-> (0 <= (1 - A) * (A - v))
-> (0 <= (B - 1) * A)
-> (0 <= (B - 1) * (1 - A))
-> (0 <= (B - 1) * (B - 1))
-> (0 <= (B - 1) * (B - x))
-> (0 <= (B - 1) * (B - y))
-> (0 <= (B - 1) * u)
-> (0 <= (B - 1) * v)
-> (0 <= (B - 1) * (A - u))
-> (0 <= (B - 1) * (A - v))
-> (0 <= (B - x) * A)
-> (0 <= (B - x) * (1 - A))
-> (0 <= (B - x) * (B - 1))
-> (0 <= (B - x) * (B - x))
-> (0 <= (B - x) * (B - y))
-> (0 <= (B - x) * u)
-> (0 <= (B - x) * v)
-> (0 <= (B - x) * (A - u))
-> (0 <= (B - x) * (A - v))
-> (0 <= (B - y) * A)
-> (0 <= (B - y) * (1 - A))
-> (0 <= (B - y) * (B - 1))
-> (0 <= (B - y) * (B - x))
-> (0 <= (B - y) * (B - y))
-> (0 <= (B - y) * u)
-> (0 <= (B - y) * v)
-> (0 <= (B - y) * (A - u))
-> (0 <= (B - y) * (A - v))
-> (0 <= u * A)
-> (0 <= u * (1 - A))
-> (0 <= u * (B - 1))
-> (0 <= u * (B - x))
-> (0 <= u * (B - y))
-> (0 <= u * u)
-> (0 <= u * v)
-> (0 <= u * (A - u))
-> (0 <= u * (A - v))
-> (0 <= v * A)
-> (0 <= v * (1 - A))
-> (0 <= v * (B - 1))
-> (0 <= v * (B - x))
-> (0 <= v * (B - y))
-> (0 <= v * u)
-> (0 <= v * v)
-> (0 <= v * (A - u))
-> (0 <= v * (A - v))
-> (0 < (A - u) * A)
-> (0 <= (A - u) * (1 - A))
-> (0 <= (A - u) * (B - 1))
-> (0 <= (A - u) * (B - x))
-> (0 <= (A - u) * (B - y))
-> (0 <= (A - u) * u)
-> (0 <= (A - u) * v)
-> (0 < (A - u) * (A - u))
-> (0 < (A - u) * (A - v))
-> (0 < (A - v) * A)
-> (0 <= (A - v) * (1 - A))
-> (0 <= (A - v) * (B - 1))
-> (0 <= (A - v) * (B - x))
-> (0 <= (A - v) * (B - y))
-> (0 <= (A - v) * u)
-> (0 <= (A - v) * v)
-> (0 < (A - v) * (A - u))
-> (0 < (A - v) * (A - v))
->
u * y + v * x + u * v < 3 * A * B :=
begin
intros,
linarith
end
example (A B : ℚ) : (0 < A) → (1 ≤ B) → (0 < A / 8 * B) :=
begin
intros, nlinarith
end
example (x y : ℚ) : 0 ≤ x ^2 + y ^2 :=
by nlinarith
example (x y : ℚ) : 0 ≤ x*x + y*y :=
by nlinarith
example (x y : ℚ) : x = 0 → y = 0 → x*x + y*y = 0 :=
by intros; nlinarith
lemma norm_eq_zero_iff {x y : ℚ} : x * x + y * y = 0 ↔ x = 0 ∧ y = 0 :=
begin
split,
{ intro, split; nlinarith },
{ intro, nlinarith }
end
lemma norm_nonpos_right {x y : ℚ} (h1 : x * x + y * y ≤ 0) : y = 0 :=
by nlinarith
lemma norm_nonpos_left (x y : ℚ) (h1 : x * x + y * y ≤ 0) : x = 0 :=
by nlinarith
variables {E : Type*} [add_group E]
example (f : ℤ → E) (h : 0 = f 0) : 1 ≤ 2 := by nlinarith
example (a : E) (h : a = a) : 1 ≤ 2 := by nlinarith
-- test that the apply bug doesn't affect linarith preprocessing
constant α : Type
variable [fact false] -- we work in an inconsistent context below
def leα : α → α → Prop := λ a b, ∀ c : α, true
noncomputable instance : linear_ordered_field α :=
by refine_struct { le := leα }; exact false.elim _inst_2
example (a : α) (ha : a < 2) : a ≤ a :=
by linarith
example (p q r s t u v w : ℕ) (h1 : p + u = q + t) (h2 : r + w = s + v) :
p * r + q * s + (t * w + u * v) = p * s + q * r + (t * v + u * w) :=
by nlinarith
-- Tests involving a norm, including that squares in a type where `pow_two_nonneg` does not apply
-- do not cause an exception
variables {R : Type*} [ring R] (abs : R → ℚ)
lemma abs_nonneg' : ∀ r, 0 ≤ abs r := false.elim _inst_2
example (t : R) (a b : ℚ) (h : a ≤ b) : abs (t^2) * a ≤ abs (t^2) * b :=
by nlinarith [abs_nonneg' abs (t^2)]
example (t : R) (a b : ℚ) (h : a ≤ b) : a ≤ abs (t^2) + b :=
by linarith [abs_nonneg' abs (t^2)]
example (t : R) (a b : ℚ) (h : a ≤ b) : abs t * a ≤ abs t * b :=
by nlinarith [abs_nonneg' abs t]
constant T : Type
attribute [instance]
constant T_zero : ordered_ring T
namespace T
lemma zero_lt_one : (0 : T) < 1 := false.elim _inst_2
lemma works {a b : ℕ} (hab : a ≤ b) (h : b < a) : false :=
begin
linarith,
end
end T
example (a b c : ℚ) (h : a ≠ b) (h3 : b ≠ c) (h2 : a ≥ b) : b ≠ c :=
by linarith {split_ne := tt}
example (a b c : ℚ) (h : a ≠ b) (h2 : a ≥ b) (h3 : b ≠ c) : a > b :=
by linarith {split_ne := tt}
example (x y : ℚ) (h₁ : 0 ≤ y) (h₂ : y ≤ x) : y * x ≤ x * x := by nlinarith
example (x y : ℚ) (h₁ : 0 ≤ y) (h₂ : y ≤ x) : y * x ≤ x ^ 2 := by nlinarith
axiom foo {x : int} : 1 ≤ x → 1 ≤ x*x
lemma bar (x y: int)(h : 0 ≤ y ∧ 1 ≤ x) : 1 ≤ y + x*x := by linarith [foo h.2]
|
b3c9c89965eabf96082d0987de3c20a91e5b12fb | 302b541ac2e998a523ae04da7673fd0932ded126 | /tests/playground/listTest.lean | 50997966158db2ed8974125aaf7ac40958bfb689 | [] | no_license | mattweingarten/lambdapure | 4aeff69e8e3b8e78ea3c0a2b9b61770ef5a689b1 | f920a4ad78e6b1e3651f30bf8445c9105dfa03a8 | refs/heads/master | 1,680,665,168,790 | 1,618,420,180,000 | 1,618,420,180,000 | 310,816,264 | 2 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 254 | lean | set_option trace.compiler.ir.init true
inductive L
| Nil
| Cons : Nat -> L -> L
open L
def map : (Nat -> Nat) -> L -> L
| f , Nil => Nil
| f, Cons n l => Cons (f n) l
def makeList : Nat -> L
| n => Cons n (makeList n-1)
| 0 => Nil
|
248b4a40d9087854f5e2111e2b017f2cf320d41e | 206422fb9edabf63def0ed2aa3f489150fb09ccb | /src/measure_theory/lebesgue_measure.lean | b93316b152de8b7143e65a743701e387911bb322 | [
"Apache-2.0"
] | permissive | hamdysalah1/mathlib | b915f86b2503feeae268de369f1b16932321f097 | 95454452f6b3569bf967d35aab8d852b1ddf8017 | refs/heads/master | 1,677,154,116,545 | 1,611,797,994,000 | 1,611,797,994,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 16,762 | 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, Yury Kudryashov
-/
import measure_theory.pi
/-!
# Lebesgue measure on the real line and on `ℝⁿ`
-/
noncomputable theory
open classical set filter
open ennreal (of_real)
open_locale big_operators ennreal
namespace measure_theory
/-!
### Preliminary definitions
-/
/-- Length of an interval. This is the largest monotonic function which correctly
measures all intervals. -/
def lebesgue_length (s : set ℝ) : ennreal := ⨅a b (h : s ⊆ Ico a b), of_real (b - a)
@[simp] lemma lebesgue_length_empty : lebesgue_length ∅ = 0 :=
nonpos_iff_eq_zero.1 $ infi_le_of_le 0 $ infi_le_of_le 0 $ by simp
@[simp] lemma lebesgue_length_Ico (a b : ℝ) :
lebesgue_length (Ico a b) = of_real (b - a) :=
begin
refine le_antisymm (infi_le_of_le a $ binfi_le b (subset.refl _))
(le_infi $ λ a', le_infi $ λ b', le_infi $ λ h, ennreal.coe_le_coe.2 _),
cases le_or_lt b a with ab ab,
{ rw nnreal.of_real_of_nonpos (sub_nonpos.2 ab), apply zero_le },
cases (Ico_subset_Ico_iff ab).1 h with h₁ h₂,
exact nnreal.of_real_le_of_real (sub_le_sub h₂ h₁)
end
lemma lebesgue_length_mono {s₁ s₂ : set ℝ} (h : s₁ ⊆ s₂) :
lebesgue_length s₁ ≤ lebesgue_length s₂ :=
infi_le_infi $ λ a, infi_le_infi $ λ b, infi_le_infi2 $ λ h', ⟨subset.trans h h', le_refl _⟩
lemma lebesgue_length_eq_infi_Ioo (s) :
lebesgue_length s = ⨅a b (h : s ⊆ Ioo a b), of_real (b - a) :=
begin
refine le_antisymm
(infi_le_infi $ λ a, infi_le_infi $ λ b, infi_le_infi2 $ λ h,
⟨subset.trans h Ioo_subset_Ico_self, le_refl _⟩) _,
refine le_infi (λ a, le_infi $ λ b, le_infi $ λ h, _),
refine ennreal.le_of_forall_pos_le_add (λ ε ε0 _, _),
refine infi_le_of_le (a - ε) (infi_le_of_le b $ infi_le_of_le
(subset.trans h $ Ico_subset_Ioo_left $ (sub_lt_self_iff _).2 ε0) _),
rw ← sub_add,
refine le_trans ennreal.of_real_add_le (add_le_add_left _ _),
simp only [ennreal.of_real_coe_nnreal, le_refl]
end
@[simp] lemma lebesgue_length_Ioo (a b : ℝ) :
lebesgue_length (Ioo a b) = of_real (b - a) :=
begin
rw ← lebesgue_length_Ico,
refine le_antisymm (lebesgue_length_mono Ioo_subset_Ico_self) _,
rw lebesgue_length_eq_infi_Ioo (Ioo a b),
refine (le_infi $ λ a', le_infi $ λ b', le_infi $ λ h, _),
cases le_or_lt b a with ab ab, {simp [ab]},
cases (Ioo_subset_Ioo_iff ab).1 h with h₁ h₂,
rw [lebesgue_length_Ico],
exact ennreal.of_real_le_of_real (sub_le_sub h₂ h₁)
end
lemma lebesgue_length_eq_infi_Icc (s) :
lebesgue_length s = ⨅a b (h : s ⊆ Icc a b), of_real (b - a) :=
begin
refine le_antisymm _
(infi_le_infi $ λ a, infi_le_infi $ λ b, infi_le_infi2 $ λ h,
⟨subset.trans h Ico_subset_Icc_self, le_refl _⟩),
refine le_infi (λ a, le_infi $ λ b, le_infi $ λ h, _),
refine ennreal.le_of_forall_pos_le_add (λ ε ε0 _, _),
refine infi_le_of_le a (infi_le_of_le (b + ε) $ infi_le_of_le
(subset.trans h $ Icc_subset_Ico_right $ (lt_add_iff_pos_right _).2 ε0) _),
rw [← sub_add_eq_add_sub],
refine le_trans ennreal.of_real_add_le (add_le_add_left _ _),
simp only [ennreal.of_real_coe_nnreal, le_refl]
end
@[simp] lemma lebesgue_length_Icc (a b : ℝ) :
lebesgue_length (Icc a b) = of_real (b - a) :=
begin
rw ← lebesgue_length_Ico,
refine le_antisymm _ (lebesgue_length_mono Ico_subset_Icc_self),
rw lebesgue_length_eq_infi_Icc (Icc a b),
exact infi_le_of_le a (infi_le_of_le b $ infi_le_of_le (by refl) (by simp [le_refl]))
end
/-- The Lebesgue outer measure, as an outer measure of ℝ. -/
def lebesgue_outer : outer_measure ℝ :=
outer_measure.of_function lebesgue_length lebesgue_length_empty
lemma lebesgue_outer_le_length (s : set ℝ) : lebesgue_outer s ≤ lebesgue_length s :=
outer_measure.of_function_le _
lemma lebesgue_length_subadditive {a b : ℝ} {c d : ℕ → ℝ}
(ss : Icc a b ⊆ ⋃i, Ioo (c i) (d i)) :
(of_real (b - a) : ennreal) ≤ ∑' i, of_real (d i - c i) :=
begin
suffices : ∀ (s:finset ℕ) b
(cv : Icc a b ⊆ ⋃ i ∈ (↑s:set ℕ), Ioo (c i) (d i)),
(of_real (b - a) : ennreal) ≤ ∑ i in s, of_real (d i - c i),
{ rcases compact_Icc.elim_finite_subcover_image (λ (i : ℕ) (_ : i ∈ univ),
@is_open_Ioo _ _ _ _ (c i) (d i)) (by simpa using ss) with ⟨s, su, hf, hs⟩,
have e : (⋃ i ∈ (↑hf.to_finset:set ℕ),
Ioo (c i) (d i)) = (⋃ i ∈ s, Ioo (c i) (d i)), {simp [set.ext_iff]},
rw ennreal.tsum_eq_supr_sum,
refine le_trans _ (le_supr _ hf.to_finset),
exact this hf.to_finset _ (by simpa [e]) },
clear ss b,
refine λ s, finset.strong_induction_on s (λ s IH b cv, _),
cases le_total b a with ab ab,
{ rw ennreal.of_real_eq_zero.2 (sub_nonpos.2 ab), exact zero_le _ },
have := cv ⟨ab, le_refl _⟩, simp at this,
rcases this with ⟨i, is, cb, bd⟩,
rw [← finset.insert_erase is] at cv ⊢,
rw [finset.coe_insert, bUnion_insert] at cv,
rw [finset.sum_insert (finset.not_mem_erase _ _)],
refine le_trans _ (add_le_add_left (IH _ (finset.erase_ssubset is) (c i) _) _),
{ refine le_trans (ennreal.of_real_le_of_real _) ennreal.of_real_add_le,
rw sub_add_sub_cancel,
exact sub_le_sub_right (le_of_lt bd) _ },
{ rintro x ⟨h₁, h₂⟩,
refine (cv ⟨h₁, le_trans h₂ (le_of_lt cb)⟩).resolve_left
(mt and.left (not_lt_of_le h₂)) }
end
@[simp] lemma lebesgue_outer_Icc (a b : ℝ) :
lebesgue_outer (Icc a b) = of_real (b - a) :=
begin
refine le_antisymm (by rw ← lebesgue_length_Icc; apply lebesgue_outer_le_length)
(le_binfi $ λ f hf, ennreal.le_of_forall_pos_le_add $ λ ε ε0 h, _),
rcases ennreal.exists_pos_sum_of_encodable
(ennreal.zero_lt_coe_iff.2 ε0) ℕ with ⟨ε', ε'0, hε⟩,
refine le_trans _ (add_le_add_left (le_of_lt hε) _),
rw ← ennreal.tsum_add,
choose g hg using show
∀ i, ∃ p:ℝ×ℝ, f i ⊆ Ioo p.1 p.2 ∧ (of_real (p.2 - p.1) : ennreal) <
lebesgue_length (f i) + ε' i,
{ intro i,
have := (ennreal.lt_add_right (lt_of_le_of_lt (ennreal.le_tsum i) h)
(ennreal.zero_lt_coe_iff.2 (ε'0 i))),
conv at this {to_lhs, rw lebesgue_length_eq_infi_Ioo},
simpa [infi_lt_iff] },
refine le_trans _ (ennreal.tsum_le_tsum $ λ i, le_of_lt (hg i).2),
exact lebesgue_length_subadditive (subset.trans hf $
Union_subset_Union $ λ i, (hg i).1)
end
@[simp] lemma lebesgue_outer_singleton (a : ℝ) : lebesgue_outer {a} = 0 :=
by simpa using lebesgue_outer_Icc a a
@[simp] lemma lebesgue_outer_Ico (a b : ℝ) :
lebesgue_outer (Ico a b) = of_real (b - a) :=
by rw [← Icc_diff_right, lebesgue_outer.diff_null _ (lebesgue_outer_singleton _),
lebesgue_outer_Icc]
@[simp] lemma lebesgue_outer_Ioo (a b : ℝ) :
lebesgue_outer (Ioo a b) = of_real (b - a) :=
by rw [← Ico_diff_left, lebesgue_outer.diff_null _ (lebesgue_outer_singleton _), lebesgue_outer_Ico]
@[simp] lemma lebesgue_outer_Ioc (a b : ℝ) :
lebesgue_outer (Ioc a b) = of_real (b - a) :=
by rw [← Icc_diff_left, lebesgue_outer.diff_null _ (lebesgue_outer_singleton _), lebesgue_outer_Icc]
lemma is_lebesgue_measurable_Iio {c : ℝ} :
lebesgue_outer.caratheodory.is_measurable' (Iio c) :=
outer_measure.of_function_caratheodory $ λ t,
le_infi $ λ a, le_infi $ λ b, le_infi $ λ h, begin
refine le_trans (add_le_add
(lebesgue_length_mono $ inter_subset_inter_left _ h)
(lebesgue_length_mono $ diff_subset_diff_left h)) _,
cases le_total a c with hac hca; cases le_total b c with hbc hcb;
simp [*, -sub_eq_add_neg, sub_add_sub_cancel', le_refl],
{ simp [*, ← ennreal.of_real_add, -sub_eq_add_neg, sub_add_sub_cancel', le_refl] },
{ simp only [ennreal.of_real_eq_zero.2 (sub_nonpos.2 (le_trans hbc hca)), zero_add, le_refl] }
end
theorem lebesgue_outer_trim : lebesgue_outer.trim = lebesgue_outer :=
begin
refine le_antisymm (λ s, _) (outer_measure.le_trim _),
rw outer_measure.trim_eq_infi,
refine le_infi (λ f, le_infi $ λ hf,
ennreal.le_of_forall_pos_le_add $ λ ε ε0 h, _),
rcases ennreal.exists_pos_sum_of_encodable
(ennreal.zero_lt_coe_iff.2 ε0) ℕ with ⟨ε', ε'0, hε⟩,
refine le_trans _ (add_le_add_left (le_of_lt hε) _),
rw ← ennreal.tsum_add,
choose g hg using show
∀ i, ∃ s, f i ⊆ s ∧ is_measurable s ∧ lebesgue_outer s ≤ lebesgue_length (f i) + of_real (ε' i),
{ intro i,
have := (ennreal.lt_add_right (lt_of_le_of_lt (ennreal.le_tsum i) h)
(ennreal.zero_lt_coe_iff.2 (ε'0 i))),
conv at this {to_lhs, rw lebesgue_length},
simp only [infi_lt_iff] at this,
rcases this with ⟨a, b, h₁, h₂⟩,
rw ← lebesgue_outer_Ico at h₂,
exact ⟨_, h₁, is_measurable_Ico, le_of_lt $ by simpa using h₂⟩ },
simp at hg,
apply infi_le_of_le (Union g) _,
apply infi_le_of_le (subset.trans hf $ Union_subset_Union (λ i, (hg i).1)) _,
apply infi_le_of_le (is_measurable.Union (λ i, (hg i).2.1)) _,
exact le_trans (lebesgue_outer.Union _) (ennreal.tsum_le_tsum $ λ i, (hg i).2.2)
end
lemma borel_le_lebesgue_measurable : borel ℝ ≤ lebesgue_outer.caratheodory :=
begin
rw real.borel_eq_generate_from_Iio_rat,
refine measurable_space.generate_from_le _,
simp [is_lebesgue_measurable_Iio] { contextual := tt }
end
/-!
### Definition of the Lebesgue measure and lengths of intervals
-/
/-- Lebesgue measure on the Borel sets
The outer Lebesgue measure is the completion of this measure. (TODO: proof this)
-/
instance real.measure_space : measure_space ℝ :=
⟨{to_outer_measure := lebesgue_outer,
m_Union := λ f hf, lebesgue_outer.Union_eq_of_caratheodory $
λ i, borel_le_lebesgue_measurable _ (hf i),
trimmed := lebesgue_outer_trim }⟩
@[simp] theorem lebesgue_to_outer_measure :
(volume : measure ℝ).to_outer_measure = lebesgue_outer := rfl
end measure_theory
open measure_theory
namespace real
variables {ι : Type*} [fintype ι]
open_locale topological_space
theorem volume_val (s) : volume s = lebesgue_outer s := rfl
instance has_no_atoms_volume : has_no_atoms (volume : measure ℝ) :=
⟨lebesgue_outer_singleton⟩
@[simp] lemma volume_Ico {a b : ℝ} : volume (Ico a b) = of_real (b - a) := lebesgue_outer_Ico a b
@[simp] lemma volume_Icc {a b : ℝ} : volume (Icc a b) = of_real (b - a) := lebesgue_outer_Icc a b
@[simp] lemma volume_Ioo {a b : ℝ} : volume (Ioo a b) = of_real (b - a) := lebesgue_outer_Ioo a b
@[simp] lemma volume_Ioc {a b : ℝ} : volume (Ioc a b) = of_real (b - a) := lebesgue_outer_Ioc a b
@[simp] lemma volume_singleton {a : ℝ} : volume ({a} : set ℝ) = 0 := lebesgue_outer_singleton a
@[simp] lemma volume_interval {a b : ℝ} : volume (interval a b) = of_real (abs (b - a)) :=
by rw [interval, volume_Icc, max_sub_min_eq_abs]
@[simp] lemma volume_Ioi {a : ℝ} : volume (Ioi a) = ∞ :=
top_unique $ le_of_tendsto' ennreal.tendsto_nat_nhds_top $ λ n,
calc (n : ennreal) = volume (Ioo a (a + n)) : by simp
... ≤ volume (Ioi a) : measure_mono Ioo_subset_Ioi_self
@[simp] lemma volume_Ici {a : ℝ} : volume (Ici a) = ∞ :=
by simp [← measure_congr Ioi_ae_eq_Ici]
@[simp] lemma volume_Iio {a : ℝ} : volume (Iio a) = ∞ :=
top_unique $ le_of_tendsto' ennreal.tendsto_nat_nhds_top $ λ n,
calc (n : ennreal) = volume (Ioo (a - n) a) : by simp
... ≤ volume (Iio a) : measure_mono Ioo_subset_Iio_self
@[simp] lemma volume_Iic {a : ℝ} : volume (Iic a) = ∞ :=
by simp [← measure_congr Iio_ae_eq_Iic]
instance locally_finite_volume : locally_finite_measure (volume : measure ℝ) :=
⟨λ x, ⟨Ioo (x - 1) (x + 1),
mem_nhds_sets is_open_Ioo ⟨sub_lt_self _ zero_lt_one, lt_add_of_pos_right _ zero_lt_one⟩,
by simp only [real.volume_Ioo, ennreal.of_real_lt_top]⟩⟩
/-!
### Volume of a box in `ℝⁿ`
-/
lemma volume_Icc_pi {a b : ι → ℝ} : volume (Icc a b) = ∏ i, ennreal.of_real (b i - a i) :=
begin
rw [← pi_univ_Icc, volume_pi_pi],
{ simp only [real.volume_Icc] },
{ exact λ i, is_measurable_Icc }
end
@[simp] lemma volume_Icc_pi_to_real {a b : ι → ℝ} (h : a ≤ b) :
(volume (Icc a b)).to_real = ∏ i, (b i - a i) :=
by simp only [volume_Icc_pi, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))]
lemma volume_pi_Ioo {a b : ι → ℝ} :
volume (pi univ (λ i, Ioo (a i) (b i))) = ∏ i, ennreal.of_real (b i - a i) :=
(measure_congr measure.univ_pi_Ioo_ae_eq_Icc).trans volume_Icc_pi
@[simp] lemma volume_pi_Ioo_to_real {a b : ι → ℝ} (h : a ≤ b) :
(volume (pi univ (λ i, Ioo (a i) (b i)))).to_real = ∏ i, (b i - a i) :=
by simp only [volume_pi_Ioo, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))]
lemma volume_pi_Ioc {a b : ι → ℝ} :
volume (pi univ (λ i, Ioc (a i) (b i))) = ∏ i, ennreal.of_real (b i - a i) :=
(measure_congr measure.univ_pi_Ioc_ae_eq_Icc).trans volume_Icc_pi
@[simp] lemma volume_pi_Ioc_to_real {a b : ι → ℝ} (h : a ≤ b) :
(volume (pi univ (λ i, Ioc (a i) (b i)))).to_real = ∏ i, (b i - a i) :=
by simp only [volume_pi_Ioc, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))]
lemma volume_pi_Ico {a b : ι → ℝ} :
volume (pi univ (λ i, Ico (a i) (b i))) = ∏ i, ennreal.of_real (b i - a i) :=
(measure_congr measure.univ_pi_Ico_ae_eq_Icc).trans volume_Icc_pi
@[simp] lemma volume_pi_Ico_to_real {a b : ι → ℝ} (h : a ≤ b) :
(volume (pi univ (λ i, Ico (a i) (b i)))).to_real = ∏ i, (b i - a i) :=
by simp only [volume_pi_Ico, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))]
/-!
### Images of the Lebesgue measure under translation/multiplication/...
-/
lemma map_volume_add_left (a : ℝ) : measure.map ((+) a) volume = volume :=
eq.symm $ real.measure_ext_Ioo_rat $ λ p q,
by simp [measure.map_apply (measurable_add_left a) is_measurable_Ioo, sub_sub_sub_cancel_right]
lemma map_volume_add_right (a : ℝ) : measure.map (+ a) volume = volume :=
by simpa only [add_comm] using real.map_volume_add_left a
lemma smul_map_volume_mul_left {a : ℝ} (h : a ≠ 0) :
ennreal.of_real (abs a) • measure.map ((*) a) volume = volume :=
begin
refine (real.measure_ext_Ioo_rat $ λ p q, _).symm,
cases lt_or_gt_of_ne h with h h,
{ simp only [real.volume_Ioo, measure.smul_apply, ← ennreal.of_real_mul (le_of_lt $ neg_pos.2 h),
measure.map_apply (measurable_mul_left a) is_measurable_Ioo, neg_sub_neg,
← neg_mul_eq_neg_mul, preimage_const_mul_Ioo_of_neg _ _ h, abs_of_neg h, mul_sub,
mul_div_cancel' _ (ne_of_lt h)] },
{ simp only [real.volume_Ioo, measure.smul_apply, ← ennreal.of_real_mul (le_of_lt h),
measure.map_apply (measurable_mul_left a) is_measurable_Ioo, preimage_const_mul_Ioo _ _ h,
abs_of_pos h, mul_sub, mul_div_cancel' _ (ne_of_gt h)] }
end
lemma map_volume_mul_left {a : ℝ} (h : a ≠ 0) :
measure.map ((*) a) volume = ennreal.of_real (abs a⁻¹) • volume :=
by conv_rhs { rw [← real.smul_map_volume_mul_left h, smul_smul,
← ennreal.of_real_mul (abs_nonneg _), ← abs_mul, inv_mul_cancel h, abs_one, ennreal.of_real_one,
one_smul] }
lemma smul_map_volume_mul_right {a : ℝ} (h : a ≠ 0) :
ennreal.of_real (abs a) • measure.map (* a) volume = volume :=
by simpa only [mul_comm] using real.smul_map_volume_mul_left h
lemma map_volume_mul_right {a : ℝ} (h : a ≠ 0) :
measure.map (* a) volume = ennreal.of_real (abs a⁻¹) • volume :=
by simpa only [mul_comm] using real.map_volume_mul_left h
@[simp] lemma map_volume_neg : measure.map has_neg.neg (volume : measure ℝ) = volume :=
eq.symm $ real.measure_ext_Ioo_rat $ λ p q,
by simp [measure.map_apply measurable_neg is_measurable_Ioo]
end real
open_locale topological_space
lemma filter.eventually.volume_pos_of_nhds_real {p : ℝ → Prop} {a : ℝ} (h : ∀ᶠ x in 𝓝 a, p x) :
(0 : ennreal) < volume {x | p x} :=
begin
rcases h.exists_Ioo_subset with ⟨l, u, hx, hs⟩,
refine lt_of_lt_of_le _ (measure_mono hs),
simpa [-mem_Ioo] using hx.1.trans hx.2
end
/-
section vitali
def vitali_aux_h (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) :
∃ y ∈ Icc (0:ℝ) 1, ∃ q:ℚ, ↑q = x - y :=
⟨x, h, 0, by simp⟩
def vitali_aux (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) : ℝ :=
classical.some (vitali_aux_h x h)
theorem vitali_aux_mem (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) : vitali_aux x h ∈ Icc (0:ℝ) 1 :=
Exists.fst (classical.some_spec (vitali_aux_h x h):_)
theorem vitali_aux_rel (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) :
∃ q:ℚ, ↑q = x - vitali_aux x h :=
Exists.snd (classical.some_spec (vitali_aux_h x h):_)
def vitali : set ℝ := {x | ∃ h, x = vitali_aux x h}
theorem vitali_nonmeasurable : ¬ is_null_measurable measure_space.μ vitali :=
sorry
end vitali
-/
|
4c13c13e2cacb33df3b0666835f1c2f6c0404a92 | 54deab7025df5d2df4573383df7e1e5497b7a2c2 | /order/complete_lattice.lean | 0f44ea3a86083808b82f54eebd13c531b1ec7334 | [
"Apache-2.0"
] | permissive | HGldJ1966/mathlib | f8daac93a5b4ae805cfb0ecebac21a9ce9469009 | c5c5b504b918a6c5e91e372ee29ed754b0513e85 | refs/heads/master | 1,611,340,395,683 | 1,503,040,489,000 | 1,503,040,489,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 24,057 | 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 lattices.
-/
import order.bounded_lattice data.set.basic
set_option old_structure_cmd true
universes u v w w₂
variables {α : Type u} {β : Type v} {ι : Sort w} {ι₂ : Sort w₂}
namespace lattice
class has_Sup (α : Type u) := (Sup : set α → α)
class has_Inf (α : Type u) := (Inf : set α → α)
def Sup [has_Sup α] : set α → α := has_Sup.Sup
def Inf [has_Inf α] : set α → α := has_Inf.Inf
class complete_lattice (α : Type u) extends bounded_lattice α, has_Sup α, has_Inf α :=
(le_Sup : ∀s, ∀a∈s, a ≤ Sup s)
(Sup_le : ∀s a, (∀b∈s, b ≤ a) → Sup s ≤ a)
(Inf_le : ∀s, ∀a∈s, Inf s ≤ a)
(le_Inf : ∀s a, (∀b∈s, a ≤ b) → a ≤ Inf s)
def supr [complete_lattice α] (s : ι → α) : α := Sup {a : α | ∃i : ι, a = s i}
def infi [complete_lattice α] (s : ι → α) : α := Inf {a : α | ∃i : ι, a = s i}
notation `⨆` binders `, ` r:(scoped f, supr f) := r
notation `⨅` binders `, ` r:(scoped f, infi f) := r
section
open set
variables [complete_lattice α] {s t : set α} {a b : α}
@[ematch] theorem le_Sup : a ∈ s → a ≤ Sup s := complete_lattice.le_Sup s a
theorem Sup_le : (∀b∈s, b ≤ a) → Sup s ≤ a := complete_lattice.Sup_le s a
@[ematch] theorem Inf_le : a ∈ s → Inf s ≤ a := complete_lattice.Inf_le s a
theorem le_Inf : (∀b∈s, a ≤ b) → a ≤ Inf s := complete_lattice.le_Inf s a
theorem le_Sup_of_le (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s :=
le_trans h (le_Sup hb)
theorem Inf_le_of_le (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a :=
le_trans (Inf_le hb) h
theorem Sup_le_Sup (h : s ⊆ t) : Sup s ≤ Sup t :=
Sup_le (assume a, assume ha : a ∈ s, le_Sup $ h ha)
theorem Inf_le_Inf (h : s ⊆ t) : Inf t ≤ Inf s :=
le_Inf (assume a, assume ha : a ∈ s, Inf_le $ h ha)
@[simp] theorem Sup_le_iff : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) :=
⟨assume : Sup s ≤ a, assume b, assume : b ∈ s,
le_trans (le_Sup ‹b ∈ s›) ‹Sup s ≤ a›,
Sup_le⟩
@[simp] theorem le_Inf_iff : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) :=
⟨assume : a ≤ Inf s, assume b, assume : b ∈ s,
le_trans ‹a ≤ Inf s› (Inf_le ‹b ∈ s›),
le_Inf⟩
-- how to state this? instead a parameter `a`, use `∃a, a ∈ s` or `s ≠ ∅`?
theorem Inf_le_Sup (h : a ∈ s) : Inf s ≤ Sup s :=
by have := le_Sup h; finish
--Inf_le_of_le h (le_Sup h)
-- TODO: it is weird that we have to add union_def
theorem Sup_union {s t : set α} : Sup (s ∪ t) = Sup s ⊔ Sup t :=
le_antisymm
(by finish)
(sup_le (Sup_le_Sup $ subset_union_left _ _) (Sup_le_Sup $ subset_union_right _ _))
/- old proof:
le_antisymm
(Sup_le $ assume a h, or.rec_on h (le_sup_left_of_le ∘ le_Sup) (le_sup_right_of_le ∘ le_Sup))
(sup_le (Sup_le_Sup $ subset_union_left _ _) (Sup_le_Sup $ subset_union_right _ _))
-/
theorem Sup_inter_le {s t : set α} : Sup (s ∩ t) ≤ Sup s ⊓ Sup t :=
by finish
/-
Sup_le (assume a ⟨a_s, a_t⟩, le_inf (le_Sup a_s) (le_Sup a_t))
-/
theorem Inf_union {s t : set α} : Inf (s ∪ t) = Inf s ⊓ Inf t :=
le_antisymm
(le_inf (Inf_le_Inf $ subset_union_left _ _) (Inf_le_Inf $ subset_union_right _ _))
(by finish)
/- old proof:
le_antisymm
(le_inf (Inf_le_Inf $ subset_union_left _ _) (Inf_le_Inf $ subset_union_right _ _))
(le_Inf $ assume a h, or.rec_on h (inf_le_left_of_le ∘ Inf_le) (inf_le_right_of_le ∘ Inf_le))
-/
theorem le_Inf_inter {s t : set α} : Inf s ⊔ Inf t ≤ Inf (s ∩ t) :=
by finish
/-
le_Inf (assume a ⟨a_s, a_t⟩, sup_le (Inf_le a_s) (Inf_le a_t))
-/
@[simp] theorem Sup_empty : Sup ∅ = (⊥ : α) :=
le_antisymm (by finish) (by finish)
-- le_antisymm (Sup_le (assume _, false.elim)) bot_le
@[simp] theorem Inf_empty : Inf ∅ = (⊤ : α) :=
le_antisymm (by finish) (by finish)
--le_antisymm le_top (le_Inf (assume _, false.elim))
@[simp] theorem Sup_univ : Sup univ = (⊤ : α) :=
le_antisymm (by finish) (le_Sup ⟨⟩) -- finish fails because ⊤ ≤ a simplifies to a = ⊤
--le_antisymm le_top (le_Sup ⟨⟩)
@[simp] theorem Inf_univ : Inf univ = (⊥ : α) :=
le_antisymm (Inf_le ⟨⟩) bot_le
-- TODO(Jeremy): get this automatically
@[simp] theorem Sup_insert {a : α} {s : set α} : Sup (insert a s) = a ⊔ Sup s :=
have Sup {b | b = a} = a,
from le_antisymm (Sup_le $ assume b b_eq, b_eq ▸ le_refl _) (le_Sup rfl),
calc Sup (insert a s) = Sup {b | b = a} ⊔ Sup s : Sup_union
... = a ⊔ Sup s : by rw [this]
@[simp] theorem Inf_insert {a : α} {s : set α} : Inf (insert a s) = a ⊓ Inf s :=
have Inf {b | b = a} = a,
from le_antisymm (Inf_le rfl) (le_Inf $ assume b b_eq, b_eq ▸ le_refl _),
calc Inf (insert a s) = Inf {b | b = a} ⊓ Inf s : Inf_union
... = a ⊓ Inf s : by rw [this]
@[simp] theorem Sup_singleton {a : α} : Sup {a} = a :=
by finish [singleton_def]
--eq.trans Sup_insert $ by simp
@[simp] theorem Inf_singleton {a : α} : Inf {a} = a :=
by finish [singleton_def]
--eq.trans Inf_insert $ by simp
end
/- supr & infi -/
section
open set
variables [complete_lattice α] {s t : ι → α} {a b : α}
-- TODO: this declaration gives error when starting smt state
--@[ematch]
theorem le_supr (s : ι → α) (i : ι) : s i ≤ supr s :=
le_Sup ⟨i, rfl⟩
@[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i ≤ supr s :) :=
le_Sup ⟨i, rfl⟩
/- TODO: this version would be more powerful, but, alas, the pattern matcher
doesn't accept it.
@[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i :) ≤ (: supr s :) :=
le_Sup ⟨i, rfl⟩
-/
theorem le_supr_of_le (i : ι) (h : a ≤ s i) : a ≤ supr s :=
le_trans h (le_supr _ i)
theorem supr_le (h : ∀i, s i ≤ a) : supr s ≤ a :=
Sup_le $ assume b ⟨i, eq⟩, eq.symm ▸ h i
theorem supr_le_supr (h : ∀i, s i ≤ t i) : supr s ≤ supr t :=
supr_le $ assume i, le_supr_of_le i (h i)
theorem supr_le_supr2 {t : ι₂ → α} (h : ∀i, ∃j, s i ≤ t j) : supr s ≤ supr t :=
supr_le $ assume j, exists.elim (h j) le_supr_of_le
theorem supr_le_supr_const (h : ι → ι₂) : (⨆ i:ι, a) ≤ (⨆ j:ι₂, a) :=
supr_le $ le_supr _ ∘ h
@[simp] theorem supr_le_iff : supr s ≤ a ↔ (∀i, s i ≤ a) :=
⟨assume : supr s ≤ a, assume i, le_trans (le_supr _ _) this, supr_le⟩
-- TODO: finish doesn't do well here.
@[congr] theorem supr_congr_Prop {p q : Prop} {f₁ : p → α} {f₂ : q → α}
(pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : supr f₁ = supr f₂ :=
le_antisymm
(supr_le_supr2 $ assume j, ⟨pq.mp j, le_of_eq $ f _⟩)
(supr_le_supr2 $ assume j, ⟨pq.mpr j, le_of_eq $ (f j).symm⟩)
theorem infi_le (s : ι → α) (i : ι) : infi s ≤ s i :=
Inf_le ⟨i, rfl⟩
@[ematch] theorem infi_le' (s : ι → α) (i : ι) : (: infi s ≤ s i :) :=
Inf_le ⟨i, rfl⟩
example {f : β → α} (b : β) : (⨅ x, f x) ≤ f b :=
begin [smt]
eblast
end
/- I wanted to see if this would help for infi_comm; it doesn't.
@[ematch] theorem infi_le₂' (s : ι → ι₂ → α) (i : ι) (j : ι₂): (: ⨅ i j, s i j :) ≤ (: s i j :) :=
begin
transitivity,
apply (infi_le (λ i, ⨅ j, s i j) i),
apply infi_le
end
-/
theorem infi_le_of_le (i : ι) (h : s i ≤ a) : infi s ≤ a :=
le_trans (infi_le _ i) h
theorem le_infi (h : ∀i, a ≤ s i) : a ≤ infi s :=
le_Inf $ assume b ⟨i, eq⟩, eq.symm ▸ h i
theorem infi_le_infi (h : ∀i, s i ≤ t i) : infi s ≤ infi t :=
le_infi $ assume i, infi_le_of_le i (h i)
theorem infi_le_infi2 {t : ι₂ → α} (h : ∀j, ∃i, s i ≤ t j) : infi s ≤ infi t :=
le_infi $ assume j, exists.elim (h j) infi_le_of_le
theorem infi_le_infi_const (h : ι₂ → ι) : (⨅ i:ι, a) ≤ (⨅ j:ι₂, a) :=
le_infi $ infi_le _ ∘ h
@[simp] theorem le_infi_iff : a ≤ infi s ↔ (∀i, a ≤ s i) :=
⟨assume : a ≤ infi s, assume i, le_trans this (infi_le _ _), le_infi⟩
@[congr] theorem infi_congr_Prop {p q : Prop} {f₁ : p → α} {f₂ : q → α}
(pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : infi f₁ = infi f₂ :=
le_antisymm
(infi_le_infi2 $ assume j, ⟨pq.mpr j, le_of_eq $ f j⟩)
(infi_le_infi2 $ assume j, ⟨pq.mp j, le_of_eq $ (f _).symm⟩)
@[simp] theorem infi_const {a : α} [inhabited ι] : (⨅ b:ι, a) = a :=
le_antisymm (Inf_le ⟨arbitrary ι, rfl⟩) (by finish)
@[simp] theorem supr_const {a : α} [inhabited ι] : (⨆ b:ι, a) = a :=
le_antisymm (by finish) (le_Sup ⟨arbitrary ι, rfl⟩)
-- TODO: should this be @[simp]?
theorem infi_comm {f : ι → ι₂ → α} : (⨅i, ⨅j, f i j) = (⨅j, ⨅i, f i j) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume j, infi_le_of_le j $ infi_le _ i)
(le_infi $ assume j, le_infi $ assume i, infi_le_of_le i $ infi_le _ j)
/- TODO: this is strange. In the proof below, we get exactly the desired
among the equalities, but close does not get it.
begin
apply @le_antisymm,
simp, intros,
begin [smt]
ematch, ematch, ematch, trace_state, have := le_refl (f i_1 i),
trace_state, close
end
end
-/
-- TODO: should this be @[simp]?
theorem supr_comm {f : ι → ι₂ → α} : (⨆i, ⨆j, f i j) = (⨆j, ⨆i, f i j) :=
le_antisymm
(supr_le $ assume i, supr_le $ assume j, le_supr_of_le j $ le_supr _ i)
(supr_le $ assume j, supr_le $ assume i, le_supr_of_le i $ le_supr _ j)
@[simp] theorem infi_infi_eq_left {b : β} {f : Πx:β, x = b → α} : (⨅x, ⨅h:x = b, f x h) = f b rfl :=
le_antisymm
(infi_le_of_le b $ infi_le _ rfl)
(le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end)
@[simp] theorem infi_infi_eq_right {b : β} {f : Πx:β, b = x → α} : (⨅x, ⨅h:b = x, f x h) = f b rfl :=
le_antisymm
(infi_le_of_le b $ infi_le _ rfl)
(le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end)
@[simp] theorem supr_supr_eq_left {b : β} {f : Πx:β, x = b → α} : (⨆x, ⨆h : x = b, f x h) = f b rfl :=
le_antisymm
(supr_le $ assume b', supr_le $ assume eq, match b', eq with ._, rfl := le_refl _ end)
(le_supr_of_le b $ le_supr _ rfl)
@[simp] theorem supr_supr_eq_right {b : β} {f : Πx:β, b = x → α} : (⨆x, ⨆h : b = x, f x h) = f b rfl :=
le_antisymm
(supr_le $ assume b', supr_le $ assume eq, match b', eq with ._, rfl := le_refl _ end)
(le_supr_of_le b $ le_supr _ rfl)
attribute [ematch] le_refl
@[ematch] theorem foo {a b : α} (h : a = b) : a ≤ b :=
by rw h; apply le_refl
@[ematch] theorem foo' {a b : α} (h : b = a) : a ≤ b :=
by rw h; apply le_refl
theorem infi_inf_eq {f g : β → α} : (⨅ x, f x ⊓ g x) = (⨅ x, f x) ⊓ (⨅ x, g x) :=
le_antisymm
(le_inf
(le_infi $ assume i, infi_le_of_le i inf_le_left)
(le_infi $ assume i, infi_le_of_le i inf_le_right))
(le_infi $ assume i, le_inf
(inf_le_left_of_le $ infi_le _ _)
(inf_le_right_of_le $ infi_le _ _))
/- TODO: here is another example where more flexible pattern matching
might help.
begin
apply @le_antisymm,
safe, pose h := f a ⊓ g a, begin [smt] ematch, ematch end
end
-/
theorem supr_sup_eq {f g : β → α} : (⨆ x, f x ⊔ g x) = (⨆ x, f x) ⊔ (⨆ x, g x) :=
le_antisymm
(supr_le $ assume i, sup_le
(le_sup_left_of_le $ le_supr _ _)
(le_sup_right_of_le $ le_supr _ _))
(sup_le
(supr_le $ assume i, le_supr_of_le i le_sup_left)
(supr_le $ assume i, le_supr_of_le i le_sup_right))
/- supr and infi under Prop -/
@[simp] theorem infi_false {s : false → α} : infi s = ⊤ :=
le_antisymm le_top (le_infi $ assume i, false.elim i)
@[simp] theorem supr_false {s : false → α} : supr s = ⊥ :=
le_antisymm (supr_le $ assume i, false.elim i) bot_le
@[simp] theorem infi_true {s : true → α} : infi s = s trivial :=
le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _)
@[simp] theorem supr_true {s : true → α} : supr s = s trivial :=
le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _)
@[simp] theorem infi_exists {p : ι → Prop} {f : Exists p → α} : (⨅ x, f x) = (⨅ i, ⨅ h:p i, f ⟨i, h⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume : p i, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
@[simp] theorem supr_exists {p : ι → Prop} {f : Exists p → α} : (⨆ x, f x) = (⨆ i, ⨆ h:p i, f ⟨i, h⟩) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _)
(supr_le $ assume i, supr_le $ assume : p i, le_supr _ _)
theorem infi_and {p q : Prop} {s : p ∧ q → α} : infi s = (⨅ h₁ : p, ⨅ h₂ : q, s ⟨h₁, h₂⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume j, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
theorem supr_and {p q : Prop} {s : p ∧ q → α} : supr s = (⨆ h₁ : p, ⨆ h₂ : q, s ⟨h₁, h₂⟩) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λj, s ⟨i, j⟩) _)
(supr_le $ assume i, supr_le $ assume j, le_supr _ _)
theorem infi_or {p q : Prop} {s : p ∨ q → α} :
infi s = (⨅ h : p, s (or.inl h)) ⊓ (⨅ h : q, s (or.inr h)) :=
le_antisymm
(le_inf
(infi_le_infi2 $ assume j, ⟨_, le_refl _⟩)
(infi_le_infi2 $ assume j, ⟨_, le_refl _⟩))
(le_infi $ assume i, match i with
| or.inl i := inf_le_left_of_le $ infi_le _ _
| or.inr j := inf_le_right_of_le $ infi_le _ _
end)
theorem supr_or {p q : Prop} {s : p ∨ q → α} :
(⨆ x, s x) = (⨆ i, s (or.inl i)) ⊔ (⨆ j, s (or.inr j)) :=
le_antisymm
(supr_le $ assume s, match s with
| or.inl i := le_sup_left_of_le $ le_supr _ i
| or.inr j := le_sup_right_of_le $ le_supr _ j
end)
(sup_le
(supr_le_supr2 $ assume i, ⟨or.inl i, le_refl _⟩)
(supr_le_supr2 $ assume j, ⟨or.inr j, le_refl _⟩))
theorem Inf_eq_infi {s : set α} : Inf s = (⨅a ∈ s, a) :=
le_antisymm
(le_infi $ assume b, le_infi $ assume h, Inf_le h)
(le_Inf $ assume b h, infi_le_of_le b $ infi_le _ h)
theorem Sup_eq_supr {s : set α} : Sup s = (⨆a ∈ s, a) :=
le_antisymm
(Sup_le $ assume b h, le_supr_of_le b $ le_supr _ h)
(supr_le $ assume b, supr_le $ assume h, le_Sup h)
lemma Sup_range {f : ι → α} : Sup (range f) = supr f :=
le_antisymm
(Sup_le $ forall_range_iff.mpr $ assume i, le_supr _ _)
(supr_le $ assume i, le_Sup mem_range)
lemma Inf_range {f : ι → α} : Inf (range f) = infi f :=
le_antisymm
(le_infi $ assume i, Inf_le mem_range)
(le_Inf $ forall_range_iff.mpr $ assume i, infi_le _ _)
lemma supr_range {g : β → α} {f : ι → β} : (⨆b∈range f, g b) = (⨆i, g (f i)) :=
le_antisymm
(supr_le $ assume b, supr_le $ assume ⟨i, (h : f i = b)⟩, h ▸ le_supr _ i)
(supr_le $ assume i, le_supr_of_le (f i) $ le_supr (λp, g (f i)) mem_range)
lemma infi_range {g : β → α} {f : ι → β} : (⨅b∈range f, g b) = (⨅i, g (f i)) :=
le_antisymm
(le_infi $ assume i, infi_le_of_le (f i) $ infi_le (λp, g (f i)) mem_range)
(le_infi $ assume b, le_infi $ assume ⟨i, (h : f i = b)⟩, h ▸ infi_le _ i)
theorem Inf_image {s : set β} {f : β → α} : Inf (f '' s) = (⨅ a ∈ s, f a) :=
calc Inf (set.image f s) = (⨅a, ⨅h : ∃b, b ∈ s ∧ f b = a, a) : Inf_eq_infi
... = (⨅a, ⨅b, ⨅h : f b = a ∧ b ∈ s, a) : by simp
... = (⨅a, ⨅b, ⨅h : a = f b, ⨅h : b ∈ s, a) : by simp [infi_and, eq_comm]
... = (⨅b, ⨅a, ⨅h : a = f b, ⨅h : b ∈ s, a) : by rw [infi_comm]
... = (⨅a∈s, f a) : congr_arg infi $ funext $ assume x, by rw [infi_infi_eq_left]
theorem Sup_image {s : set β} {f : β → α} : Sup (f '' s) = (⨆ a ∈ s, f a) :=
calc Sup (set.image f s) = (⨆a, ⨆h : ∃b, b ∈ s ∧ f b = a, a) : Sup_eq_supr
... = (⨆a, ⨆b, ⨆h : f b = a ∧ b ∈ s, a) : by simp
... = (⨆a, ⨆b, ⨆h : a = f b, ⨆h : b ∈ s, a) : by simp [supr_and, eq_comm]
... = (⨆b, ⨆a, ⨆h : a = f b, ⨆h : b ∈ s, a) : by rw [supr_comm]
... = (⨆a∈s, f a) : congr_arg supr $ funext $ assume x, by rw [supr_supr_eq_left]
/- supr and infi under set constructions -/
/- should work using the simplifier! -/
@[simp] theorem infi_emptyset {f : β → α} : (⨅ x ∈ (∅ : set β), f x) = ⊤ :=
le_antisymm le_top (le_infi $ assume x, le_infi false.elim)
@[simp] theorem supr_emptyset {f : β → α} : (⨆ x ∈ (∅ : set β), f x) = ⊥ :=
le_antisymm (supr_le $ assume x, supr_le false.elim) bot_le
@[simp] theorem infi_univ {f : β → α} : (⨅ x ∈ (univ : set β), f x) = (⨅ x, f x) :=
show (⨅ (x : β) (H : true), f x) = ⨅ (x : β), f x,
from congr_arg infi $ funext $ assume x, infi_const
@[simp] theorem supr_univ {f : β → α} : (⨆ x ∈ (univ : set β), f x) = (⨆ x, f x) :=
show (⨆ (x : β) (H : true), f x) = ⨆ (x : β), f x,
from congr_arg supr $ funext $ assume x, supr_const
@[simp] theorem infi_union {f : β → α} {s t : set β} : (⨅ x ∈ s ∪ t, f x) = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) :=
calc (⨅ x ∈ s ∪ t, f x) = (⨅ x, (⨅h : x∈s, f x) ⊓ (⨅h : x∈t, f x)) : congr_arg infi $ funext $ assume x, infi_or
... = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) : infi_inf_eq
@[simp] theorem supr_union {f : β → α} {s t : set β} : (⨆ x ∈ s ∪ t, f x) = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) :=
calc (⨆ x ∈ s ∪ t, f x) = (⨆ x, (⨆h : x∈s, f x) ⊔ (⨆h : x∈t, f x)) : congr_arg supr $ funext $ assume x, supr_or
... = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) : supr_sup_eq
@[simp] theorem insert_of_has_insert (x : α) (a : set α) : has_insert.insert x a = insert x a := rfl
@[simp] theorem infi_insert {f : β → α} {s : set β} {b : β} : (⨅ x ∈ insert b s, f x) = f b ⊓ (⨅x∈s, f x) :=
eq.trans infi_union $ congr_arg (λx:α, x ⊓ (⨅x∈s, f x)) infi_infi_eq_left
@[simp] theorem supr_insert {f : β → α} {s : set β} {b : β} : (⨆ x ∈ insert b s, f x) = f b ⊔ (⨆x∈s, f x) :=
eq.trans supr_union $ congr_arg (λx:α, x ⊔ (⨆x∈s, f x)) supr_supr_eq_left
@[simp] theorem infi_singleton {f : β → α} {b : β} : (⨅ x ∈ (singleton b : set β), f x) = f b :=
show (⨅ x ∈ insert b (∅ : set β), f x) = f b,
by simp
@[simp] theorem supr_singleton {f : β → α} {b : β} : (⨆ x ∈ (singleton b : set β), f x) = f b :=
show (⨆ x ∈ insert b (∅ : set β), f x) = f b,
by simp
/- supr and infi under Type -/
@[simp] theorem infi_empty {s : empty → α} : infi s = ⊤ :=
le_antisymm le_top (le_infi $ assume i, empty.rec_on _ i)
@[simp] theorem supr_empty {s : empty → α} : supr s = ⊥ :=
le_antisymm (supr_le $ assume i, empty.rec_on _ i) bot_le
@[simp] theorem infi_unit {f : unit → α} : (⨅ x, f x) = f () :=
le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _)
@[simp] theorem supr_unit {f : unit → α} : (⨆ x, f x) = f () :=
le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _)
theorem infi_subtype {p : ι → Prop} {f : subtype p → α} : (⨅ x, f x) = (⨅ i, ⨅ h:p i, f ⟨i, h⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume : p i, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
theorem supr_subtype {p : ι → Prop} {f : subtype p → α} : (⨆ x, f x) = (⨆ i, ⨆ h:p i, f ⟨i, h⟩) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _)
(supr_le $ assume i, supr_le $ assume : p i, le_supr _ _)
theorem infi_sigma {p : β → Type w} {f : sigma p → α} : (⨅ x, f x) = (⨅ i, ⨅ h:p i, f ⟨i, h⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume : p i, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
theorem supr_sigma {p : β → Type w} {f : sigma p → α} : (⨆ x, f x) = (⨆ i, ⨆ h:p i, f ⟨i, h⟩) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _)
(supr_le $ assume i, supr_le $ assume : p i, le_supr _ _)
theorem infi_prod {γ : Type w} {f : β × γ → α} : (⨅ x, f x) = (⨅ i, ⨅ j, f (i, j)) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume j, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
theorem supr_prod {γ : Type w} {f : β × γ → α} : (⨆ x, f x) = (⨆ i, ⨆ j, f (i, j)) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λj, f ⟨i, j⟩) _)
(supr_le $ assume i, supr_le $ assume j, le_supr _ _)
theorem infi_sum {γ : Type w} {f : β ⊕ γ → α} :
(⨅ x, f x) = (⨅ i, f (sum.inl i)) ⊓ (⨅ j, f (sum.inr j)) :=
le_antisymm
(le_inf
(infi_le_infi2 $ assume i, ⟨_, le_refl _⟩)
(infi_le_infi2 $ assume j, ⟨_, le_refl _⟩))
(le_infi $ assume s, match s with
| sum.inl i := inf_le_left_of_le $ infi_le _ _
| sum.inr j := inf_le_right_of_le $ infi_le _ _
end)
theorem supr_sum {γ : Type w} {f : β ⊕ γ → α} :
(⨆ x, f x) = (⨆ i, f (sum.inl i)) ⊔ (⨆ j, f (sum.inr j)) :=
le_antisymm
(supr_le $ assume s, match s with
| sum.inl i := le_sup_left_of_le $ le_supr _ i
| sum.inr j := le_sup_right_of_le $ le_supr _ j
end)
(sup_le
(supr_le_supr2 $ assume i, ⟨sum.inl i, le_refl _⟩)
(supr_le_supr2 $ assume j, ⟨sum.inr j, le_refl _⟩))
end
/- Instances -/
instance complete_lattice_Prop : complete_lattice Prop :=
{ lattice.bounded_lattice_Prop with
Sup := λs, ∃a∈s, a,
le_Sup := assume s a h p, ⟨a, h, p⟩,
Sup_le := assume s a h ⟨b, h', p⟩, h b h' p,
Inf := λs, ∀a:Prop, a∈s → a,
Inf_le := assume s a h p, p a h,
le_Inf := assume s a h p b hb, h b hb p }
instance complete_lattice_fun {α : Type u} {β : Type v} [complete_lattice β] :
complete_lattice (α → β) :=
{ lattice.bounded_lattice_fun with
Sup := λs a, Sup (set.image (λf : α → β, f a) s),
le_Sup := assume s f h a, le_Sup ⟨f, h, rfl⟩,
Sup_le := assume s f h a, Sup_le $ assume b ⟨f', h', b_eq⟩, b_eq ▸ h _ h' a,
Inf := λs a, Inf (set.image (λf : α → β, f a) s),
Inf_le := assume s f h a, Inf_le ⟨f, h, rfl⟩,
le_Inf := assume s f h a, le_Inf $ assume b ⟨f', h', b_eq⟩, b_eq ▸ h _ h' a }
section complete_lattice
variables [preorder α] [complete_lattice β]
theorem monotone_Sup_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Sup s) :=
assume x y h, Sup_le $ assume x' ⟨f, f_in, fx_eq⟩, le_Sup_of_le ⟨f, f_in, rfl⟩ $ fx_eq ▸ m_s _ f_in h
theorem monotone_Inf_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Inf s) :=
assume x y h, le_Inf $ assume x' ⟨f, f_in, fx_eq⟩, Inf_le_of_le ⟨f, f_in, rfl⟩ $ fx_eq ▸ m_s _ f_in h
end complete_lattice
end lattice
section ord_continuous
open lattice
variables [complete_lattice α] [complete_lattice β]
def ord_continuous (f : α → β) := ∀s : set α, f (Sup s) = (⨆i∈s, f i)
lemma ord_continuous_sup {f : α → β} {a₁ a₂ : α} (hf : ord_continuous f) : f (a₁ ⊔ a₂) = f a₁ ⊔ f a₂ :=
have h : f (Sup {a₁, a₂}) = (⨆i∈({a₁, a₂} : set α), f i), from hf _,
have h₁ : {a₁, a₂} = (insert a₂ {a₁} : set α), from rfl,
begin
rw [h₁, Sup_insert, Sup_singleton, sup_comm] at h,
rw [h, supr_insert, supr_singleton, sup_comm]
end
lemma ord_continuous_mono {f : α → β} (hf : ord_continuous f) : monotone f :=
assume a₁ a₂ h,
calc f a₁ ≤ f a₁ ⊔ f a₂ : le_sup_left
... = f (a₁ ⊔ a₂) : (ord_continuous_sup hf).symm
... = _ : by rw [sup_of_le_right h]
end ord_continuous
/- Classical statements:
@[simp] theorem Inf_eq_top : Inf s = ⊤ ↔ (∀a∈s, a = ⊤) :=
_
@[simp] theorem infi_eq_top : infi s = ⊤ ↔ (∀i, s i = ⊤) :=
_
@[simp] theorem Sup_eq_bot : Sup s = ⊤ ↔ (∀a∈s, a = ⊥) :=
_
@[simp] theorem supr_eq_top : supr s = ⊤ ↔ (∀i, s i = ⊥) :=
_
-/
|
c5327a8cff5b3eac753fbb133df02a1f54dbab7f | 1136b4d61007050cc632ede270de45a662f8dba4 | /tests/lean/structure_notation_dep_mvars.lean | 0fe9fbc29a12330712c7ec3edf1e5495bbaa6e3f | [
"Apache-2.0"
] | permissive | zk744750315/lean | 7fe895f16cc0ef1869238a01cae903bbd623b4a9 | c17e5b913b2db687ab38f53285326b9dbb2b1b6e | refs/heads/master | 1,618,208,425,413 | 1,521,520,544,000 | 1,521,520,936,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 32 | lean | instance : monad list := { .. }
|
72bebce808f62026c1d155cc83dbc0500553e44b | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/algebraic_geometry/presheafed_space.lean | 8e7b574fd2d9c0c05f7deaa884a23c2ba69cc868 | [
"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 | 9,674 | 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.sheaves.presheaf
/-!
# Presheafed spaces
Introduces the category of topological spaces equipped with a presheaf (taking values in an
arbitrary target category `C`.)
We further describe how to apply functors and natural transformations to the values of the
presheaves.
-/
universes v u
open category_theory
open Top
open topological_space
open opposite
open category_theory.category category_theory.functor
variables (C : Type u) [category.{v} C]
local attribute [tidy] tactic.op_induction'
namespace algebraic_geometry
/-- A `PresheafedSpace C` is a topological space equipped with a presheaf of `C`s. -/
structure PresheafedSpace :=
(carrier : Top)
(presheaf : carrier.presheaf C)
variables {C}
namespace PresheafedSpace
attribute [protected] presheaf
instance coe_carrier : has_coe (PresheafedSpace C) Top :=
{ coe := λ X, X.carrier }
@[simp] lemma as_coe (X : PresheafedSpace C) : X.carrier = (X : Top.{v}) := rfl
@[simp] lemma mk_coe (carrier) (presheaf) : (({ carrier := carrier, presheaf := presheaf } :
PresheafedSpace.{v} C) : Top.{v}) = carrier := rfl
instance (X : PresheafedSpace.{v} C) : topological_space X := X.carrier.str
/-- The constant presheaf on `X` with value `Z`. -/
def const (X : Top) (Z : C) : PresheafedSpace C :=
{ carrier := X,
presheaf :=
{ obj := λ U, Z,
map := λ U V f, 𝟙 Z, } }
instance [inhabited C] : inhabited (PresheafedSpace C) := ⟨const (Top.of pempty) (default C)⟩
/-- A morphism between presheafed spaces `X` and `Y` consists of a continuous map
`f` between the underlying topological spaces, and a (notice contravariant!) map
from the presheaf on `Y` to the pushforward of the presheaf on `X` via `f`. -/
structure hom (X Y : PresheafedSpace C) :=
(base : (X : Top.{v}) ⟶ (Y : Top.{v}))
(c : Y.presheaf ⟶ base _* X.presheaf)
@[ext] lemma ext {X Y : PresheafedSpace C} (α β : hom X Y)
(w : α.base = β.base)
(h : α.c ≫ eq_to_hom (by rw w) = β.c) :
α = β :=
begin
cases α, cases β,
dsimp [presheaf.pushforward_obj] at *,
tidy, -- TODO including `injections` would make tidy work earlier.
end
lemma hext {X Y : PresheafedSpace C} (α β : hom X Y)
(w : α.base = β.base)
(h : α.c == β.c) :
α = β :=
by { cases α, cases β, congr, exacts [w,h] }
.
/-- The identity morphism of a `PresheafedSpace`. -/
def id (X : PresheafedSpace C) : hom X X :=
{ base := 𝟙 (X : Top.{v}),
c := eq_to_hom (presheaf.pushforward.id_eq X.presheaf).symm }
instance hom_inhabited (X : PresheafedSpace C) : inhabited (hom X X) := ⟨id X⟩
/-- Composition of morphisms of `PresheafedSpace`s. -/
def comp {X Y Z : PresheafedSpace C} (α : hom X Y) (β : hom Y Z) : hom X Z :=
{ base := α.base ≫ β.base,
c := β.c ≫ (presheaf.pushforward _ β.base).map α.c }
lemma comp_c {X Y Z : PresheafedSpace C} (α : hom X Y) (β : hom Y Z) :
(comp α β).c = β.c ≫ (presheaf.pushforward _ β.base).map α.c := rfl
variables (C)
section
local attribute [simp] id comp
/- The proofs below can be done by `tidy`, but it is too slow,
and we don't have a tactic caching mechanism. -/
/-- The category of PresheafedSpaces. Morphisms are pairs, a continuous map and a presheaf map
from the presheaf on the target to the pushforward of the presheaf on the source. -/
instance category_of_PresheafedSpaces : category (PresheafedSpace C) :=
{ hom := hom,
id := id,
comp := λ X Y Z f g, comp f g,
id_comp' := λ X Y f, by { ext1,
{ rw comp_c, erw eq_to_hom_map, simp, apply comp_id }, apply id_comp },
comp_id' := λ X Y f, by { ext1,
{ rw comp_c, erw congr_hom (presheaf.id_pushforward _) f.c,
simp, erw eq_to_hom_trans_assoc, simp }, apply comp_id },
assoc' := λ W X Y Z f g h, by { ext1,
repeat {rw comp_c}, simpa, refl } }
end
variables {C}
@[simp] lemma id_base (X : PresheafedSpace C) :
((𝟙 X) : X ⟶ X).base = 𝟙 (X : Top.{v}) := rfl
lemma id_c (X : PresheafedSpace C) :
((𝟙 X) : X ⟶ X).c = eq_to_hom (presheaf.pushforward.id_eq X.presheaf).symm := rfl
@[simp] lemma id_c_app (X : PresheafedSpace C) (U) :
((𝟙 X) : X ⟶ X).c.app U = eq_to_hom (by { induction U using opposite.rec, cases U, refl }) :=
by { induction U using opposite.rec, cases U, simp only [id_c], dsimp, simp, }
@[simp] lemma comp_base {X Y Z : PresheafedSpace C} (f : X ⟶ Y) (g : Y ⟶ Z) :
(f ≫ g).base = f.base ≫ g.base := rfl
@[simp] lemma comp_c_app {X Y Z : PresheafedSpace C} (α : X ⟶ Y) (β : Y ⟶ Z) (U) :
(α ≫ β).c.app U = (β.c).app U ≫ (α.c).app (op ((opens.map (β.base)).obj (unop U))) := rfl
lemma congr_app {X Y : PresheafedSpace C} {α β : X ⟶ Y} (h : α = β) (U) :
α.c.app U = β.c.app U ≫ X.presheaf.map (eq_to_hom (by subst h)) :=
by { subst h, dsimp, simp, }
section
variables (C)
/-- The forgetful functor from `PresheafedSpace` to `Top`. -/
@[simps]
def forget : PresheafedSpace C ⥤ Top :=
{ obj := λ X, (X : Top.{v}),
map := λ X Y f, f.base }
end
/--
The restriction of a presheafed space along an open embedding into the space.
-/
@[simps]
def restrict {U : Top} (X : PresheafedSpace C)
{f : U ⟶ (X : Top.{v})} (h : open_embedding f) : PresheafedSpace C :=
{ carrier := U,
presheaf := h.is_open_map.functor.op ⋙ X.presheaf }
/--
The map from the restriction of a presheafed space.
-/
def of_restrict {U : Top} (X : PresheafedSpace C)
{f : U ⟶ (X : Top.{v})} (h : open_embedding f) :
X.restrict h ⟶ X :=
{ base := f,
c := { app := λ V, X.presheaf.map (h.is_open_map.adjunction.counit.app V.unop).op,
naturality' := λ U V f, show _ = _ ≫ X.presheaf.map _,
by { rw [← map_comp, ← map_comp], refl } } }
lemma restrict_top_presheaf (X : PresheafedSpace C) :
(X.restrict (opens.open_embedding ⊤)).presheaf =
(opens.inclusion_top_iso X.carrier).inv _* X.presheaf :=
by { dsimp, rw opens.inclusion_top_functor X.carrier, refl }
lemma of_restrict_top_c (X : PresheafedSpace C) :
(X.of_restrict (opens.open_embedding ⊤)).c = eq_to_hom
(by { rw [restrict_top_presheaf, ←presheaf.pushforward.comp_eq],
erw iso.inv_hom_id, rw presheaf.pushforward.id_eq }) :=
/- another approach would be to prove the left hand side
is a natural isoomorphism, but I encountered a universe
issue when `apply nat_iso.is_iso_of_is_iso_app`. -/
begin
ext U, change X.presheaf.map _ = _, convert eq_to_hom_map _ _ using 1,
congr, simpa,
{ induction U using opposite.rec, dsimp, congr, ext,
exact ⟨ λ h, ⟨⟨x,trivial⟩,h,rfl⟩, λ ⟨⟨_,_⟩,h,rfl⟩, h ⟩ },
/- or `rw [opens.inclusion_top_functor, ←comp_obj, ←opens.map_comp_eq],
erw iso.inv_hom_id, cases U, refl` after `dsimp` -/
end
/--
The map to the restriction of a presheafed space along the canonical inclusion from the top
subspace.
-/
@[simps]
def to_restrict_top (X : PresheafedSpace C) :
X ⟶ X.restrict (opens.open_embedding ⊤) :=
{ base := (opens.inclusion_top_iso X.carrier).inv,
c := eq_to_hom (restrict_top_presheaf X) }
/--
The isomorphism from the restriction to the top subspace.
-/
@[simps]
def restrict_top_iso (X : PresheafedSpace C) :
X.restrict (opens.open_embedding ⊤) ≅ X :=
{ hom := X.of_restrict _,
inv := X.to_restrict_top,
hom_inv_id' := ext _ _ (concrete_category.hom_ext _ _ $ λ ⟨x, _⟩, rfl) $
by { erw comp_c, rw X.of_restrict_top_c, simpa },
inv_hom_id' := ext _ _ rfl $
by { erw comp_c, rw X.of_restrict_top_c, simpa } }
/--
The global sections, notated Gamma.
-/
@[simps]
def Γ : (PresheafedSpace C)ᵒᵖ ⥤ C :=
{ obj := λ X, (unop X).presheaf.obj (op ⊤),
map := λ X Y f, f.unop.c.app (op ⊤) }
lemma Γ_obj_op (X : PresheafedSpace C) : Γ.obj (op X) = X.presheaf.obj (op ⊤) := rfl
lemma Γ_map_op {X Y : PresheafedSpace C} (f : X ⟶ Y) :
Γ.map f.op = f.c.app (op ⊤) := rfl
end PresheafedSpace
end algebraic_geometry
open algebraic_geometry algebraic_geometry.PresheafedSpace
variables {C}
namespace category_theory
variables {D : Type u} [category.{v} D]
local attribute [simp] presheaf.pushforward_obj
namespace functor
/-- We can apply a functor `F : C ⥤ D` to the values of the presheaf in any `PresheafedSpace C`,
giving a functor `PresheafedSpace C ⥤ PresheafedSpace D` -/
def map_presheaf (F : C ⥤ D) : PresheafedSpace C ⥤ PresheafedSpace D :=
{ obj := λ X, { carrier := X.carrier, presheaf := X.presheaf ⋙ F },
map := λ X Y f, { base := f.base, c := whisker_right f.c F }, }
@[simp] lemma map_presheaf_obj_X (F : C ⥤ D) (X : PresheafedSpace C) :
((F.map_presheaf.obj X) : Top.{v}) = (X : Top.{v}) := rfl
@[simp] lemma map_presheaf_obj_presheaf (F : C ⥤ D) (X : PresheafedSpace C) :
(F.map_presheaf.obj X).presheaf = X.presheaf ⋙ F := rfl
@[simp] lemma map_presheaf_map_f (F : C ⥤ D) {X Y : PresheafedSpace C} (f : X ⟶ Y) :
(F.map_presheaf.map f).base = f.base := rfl
@[simp] lemma map_presheaf_map_c (F : C ⥤ D) {X Y : PresheafedSpace C} (f : X ⟶ Y) :
(F.map_presheaf.map f).c = whisker_right f.c F := rfl
end functor
namespace nat_trans
/--
A natural transformation induces a natural transformation between the `map_presheaf` functors.
-/
def on_presheaf {F G : C ⥤ D} (α : F ⟶ G) : G.map_presheaf ⟶ F.map_presheaf :=
{ app := λ X,
{ base := 𝟙 _,
c := whisker_left X.presheaf α ≫ eq_to_hom (presheaf.pushforward.id_eq _).symm } }
-- TODO Assemble the last two constructions into a functor
-- `(C ⥤ D) ⥤ (PresheafedSpace C ⥤ PresheafedSpace D)`
end nat_trans
end category_theory
|
b6d230c0e5b28e8e65d582cff8eaf6d0c258f2b9 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/category_theory/over.lean | 6d7fb295ed431ef9fd6c28f2f671093410fc3664 | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 11,375 | lean | /-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Bhavik Mehta
-/
import category_theory.structured_arrow
import category_theory.punit
import category_theory.reflects_isomorphisms
import category_theory.epi_mono
/-!
# Over and under categories
Over (and under) categories are special cases of comma categories.
* If `L` is the identity functor and `R` is a constant functor, then `comma L R` is the "slice" or
"over" category over the object `R` maps to.
* Conversely, if `L` is a constant functor and `R` is the identity functor, then `comma L R` is the
"coslice" or "under" category under the object `L` maps to.
## Tags
comma, slice, coslice, over, under
-/
namespace category_theory
universes v₁ v₂ u₁ u₂ -- morphism levels before object levels. See note [category_theory universes].
variables {T : Type u₁} [category.{v₁} T]
/--
The over category has as objects arrows in `T` with codomain `X` and as morphisms commutative
triangles.
See https://stacks.math.columbia.edu/tag/001G.
-/
@[derive category]
def over (X : T) := costructured_arrow (𝟭 T) X
-- Satisfying the inhabited linter
instance over.inhabited [inhabited T] : inhabited (over (default T)) :=
{ default :=
{ left := default T,
hom := 𝟙 _ } }
namespace over
variables {X : T}
@[ext] lemma over_morphism.ext {X : T} {U V : over X} {f g : U ⟶ V}
(h : f.left = g.left) : f = g :=
by tidy
@[simp] lemma over_right (U : over X) : U.right = punit.star := by tidy
@[simp] lemma id_left (U : over X) : comma_morphism.left (𝟙 U) = 𝟙 U.left := rfl
@[simp] lemma comp_left (a b c : over X) (f : a ⟶ b) (g : b ⟶ c) :
(f ≫ g).left = f.left ≫ g.left := rfl
@[simp, reassoc] lemma w {A B : over X} (f : A ⟶ B) : f.left ≫ B.hom = A.hom :=
by have := f.w; tidy
/-- To give an object in the over category, it suffices to give a morphism with codomain `X`. -/
@[simps]
def mk {X Y : T} (f : Y ⟶ X) : over X :=
costructured_arrow.mk f
/-- We can set up a coercion from arrows with codomain `X` to `over X`. This most likely should not
be a global instance, but it is sometimes useful. -/
def coe_from_hom {X Y : T} : has_coe (Y ⟶ X) (over X) :=
{ coe := mk }
section
local attribute [instance] coe_from_hom
@[simp] lemma coe_hom {X Y : T} (f : Y ⟶ X) : (f : over X).hom = f := rfl
end
/-- To give a morphism in the over category, it suffices to give an arrow fitting in a commutative
triangle. -/
@[simps]
def hom_mk {U V : over X} (f : U.left ⟶ V.left) (w : f ≫ V.hom = U.hom . obviously) :
U ⟶ V :=
costructured_arrow.hom_mk f w
/--
Construct an isomorphism in the over category given isomorphisms of the objects whose forward
direction gives a commutative triangle.
-/
@[simps]
def iso_mk {f g : over X} (hl : f.left ≅ g.left) (hw : hl.hom ≫ g.hom = f.hom . obviously) :
f ≅ g :=
costructured_arrow.iso_mk hl hw
section
variable (X)
/--
The forgetful functor mapping an arrow to its domain.
See https://stacks.math.columbia.edu/tag/001G.
-/
def forget : over X ⥤ T := comma.fst _ _
end
@[simp] lemma forget_obj {U : over X} : (forget X).obj U = U.left := rfl
@[simp] lemma forget_map {U V : over X} {f : U ⟶ V} : (forget X).map f = f.left := rfl
/--
A morphism `f : X ⟶ Y` induces a functor `over X ⥤ over Y` in the obvious way.
See https://stacks.math.columbia.edu/tag/001G.
-/
def map {Y : T} (f : X ⟶ Y) : over X ⥤ over Y := comma.map_right _ $ discrete.nat_trans (λ _, f)
section
variables {Y : T} {f : X ⟶ Y} {U V : over X} {g : U ⟶ V}
@[simp] lemma map_obj_left : ((map f).obj U).left = U.left := rfl
@[simp] lemma map_obj_hom : ((map f).obj U).hom = U.hom ≫ f := rfl
@[simp] lemma map_map_left : ((map f).map g).left = g.left := rfl
/-- Mapping by the identity morphism is just the identity functor. -/
def map_id : map (𝟙 Y) ≅ 𝟭 _ :=
nat_iso.of_components (λ X, iso_mk (iso.refl _) (by tidy)) (by tidy)
/-- Mapping by the composite morphism `f ≫ g` is the same as mapping by `f` then by `g`. -/
def map_comp {Y Z : T} (f : X ⟶ Y) (g : Y ⟶ Z) : map (f ≫ g) ≅ map f ⋙ map g :=
nat_iso.of_components (λ X, iso_mk (iso.refl _) (by tidy)) (by tidy)
end
instance forget_reflects_iso : reflects_isomorphisms (forget X) :=
{ reflects := λ Y Z f t, by exactI
⟨⟨over.hom_mk (inv ((forget X).map f))
((as_iso ((forget X).map f)).inv_comp_eq.2 (over.w f).symm),
by tidy⟩⟩ }
instance forget_faithful : faithful (forget X) := {}.
/--
If `k.left` is an epimorphism, then `k` is an epimorphism. In other words, `over.forget X` reflects
epimorphisms.
The converse does not hold without additional assumptions on the underlying category.
-/
-- TODO: Show the converse holds if `T` has binary products or pushouts.
lemma epi_of_epi_left {f g : over X} (k : f ⟶ g) [hk : epi k.left] : epi k :=
faithful_reflects_epi (forget X) hk
/--
If `k.left` is a monomorphism, then `k` is a monomorphism. In other words, `over.forget X` reflects
monomorphisms.
The converse of `category_theory.over.mono_left_of_mono`.
This lemma is not an instance, to avoid loops in type class inference.
-/
lemma mono_of_mono_left {f g : over X} (k : f ⟶ g) [hk : mono k.left] : mono k :=
faithful_reflects_mono (forget X) hk
/--
If `k` is a monomorphism, then `k.left` is a monomorphism. In other words, `over.forget X` preserves
monomorphisms.
The converse of `category_theory.over.mono_of_mono_left`.
-/
instance mono_left_of_mono {f g : over X} (k : f ⟶ g) [mono k] : mono k.left :=
begin
refine ⟨λ (Y : T) l m a, _⟩,
let l' : mk (m ≫ f.hom) ⟶ f := hom_mk l (by { dsimp, rw [←over.w k, reassoc_of a] }),
suffices : l' = hom_mk m,
{ apply congr_arg comma_morphism.left this },
rw ← cancel_mono k,
ext,
apply a,
end
section iterated_slice
variables (f : over X)
/-- Given f : Y ⟶ X, this is the obvious functor from (T/X)/f to T/Y -/
@[simps]
def iterated_slice_forward : over f ⥤ over f.left :=
{ obj := λ α, over.mk α.hom.left,
map := λ α β κ, over.hom_mk κ.left.left (by { rw auto_param_eq, rw ← over.w κ, refl }) }
/-- Given f : Y ⟶ X, this is the obvious functor from T/Y to (T/X)/f -/
@[simps]
def iterated_slice_backward : over f.left ⥤ over f :=
{ obj := λ g, mk (hom_mk g.hom : mk (g.hom ≫ f.hom) ⟶ f),
map := λ g h α, hom_mk (hom_mk α.left (w_assoc α f.hom)) (over_morphism.ext (w α)) }
/-- Given f : Y ⟶ X, we have an equivalence between (T/X)/f and T/Y -/
@[simps]
def iterated_slice_equiv : over f ≌ over f.left :=
{ functor := iterated_slice_forward f,
inverse := iterated_slice_backward f,
unit_iso :=
nat_iso.of_components
(λ g, over.iso_mk (over.iso_mk (iso.refl _) (by tidy)) (by tidy))
(λ X Y g, by { ext, dsimp, simp }),
counit_iso :=
nat_iso.of_components
(λ g, over.iso_mk (iso.refl _) (by tidy))
(λ X Y g, by { ext, dsimp, simp }) }
lemma iterated_slice_forward_forget :
iterated_slice_forward f ⋙ forget f.left = forget f ⋙ forget X :=
rfl
lemma iterated_slice_backward_forget_forget :
iterated_slice_backward f ⋙ forget f ⋙ forget X = forget f.left :=
rfl
end iterated_slice
section
variables {D : Type u₂} [category.{v₂} D]
/-- A functor `F : T ⥤ D` induces a functor `over X ⥤ over (F.obj X)` in the obvious way. -/
@[simps]
def post (F : T ⥤ D) : over X ⥤ over (F.obj X) :=
{ obj := λ Y, mk $ F.map Y.hom,
map := λ Y₁ Y₂ f,
{ left := F.map f.left,
w' := by tidy; erw [← F.map_comp, w] } }
end
end over
/-- The under category has as objects arrows with domain `X` and as morphisms commutative
triangles. -/
@[derive category]
def under (X : T) := structured_arrow X (𝟭 T)
-- Satisfying the inhabited linter
instance under.inhabited [inhabited T] : inhabited (under (default T)) :=
{ default :=
{ right := default T,
hom := 𝟙 _ } }
namespace under
variables {X : T}
@[ext] lemma under_morphism.ext {X : T} {U V : under X} {f g : U ⟶ V}
(h : f.right = g.right) : f = g :=
by tidy
@[simp] lemma under_left (U : under X) : U.left = punit.star := by tidy
@[simp] lemma id_right (U : under X) : comma_morphism.right (𝟙 U) = 𝟙 U.right := rfl
@[simp] lemma comp_right (a b c : under X) (f : a ⟶ b) (g : b ⟶ c) :
(f ≫ g).right = f.right ≫ g.right := rfl
@[simp, reassoc] lemma w {A B : under X} (f : A ⟶ B) : A.hom ≫ f.right = B.hom :=
by have := f.w; tidy
/-- To give an object in the under category, it suffices to give an arrow with domain `X`. -/
@[simps]
def mk {X Y : T} (f : X ⟶ Y) : under X :=
structured_arrow.mk f
/-- To give a morphism in the under category, it suffices to give a morphism fitting in a
commutative triangle. -/
@[simps]
def hom_mk {U V : under X} (f : U.right ⟶ V.right) (w : U.hom ≫ f = V.hom . obviously) :
U ⟶ V :=
structured_arrow.hom_mk f w
/--
Construct an isomorphism in the over category given isomorphisms of the objects whose forward
direction gives a commutative triangle.
-/
def iso_mk {f g : under X} (hr : f.right ≅ g.right) (hw : f.hom ≫ hr.hom = g.hom) : f ≅ g :=
structured_arrow.iso_mk hr hw
@[simp]
lemma iso_mk_hom_right {f g : under X} (hr : f.right ≅ g.right) (hw : f.hom ≫ hr.hom = g.hom) :
(iso_mk hr hw).hom.right = hr.hom := rfl
@[simp]
lemma iso_mk_inv_right {f g : under X} (hr : f.right ≅ g.right) (hw : f.hom ≫ hr.hom = g.hom) :
(iso_mk hr hw).inv.right = hr.inv := rfl
section
variables (X)
/-- The forgetful functor mapping an arrow to its domain. -/
def forget : under X ⥤ T := comma.snd _ _
end
@[simp] lemma forget_obj {U : under X} : (forget X).obj U = U.right := rfl
@[simp] lemma forget_map {U V : under X} {f : U ⟶ V} : (forget X).map f = f.right := rfl
/-- A morphism `X ⟶ Y` induces a functor `under Y ⥤ under X` in the obvious way. -/
def map {Y : T} (f : X ⟶ Y) : under Y ⥤ under X := comma.map_left _ $ discrete.nat_trans (λ _, f)
section
variables {Y : T} {f : X ⟶ Y} {U V : under Y} {g : U ⟶ V}
@[simp] lemma map_obj_right : ((map f).obj U).right = U.right := rfl
@[simp] lemma map_obj_hom : ((map f).obj U).hom = f ≫ U.hom := rfl
@[simp] lemma map_map_right : ((map f).map g).right = g.right := rfl
/-- Mapping by the identity morphism is just the identity functor. -/
def map_id : map (𝟙 Y) ≅ 𝟭 _ :=
nat_iso.of_components (λ X, iso_mk (iso.refl _) (by tidy)) (by tidy)
/-- Mapping by the composite morphism `f ≫ g` is the same as mapping by `f` then by `g`. -/
def map_comp {Y Z : T} (f : X ⟶ Y) (g : Y ⟶ Z) : map (f ≫ g) ≅ map g ⋙ map f :=
nat_iso.of_components (λ X, iso_mk (iso.refl _) (by tidy)) (by tidy)
end
instance forget_reflects_iso : reflects_isomorphisms (forget X) :=
{ reflects := λ Y Z f t, by exactI
⟨⟨under.hom_mk (inv ((under.forget X).map f)) ((is_iso.comp_inv_eq _).2 (under.w f).symm),
by tidy⟩⟩ }
instance forget_faithful : faithful (forget X) := {}.
section
variables {D : Type u₂} [category.{v₂} D]
/-- A functor `F : T ⥤ D` induces a functor `under X ⥤ under (F.obj X)` in the obvious way. -/
@[simps]
def post {X : T} (F : T ⥤ D) : under X ⥤ under (F.obj X) :=
{ obj := λ Y, mk $ F.map Y.hom,
map := λ Y₁ Y₂ f,
{ right := F.map f.right,
w' := by tidy; erw [← F.map_comp, w] } }
end
end under
end category_theory
|
28b5a442c633d13dcdb59e549ca44bbb612d207d | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/topology/homeomorph.lean | 511d6d63254e65f9124029b6d32652651704ff98 | [
"Apache-2.0"
] | permissive | abentkamp/mathlib | d9a75d291ec09f4637b0f30cc3880ffb07549ee5 | 5360e476391508e092b5a1e5210bd0ed22dc0755 | refs/heads/master | 1,682,382,954,948 | 1,622,106,077,000 | 1,622,106,077,000 | 149,285,665 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 14,042 | lean | /-
Copyright (c) 2019 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Patrick Massot, Sébastien Gouëzel, Zhouhang Zhou, Reid Barton
-/
import topology.dense_embedding
open set filter
open_locale topological_space
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
/-- Homeomorphism between `α` and `β`, also called topological isomorphism -/
@[nolint has_inhabited_instance] -- not all spaces are homeomorphic to each other
structure homeomorph (α : Type*) (β : Type*) [topological_space α] [topological_space β]
extends α ≃ β :=
(continuous_to_fun : continuous to_fun . tactic.interactive.continuity')
(continuous_inv_fun : continuous inv_fun . tactic.interactive.continuity')
infix ` ≃ₜ `:25 := homeomorph
namespace homeomorph
variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
instance : has_coe_to_fun (α ≃ₜ β) := ⟨λ_, α → β, λe, e.to_equiv⟩
@[simp] lemma homeomorph_mk_coe (a : equiv α β) (b c) :
((homeomorph.mk a b c) : α → β) = a :=
rfl
@[simp] lemma coe_to_equiv (h : α ≃ₜ β) : ⇑h.to_equiv = h := rfl
/-- Inverse of a homeomorphism. -/
protected def symm (h : α ≃ₜ β) : β ≃ₜ α :=
{ continuous_to_fun := h.continuous_inv_fun,
continuous_inv_fun := h.continuous_to_fun,
to_equiv := h.to_equiv.symm }
/-- See Note [custom simps projection]. We need to specify this projection explicitly in this case,
because it is a composition of multiple projections. -/
def simps.apply (h : α ≃ₜ β) : α → β := h
/-- See Note [custom simps projection] -/
def simps.symm_apply (h : α ≃ₜ β) : β → α := h.symm
initialize_simps_projections homeomorph
(to_equiv_to_fun → apply, to_equiv_inv_fun → symm_apply, -to_equiv)
lemma to_equiv_injective : function.injective (to_equiv : α ≃ₜ β → α ≃ β)
| ⟨e, h₁, h₂⟩ ⟨e', h₁', h₂'⟩ rfl := rfl
@[ext] lemma ext {h h' : α ≃ₜ β} (H : ∀ x, h x = h' x) : h = h' :=
to_equiv_injective $ equiv.ext H
/-- Identity map as a homeomorphism. -/
@[simps apply {fully_applied := ff}]
protected def refl (α : Type*) [topological_space α] : α ≃ₜ α :=
{ continuous_to_fun := continuous_id,
continuous_inv_fun := continuous_id,
to_equiv := equiv.refl α }
/-- Composition of two homeomorphisms. -/
protected def trans (h₁ : α ≃ₜ β) (h₂ : β ≃ₜ γ) : α ≃ₜ γ :=
{ continuous_to_fun := h₂.continuous_to_fun.comp h₁.continuous_to_fun,
continuous_inv_fun := h₁.continuous_inv_fun.comp h₂.continuous_inv_fun,
to_equiv := equiv.trans h₁.to_equiv h₂.to_equiv }
@[simp] lemma homeomorph_mk_coe_symm (a : equiv α β) (b c) :
((homeomorph.mk a b c).symm : β → α) = a.symm :=
rfl
@[simp] lemma refl_symm : (homeomorph.refl α).symm = homeomorph.refl α := rfl
@[continuity]
protected lemma continuous (h : α ≃ₜ β) : continuous h := h.continuous_to_fun
@[continuity] -- otherwise `by continuity` can't prove continuity of `h.to_equiv.symm`
protected lemma continuous_symm (h : α ≃ₜ β) : continuous (h.symm) := h.continuous_inv_fun
@[simp] lemma apply_symm_apply (h : α ≃ₜ β) (x : β) : h (h.symm x) = x :=
h.to_equiv.apply_symm_apply x
@[simp] lemma symm_apply_apply (h : α ≃ₜ β) (x : α) : h.symm (h x) = x :=
h.to_equiv.symm_apply_apply x
protected lemma bijective (h : α ≃ₜ β) : function.bijective h := h.to_equiv.bijective
protected lemma injective (h : α ≃ₜ β) : function.injective h := h.to_equiv.injective
protected lemma surjective (h : α ≃ₜ β) : function.surjective h := h.to_equiv.surjective
/-- Change the homeomorphism `f` to make the inverse function definitionally equal to `g`. -/
def change_inv (f : α ≃ₜ β) (g : β → α) (hg : function.right_inverse g f) : α ≃ₜ β :=
have g = f.symm, from funext (λ x, calc g x = f.symm (f (g x)) : (f.left_inv (g x)).symm
... = f.symm x : by rw hg x),
{ to_fun := f,
inv_fun := g,
left_inv := by convert f.left_inv,
right_inv := by convert f.right_inv,
continuous_to_fun := f.continuous,
continuous_inv_fun := by convert f.symm.continuous }
@[simp] lemma symm_comp_self (h : α ≃ₜ β) : ⇑h.symm ∘ ⇑h = id :=
funext h.symm_apply_apply
@[simp] lemma self_comp_symm (h : α ≃ₜ β) : ⇑h ∘ ⇑h.symm = id :=
funext h.apply_symm_apply
@[simp] lemma range_coe (h : α ≃ₜ β) : range h = univ :=
h.surjective.range_eq
lemma image_symm (h : α ≃ₜ β) : image h.symm = preimage h :=
funext h.symm.to_equiv.image_eq_preimage
lemma preimage_symm (h : α ≃ₜ β) : preimage h.symm = image h :=
(funext h.to_equiv.image_eq_preimage).symm
@[simp] lemma image_preimage (h : α ≃ₜ β) (s : set β) : h '' (h ⁻¹' s) = s :=
h.to_equiv.image_preimage s
@[simp] lemma preimage_image (h : α ≃ₜ β) (s : set α) : h ⁻¹' (h '' s) = s :=
h.to_equiv.preimage_image s
protected lemma inducing (h : α ≃ₜ β) : inducing h :=
inducing_of_inducing_compose h.continuous h.symm.continuous $
by simp only [symm_comp_self, inducing_id]
lemma induced_eq (h : α ≃ₜ β) : topological_space.induced h ‹_› = ‹_› := h.inducing.1.symm
protected lemma quotient_map (h : α ≃ₜ β) : quotient_map h :=
quotient_map.of_quotient_map_compose h.symm.continuous h.continuous $
by simp only [self_comp_symm, quotient_map.id]
lemma coinduced_eq (h : α ≃ₜ β) : topological_space.coinduced h ‹_› = ‹_› :=
h.quotient_map.2.symm
protected lemma embedding (h : α ≃ₜ β) : embedding h :=
⟨h.inducing, h.injective⟩
/-- Homeomorphism given an embedding. -/
noncomputable def of_embedding (f : α → β) (hf : embedding f) : α ≃ₜ (set.range f) :=
{ continuous_to_fun := continuous_subtype_mk _ hf.continuous,
continuous_inv_fun := by simp [hf.continuous_iff, continuous_subtype_coe],
.. equiv.of_injective f hf.inj }
protected lemma second_countable_topology [topological_space.second_countable_topology β]
(h : α ≃ₜ β) :
topological_space.second_countable_topology α :=
h.inducing.second_countable_topology
lemma compact_image {s : set α} (h : α ≃ₜ β) : is_compact (h '' s) ↔ is_compact s :=
h.embedding.is_compact_iff_is_compact_image.symm
lemma compact_preimage {s : set β} (h : α ≃ₜ β) : is_compact (h ⁻¹' s) ↔ is_compact s :=
by rw ← image_symm; exact h.symm.compact_image
protected lemma dense_embedding (h : α ≃ₜ β) : dense_embedding h :=
{ dense := h.surjective.dense_range,
.. h.embedding }
@[simp] lemma is_open_preimage (h : α ≃ₜ β) {s : set β} : is_open (h ⁻¹' s) ↔ is_open s :=
h.quotient_map.is_open_preimage
@[simp] lemma is_open_image (h : α ≃ₜ β) {s : set α} : is_open (h '' s) ↔ is_open s :=
by rw [← preimage_symm, is_open_preimage]
@[simp] lemma is_closed_preimage (h : α ≃ₜ β) {s : set β} : is_closed (h ⁻¹' s) ↔ is_closed s :=
by simp only [← is_open_compl_iff, ← preimage_compl, is_open_preimage]
@[simp] lemma is_closed_image (h : α ≃ₜ β) {s : set α} : is_closed (h '' s) ↔ is_closed s :=
by rw [← preimage_symm, is_closed_preimage]
lemma preimage_closure (h : α ≃ₜ β) (s : set β) : h ⁻¹' (closure s) = closure (h ⁻¹' s) :=
by rw [h.embedding.closure_eq_preimage_closure_image, h.image_preimage]
lemma image_closure (h : α ≃ₜ β) (s : set α) : h '' (closure s) = closure (h '' s) :=
by rw [← preimage_symm, preimage_closure]
protected lemma is_open_map (h : α ≃ₜ β) : is_open_map h := λ s, h.is_open_image.2
protected lemma is_closed_map (h : α ≃ₜ β) : is_closed_map h := λ s, h.is_closed_image.2
protected lemma closed_embedding (h : α ≃ₜ β) : closed_embedding h :=
closed_embedding_of_embedding_closed h.embedding h.is_closed_map
@[simp] lemma map_nhds_eq (h : α ≃ₜ β) (x : α) : map h (𝓝 x) = 𝓝 (h x) :=
h.embedding.map_nhds_of_mem _ (by simp)
lemma symm_map_nhds_eq (h : α ≃ₜ β) (x : α) : map h.symm (𝓝 (h x)) = 𝓝 x :=
by rw [h.symm.map_nhds_eq, h.symm_apply_apply]
lemma nhds_eq_comap (h : α ≃ₜ β) (x : α) : 𝓝 x = comap h (𝓝 (h x)) :=
h.embedding.to_inducing.nhds_eq_comap x
@[simp] lemma comap_nhds_eq (h : α ≃ₜ β) (y : β) : comap h (𝓝 y) = 𝓝 (h.symm y) :=
by rw [h.nhds_eq_comap, h.apply_symm_apply]
/-- If an bijective map `e : α ≃ β` is continuous and open, then it is a homeomorphism. -/
def homeomorph_of_continuous_open (e : α ≃ β) (h₁ : continuous e) (h₂ : is_open_map e) :
α ≃ₜ β :=
{ continuous_to_fun := h₁,
continuous_inv_fun := begin
rw continuous_def,
intros s hs,
convert ← h₂ s hs using 1,
apply e.image_eq_preimage
end,
to_equiv := e }
@[simp] lemma comp_continuous_on_iff (h : α ≃ₜ β) (f : γ → α) (s : set γ) :
continuous_on (h ∘ f) s ↔ continuous_on f s :=
h.inducing.continuous_on_iff.symm
@[simp] lemma comp_continuous_iff (h : α ≃ₜ β) {f : γ → α} :
continuous (h ∘ f) ↔ continuous f :=
h.inducing.continuous_iff.symm
@[simp] lemma comp_continuous_iff' (h : α ≃ₜ β) {f : β → γ} :
continuous (f ∘ h) ↔ continuous f :=
h.quotient_map.continuous_iff.symm
/-- If two sets are equal, then they are homeomorphic. -/
def set_congr {s t : set α} (h : s = t) : s ≃ₜ t :=
{ continuous_to_fun := continuous_subtype_mk _ continuous_subtype_val,
continuous_inv_fun := continuous_subtype_mk _ continuous_subtype_val,
to_equiv := equiv.set_congr h }
/-- Sum of two homeomorphisms. -/
def sum_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : α ⊕ γ ≃ₜ β ⊕ δ :=
{ continuous_to_fun :=
begin
convert continuous_sum_rec (continuous_inl.comp h₁.continuous)
(continuous_inr.comp h₂.continuous),
ext x, cases x; refl,
end,
continuous_inv_fun :=
begin
convert continuous_sum_rec (continuous_inl.comp h₁.symm.continuous)
(continuous_inr.comp h₂.symm.continuous),
ext x, cases x; refl
end,
to_equiv := h₁.to_equiv.sum_congr h₂.to_equiv }
/-- Product of two homeomorphisms. -/
def prod_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : α × γ ≃ₜ β × δ :=
{ continuous_to_fun := (h₁.continuous.comp continuous_fst).prod_mk
(h₂.continuous.comp continuous_snd),
continuous_inv_fun := (h₁.symm.continuous.comp continuous_fst).prod_mk
(h₂.symm.continuous.comp continuous_snd),
to_equiv := h₁.to_equiv.prod_congr h₂.to_equiv }
@[simp] lemma prod_congr_symm (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) :
(h₁.prod_congr h₂).symm = h₁.symm.prod_congr h₂.symm := rfl
@[simp] lemma coe_prod_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) :
⇑(h₁.prod_congr h₂) = prod.map h₁ h₂ := rfl
section
variables (α β γ)
/-- `α × β` is homeomorphic to `β × α`. -/
def prod_comm : α × β ≃ₜ β × α :=
{ continuous_to_fun := continuous_snd.prod_mk continuous_fst,
continuous_inv_fun := continuous_snd.prod_mk continuous_fst,
to_equiv := equiv.prod_comm α β }
@[simp] lemma prod_comm_symm : (prod_comm α β).symm = prod_comm β α := rfl
@[simp] lemma coe_prod_comm : ⇑(prod_comm α β) = prod.swap := rfl
/-- `(α × β) × γ` is homeomorphic to `α × (β × γ)`. -/
def prod_assoc : (α × β) × γ ≃ₜ α × (β × γ) :=
{ continuous_to_fun := (continuous_fst.comp continuous_fst).prod_mk
((continuous_snd.comp continuous_fst).prod_mk continuous_snd),
continuous_inv_fun := (continuous_fst.prod_mk (continuous_fst.comp continuous_snd)).prod_mk
(continuous_snd.comp continuous_snd),
to_equiv := equiv.prod_assoc α β γ }
/-- `α × {*}` is homeomorphic to `α`. -/
@[simps apply {fully_applied := ff}]
def prod_punit : α × punit ≃ₜ α :=
{ to_equiv := equiv.prod_punit α,
continuous_to_fun := continuous_fst,
continuous_inv_fun := continuous_id.prod_mk continuous_const }
/-- `{*} × α` is homeomorphic to `α`. -/
def punit_prod : punit × α ≃ₜ α :=
(prod_comm _ _).trans (prod_punit _)
@[simp] lemma coe_punit_prod : ⇑(punit_prod α) = prod.snd := rfl
end
/-- `ulift α` is homeomorphic to `α`. -/
def {u v} ulift {α : Type u} [topological_space α] : ulift.{v u} α ≃ₜ α :=
{ continuous_to_fun := continuous_ulift_down,
continuous_inv_fun := continuous_ulift_up,
to_equiv := equiv.ulift }
section distrib
/-- `(α ⊕ β) × γ` is homeomorphic to `α × γ ⊕ β × γ`. -/
def sum_prod_distrib : (α ⊕ β) × γ ≃ₜ α × γ ⊕ β × γ :=
begin
refine (homeomorph.homeomorph_of_continuous_open (equiv.sum_prod_distrib α β γ).symm _ _).symm,
{ convert continuous_sum_rec
((continuous_inl.comp continuous_fst).prod_mk continuous_snd)
((continuous_inr.comp continuous_fst).prod_mk continuous_snd),
ext1 x, cases x; refl, },
{ exact (is_open_map_sum
(open_embedding_inl.prod open_embedding_id).is_open_map
(open_embedding_inr.prod open_embedding_id).is_open_map) }
end
/-- `α × (β ⊕ γ)` is homeomorphic to `α × β ⊕ α × γ`. -/
def prod_sum_distrib : α × (β ⊕ γ) ≃ₜ α × β ⊕ α × γ :=
(prod_comm _ _).trans $
sum_prod_distrib.trans $
sum_congr (prod_comm _ _) (prod_comm _ _)
variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)]
/-- `(Σ i, σ i) × β` is homeomorphic to `Σ i, (σ i × β)`. -/
def sigma_prod_distrib : ((Σ i, σ i) × β) ≃ₜ (Σ i, (σ i × β)) :=
homeomorph.symm $
homeomorph_of_continuous_open (equiv.sigma_prod_distrib σ β).symm
(continuous_sigma $ λ i,
(continuous_sigma_mk.comp continuous_fst).prod_mk continuous_snd)
(is_open_map_sigma $ λ i,
(open_embedding_sigma_mk.prod open_embedding_id).is_open_map)
end distrib
/--
A subset of a topological space is homeomorphic to its image under a homeomorphism.
-/
def image (e : α ≃ₜ β) (s : set α) : s ≃ₜ e '' s :=
{ continuous_to_fun := by continuity!,
continuous_inv_fun := by continuity!,
..e.to_equiv.image s, }
end homeomorph
|
e5398b4ad26d776267a7cb71cd39755294905082 | 367134ba5a65885e863bdc4507601606690974c1 | /src/category_theory/endomorphism.lean | 5b0ef37feb6c2f21cb6ea632d1ad9b82c641b552 | [
"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 | 3,078 | lean | /-
Copyright (c) 2019 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, Scott Morrison, Simon Hudon
Definition and basic properties of endomorphisms and automorphisms of an object in a category.
-/
import category_theory.groupoid
import data.equiv.mul_add
universes v v' u u'
namespace category_theory
/-- Endomorphisms of an object in a category. Arguments order in multiplication agrees with
`function.comp`, not with `category.comp`. -/
def End {C : Type u} [category_struct.{v} C] (X : C) := X ⟶ X
namespace End
section struct
variables {C : Type u} [category_struct.{v} C] (X : C)
instance has_one : has_one (End X) := ⟨𝟙 X⟩
instance inhabited : inhabited (End X) := ⟨𝟙 X⟩
/-- Multiplication of endomorphisms agrees with `function.comp`, not `category_struct.comp`. -/
instance has_mul : has_mul (End X) := ⟨λ x y, y ≫ x⟩
variable {X}
@[simp] lemma one_def : (1 : End X) = 𝟙 X := rfl
@[simp] lemma mul_def (xs ys : End X) : xs * ys = ys ≫ xs := rfl
end struct
/-- Endomorphisms of an object form a monoid -/
instance monoid {C : Type u} [category.{v} C] {X : C} : monoid (End X) :=
{ mul_one := category.id_comp,
one_mul := category.comp_id,
mul_assoc := λ x y z, (category.assoc z y x).symm,
..End.has_mul X, ..End.has_one X }
/-- In a groupoid, endomorphisms form a group -/
instance group {C : Type u} [groupoid.{v} C] (X : C) : group (End X) :=
{ mul_left_inv := groupoid.comp_inv, inv := groupoid.inv, ..End.monoid }
end End
variables {C : Type u} [category.{v} C] (X : C)
/--
Automorphisms of an object in a category.
The order of arguments in multiplication agrees with
`function.comp`, not with `category.comp`.
-/
def Aut (X : C) := X ≅ X
attribute [ext Aut] iso.ext
namespace Aut
instance inhabited : inhabited (Aut X) := ⟨iso.refl X⟩
instance : group (Aut X) :=
by refine { one := iso.refl X,
inv := iso.symm,
mul := flip iso.trans,
div_eq_mul_inv := λ _ _, rfl, .. } ;
simp [flip, (*), has_one.one, monoid.one, has_inv.inv]
/--
Units in the monoid of endomorphisms of an object
are (multiplicatively) equivalent to automorphisms of that object.
-/
def units_End_equiv_Aut : units (End X) ≃* Aut X :=
{ to_fun := λ f, ⟨f.1, f.2, f.4, f.3⟩,
inv_fun := λ f, ⟨f.1, f.2, f.4, f.3⟩,
left_inv := λ ⟨f₁, f₂, f₃, f₄⟩, rfl,
right_inv := λ ⟨f₁, f₂, f₃, f₄⟩, rfl,
map_mul' := λ f g, by rcases f; rcases g; refl }
end Aut
namespace functor
variables {D : Type u'} [category.{v'} D] (f : C ⥤ D) (X)
/-- `f.map` as a monoid hom between endomorphism monoids. -/
def map_End : End X →* End (f.obj X) :=
{ to_fun := functor.map f,
map_mul' := λ x y, f.map_comp y x,
map_one' := f.map_id X }
/-- `f.map_iso` as a group hom between automorphism groups. -/
def map_Aut : Aut X →* Aut (f.obj X) :=
{ to_fun := f.map_iso,
map_mul' := λ x y, f.map_iso_trans y x,
map_one' := f.map_iso_refl X }
end functor
end category_theory
|
437297096de6ea55168dc4a70269a3bcf06e63c1 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/data/equiv/encodable/basic.lean | 4b869596ec91c9f7b9a068d3d397b480af296e90 | [
"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 | 14,737 | 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, Mario Carneiro
Type class for encodable Types.
Note that every encodable Type is countable.
-/
import data.equiv.nat
import order.rel_iso
import order.directed
open option list nat function
/-- An encodable type is a "constructively countable" type. This is where
we have an explicit injection `encode : α → nat` and a partial inverse
`decode : nat → option α`. This makes the range of `encode` decidable,
although it is not decidable if `α` is finite or not. -/
class encodable (α : Type*) :=
(encode : α → nat)
(decode [] : nat → option α)
(encodek : ∀ a, decode (encode a) = some a)
attribute [simp] encodable.encodek
namespace encodable
variables {α : Type*} {β : Type*}
universe u
open encodable
theorem encode_injective [encodable α] : function.injective (@encode α _)
| x y e := option.some.inj $ by rw [← encodek, e, encodek]
/- This is not set as an instance because this is usually not the best way
to infer decidability. -/
def decidable_eq_of_encodable (α) [encodable α] : decidable_eq α
| a b := decidable_of_iff _ encode_injective.eq_iff
def of_left_injection [encodable α]
(f : β → α) (finv : α → option β) (linv : ∀ b, finv (f b) = some b) : encodable β :=
⟨λ b, encode (f b),
λ n, (decode α n).bind finv,
λ b, by simp [encodable.encodek, linv]⟩
def of_left_inverse [encodable α]
(f : β → α) (finv : α → β) (linv : ∀ b, finv (f b) = b) : encodable β :=
of_left_injection f (some ∘ finv) (λ b, congr_arg some (linv b))
/-- If `α` is encodable and `β ≃ α`, then so is `β` -/
def of_equiv (α) [encodable α] (e : β ≃ α) : encodable β :=
of_left_inverse e e.symm e.left_inv
@[simp] theorem encode_of_equiv {α β} [encodable α] (e : β ≃ α) (b : β) :
@encode _ (of_equiv _ e) b = encode (e b) := rfl
@[simp] theorem decode_of_equiv {α β} [encodable α] (e : β ≃ α) (n : ℕ) :
@decode _ (of_equiv _ e) n = (decode α n).map e.symm := rfl
instance nat : encodable nat :=
⟨id, some, λ a, rfl⟩
@[simp] theorem encode_nat (n : ℕ) : encode n = n := rfl
@[simp] theorem decode_nat (n : ℕ) : decode ℕ n = some n := rfl
instance empty : encodable empty :=
⟨λ a, a.rec _, λ n, none, λ a, a.rec _⟩
instance unit : encodable punit :=
⟨λ_, zero, λn, nat.cases_on n (some punit.star) (λ _, none), λ⟨⟩, by simp⟩
@[simp] theorem encode_star : encode punit.star = 0 := rfl
@[simp] theorem decode_unit_zero : decode punit 0 = some punit.star := rfl
@[simp] theorem decode_unit_succ (n) : decode punit (succ n) = none := rfl
instance option {α : Type*} [h : encodable α] : encodable (option α) :=
⟨λ o, option.cases_on o nat.zero (λ a, succ (encode a)),
λ n, nat.cases_on n (some none) (λ m, (decode α m).map some),
λ o, by cases o; dsimp; simp [encodek, nat.succ_ne_zero]⟩
@[simp] theorem encode_none [encodable α] : encode (@none α) = 0 := rfl
@[simp] theorem encode_some [encodable α] (a : α) :
encode (some a) = succ (encode a) := rfl
@[simp] theorem decode_option_zero [encodable α] : decode (option α) 0 = some none := rfl
@[simp] theorem decode_option_succ [encodable α] (n) :
decode (option α) (succ n) = (decode α n).map some := rfl
def decode2 (α) [encodable α] (n : ℕ) : option α :=
(decode α n).bind (option.guard (λ a, encode a = n))
theorem mem_decode2' [encodable α] {n : ℕ} {a : α} :
a ∈ decode2 α n ↔ a ∈ decode α n ∧ encode a = n :=
by simp [decode2]; exact
⟨λ ⟨_, h₁, rfl, h₂⟩, ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨_, h₁, rfl, h₂⟩⟩
theorem mem_decode2 [encodable α] {n : ℕ} {a : α} :
a ∈ decode2 α n ↔ encode a = n :=
mem_decode2'.trans (and_iff_right_of_imp $ λ e, e ▸ encodek _)
theorem decode2_is_partial_inv [encodable α] : is_partial_inv encode (decode2 α) :=
λ a n, mem_decode2
theorem decode2_inj [encodable α] {n : ℕ} {a₁ a₂ : α}
(h₁ : a₁ ∈ decode2 α n) (h₂ : a₂ ∈ decode2 α n) : a₁ = a₂ :=
encode_injective $ (mem_decode2.1 h₁).trans (mem_decode2.1 h₂).symm
theorem encodek2 [encodable α] (a : α) : decode2 α (encode a) = some a :=
mem_decode2.2 rfl
def decidable_range_encode (α : Type*) [encodable α] : decidable_pred (set.range (@encode α _)) :=
λ x, decidable_of_iff (option.is_some (decode2 α x))
⟨λ h, ⟨option.get h, by rw [← decode2_is_partial_inv (option.get h), option.some_get]⟩,
λ ⟨n, hn⟩, by rw [← hn, encodek2]; exact rfl⟩
def equiv_range_encode (α : Type*) [encodable α] : α ≃ set.range (@encode α _) :=
{ to_fun := λ a : α, ⟨encode a, set.mem_range_self _⟩,
inv_fun := λ n, option.get (show is_some (decode2 α n.1),
by cases n.2 with x hx; rw [← hx, encodek2]; exact rfl),
left_inv := λ a, by dsimp;
rw [← option.some_inj, option.some_get, encodek2],
right_inv := λ ⟨n, x, hx⟩, begin
apply subtype.eq,
dsimp,
conv {to_rhs, rw ← hx},
rw [encode_injective.eq_iff, ← option.some_inj, option.some_get, ← hx, encodek2],
end }
section sum
variables [encodable α] [encodable β]
def encode_sum : α ⊕ β → nat
| (sum.inl a) := bit0 $ encode a
| (sum.inr b) := bit1 $ encode b
def decode_sum (n : nat) : option (α ⊕ β) :=
match bodd_div2 n with
| (ff, m) := (decode α m).map sum.inl
| (tt, m) := (decode β m).map sum.inr
end
instance sum : encodable (α ⊕ β) :=
⟨encode_sum, decode_sum, λ s,
by cases s; simp [encode_sum, decode_sum, encodek]; refl⟩
@[simp] theorem encode_inl (a : α) :
@encode (α ⊕ β) _ (sum.inl a) = bit0 (encode a) := rfl
@[simp] theorem encode_inr (b : β) :
@encode (α ⊕ β) _ (sum.inr b) = bit1 (encode b) := rfl
@[simp] theorem decode_sum_val (n : ℕ) :
decode (α ⊕ β) n = decode_sum n := rfl
end sum
instance bool : encodable bool :=
of_equiv (unit ⊕ unit) equiv.bool_equiv_punit_sum_punit
@[simp] theorem encode_tt : encode tt = 1 := rfl
@[simp] theorem encode_ff : encode ff = 0 := rfl
@[simp] theorem decode_zero : decode bool 0 = some ff := rfl
@[simp] theorem decode_one : decode bool 1 = some tt := rfl
theorem decode_ge_two (n) (h : 2 ≤ n) : decode bool n = none :=
begin
suffices : decode_sum n = none,
{ change (decode_sum n).map _ = none, rw this, refl },
have : 1 ≤ div2 n,
{ rw [div2_val, nat.le_div_iff_mul_le],
exacts [h, dec_trivial] },
cases exists_eq_succ_of_ne_zero (ne_of_gt this) with m e,
simp [decode_sum]; cases bodd n; simp [decode_sum]; rw e; refl
end
section sigma
variables {γ : α → Type*} [encodable α] [∀ a, encodable (γ a)]
def encode_sigma : sigma γ → ℕ
| ⟨a, b⟩ := mkpair (encode a) (encode b)
def decode_sigma (n : ℕ) : option (sigma γ) :=
let (n₁, n₂) := unpair n in
(decode α n₁).bind $ λ a, (decode (γ a) n₂).map $ sigma.mk a
instance sigma : encodable (sigma γ) :=
⟨encode_sigma, decode_sigma, λ ⟨a, b⟩,
by simp [encode_sigma, decode_sigma, unpair_mkpair, encodek]⟩
@[simp] theorem decode_sigma_val (n : ℕ) : decode (sigma γ) n =
(decode α n.unpair.1).bind (λ a, (decode (γ a) n.unpair.2).map $ sigma.mk a) :=
show decode_sigma._match_1 _ = _, by cases n.unpair; refl
@[simp] theorem encode_sigma_val (a b) : @encode (sigma γ) _ ⟨a, b⟩ =
mkpair (encode a) (encode b) := rfl
end sigma
section prod
variables [encodable α] [encodable β]
instance prod : encodable (α × β) :=
of_equiv _ (equiv.sigma_equiv_prod α β).symm
@[simp] theorem decode_prod_val (n : ℕ) : decode (α × β) n =
(decode α n.unpair.1).bind (λ a, (decode β n.unpair.2).map $ prod.mk a) :=
show (decode (sigma (λ _, β)) n).map (equiv.sigma_equiv_prod α β) = _,
by simp; cases decode α n.unpair.1; simp;
cases decode β n.unpair.2; refl
@[simp] theorem encode_prod_val (a b) : @encode (α × β) _ (a, b) =
mkpair (encode a) (encode b) := rfl
end prod
section subtype
open subtype decidable
variable {P : α → Prop}
variable [encA : encodable α]
variable [decP : decidable_pred P]
include encA
def encode_subtype : {a : α // P a} → nat
| ⟨v, h⟩ := encode v
include decP
def decode_subtype (v : nat) : option {a : α // P a} :=
(decode α v).bind $ λ a,
if h : P a then some ⟨a, h⟩ else none
instance subtype : encodable {a : α // P a} :=
⟨encode_subtype, decode_subtype,
λ ⟨v, h⟩, by simp [encode_subtype, decode_subtype, encodek, h]⟩
lemma subtype.encode_eq (a : subtype P) : encode a = encode a.val :=
by cases a; refl
end subtype
instance fin (n) : encodable (fin n) :=
of_equiv _ (equiv.fin_equiv_subtype _)
instance int : encodable ℤ :=
of_equiv _ equiv.int_equiv_nat
instance ulift [encodable α] : encodable (ulift α) :=
of_equiv _ equiv.ulift
instance plift [encodable α] : encodable (plift α) :=
of_equiv _ equiv.plift
noncomputable def of_inj [encodable β] (f : α → β) (hf : injective f) : encodable α :=
of_left_injection f (partial_inv f) (λ x, (partial_inv_of_injective hf _ _).2 rfl)
end encodable
section ulower
local attribute [instance, priority 100] encodable.decidable_range_encode
/--
`ulower α : Type 0` is an equivalent type in the lowest universe, given `encodable α`.
-/
@[derive decidable_eq, derive encodable]
def ulower (α : Type*) [encodable α] : Type :=
set.range (encodable.encode : α → ℕ)
end ulower
namespace ulower
variables (α : Type*) [encodable α]
/--
The equivalence between the encodable type `α` and `ulower α : Type 0`.
-/
def equiv : α ≃ ulower α :=
encodable.equiv_range_encode α
variables {α}
/--
Lowers an `a : α` into `ulower α`.
-/
def down (a : α) : ulower α := equiv α a
instance [inhabited α] : inhabited (ulower α) := ⟨down (default _)⟩
/--
Lifts an `a : ulower α` into `α`.
-/
def up (a : ulower α) : α := (equiv α).symm a
@[simp] lemma down_up {a : ulower α} : down a.up = a := equiv.right_inv _ _
@[simp] lemma up_down {a : α} : (down a).up = a := equiv.left_inv _ _
@[simp] lemma up_eq_up {a b : ulower α} : a.up = b.up ↔ a = b :=
equiv.apply_eq_iff_eq _ _ _
@[simp] lemma down_eq_down {a b : α} : down a = down b ↔ a = b :=
equiv.apply_eq_iff_eq _ _ _
@[ext] protected lemma ext {a b : ulower α} : a.up = b.up → a = b :=
up_eq_up.1
end ulower
/-
Choice function for encodable types and decidable predicates.
We provide the following API
choose {α : Type*} {p : α → Prop} [c : encodable α] [d : decidable_pred p] : (∃ x, p x) → α :=
choose_spec {α : Type*} {p : α → Prop} [c : encodable α] [d : decidable_pred p] (ex : ∃ x, p x) :
p (choose ex) :=
-/
namespace encodable
section find_a
variables {α : Type*} (p : α → Prop) [encodable α] [decidable_pred p]
private def good : option α → Prop
| (some a) := p a
| none := false
private def decidable_good : decidable_pred (good p)
| n := by cases n; unfold good; apply_instance
local attribute [instance] decidable_good
open encodable
variable {p}
def choose_x (h : ∃ x, p x) : {a:α // p a} :=
have ∃ n, good p (decode α n), from
let ⟨w, pw⟩ := h in ⟨encode w, by simp [good, encodek, pw]⟩,
match _, nat.find_spec this : ∀ o, good p o → {a // p a} with
| some a, h := ⟨a, h⟩
end
def choose (h : ∃ x, p x) : α := (choose_x h).1
lemma choose_spec (h : ∃ x, p x) : p (choose h) := (choose_x h).2
end find_a
theorem axiom_of_choice {α : Type*} {β : α → Type*} {R : Π x, β x → Prop}
[Π a, encodable (β a)] [∀ x y, decidable (R x y)]
(H : ∀x, ∃y, R x y) : ∃f:Πa, β a, ∀x, R x (f x) :=
⟨λ x, choose (H x), λ x, choose_spec (H x)⟩
theorem skolem {α : Type*} {β : α → Type*} {P : Π x, β x → Prop}
[c : Π a, encodable (β a)] [d : ∀ x y, decidable (P x y)] :
(∀x, ∃y, P x y) ↔ ∃f : Π a, β a, (∀x, P x (f x)) :=
⟨axiom_of_choice, λ ⟨f, H⟩ x, ⟨_, H x⟩⟩
/-
There is a total ordering on the elements of an encodable type, induced by the map to ℕ.
-/
/-- The `encode` function, viewed as an embedding. -/
def encode' (α) [encodable α] : α ↪ nat :=
⟨encodable.encode, encodable.encode_injective⟩
instance {α} [encodable α] : is_trans _ (encode' α ⁻¹'o (≤)) :=
(rel_embedding.preimage _ _).is_trans
instance {α} [encodable α] : is_antisymm _ (encodable.encode' α ⁻¹'o (≤)) :=
(rel_embedding.preimage _ _).is_antisymm
instance {α} [encodable α] : is_total _ (encodable.encode' α ⁻¹'o (≤)) :=
(rel_embedding.preimage _ _).is_total
end encodable
namespace directed
open encodable
variables {α : Type*} {β : Type*} [encodable α] [inhabited α]
/-- Given a `directed r` function `f : α → β` defined on an encodable inhabited type,
construct a noncomputable sequence such that `r (f (x n)) (f (x (n + 1)))`
and `r (f a) (f (x (encode a + 1))`. -/
protected noncomputable def sequence {r : β → β → Prop} (f : α → β) (hf : directed r f) : ℕ → α
| 0 := default α
| (n + 1) :=
let p := sequence n in
match decode α n with
| none := classical.some (hf p p)
| (some a) := classical.some (hf p a)
end
lemma sequence_mono_nat {r : β → β → Prop} {f : α → β} (hf : directed r f) (n : ℕ) :
r (f (hf.sequence f n)) (f (hf.sequence f (n+1))) :=
begin
dsimp [directed.sequence],
generalize eq : hf.sequence f n = p,
cases h : decode α n with a,
{ exact (classical.some_spec (hf p p)).1 },
{ exact (classical.some_spec (hf p a)).1 }
end
lemma rel_sequence {r : β → β → Prop} {f : α → β} (hf : directed r f) (a : α) :
r (f a) (f (hf.sequence f (encode a + 1))) :=
begin
simp only [directed.sequence, encodek],
exact (classical.some_spec (hf _ a)).2
end
variables [preorder β] {f : α → β} (hf : directed (≤) f)
lemma sequence_mono : monotone (f ∘ (hf.sequence f)) :=
monotone_of_monotone_nat $ hf.sequence_mono_nat
lemma le_sequence (a : α) : f a ≤ f (hf.sequence f (encode a + 1)) :=
hf.rel_sequence a
end directed
section quotient
open encodable quotient
variables {α : Type*} {s : setoid α} [@decidable_rel α (≈)] [encodable α]
/-- Representative of an equivalence class. This is a computable version of `quot.out` for a setoid
on an encodable type. -/
def quotient.rep (q : quotient s) : α :=
choose (exists_rep q)
theorem quotient.rep_spec (q : quotient s) : ⟦q.rep⟧ = q :=
choose_spec (exists_rep q)
/-- The quotient of an encodable space by a decidable equivalence relation is encodable. -/
def encodable_quotient : encodable (quotient s) :=
⟨λ q, encode q.rep,
λ n, quotient.mk <$> decode α n,
by rintros ⟨l⟩; rw encodek; exact congr_arg some ⟦l⟧.rep_spec⟩
end quotient
|
cbc52cc63a57197b07677a54781dd2e3f01e4ec8 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/analysis/special_functions/exp_deriv.lean | eccbb6494a222deb640cc5327ff42cadb2eaa055 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 10,469 | 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.calculus.inverse
import analysis.complex.real_deriv
import analysis.special_functions.exp
/-!
# Complex and real exponential
In this file we prove that `complex.exp` and `real.exp` are infinitely smooth functions.
## Tags
exp, derivative
-/
noncomputable theory
open filter asymptotics set function
open_locale classical topological_space
namespace complex
/-- The complex exponential is everywhere differentiable, with the derivative `exp x`. -/
lemma has_deriv_at_exp (x : ℂ) : has_deriv_at exp (exp x) x :=
begin
rw has_deriv_at_iff_is_o_nhds_zero,
have : (1 : ℕ) < 2 := by norm_num,
refine (is_O.of_bound (∥exp x∥) _).trans_is_o (is_o_pow_id this),
filter_upwards [metric.ball_mem_nhds (0 : ℂ) zero_lt_one],
simp only [metric.mem_ball, dist_zero_right, norm_pow],
exact λ z hz, exp_bound_sq x z hz.le,
end
lemma differentiable_exp : differentiable ℂ exp :=
λx, (has_deriv_at_exp x).differentiable_at
lemma differentiable_at_exp {x : ℂ} : differentiable_at ℂ exp x :=
differentiable_exp x
@[simp] lemma deriv_exp : deriv exp = exp :=
funext $ λ x, (has_deriv_at_exp x).deriv
@[simp] lemma iter_deriv_exp : ∀ n : ℕ, (deriv^[n] exp) = exp
| 0 := rfl
| (n+1) := by rw [iterate_succ_apply, deriv_exp, iter_deriv_exp n]
lemma cont_diff_exp : ∀ {n}, cont_diff ℂ n exp :=
begin
refine cont_diff_all_iff_nat.2 (λ n, _),
induction n with n ihn,
{ exact cont_diff_zero.2 continuous_exp },
{ rw cont_diff_succ_iff_deriv,
use differentiable_exp,
rwa deriv_exp }
end
lemma has_strict_deriv_at_exp (x : ℂ) : has_strict_deriv_at exp (exp x) x :=
cont_diff_exp.cont_diff_at.has_strict_deriv_at' (has_deriv_at_exp x) le_rfl
lemma has_strict_fderiv_at_exp_real (x : ℂ) :
has_strict_fderiv_at exp (exp x • (1 : ℂ →L[ℝ] ℂ)) x :=
(has_strict_deriv_at_exp x).complex_to_real_fderiv
lemma is_open_map_exp : is_open_map exp :=
open_map_of_strict_deriv has_strict_deriv_at_exp exp_ne_zero
end complex
section
variables {f : ℂ → ℂ} {f' x : ℂ} {s : set ℂ}
lemma has_strict_deriv_at.cexp (hf : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ x, complex.exp (f x)) (complex.exp (f x) * f') x :=
(complex.has_strict_deriv_at_exp (f x)).comp x hf
lemma has_deriv_at.cexp (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, complex.exp (f x)) (complex.exp (f x) * f') x :=
(complex.has_deriv_at_exp (f x)).comp x hf
lemma has_deriv_within_at.cexp (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, complex.exp (f x)) (complex.exp (f x) * f') s x :=
(complex.has_deriv_at_exp (f x)).comp_has_deriv_within_at x hf
lemma deriv_within_cexp (hf : differentiable_within_at ℂ f s x)
(hxs : unique_diff_within_at ℂ s x) :
deriv_within (λx, complex.exp (f x)) s x = complex.exp (f x) * (deriv_within f s x) :=
hf.has_deriv_within_at.cexp.deriv_within hxs
@[simp] lemma deriv_cexp (hc : differentiable_at ℂ f x) :
deriv (λx, complex.exp (f x)) x = complex.exp (f x) * (deriv f x) :=
hc.has_deriv_at.cexp.deriv
end
section
variables {f : ℝ → ℂ} {f' : ℂ} {x : ℝ} {s : set ℝ}
open complex
lemma has_strict_deriv_at.cexp_real (h : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ x, exp (f x)) (exp (f x) * f') x :=
(has_strict_fderiv_at_exp_real (f x)).comp_has_strict_deriv_at x h
lemma has_deriv_at.cexp_real (h : has_deriv_at f f' x) :
has_deriv_at (λ x, exp (f x)) (exp (f x) * f') x :=
(has_strict_fderiv_at_exp_real (f x)).has_fderiv_at.comp_has_deriv_at x h
lemma has_deriv_within_at.cexp_real (h : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, exp (f x)) (exp (f x) * f') s x :=
(has_strict_fderiv_at_exp_real (f x)).has_fderiv_at.comp_has_deriv_within_at x h
end
section
variables {E : Type*} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {f' : E →L[ℂ] ℂ}
{x : E} {s : set E}
lemma has_strict_fderiv_at.cexp (hf : has_strict_fderiv_at f f' x) :
has_strict_fderiv_at (λ x, complex.exp (f x)) (complex.exp (f x) • f') x :=
(complex.has_strict_deriv_at_exp (f x)).comp_has_strict_fderiv_at x hf
lemma has_fderiv_within_at.cexp (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (λ x, complex.exp (f x)) (complex.exp (f x) • f') s x :=
(complex.has_deriv_at_exp (f x)).comp_has_fderiv_within_at x hf
lemma has_fderiv_at.cexp (hf : has_fderiv_at f f' x) :
has_fderiv_at (λ x, complex.exp (f x)) (complex.exp (f x) • f') x :=
has_fderiv_within_at_univ.1 $ hf.has_fderiv_within_at.cexp
lemma differentiable_within_at.cexp (hf : differentiable_within_at ℂ f s x) :
differentiable_within_at ℂ (λ x, complex.exp (f x)) s x :=
hf.has_fderiv_within_at.cexp.differentiable_within_at
@[simp] lemma differentiable_at.cexp (hc : differentiable_at ℂ f x) :
differentiable_at ℂ (λx, complex.exp (f x)) x :=
hc.has_fderiv_at.cexp.differentiable_at
lemma differentiable_on.cexp (hc : differentiable_on ℂ f s) :
differentiable_on ℂ (λx, complex.exp (f x)) s :=
λx h, (hc x h).cexp
@[simp] lemma differentiable.cexp (hc : differentiable ℂ f) :
differentiable ℂ (λx, complex.exp (f x)) :=
λx, (hc x).cexp
lemma cont_diff.cexp {n} (h : cont_diff ℂ n f) :
cont_diff ℂ n (λ x, complex.exp (f x)) :=
complex.cont_diff_exp.comp h
lemma cont_diff_at.cexp {n} (hf : cont_diff_at ℂ n f x) :
cont_diff_at ℂ n (λ x, complex.exp (f x)) x :=
complex.cont_diff_exp.cont_diff_at.comp x hf
lemma cont_diff_on.cexp {n} (hf : cont_diff_on ℂ n f s) :
cont_diff_on ℂ n (λ x, complex.exp (f x)) s :=
complex.cont_diff_exp.comp_cont_diff_on hf
lemma cont_diff_within_at.cexp {n} (hf : cont_diff_within_at ℂ n f s x) :
cont_diff_within_at ℂ n (λ x, complex.exp (f x)) s x :=
complex.cont_diff_exp.cont_diff_at.comp_cont_diff_within_at x hf
end
namespace real
variables {x y z : ℝ}
lemma has_strict_deriv_at_exp (x : ℝ) : has_strict_deriv_at exp (exp x) x :=
(complex.has_strict_deriv_at_exp x).real_of_complex
lemma has_deriv_at_exp (x : ℝ) : has_deriv_at exp (exp x) x :=
(complex.has_deriv_at_exp x).real_of_complex
lemma cont_diff_exp {n} : cont_diff ℝ n exp :=
complex.cont_diff_exp.real_of_complex
lemma differentiable_exp : differentiable ℝ exp :=
λx, (has_deriv_at_exp x).differentiable_at
lemma differentiable_at_exp : differentiable_at ℝ exp x :=
differentiable_exp x
@[simp] lemma deriv_exp : deriv exp = exp :=
funext $ λ x, (has_deriv_at_exp x).deriv
@[simp] lemma iter_deriv_exp : ∀ n : ℕ, (deriv^[n] exp) = exp
| 0 := rfl
| (n+1) := by rw [iterate_succ_apply, deriv_exp, iter_deriv_exp n]
end real
section
/-! Register lemmas for the derivatives of the composition of `real.exp` with a differentiable
function, for standalone use and use with `simp`. -/
variables {f : ℝ → ℝ} {f' x : ℝ} {s : set ℝ}
lemma has_strict_deriv_at.exp (hf : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ x, real.exp (f x)) (real.exp (f x) * f') x :=
(real.has_strict_deriv_at_exp (f x)).comp x hf
lemma has_deriv_at.exp (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, real.exp (f x)) (real.exp (f x) * f') x :=
(real.has_deriv_at_exp (f x)).comp x hf
lemma has_deriv_within_at.exp (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, real.exp (f x)) (real.exp (f x) * f') s x :=
(real.has_deriv_at_exp (f x)).comp_has_deriv_within_at x hf
lemma deriv_within_exp (hf : differentiable_within_at ℝ f s x)
(hxs : unique_diff_within_at ℝ s x) :
deriv_within (λx, real.exp (f x)) s x = real.exp (f x) * (deriv_within f s x) :=
hf.has_deriv_within_at.exp.deriv_within hxs
@[simp] lemma deriv_exp (hc : differentiable_at ℝ f x) :
deriv (λx, real.exp (f x)) x = real.exp (f x) * (deriv f x) :=
hc.has_deriv_at.exp.deriv
end
section
/-! Register lemmas for the derivatives of the composition of `real.exp` with a differentiable
function, for standalone use and use with `simp`. -/
variables {E : Type*} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {f' : E →L[ℝ] ℝ}
{x : E} {s : set E}
lemma cont_diff.exp {n} (hf : cont_diff ℝ n f) :
cont_diff ℝ n (λ x, real.exp (f x)) :=
real.cont_diff_exp.comp hf
lemma cont_diff_at.exp {n} (hf : cont_diff_at ℝ n f x) :
cont_diff_at ℝ n (λ x, real.exp (f x)) x :=
real.cont_diff_exp.cont_diff_at.comp x hf
lemma cont_diff_on.exp {n} (hf : cont_diff_on ℝ n f s) :
cont_diff_on ℝ n (λ x, real.exp (f x)) s :=
real.cont_diff_exp.comp_cont_diff_on hf
lemma cont_diff_within_at.exp {n} (hf : cont_diff_within_at ℝ n f s x) :
cont_diff_within_at ℝ n (λ x, real.exp (f x)) s x :=
real.cont_diff_exp.cont_diff_at.comp_cont_diff_within_at x hf
lemma has_fderiv_within_at.exp (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (λ x, real.exp (f x)) (real.exp (f x) • f') s x :=
(real.has_deriv_at_exp (f x)).comp_has_fderiv_within_at x hf
lemma has_fderiv_at.exp (hf : has_fderiv_at f f' x) :
has_fderiv_at (λ x, real.exp (f x)) (real.exp (f x) • f') x :=
(real.has_deriv_at_exp (f x)).comp_has_fderiv_at x hf
lemma has_strict_fderiv_at.exp (hf : has_strict_fderiv_at f f' x) :
has_strict_fderiv_at (λ x, real.exp (f x)) (real.exp (f x) • f') x :=
(real.has_strict_deriv_at_exp (f x)).comp_has_strict_fderiv_at x hf
lemma differentiable_within_at.exp (hf : differentiable_within_at ℝ f s x) :
differentiable_within_at ℝ (λ x, real.exp (f x)) s x :=
hf.has_fderiv_within_at.exp.differentiable_within_at
@[simp] lemma differentiable_at.exp (hc : differentiable_at ℝ f x) :
differentiable_at ℝ (λx, real.exp (f x)) x :=
hc.has_fderiv_at.exp.differentiable_at
lemma differentiable_on.exp (hc : differentiable_on ℝ f s) :
differentiable_on ℝ (λx, real.exp (f x)) s :=
λ x h, (hc x h).exp
@[simp] lemma differentiable.exp (hc : differentiable ℝ f) :
differentiable ℝ (λx, real.exp (f x)) :=
λ x, (hc x).exp
lemma fderiv_within_exp (hf : differentiable_within_at ℝ f s x)
(hxs : unique_diff_within_at ℝ s x) :
fderiv_within ℝ (λx, real.exp (f x)) s x = real.exp (f x) • (fderiv_within ℝ f s x) :=
hf.has_fderiv_within_at.exp.fderiv_within hxs
@[simp] lemma fderiv_exp (hc : differentiable_at ℝ f x) :
fderiv ℝ (λx, real.exp (f x)) x = real.exp (f x) • (fderiv ℝ f x) :=
hc.has_fderiv_at.exp.fderiv
end
|
7ae4195ebbb238ace4d2cbf47830a590c01aba0d | fe84e287c662151bb313504482b218a503b972f3 | /src/poset/basic.lean | 0492273e839d3f8251c0e571e2372b59980b06db | [] | no_license | NeilStrickland/lean_lib | 91e163f514b829c42fe75636407138b5c75cba83 | 6a9563de93748ace509d9db4302db6cd77d8f92c | refs/heads/master | 1,653,408,198,261 | 1,652,996,419,000 | 1,652,996,419,000 | 181,006,067 | 4 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 16,296 | lean | /-
Copyright (c) 2019 Neil Strickland. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Neil Strickland
This file effectively deals with the cartesian-closed category
of finite posets and the associated "strong homotopy category".
However, we have taken an ad hoc approach rather than using the
category theory library.
-/
import order.basic order.sort_rank
import logic.equiv.basic
import data.fintype.basic data.fin_extra
import logic.relation
import algebra.punit_instances
universes uP uQ uR uS
variables (P : Type uP) [partial_order P]
variables (Q : Type uQ) [partial_order Q]
variables (R : Type uR) [partial_order R]
variables (S : Type uS) [partial_order S]
namespace poset
structure hom :=
(val : P → Q)
(property : monotone val)
instance : has_coe_to_fun (hom P Q) (λ _, P → Q) := {
coe := λ f, f.val
}
@[ext]
lemma hom_ext (f g : hom P Q) :
(∀ (p : P), f p = g p) → f = g :=
begin
rcases f with ⟨f,hf⟩,
rcases g with ⟨g,hg⟩,
intro h,
have h' : f = g := funext h,
rcases h', refl,
end
def id : hom P P := ⟨_root_.id,monotone_id⟩
lemma id_val : (id P).val = _root_.id := rfl
variables {P Q R}
instance hom_order : partial_order (hom P Q) := {
le := λ f g, ∀ p, (f p) ≤ (g p),
le_refl := λ f p,le_refl (f p),
le_antisymm := λ f g f_le_g g_le_f,
begin ext p, exact le_antisymm (f_le_g p) (g_le_f p), end,
le_trans := λ f g h f_le_g g_le_h p,
le_trans (f_le_g p) (g_le_h p)
}
@[simp]
lemma id_eval (p : P) : (id P) p = p := rfl
variable (P)
def const (q : Q) : hom P Q := ⟨λ p,q, λ p₀ p₁ hp, le_refl q⟩
def terminal : hom P punit.{uP + 1} := const P punit.star
variable {P}
lemma eq_terminal (f : hom P punit.{uP + 1}) : f = terminal P := by { ext p }
@[irreducible]
def adjoint (f : hom P Q) (g : hom Q P) : Prop :=
∀ {p : P} {q : Q}, f p ≤ q ↔ p ≤ g q
def adjoint.iff {f : hom P Q} {g : hom Q P} (h : adjoint f g) :
∀ {p : P} {q : Q}, f p ≤ q ↔ p ≤ g q :=
by { intros p q, unfold adjoint at h, exact h }
def comp : (hom Q R) → (hom P Q) → (hom P R) :=
λ g f, ⟨g.val ∘ f.val, monotone.comp g.property f.property⟩
lemma comp_val (g : hom Q R) (f : hom P Q) :
(comp g f).val = g.val ∘ f.val := rfl
lemma id_comp (f : hom P Q) : comp (id Q) f = f := by {ext, refl}
lemma comp_id (f : hom P Q) : comp f (id P) = f := by {ext, refl}
lemma comp_assoc (h : hom R S) (g : hom Q R) (f : hom P Q) :
comp (comp h g) f = comp h (comp g f) := by {ext, refl}
lemma const_comp (r : R) (f : hom P Q) :
comp (const Q r) f = const P r := by {ext, refl}
lemma comp_const (g : hom Q R) (q : Q) :
comp g (const P q) = const P (g q) := by {ext, refl}
lemma comp_mono₂ {g₀ g₁ : hom Q R} {f₀ f₁ : hom P Q}
(eg : g₀ ≤ g₁) (ef : f₀ ≤ f₁) : comp g₀ f₀ ≤ comp g₁ f₁ :=
λ p, calc
g₀.val (f₀.val p) ≤ g₀.val (f₁.val p) : g₀.property (ef p)
... ≤ g₁.val (f₁.val p) : eg (f₁.val p)
@[simp]
lemma comp_eval (g : hom Q R) (f : hom P Q) (p : P) :
(comp g f) p = g (f p) := rfl
def comp' : (hom Q R) × (hom P Q) → (hom P R) :=
λ ⟨g,f⟩, comp g f
lemma comp'_mono : monotone (@comp' P _ Q _ R _) :=
λ ⟨g₀,f₀⟩ ⟨g₁,f₁⟩ ⟨eg,ef⟩, comp_mono₂ eg ef
def eval : (hom P Q) → P → Q := λ f p, f.val p
lemma eval_mono₂ {f₀ f₁ : hom P Q} {p₀ p₁ : P}
(ef : f₀ ≤ f₁) (ep : p₀ ≤ p₁) : eval f₀ p₀ ≤ eval f₁ p₁ :=
calc
f₀.val p₀ ≤ f₀.val p₁ : f₀.property ep
... ≤ f₁.val p₁ : ef p₁
def eval' : (hom P Q) × P → Q := λ ⟨f,p⟩, eval f p
lemma eval'_mono : monotone (@eval' P _ Q _) :=
λ ⟨f₀,p₀⟩ ⟨f₁,p₁⟩ ⟨ef,ep⟩, eval_mono₂ ef ep
def ins' : P → (hom Q (P × Q)) :=
λ p, ⟨λ q,⟨p,q⟩, λ q₀ q₁ eq, ⟨le_refl p,eq⟩⟩
lemma ins_mono : monotone (@ins' P _ Q _) :=
λ p₀ p₁ ep q, ⟨ep,le_refl q⟩
lemma adjoint.unit {f : hom P Q} {g : hom Q P} (h : adjoint f g) :
id P ≤ comp g f := λ p, h.iff.mp (le_refl (f p))
lemma adjoint.counit {f : hom P Q} {g : hom Q P} (h : adjoint f g) :
comp f g ≤ id Q := λ q, h.iff.mpr (le_refl (g q))
variable (P)
def π₀ : Type* := quot (has_le.le : P → P → Prop)
variable {P}
def component (p : P) : π₀ P := quot.mk _ p
def connected : P → P → Prop := λ p₀ p₁, component p₀ = component p₁
lemma π₀.sound {p₀ p₁ : P} (hp : p₀ ≤ p₁) :
component p₀ = component p₁ := quot.sound hp
lemma π₀.epi {X : Type*} (f₀ f₁ : π₀ P → X)
(h : ∀ p, f₀ (component p) = f₁ (component p)) : f₀ = f₁ :=
by {apply funext, rintro ⟨p⟩, exact (h p),}
def π₀.lift {X : Type*} (f : P → X)
(h : ∀ p₀ p₁ : P, p₀ ≤ p₁ → f p₀ = f p₁) :
(π₀ P) → X := @quot.lift P has_le.le X f h
lemma π₀.lift_beta {X : Type*} (f : P → X)
(h : ∀ p₀ p₁ : P, p₀ ≤ p₁ → f p₀ = f p₁) (p : P) :
π₀.lift f h (component p) = f p :=
@quot.lift_beta P has_le.le X f h p
def π₀.lift₂ {X : Type*} (f : P → Q → X)
(h : ∀ p₀ p₁ q₀ q₁, p₀ ≤ p₁ → q₀ ≤ q₁ → f p₀ q₀ = f p₁ q₁) :
(π₀ P) → (π₀ Q) → X :=
begin
let h1 := λ p q₀ q₁ hq, h p p q₀ q₁ (le_refl p) hq,
let f1 : P → (π₀ Q) → X := λ p, π₀.lift (f p) (h1 p),
let hf1 : ∀ p q, f1 p (component q) = f p q := λ p, π₀.lift_beta (f p) (h1 p),
let h2 : ∀ p₀ p₁, p₀ ≤ p₁ → f1 p₀ = f1 p₁ := λ p₀ p₁ hp,
begin
apply π₀.epi,intro q,rw[hf1,hf1],
exact h p₀ p₁ q q hp (le_refl q),
end,
exact π₀.lift f1 h2
end
lemma π₀.lift₂_beta {X : Type*} (f : P → Q → X)
(h : ∀ p₀ p₁ q₀ q₁, p₀ ≤ p₁ → q₀ ≤ q₁ → f p₀ q₀ = f p₁ q₁)
(p : P) (q : Q) : (π₀.lift₂ f h) (component p) (component q) = f p q :=
begin
unfold π₀.lift₂,simp only [],rw[π₀.lift_beta,π₀.lift_beta],
end
lemma parity_induction (u : ℕ → Prop)
(h_zero : u 0)
(h_even : ∀ i, u (2 * i) → u (2 * i + 1))
(h_odd : ∀ i, u (2 * i + 1) → u (2 * i + 2)) :
∀ i, u i
| 0 := h_zero
| (i + 1) :=
begin
have ih := parity_induction i,
let k := i.div2,
have hi : cond i.bodd 1 0 + 2 * k = i := nat.bodd_add_div2 i,
rcases i.bodd ; intro hk; rw[cond] at hk,
{ rw [zero_add] at hk,
rw [← hk] at ih ⊢,
exact h_even k ih },
{ rw [add_comm] at hk,
rw [← hk] at ih ⊢,
exact h_odd k ih }
end
lemma zigzag (u : ℕ → P)
(h_even : ∀ i, u (2 * i) ≤ u (2 * i + 1))
(h_odd : ∀ i, u (2 * i + 2) ≤ u(2 * i + 1)) :
∀ i, component (u i) = component (u 0) :=
parity_induction
(λ i, component (u i) = component (u 0))
rfl
(λ i h, (π₀.sound (h_even i)).symm.trans h)
(λ i h, (π₀.sound (h_odd i)).trans h)
variables (P Q)
def homₕ := π₀ (hom P Q)
def idₕ : homₕ P P := component (id P)
variables {P Q}
def compₕ : (homₕ Q R) → (homₕ P Q) → (homₕ P R) :=
π₀.lift₂ (λ g f, component (comp g f)) (begin
intros g₀ g₁ f₀ f₁ hg hf,
let hgf := comp_mono₂ hg hf,
let hgf' := π₀.sound hgf,
exact (π₀.sound (comp_mono₂ hg hf))
end)
lemma compₕ_def (g : hom Q R) (f : hom P Q) :
compₕ (component g) (component f) = component (comp g f) :=
by {simp[compₕ,π₀.lift₂_beta]}
lemma id_compₕ (f : homₕ P Q) : compₕ (idₕ Q) f = f :=
begin
rcases f with ⟨f⟩,
change compₕ (component (id Q)) (component f) = component f,
rw[compₕ_def,id_comp],
end
lemma comp_idₕ (f : homₕ P Q) : compₕ f (idₕ P) = f :=
begin
rcases f with ⟨f⟩,
change compₕ (component f) (component (id P)) = component f,
rw[compₕ_def,comp_id],
end
lemma comp_assocₕ (h : homₕ R S) (g : homₕ Q R) (f : homₕ P Q) :
compₕ (compₕ h g) f = compₕ h (compₕ g f) :=
begin
rcases h with ⟨h⟩, rcases g with ⟨g⟩, rcases f with ⟨f⟩,
change compₕ (compₕ (component h) (component g)) (component f) =
compₕ (component h) (compₕ (component g) (component f)),
repeat {rw[compₕ_def]},rw[comp_assoc],
end
variables (P Q)
structure equivₕ :=
(to_fun : homₕ P Q)
(inv_fun : homₕ Q P)
(left_inv : compₕ inv_fun to_fun = idₕ P)
(right_inv : compₕ to_fun inv_fun = idₕ Q)
@[refl] def equivₕ.refl : equivₕ P P :=
{ to_fun := idₕ P, inv_fun := idₕ P,
left_inv := comp_idₕ _,
right_inv := comp_idₕ _ }
variables {P Q}
@[symm] def equivₕ.symm (e : equivₕ P Q) : equivₕ Q P :=
{ to_fun := e.inv_fun, inv_fun := e.to_fun,
left_inv := e.right_inv, right_inv := e.left_inv }
@[trans] def equivₕ.trans (e : equivₕ P Q) (f : equivₕ Q R) : (equivₕ P R) :=
{ to_fun := compₕ f.to_fun e.to_fun,
inv_fun := compₕ e.inv_fun f.inv_fun,
left_inv := by
rw [comp_assocₕ, ← comp_assocₕ _ f.inv_fun, f.left_inv,
id_compₕ, e.left_inv],
right_inv := by
rw [comp_assocₕ, ← comp_assocₕ _ e.to_fun, e.right_inv,
id_compₕ, f.right_inv] }
lemma adjoint.unitₕ {f : hom P Q} {g : hom Q P} (h : adjoint f g) :
compₕ (component g) (component f) = idₕ P :=
begin
have : id P ≤ comp g f := by { apply adjoint.unit, assumption },
exact (π₀.sound this).symm
end
lemma adjoint.counitₕ {f : hom P Q} {g : hom Q P} (h : adjoint f g) :
compₕ (component f) (component g) = idₕ Q :=
begin
have : comp f g ≤ id Q := by { apply adjoint.counit, assumption },
exact (π₀.sound this)
end
/-- LaTeX: rem-adjoint-strong -/
def equivₕ_of_adjoint {f : hom P Q} {g : hom Q P} (h : adjoint f g) :
equivₕ P Q :=
{ to_fun := component f,
inv_fun := component g,
left_inv := adjoint.unitₕ h,
right_inv := adjoint.counitₕ h }
variable (P)
/-- defn-strongly-contractible -/
def contractibleₕ := nonempty (equivₕ P punit.{uP + 1})
variable {P}
lemma contractibleₕ_of_smallest {m : P} (h : ∀ p, m ≤ p) : contractibleₕ P :=
begin
have : adjoint (const punit.{uP + 1} m) (terminal P) :=
begin
unfold adjoint,
rintro ⟨⟩ p,
change m ≤ p ↔ punit.star ≤ punit.star,
simp only [le_refl, h p],
end,
let hh := equivₕ_of_adjoint this,
exact ⟨hh.symm⟩,
end
def π₀.map (f : hom P Q) : (π₀ P) → (π₀ Q) :=
π₀.lift (λ p, component (f p)) (λ p₀ p₁ ep, quot.sound (f.property ep))
lemma π₀.map_def (f : hom P Q) (p : P) : π₀.map f (component p) = component (f p) :=
by { simp [π₀.map, π₀.lift_beta] }
lemma π₀.map_congr {f₀ f₁ : hom P Q} (ef : f₀ ≤ f₁) : π₀.map f₀ = π₀.map f₁ :=
begin
apply π₀.epi,
intro p,
rw [π₀.map_def, π₀.map_def],
exact π₀.sound (ef p)
end
variable (P)
lemma π₀.map_id : π₀.map (id P) = _root_.id :=
by { apply π₀.epi, intro p, rw[π₀.map_def], refl }
variable {P}
lemma π₀.map_comp (g : hom Q R) (f : hom P Q) :
π₀.map (comp g f) = (π₀.map g) ∘ (π₀.map f) :=
by { apply π₀.epi, intro p, rw[π₀.map_def], refl }
def evalₕ : (homₕ P Q) → (π₀ P) → (π₀ Q) :=
π₀.lift π₀.map (@π₀.map_congr _ _ _ _)
variables {P Q}
def comma (f : hom P Q) (q : Q) := { p : P // f p ≤ q }
instance comma_order (f : hom P Q) (q : Q) :
partial_order (comma f q) := by { dsimp[comma], apply_instance }
def cocomma (f : hom P Q) (q : Q) := { p : P // q ≤ f p }
instance cocomma_order (f : hom P Q) (q : Q) :
partial_order (cocomma f q) := by { dsimp[cocomma], apply_instance }
/-- Here we define predicates finalₕ and cofinalₕ.
If (finalₕ f) holds then f is homotopy cofinal, by
prop-cofinal. The dual is also valid, but the converse
is not.
-/
def finalₕ (f : hom P Q) : Prop :=
∀ q, contractibleₕ (cocomma f q)
def cofinalₕ (f : hom P Q) : Prop :=
∀ q, contractibleₕ (comma f q)
variable (P)
structure fin_ranking :=
(card : ℕ)
(rank : P ≃ fin card)
(rank_mono : monotone rank.to_fun)
section sort
variable {P}
variable [decidable_rel (has_le.le : P → P → Prop)]
def is_semisorted (l : list P) : Prop :=
l.pairwise (λ a b, ¬ b < a)
lemma mem_ordered_insert (x p : P) (l : list P) :
x ∈ (l.ordered_insert has_le.le p) ↔ x = p ∨ x ∈ l :=
begin
rw [list.perm.mem_iff (list.perm_ordered_insert _ _ _)],
apply list.mem_cons_iff
end
lemma insert_semisorted (p : P) (l : list P) (h : is_semisorted l) :
is_semisorted (l.ordered_insert has_le.le p) :=
begin
induction h with q l hq hl ih,
{ apply list.pairwise_singleton },
{ dsimp [list.ordered_insert],
split_ifs with hpq,
{ apply list.pairwise.cons,
{ intros x x_in_ql,
rcases (list.mem_cons_iff _ _ _).mp x_in_ql with ⟨⟨⟩⟩ | x_in_l,
{ exact not_lt_of_ge hpq },
{ intro x_lt_p,
exact hq x x_in_l (lt_of_lt_of_le x_lt_p hpq) } },
{ exact list.pairwise.cons hq hl } },
{ apply list.pairwise.cons,
{ intros x x_in_pl x_lt_q,
rw [mem_ordered_insert] at x_in_pl,
rcases x_in_pl with ⟨⟨⟩⟩ | x_in_l,
{ exact hpq (le_of_lt x_lt_q) },
{ exact hq x x_in_l x_lt_q } },
{ exact ih } } }
end
lemma insertion_sort_semisorted (l : list P) :
is_semisorted (l.insertion_sort (has_le.le : P → P → Prop)) :=
begin
induction l with p l ih,
{ apply list.pairwise.nil },
{ dsimp [list.insertion_sort],
apply insert_semisorted,
exact ih }
end
variable (P)
lemma exists_fin_ranking [fintype P] : nonempty (fin_ranking P) :=
begin
rcases fintype.equiv_fin P with f,
let n := fintype.card P,
let l := (fin.elems_list n).map f.symm,
have l_nodup : l.nodup :=
list.nodup.map f.symm.injective (fin.elems_list_nodup _),
have l_univ : ∀ p, p ∈ l := λ p,
begin
apply list.mem_map.mpr,
exact ⟨f.to_fun p, ⟨fin.elems_list_complete (f.to_fun p),f.left_inv p⟩⟩
end,
have l_length : l.length = n :=
(list.length_map f.symm (fin.elems_list _)).trans (fin.elems_list_length _),
let ls := l.insertion_sort has_le.le,
let ls_perm := list.perm_insertion_sort has_le.le l,
have ls_sorted : is_semisorted ls :=
insertion_sort_semisorted l,
have ls_nodup : ls.nodup :=
(list.perm.nodup_iff ls_perm).mpr l_nodup,
have ls_univ : ∀ p, p ∈ ls := λ p,
(list.perm.mem_iff ls_perm).mpr (l_univ p),
have ls_length : ls.length = n :=
(list.perm.length_eq ls_perm).trans l_length,
let inv_fun : (fin n) → P :=
λ i, ls.nth_le i.val (@eq.subst ℕ (nat.lt i.val) _ _ ls_length.symm i.is_lt),
let to_fun_aux : ∀ a : P, {i : fin n // inv_fun i = a} :=
begin
intro p,
let i_val := ls.index_of p,
let i_lt_l := list.index_of_lt_length.mpr (ls_univ p),
let i_lt_n : i_val < n := @eq.subst ℕ (nat.lt i_val) _ _ ls_length i_lt_l,
let i : fin n := ⟨i_val,i_lt_n⟩,
have : inv_fun i = p := list.index_of_nth_le i_lt_l,
exact ⟨i,this⟩
end,
let to_fun : P → (fin n) := λ p, (to_fun_aux p).val,
let left_inv : ∀ p : P, inv_fun (to_fun p) = p :=
λ p, (to_fun_aux p).property,
let right_inv : ∀ i : (fin n), to_fun (inv_fun i) = i :=
begin
intro i,cases i with i_val i_is_lt,
apply fin.eq_of_veq,
let i_lt_l : i_val < ls.length :=
@eq.subst ℕ (nat.lt i_val) _ _ ls_length.symm i_is_lt,
exact list.nth_le_index_of ls_nodup i_val i_lt_l,
end,
let g : P ≃ (fin n) := ⟨to_fun,inv_fun,left_inv,right_inv⟩,
have g_mono : monotone g.to_fun := λ p q hpq,
begin
let i := g.to_fun p,
let j := g.to_fun q,
have hp : g.inv_fun i = p := g.left_inv p,
have hq : g.inv_fun j = q := g.left_inv q,
have hi : i.val < ls.length := by { rw [ls_length], exact i.is_lt },
have hj : j.val < ls.length := by { rw [ls_length], exact j.is_lt },
by_cases h : i ≤ j, { exact h },
exfalso,
replace h := lt_of_not_ge h,
have hp' : ls.nth_le i.val hi = g.inv_fun i := rfl,
have hq' : ls.nth_le j.val hj = g.inv_fun j := rfl,
let h_ne := list.pairwise_nth_iff.mp ls_nodup h hi,
let h_ngt := list.pairwise_nth_iff.mp ls_sorted h hi,
rw [hp', hq', hp, hq] at h_ne h_ngt,
exact h_ngt (lt_of_le_of_ne hpq h_ne.symm),
end,
exact ⟨⟨n,g,g_mono⟩⟩
end
end sort
end poset |
202487777f76267fa5787e98f731500e68494bf6 | ce6917c5bacabee346655160b74a307b4a5ab620 | /src/ch4/ex0101.lean | e8df9ee67390e0593991a9a94ee9cccbb860d6fb | [] | no_license | Ailrun/Theorem_Proving_in_Lean | ae6a23f3c54d62d401314d6a771e8ff8b4132db2 | 2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68 | refs/heads/master | 1,609,838,270,467 | 1,586,846,743,000 | 1,586,846,743,000 | 240,967,761 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 184 | lean | variables (α : Type) (p q : α → Prop)
example : (∀ x : α, p x ∧ q x) -> ∀ y : α, p y :=
assume h : ∀ x : α, p x ∧ q x,
assume y : α,
show p y, from (h y).left
|
8d7c0caa43e136f6cf8732250b05b2b2f3f778ea | 367134ba5a65885e863bdc4507601606690974c1 | /src/topology/sequences.lean | 022d182202e3c06a10c92d638caf1a46963c73f8 | [
"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 | 18,811 | lean | /-
Copyright (c) 2018 Jan-David Salchow. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jan-David Salchow, Patrick Massot
-/
import topology.bases
import topology.subset_properties
import topology.metric_space.basic
/-!
# Sequences in topological spaces
In this file we define sequences in topological spaces and show how they are related to
filters and the topology. In particular, we
* define the sequential closure of a set and prove that it's contained in the closure,
* define a type class "sequential_space" in which closure and sequential closure agree,
* define sequential continuity and show that it coincides with continuity in sequential spaces,
* provide an instance that shows that every first-countable (and in particular metric) space is
a sequential space.
* define sequential compactness, prove that compactness implies sequential compactness in first
countable spaces, and prove they are equivalent for uniform spaces having a countable uniformity
basis (in particular metric spaces).
-/
open set filter
open_locale topological_space
variables {α : Type*} {β : Type*}
local notation f ` ⟶ ` limit := tendsto f at_top (𝓝 limit)
/-! ### Sequential closures, sequential continuity, and sequential spaces. -/
section topological_space
variables [topological_space α] [topological_space β]
/-- A sequence converges in the sence of topological spaces iff the associated statement for filter
holds. -/
lemma topological_space.seq_tendsto_iff {x : ℕ → α} {limit : α} :
tendsto x at_top (𝓝 limit) ↔
∀ U : set α, limit ∈ U → is_open U → ∃ N, ∀ n ≥ N, (x n) ∈ U :=
(at_top_basis.tendsto_iff (nhds_basis_opens limit)).trans $
by simp only [and_imp, exists_prop, true_and, set.mem_Ici, ge_iff_le, id]
/-- The sequential closure of a subset M ⊆ α of a topological space α is
the set of all p ∈ α which arise as limit of sequences in M. -/
def sequential_closure (M : set α) : set α :=
{p | ∃ x : ℕ → α, (∀ n : ℕ, x n ∈ M) ∧ (x ⟶ p)}
lemma subset_sequential_closure (M : set α) : M ⊆ sequential_closure M :=
assume p (_ : p ∈ M), show p ∈ sequential_closure M, from
⟨λ n, p, assume n, ‹p ∈ M›, tendsto_const_nhds⟩
/-- A set `s` is sequentially closed if for any converging sequence `x n` of elements of `s`,
the limit belongs to `s` as well. -/
def is_seq_closed (s : set α) : Prop := s = sequential_closure s
/-- A convenience lemma for showing that a set is sequentially closed. -/
lemma is_seq_closed_of_def {A : set α}
(h : ∀(x : ℕ → α) (p : α), (∀ n : ℕ, x n ∈ A) → (x ⟶ p) → p ∈ A) : is_seq_closed A :=
show A = sequential_closure A, from subset.antisymm
(subset_sequential_closure A)
(show ∀ p, p ∈ sequential_closure A → p ∈ A, from
(assume p ⟨x, _, _⟩, show p ∈ A, from h x p ‹∀ n : ℕ, ((x n) ∈ A)› ‹(x ⟶ p)›))
/-- The sequential closure of a set is contained in the closure of that set.
The converse is not true. -/
lemma sequential_closure_subset_closure (M : set α) : sequential_closure M ⊆ closure M :=
assume p ⟨x, xM, xp⟩,
mem_closure_of_tendsto xp (univ_mem_sets' xM)
/-- A set is sequentially closed if it is closed. -/
lemma is_seq_closed_of_is_closed (M : set α) (_ : is_closed M) : is_seq_closed M :=
suffices sequential_closure M ⊆ M, from
set.eq_of_subset_of_subset (subset_sequential_closure M) this,
calc sequential_closure M ⊆ closure M : sequential_closure_subset_closure M
... = M : is_closed.closure_eq ‹is_closed M›
/-- The limit of a convergent sequence in a sequentially closed set is in that set.-/
lemma mem_of_is_seq_closed {A : set α} (_ : is_seq_closed A) {x : ℕ → α}
(_ : ∀ n, x n ∈ A) {limit : α} (_ : (x ⟶ limit)) : limit ∈ A :=
have limit ∈ sequential_closure A, from
show ∃ x : ℕ → α, (∀ n : ℕ, x n ∈ A) ∧ (x ⟶ limit), from ⟨x, ‹∀ n, x n ∈ A›, ‹(x ⟶ limit)›⟩,
eq.subst (eq.symm ‹is_seq_closed A›) ‹limit ∈ sequential_closure A›
/-- The limit of a convergent sequence in a closed set is in that set.-/
lemma mem_of_is_closed_sequential {A : set α} (_ : is_closed A) {x : ℕ → α}
(_ : ∀ n, x n ∈ A) {limit : α} (_ : x ⟶ limit) : limit ∈ A :=
mem_of_is_seq_closed (is_seq_closed_of_is_closed A ‹is_closed A›) ‹∀ n, x n ∈ A› ‹(x ⟶ limit)›
/-- A sequential space is a space in which 'sequences are enough to probe the topology'. This can be
formalised by demanding that the sequential closure and the closure coincide. The following
statements show that other topological properties can be deduced from sequences in sequential
spaces. -/
class sequential_space (α : Type*) [topological_space α] : Prop :=
(sequential_closure_eq_closure : ∀ M : set α, sequential_closure M = closure M)
/-- In a sequential space, a set is closed iff it's sequentially closed. -/
lemma is_seq_closed_iff_is_closed [sequential_space α] {M : set α} :
is_seq_closed M ↔ is_closed M :=
iff.intro
(assume _, closure_eq_iff_is_closed.mp (eq.symm
(calc M = sequential_closure M : by assumption
... = closure M : sequential_space.sequential_closure_eq_closure M)))
(is_seq_closed_of_is_closed M)
/-- In a sequential space, a point belongs to the closure of a set iff it is a limit of a sequence
taking values in this set. -/
lemma mem_closure_iff_seq_limit [sequential_space α] {s : set α} {a : α} :
a ∈ closure s ↔ ∃ x : ℕ → α, (∀ n : ℕ, x n ∈ s) ∧ (x ⟶ a) :=
by { rw ← sequential_space.sequential_closure_eq_closure, exact iff.rfl }
/-- A function between topological spaces is sequentially continuous if it commutes with limit of
convergent sequences. -/
def sequentially_continuous (f : α → β) : Prop :=
∀ (x : ℕ → α), ∀ {limit : α}, (x ⟶ limit) → (f∘x ⟶ f limit)
/- A continuous function is sequentially continuous. -/
lemma continuous.to_sequentially_continuous {f : α → β} (_ : continuous f) :
sequentially_continuous f :=
assume x limit (_ : x ⟶ limit),
have tendsto f (𝓝 limit) (𝓝 (f limit)), from continuous.tendsto ‹continuous f› limit,
show (f ∘ x) ⟶ (f limit), from tendsto.comp this ‹(x ⟶ limit)›
/-- In a sequential space, continuity and sequential continuity coincide. -/
lemma continuous_iff_sequentially_continuous {f : α → β} [sequential_space α] :
continuous f ↔ sequentially_continuous f :=
iff.intro
(assume _, ‹continuous f›.to_sequentially_continuous)
(assume : sequentially_continuous f, show continuous f, from
suffices h : ∀ {A : set β}, is_closed A → is_seq_closed (f ⁻¹' A), from
continuous_iff_is_closed.mpr (assume A _, is_seq_closed_iff_is_closed.mp $ h ‹is_closed A›),
assume A (_ : is_closed A),
is_seq_closed_of_def $
assume (x : ℕ → α) p (_ : ∀ n, f (x n) ∈ A) (_ : x ⟶ p),
have (f ∘ x) ⟶ (f p), from ‹sequentially_continuous f› x ‹(x ⟶ p)›,
show f p ∈ A, from
mem_of_is_closed_sequential ‹is_closed A› ‹∀ n, f (x n) ∈ A› ‹(f∘x ⟶ f p)›)
end topological_space
namespace topological_space
namespace first_countable_topology
variables [topological_space α] [first_countable_topology α]
/-- Every first-countable space is sequential. -/
@[priority 100] -- see Note [lower instance priority]
instance : sequential_space α :=
⟨show ∀ M, sequential_closure M = closure M, from assume M,
suffices closure M ⊆ sequential_closure M,
from set.subset.antisymm (sequential_closure_subset_closure M) this,
-- For every p ∈ closure M, we need to construct a sequence x in M that converges to p:
assume (p : α) (hp : p ∈ closure M),
-- Since we are in a first-countable space, the neighborhood filter around `p` has a decreasing
-- basis `U` indexed by `ℕ`.
let ⟨U, hU⟩ := (nhds_generated_countable p).exists_antimono_basis in
-- Since `p ∈ closure M`, there is an element in each `M ∩ U i`
have hp : ∀ (i : ℕ), ∃ (y : α), y ∈ M ∧ y ∈ U i,
by simpa using (mem_closure_iff_nhds_basis hU.1).mp hp,
begin
-- The axiom of (countable) choice builds our sequence from the later fact
choose u hu using hp,
rw forall_and_distrib at hu,
-- It clearly takes values in `M`
use [u, hu.1],
-- and converges to `p` because the basis is decreasing.
apply hU.tendsto hu.2,
end⟩
end first_countable_topology
end topological_space
section seq_compact
open topological_space topological_space.first_countable_topology
variables [topological_space α]
/-- A set `s` is sequentially compact if every sequence taking values in `s` has a
converging subsequence. -/
def is_seq_compact (s : set α) :=
∀ ⦃u : ℕ → α⦄, (∀ n, u n ∈ s) →
∃ (x ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x)
/-- A space `α` is sequentially compact if every sequence in `α` has a
converging subsequence. -/
class seq_compact_space (α : Type*) [topological_space α] : Prop :=
(seq_compact_univ : is_seq_compact (univ : set α))
lemma is_seq_compact.subseq_of_frequently_in {s : set α} (hs : is_seq_compact s) {u : ℕ → α}
(hu : ∃ᶠ n in at_top, u n ∈ s) :
∃ (x ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) :=
let ⟨ψ, hψ, huψ⟩ := extraction_of_frequently_at_top hu, ⟨x, x_in, φ, hφ, h⟩ := hs huψ in
⟨x, x_in, ψ ∘ φ, hψ.comp hφ, h⟩
lemma seq_compact_space.tendsto_subseq [seq_compact_space α] (u : ℕ → α) :
∃ x (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) :=
let ⟨x, _, φ, mono, h⟩ := seq_compact_space.seq_compact_univ (by simp : ∀ n, u n ∈ univ) in
⟨x, φ, mono, h⟩
section first_countable_topology
variables [first_countable_topology α]
open topological_space.first_countable_topology
lemma is_compact.is_seq_compact {s : set α} (hs : is_compact s) : is_seq_compact s :=
λ u u_in,
let ⟨x, x_in, hx⟩ := @hs (map u at_top) _
(le_principal_iff.mpr (univ_mem_sets' u_in : _)) in ⟨x, x_in, tendsto_subseq hx⟩
lemma is_compact.tendsto_subseq' {s : set α} {u : ℕ → α} (hs : is_compact s)
(hu : ∃ᶠ n in at_top, u n ∈ s) :
∃ (x ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) :=
hs.is_seq_compact.subseq_of_frequently_in hu
lemma is_compact.tendsto_subseq {s : set α} {u : ℕ → α} (hs : is_compact s) (hu : ∀ n, u n ∈ s) :
∃ (x ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) :=
hs.is_seq_compact hu
@[priority 100] -- see Note [lower instance priority]
instance first_countable_topology.seq_compact_of_compact [compact_space α] : seq_compact_space α :=
⟨compact_univ.is_seq_compact⟩
lemma compact_space.tendsto_subseq [compact_space α] (u : ℕ → α) :
∃ x (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) :=
seq_compact_space.tendsto_subseq u
end first_countable_topology
end seq_compact
section uniform_space_seq_compact
open_locale uniformity
open uniform_space prod
variables [uniform_space β] {s : set β}
lemma lebesgue_number_lemma_seq {ι : Type*} {c : ι → set β}
(hs : is_seq_compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i)
(hU : is_countably_generated (𝓤 β)) :
∃ V ∈ 𝓤 β, symmetric_rel V ∧ ∀ x ∈ s, ∃ i, ball x V ⊆ c i :=
begin
classical,
obtain ⟨V, hV, Vsymm⟩ :
∃ V : ℕ → set (β × β), (𝓤 β).has_antimono_basis (λ _, true) V ∧ ∀ n, swap ⁻¹' V n = V n,
from uniform_space.has_seq_basis hU, clear hU,
suffices : ∃ n, ∀ x ∈ s, ∃ i, ball x (V n) ⊆ c i,
{ cases this with n hn,
exact ⟨V n, hV.to_has_basis.mem_of_mem trivial, Vsymm n, hn⟩ },
by_contradiction H,
obtain ⟨x, x_in, hx⟩ : ∃ x : ℕ → β, (∀ n, x n ∈ s) ∧ ∀ n i, ¬ ball (x n) (V n) ⊆ c i,
{ push_neg at H,
choose x hx using H,
exact ⟨x, forall_and_distrib.mp hx⟩ }, clear H,
obtain ⟨x₀, x₀_in, φ, φ_mono, hlim⟩ : ∃ (x₀ ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ (x ∘ φ ⟶ x₀),
from hs x_in, clear hs,
obtain ⟨i₀, x₀_in⟩ : ∃ i₀, x₀ ∈ c i₀,
{ rcases hc₂ x₀_in with ⟨_, ⟨i₀, rfl⟩, x₀_in_c⟩,
exact ⟨i₀, x₀_in_c⟩ }, clear hc₂,
obtain ⟨n₀, hn₀⟩ : ∃ n₀, ball x₀ (V n₀) ⊆ c i₀,
{ rcases (nhds_basis_uniformity hV.to_has_basis).mem_iff.mp
(is_open_iff_mem_nhds.mp (hc₁ i₀) _ x₀_in) with ⟨n₀, _, h⟩,
use n₀,
rwa ← ball_eq_of_symmetry (Vsymm n₀) at h }, clear hc₁,
obtain ⟨W, W_in, hWW⟩ : ∃ W ∈ 𝓤 β, W ○ W ⊆ V n₀,
from comp_mem_uniformity_sets (hV.to_has_basis.mem_of_mem trivial),
obtain ⟨N, x_φ_N_in, hVNW⟩ : ∃ N, x (φ N) ∈ ball x₀ W ∧ V (φ N) ⊆ W,
{ obtain ⟨N₁, h₁⟩ : ∃ N₁, ∀ n ≥ N₁, x (φ n) ∈ ball x₀ W,
from tendsto_at_top'.mp hlim _ (mem_nhds_left x₀ W_in),
obtain ⟨N₂, h₂⟩ : ∃ N₂, V (φ N₂) ⊆ W,
{ rcases hV.to_has_basis.mem_iff.mp W_in with ⟨N, _, hN⟩,
use N,
exact subset.trans (hV.decreasing trivial trivial $ φ_mono.id_le _) hN },
have : φ N₂ ≤ φ (max N₁ N₂),
from φ_mono.le_iff_le.mpr (le_max_right _ _),
exact ⟨max N₁ N₂, h₁ _ (le_max_left _ _), trans (hV.decreasing trivial trivial this) h₂⟩ },
suffices : ball (x (φ N)) (V (φ N)) ⊆ c i₀,
from hx (φ N) i₀ this,
calc
ball (x $ φ N) (V $ φ N) ⊆ ball (x $ φ N) W : preimage_mono hVNW
... ⊆ ball x₀ (V n₀) : ball_subset_of_comp_subset x_φ_N_in hWW
... ⊆ c i₀ : hn₀,
end
lemma is_seq_compact.totally_bounded (h : is_seq_compact s) : totally_bounded s :=
begin
classical,
apply totally_bounded_of_forall_symm,
unfold is_seq_compact at h,
contrapose! h,
rcases h with ⟨V, V_in, V_symm, h⟩,
simp_rw [not_subset] at h,
have : ∀ (t : set β), finite t → ∃ a, a ∈ s ∧ a ∉ ⋃ y ∈ t, ball y V,
{ intros t ht,
obtain ⟨a, a_in, H⟩ : ∃ a ∈ s, ∀ (x : β), x ∈ t → (x, a) ∉ V,
by simpa [ht] using h t,
use [a, a_in],
intro H',
obtain ⟨x, x_in, hx⟩ := mem_bUnion_iff.mp H',
exact H x x_in hx },
cases seq_of_forall_finite_exists this with u hu, clear h this,
simp [forall_and_distrib] at hu,
cases hu with u_in hu,
use [u, u_in], clear u_in,
intros x x_in φ,
intros hφ huφ,
obtain ⟨N, hN⟩ : ∃ N, ∀ p q, p ≥ N → q ≥ N → (u (φ p), u (φ q)) ∈ V,
from huφ.cauchy_seq.mem_entourage V_in,
specialize hN N (N+1) (le_refl N) (nat.le_succ N),
specialize hu (φ $ N+1) (φ N) (hφ $ lt_add_one N),
exact hu hN,
end
protected lemma is_seq_compact.is_compact (h : is_countably_generated $ 𝓤 β)
(hs : is_seq_compact s) :
is_compact s :=
begin
classical,
rw compact_iff_finite_subcover,
intros ι U Uop s_sub,
rcases lebesgue_number_lemma_seq hs Uop s_sub h with ⟨V, V_in, Vsymm, H⟩,
rcases totally_bounded_iff_subset.mp hs.totally_bounded V V_in with ⟨t,t_sub, tfin, ht⟩,
have : ∀ x : t, ∃ (i : ι), ball x.val V ⊆ U i,
{ rintros ⟨x, x_in⟩,
exact H x (t_sub x_in) },
choose i hi using this,
haveI : fintype t := tfin.fintype,
use finset.image i finset.univ,
transitivity ⋃ y ∈ t, ball y V,
{ intros x x_in,
specialize ht x_in,
rw mem_bUnion_iff at *,
simp_rw ball_eq_of_symmetry Vsymm,
exact ht },
{ apply bUnion_subset_bUnion,
intros x x_in,
exact ⟨i ⟨x, x_in⟩, finset.mem_image_of_mem _ (finset.mem_univ _), hi ⟨x, x_in⟩⟩ },
end
protected lemma uniform_space.compact_iff_seq_compact (h : is_countably_generated $ 𝓤 β) :
is_compact s ↔ is_seq_compact s :=
begin
haveI := uniform_space.first_countable_topology h,
exact ⟨λ H, H.is_seq_compact, λ H, H.is_compact h⟩
end
lemma uniform_space.compact_space_iff_seq_compact_space (H : is_countably_generated $ 𝓤 β) :
compact_space β ↔ seq_compact_space β :=
have key : is_compact univ ↔ is_seq_compact univ := uniform_space.compact_iff_seq_compact H,
⟨λ ⟨h⟩, ⟨key.mp h⟩, λ ⟨h⟩, ⟨key.mpr h⟩⟩
end uniform_space_seq_compact
section metric_seq_compact
variables [metric_space β] {s : set β}
open metric
/-- A version of Bolzano-Weistrass: in a metric space, is_compact s ↔ is_seq_compact s -/
lemma metric.compact_iff_seq_compact : is_compact s ↔ is_seq_compact s :=
uniform_space.compact_iff_seq_compact emetric.uniformity_has_countable_basis
/-- A version of Bolzano-Weistrass: in a proper metric space (eg. $ℝ^n$),
every bounded sequence has a converging subsequence. This version assumes only
that the sequence is frequently in some bounded set. -/
lemma tendsto_subseq_of_frequently_bounded [proper_space β] (hs : bounded s)
{u : ℕ → β} (hu : ∃ᶠ n in at_top, u n ∈ s) :
∃ b ∈ closure s, ∃ φ : ℕ → ℕ, strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 b) :=
begin
have hcs : is_compact (closure s) :=
compact_iff_closed_bounded.mpr ⟨is_closed_closure, bounded_closure_of_bounded hs⟩,
replace hcs : is_seq_compact (closure s),
by rwa metric.compact_iff_seq_compact at hcs,
have hu' : ∃ᶠ n in at_top, u n ∈ closure s,
{ apply frequently.mono hu,
intro n,
apply subset_closure },
exact hcs.subseq_of_frequently_in hu',
end
/-- A version of Bolzano-Weistrass: in a proper metric space (eg. $ℝ^n$),
every bounded sequence has a converging subsequence. -/
lemma tendsto_subseq_of_bounded [proper_space β] (hs : bounded s)
{u : ℕ → β} (hu : ∀ n, u n ∈ s) :
∃ b ∈ closure s, ∃ φ : ℕ → ℕ, strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 b) :=
tendsto_subseq_of_frequently_bounded hs $ frequently_of_forall hu
lemma metric.compact_space_iff_seq_compact_space : compact_space β ↔ seq_compact_space β :=
uniform_space.compact_space_iff_seq_compact_space emetric.uniformity_has_countable_basis
lemma seq_compact.lebesgue_number_lemma_of_metric
{ι : Type*} {c : ι → set β} (hs : is_seq_compact s)
(hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) :
∃ δ > 0, ∀ x ∈ s, ∃ i, ball x δ ⊆ c i :=
begin
rcases lebesgue_number_lemma_seq hs hc₁ hc₂ emetric.uniformity_has_countable_basis
with ⟨V, V_in, _, hV⟩,
rcases uniformity_basis_dist.mem_iff.mp V_in with ⟨δ, δ_pos, h⟩,
use [δ, δ_pos],
intros x x_in,
rcases hV x x_in with ⟨i, hi⟩,
use i,
have := ball_mono h x,
rw ball_eq_ball' at this,
exact subset.trans this hi,
end
end metric_seq_compact
|
952764ea76144b5b3ac2346f9c1906de21933725 | 19cc34575500ee2e3d4586c15544632aa07a8e66 | /src/geometry/euclidean/basic.lean | 5c224eb321e346fe54f94d8fbc8d7c19d464202a | [
"Apache-2.0"
] | permissive | LibertasSpZ/mathlib | b9fcd46625eb940611adb5e719a4b554138dade6 | 33f7870a49d7cc06d2f3036e22543e6ec5046e68 | refs/heads/master | 1,672,066,539,347 | 1,602,429,158,000 | 1,602,429,158,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 48,486 | lean | /-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Joseph Myers.
-/
import analysis.normed_space.inner_product
import algebra.quadratic_discriminant
import analysis.normed_space.add_torsor
import data.matrix.notation
import linear_algebra.affine_space.finite_dimensional
import tactic.fin_cases
noncomputable theory
open_locale big_operators
open_locale classical
open_locale real
open_locale real_inner_product_space
/-!
# Euclidean spaces
This file makes some definitions and proves very basic geometrical
results about real inner product spaces and Euclidean affine spaces.
Results about real inner product spaces that involve the norm and
inner product but not angles generally go in
`analysis.normed_space.inner_product`. Results with longer
proofs or more geometrical content generally go in separate files.
## Main definitions
* `inner_product_geometry.angle` is the undirected angle between two
vectors.
* `euclidean_geometry.angle`, with notation `∠`, is the undirected
angle determined by three points.
* `euclidean_geometry.orthogonal_projection` is the orthogonal
projection of a point onto an affine subspace.
* `euclidean_geometry.reflection` is the reflection of a point in an
affine subspace.
## Implementation notes
To declare `P` as the type of points in a Euclidean affine space with
`V` as the type of vectors, use `[inner_product_space ℝ V] [metric_space P]
[normed_add_torsor V P]`. This works better with `out_param` to make
`V` implicit in most cases than having a separate type alias for
Euclidean affine spaces.
Rather than requiring Euclidean affine spaces to be finite-dimensional
(as in the definition on Wikipedia), this is specified only for those
theorems that need it.
## References
* https://en.wikipedia.org/wiki/Euclidean_space
-/
namespace inner_product_geometry
/-!
### Geometrical results on real inner product spaces
This section develops some geometrical definitions and results on real
inner product spaces, where those definitions and results can most
conveniently be developed in terms of vectors and then used to deduce
corresponding results for Euclidean affine spaces.
-/
variables {V : Type*} [inner_product_space ℝ V]
/-- The undirected angle between two vectors. If either vector is 0,
this is π/2. -/
def angle (x y : V) : ℝ := real.arccos (inner x y / (∥x∥ * ∥y∥))
/-- The cosine of the angle between two vectors. -/
lemma cos_angle (x y : V) : real.cos (angle x y) = inner x y / (∥x∥ * ∥y∥) :=
real.cos_arccos (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1
(abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2
/-- The angle between two vectors does not depend on their order. -/
lemma angle_comm (x y : V) : angle x y = angle y x :=
begin
unfold angle,
rw [real_inner_comm, mul_comm]
end
/-- The angle between the negation of two vectors. -/
@[simp] lemma angle_neg_neg (x y : V) : angle (-x) (-y) = angle x y :=
begin
unfold angle,
rw [inner_neg_neg, norm_neg, norm_neg]
end
/-- The angle between two vectors is nonnegative. -/
lemma angle_nonneg (x y : V) : 0 ≤ angle x y :=
real.arccos_nonneg _
/-- The angle between two vectors is at most π. -/
lemma angle_le_pi (x y : V) : angle x y ≤ π :=
real.arccos_le_pi _
/-- The angle between a vector and the negation of another vector. -/
lemma angle_neg_right (x y : V) : angle x (-y) = π - angle x y :=
begin
unfold angle,
rw [←real.arccos_neg, norm_neg, inner_neg_right, neg_div]
end
/-- The angle between the negation of a vector and another vector. -/
lemma angle_neg_left (x y : V) : angle (-x) y = π - angle x y :=
by rw [←angle_neg_neg, neg_neg, angle_neg_right]
/-- The angle between the zero vector and a vector. -/
@[simp] lemma angle_zero_left (x : V) : angle 0 x = π / 2 :=
begin
unfold angle,
rw [inner_zero_left, zero_div, real.arccos_zero]
end
/-- The angle between a vector and the zero vector. -/
@[simp] lemma angle_zero_right (x : V) : angle x 0 = π / 2 :=
begin
unfold angle,
rw [inner_zero_right, zero_div, real.arccos_zero]
end
/-- The angle between a nonzero vector and itself. -/
@[simp] lemma angle_self {x : V} (hx : x ≠ 0) : angle x x = 0 :=
begin
unfold angle,
rw [←real_inner_self_eq_norm_square, div_self (λ h, hx (inner_self_eq_zero.1 h)),
real.arccos_one]
end
/-- The angle between a nonzero vector and its negation. -/
@[simp] lemma angle_self_neg_of_nonzero {x : V} (hx : x ≠ 0) : angle x (-x) = π :=
by rw [angle_neg_right, angle_self hx, sub_zero]
/-- The angle between the negation of a nonzero vector and that
vector. -/
@[simp] lemma angle_neg_self_of_nonzero {x : V} (hx : x ≠ 0) : angle (-x) x = π :=
by rw [angle_comm, angle_self_neg_of_nonzero hx]
/-- The angle between a vector and a positive multiple of a vector. -/
@[simp] lemma angle_smul_right_of_pos (x y : V) {r : ℝ} (hr : 0 < r) :
angle x (r • y) = angle x y :=
begin
unfold angle,
rw [inner_smul_right, norm_smul, real.norm_eq_abs, abs_of_nonneg (le_of_lt hr), ←mul_assoc,
mul_comm _ r, mul_assoc, mul_div_mul_left _ _ (ne_of_gt hr)]
end
/-- The angle between a positive multiple of a vector and a vector. -/
@[simp] lemma angle_smul_left_of_pos (x y : V) {r : ℝ} (hr : 0 < r) :
angle (r • x) y = angle x y :=
by rw [angle_comm, angle_smul_right_of_pos y x hr, angle_comm]
/-- The angle between a vector and a negative multiple of a vector. -/
@[simp] lemma angle_smul_right_of_neg (x y : V) {r : ℝ} (hr : r < 0) :
angle x (r • y) = angle x (-y) :=
by rw [←neg_neg r, neg_smul, angle_neg_right, angle_smul_right_of_pos x y (neg_pos_of_neg hr),
angle_neg_right]
/-- The angle between a negative multiple of a vector and a vector. -/
@[simp] lemma angle_smul_left_of_neg (x y : V) {r : ℝ} (hr : r < 0) :
angle (r • x) y = angle (-x) y :=
by rw [angle_comm, angle_smul_right_of_neg y x hr, angle_comm]
/-- The cosine of the angle between two vectors, multiplied by the
product of their norms. -/
lemma cos_angle_mul_norm_mul_norm (x y : V) : real.cos (angle x y) * (∥x∥ * ∥y∥) = inner x y :=
begin
rw cos_angle,
by_cases h : (∥x∥ * ∥y∥) = 0,
{ rw [h, mul_zero],
cases eq_zero_or_eq_zero_of_mul_eq_zero h with hx hy,
{ rw norm_eq_zero at hx,
rw [hx, inner_zero_left] },
{ rw norm_eq_zero at hy,
rw [hy, inner_zero_right] } },
{ exact div_mul_cancel _ h }
end
/-- The sine of the angle between two vectors, multiplied by the
product of their norms. -/
lemma sin_angle_mul_norm_mul_norm (x y : V) : real.sin (angle x y) * (∥x∥ * ∥y∥) =
real.sqrt (inner x x * inner y y - inner x y * inner x y) :=
begin
unfold angle,
rw [real.sin_arccos (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1
(abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2,
←real.sqrt_mul_self (mul_nonneg (norm_nonneg x) (norm_nonneg y)),
←real.sqrt_mul' _ (mul_self_nonneg _), pow_two,
real.sqrt_mul_self (mul_nonneg (norm_nonneg x) (norm_nonneg y)), real_inner_self_eq_norm_square,
real_inner_self_eq_norm_square],
by_cases h : (∥x∥ * ∥y∥) = 0,
{ rw [(show ∥x∥ * ∥x∥ * (∥y∥ * ∥y∥) = (∥x∥ * ∥y∥) * (∥x∥ * ∥y∥), by ring), h, mul_zero, mul_zero,
zero_sub],
cases eq_zero_or_eq_zero_of_mul_eq_zero h with hx hy,
{ rw norm_eq_zero at hx,
rw [hx, inner_zero_left, zero_mul, neg_zero] },
{ rw norm_eq_zero at hy,
rw [hy, inner_zero_right, zero_mul, neg_zero] } },
{ field_simp [h],
ring }
end
/-- The angle between two vectors is zero if and only if they are
nonzero and one is a positive multiple of the other. -/
lemma angle_eq_zero_iff (x y : V) : angle x y = 0 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), 0 < r ∧ y = r • x) :=
begin
unfold angle,
rw [←real_inner_div_norm_mul_norm_eq_one_iff, ←real.arccos_one],
split,
{ intro h,
exact real.arccos_inj (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1
(abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2
(by norm_num)
(by norm_num)
h },
{ intro h,
rw h }
end
/-- The angle between two vectors is π if and only if they are nonzero
and one is a negative multiple of the other. -/
lemma angle_eq_pi_iff (x y : V) : angle x y = π ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r < 0 ∧ y = r • x) :=
begin
unfold angle,
rw [←real_inner_div_norm_mul_norm_eq_neg_one_iff, ←real.arccos_neg_one],
split,
{ intro h,
exact real.arccos_inj (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1
(abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2
(by norm_num)
(by norm_num)
h },
{ intro h,
rw h }
end
/-- If the angle between two vectors is π, the angles between those
vectors and a third vector add to π. -/
lemma angle_add_angle_eq_pi_of_angle_eq_pi {x y : V} (z : V) (h : angle x y = π) :
angle x z + angle y z = π :=
begin
rw angle_eq_pi_iff at h,
rcases h with ⟨hx, ⟨r, ⟨hr, hxy⟩⟩⟩,
rw [hxy, angle_smul_left_of_neg x z hr, angle_neg_left,
add_sub_cancel'_right]
end
/-- Two vectors have inner product 0 if and only if the angle between
them is π/2. -/
lemma inner_eq_zero_iff_angle_eq_pi_div_two (x y : V) : ⟪x, y⟫ = 0 ↔ angle x y = π / 2 :=
begin
split,
{ intro h,
unfold angle,
rw [h, zero_div, real.arccos_zero] },
{ intro h,
unfold angle at h,
rw ←real.arccos_zero at h,
have h2 : inner x y / (∥x∥ * ∥y∥) = 0 :=
real.arccos_inj (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1
(abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2
(by norm_num)
(by norm_num)
h,
by_cases h : (∥x∥ * ∥y∥) = 0,
{ cases eq_zero_or_eq_zero_of_mul_eq_zero h with hx hy,
{ rw norm_eq_zero at hx,
rw [hx, inner_zero_left] },
{ rw norm_eq_zero at hy,
rw [hy, inner_zero_right] } },
{ simpa [h, div_eq_zero_iff] using h2 } },
end
end inner_product_geometry
namespace euclidean_geometry
/-!
### Geometrical results on Euclidean affine spaces
This section develops some geometrical definitions and results on
Euclidean affine spaces.
-/
open inner_product_geometry
variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P]
[normed_add_torsor V P]
local notation `⟪`x`, `y`⟫` := @inner ℝ V _ x y
include V
/-- The undirected angle at `p2` between the line segments to `p1` and
`p3`. If either of those points equals `p2`, this is π/2. Use
`open_locale euclidean_geometry` to access the `∠ p1 p2 p3`
notation. -/
def angle (p1 p2 p3 : P) : ℝ := angle (p1 -ᵥ p2 : V) (p3 -ᵥ p2)
localized "notation `∠` := euclidean_geometry.angle" in euclidean_geometry
/-- The angle at a point does not depend on the order of the other two
points. -/
lemma angle_comm (p1 p2 p3 : P) : ∠ p1 p2 p3 = ∠ p3 p2 p1 :=
angle_comm _ _
/-- The angle at a point is nonnegative. -/
lemma angle_nonneg (p1 p2 p3 : P) : 0 ≤ ∠ p1 p2 p3 :=
angle_nonneg _ _
/-- The angle at a point is at most π. -/
lemma angle_le_pi (p1 p2 p3 : P) : ∠ p1 p2 p3 ≤ π :=
angle_le_pi _ _
/-- The angle ∠AAB at a point. -/
lemma angle_eq_left (p1 p2 : P) : ∠ p1 p1 p2 = π / 2 :=
begin
unfold angle,
rw vsub_self,
exact angle_zero_left _
end
/-- The angle ∠ABB at a point. -/
lemma angle_eq_right (p1 p2 : P) : ∠ p1 p2 p2 = π / 2 :=
by rw [angle_comm, angle_eq_left]
/-- The angle ∠ABA at a point. -/
lemma angle_eq_of_ne {p1 p2 : P} (h : p1 ≠ p2) : ∠ p1 p2 p1 = 0 :=
angle_self (λ he, h (vsub_eq_zero_iff_eq.1 he))
/-- If the angle ∠ABC at a point is π, the angle ∠BAC is 0. -/
lemma angle_eq_zero_of_angle_eq_pi_left {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) :
∠ p2 p1 p3 = 0 :=
begin
unfold angle at h,
rw angle_eq_pi_iff at h,
rcases h with ⟨hp1p2, ⟨r, ⟨hr, hpr⟩⟩⟩,
unfold angle,
rw angle_eq_zero_iff,
rw [←neg_vsub_eq_vsub_rev, neg_ne_zero] at hp1p2,
use [hp1p2, -r + 1, add_pos (neg_pos_of_neg hr) zero_lt_one],
rw [add_smul, ←neg_vsub_eq_vsub_rev p1 p2, smul_neg],
simp [←hpr]
end
/-- If the angle ∠ABC at a point is π, the angle ∠BCA is 0. -/
lemma angle_eq_zero_of_angle_eq_pi_right {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) :
∠ p2 p3 p1 = 0 :=
begin
rw angle_comm at h,
exact angle_eq_zero_of_angle_eq_pi_left h
end
/-- If ∠BCD = π, then ∠ABC = ∠ABD. -/
lemma angle_eq_angle_of_angle_eq_pi (p1 : P) {p2 p3 p4 : P} (h : ∠ p2 p3 p4 = π) :
∠ p1 p2 p3 = ∠ p1 p2 p4 :=
begin
unfold angle at h,
rw angle_eq_pi_iff at h,
rcases h with ⟨hp2p3, ⟨r, ⟨hr, hpr⟩⟩⟩,
unfold angle,
symmetry,
convert angle_smul_right_of_pos _ _ (add_pos (neg_pos_of_neg hr) zero_lt_one),
rw [add_smul, ←neg_vsub_eq_vsub_rev p2 p3, smul_neg],
simp [←hpr]
end
/-- If ∠BCD = π, then ∠ACB + ∠ACD = π. -/
lemma angle_add_angle_eq_pi_of_angle_eq_pi (p1 : P) {p2 p3 p4 : P} (h : ∠ p2 p3 p4 = π) :
∠ p1 p3 p2 + ∠ p1 p3 p4 = π :=
begin
unfold angle at h,
rw [angle_comm p1 p3 p2, angle_comm p1 p3 p4],
unfold angle,
exact angle_add_angle_eq_pi_of_angle_eq_pi _ h
end
/-- The inner product of two vectors given with `weighted_vsub`, in
terms of the pairwise distances. -/
lemma inner_weighted_vsub {ι₁ : Type*} {s₁ : finset ι₁} {w₁ : ι₁ → ℝ} (p₁ : ι₁ → P)
(h₁ : ∑ i in s₁, w₁ i = 0) {ι₂ : Type*} {s₂ : finset ι₂} {w₂ : ι₂ → ℝ} (p₂ : ι₂ → P)
(h₂ : ∑ i in s₂, w₂ i = 0) :
inner (s₁.weighted_vsub p₁ w₁) (s₂.weighted_vsub p₂ w₂) =
(-∑ i₁ in s₁, ∑ i₂ in s₂,
w₁ i₁ * w₂ i₂ * (dist (p₁ i₁) (p₂ i₂) * dist (p₁ i₁) (p₂ i₂))) / 2 :=
begin
rw [finset.weighted_vsub_apply, finset.weighted_vsub_apply,
inner_sum_smul_sum_smul_of_sum_eq_zero _ h₁ _ h₂],
simp_rw [vsub_sub_vsub_cancel_right],
rcongr i₁ i₂; rw dist_eq_norm_vsub V (p₁ i₁) (p₂ i₂)
end
/-- The distance between two points given with `affine_combination`,
in terms of the pairwise distances between the points in that
combination. -/
lemma dist_affine_combination {ι : Type*} {s : finset ι} {w₁ w₂ : ι → ℝ} (p : ι → P)
(h₁ : ∑ i in s, w₁ i = 1) (h₂ : ∑ i in s, w₂ i = 1) :
dist (s.affine_combination p w₁) (s.affine_combination p w₂) *
dist (s.affine_combination p w₁) (s.affine_combination p w₂) =
(-∑ i₁ in s, ∑ i₂ in s,
(w₁ - w₂) i₁ * (w₁ - w₂) i₂ * (dist (p i₁) (p i₂) * dist (p i₁) (p i₂))) / 2 :=
begin
rw [dist_eq_norm_vsub V (s.affine_combination p w₁) (s.affine_combination p w₂),
←inner_self_eq_norm_square, finset.affine_combination_vsub],
have h : ∑ i in s, (w₁ - w₂) i = 0,
{ simp_rw [pi.sub_apply, finset.sum_sub_distrib, h₁, h₂, sub_self] },
exact inner_weighted_vsub p h p h
end
/-- Suppose that `c₁` is equidistant from `p₁` and `p₂`, and the same
applies to `c₂`. Then the vector between `c₁` and `c₂` is orthogonal
to that between `p₁` and `p₂`. (In two dimensions, this says that the
diagonals of a kite are orthogonal.) -/
lemma inner_vsub_vsub_of_dist_eq_of_dist_eq {c₁ c₂ p₁ p₂ : P} (hc₁ : dist p₁ c₁ = dist p₂ c₁)
(hc₂ : dist p₁ c₂ = dist p₂ c₂) : ⟪c₂ -ᵥ c₁, p₂ -ᵥ p₁⟫ = 0 :=
begin
have h : ⟪(c₂ -ᵥ c₁) + (c₂ -ᵥ c₁), p₂ -ᵥ p₁⟫ = 0,
{ conv_lhs { congr, congr, rw ←vsub_sub_vsub_cancel_right c₂ c₁ p₁,
skip, rw ←vsub_sub_vsub_cancel_right c₂ c₁ p₂ },
rw [←add_sub_comm, inner_sub_left],
conv_lhs { congr, rw ←vsub_sub_vsub_cancel_right p₂ p₁ c₂,
skip, rw ←vsub_sub_vsub_cancel_right p₂ p₁ c₁ },
rw [dist_comm p₁, dist_comm p₂, dist_eq_norm_vsub V _ p₁,
dist_eq_norm_vsub V _ p₂, ←real_inner_add_sub_eq_zero_iff] at hc₁ hc₂,
simp_rw [←neg_vsub_eq_vsub_rev c₁, ←neg_vsub_eq_vsub_rev c₂, sub_neg_eq_add,
neg_add_eq_sub, hc₁, hc₂, sub_zero] },
simpa [inner_add_left, ←mul_two, (by norm_num : (2 : ℝ) ≠ 0)] using h
end
/-- The squared distance between points on a line (expressed as a
multiple of a fixed vector added to a point) and another point,
expressed as a quadratic. -/
lemma dist_smul_vadd_square (r : ℝ) (v : V) (p₁ p₂ : P) :
dist (r • v +ᵥ p₁) p₂ * dist (r • v +ᵥ p₁) p₂ =
⟪v, v⟫ * r * r + 2 * ⟪v, p₁ -ᵥ p₂⟫ * r + ⟪p₁ -ᵥ p₂, p₁ -ᵥ p₂⟫ :=
begin
rw [dist_eq_norm_vsub V _ p₂, ←real_inner_self_eq_norm_square, vadd_vsub_assoc, real_inner_add_add_self,
real_inner_smul_left, real_inner_smul_left, real_inner_smul_right],
ring
end
/-- The condition for two points on a line to be equidistant from
another point. -/
lemma dist_smul_vadd_eq_dist {v : V} (p₁ p₂ : P) (hv : v ≠ 0) (r : ℝ) :
dist (r • v +ᵥ p₁) p₂ = dist p₁ p₂ ↔ (r = 0 ∨ r = -2 * ⟪v, p₁ -ᵥ p₂⟫ / ⟪v, v⟫) :=
begin
conv_lhs { rw [←mul_self_inj_of_nonneg dist_nonneg dist_nonneg, dist_smul_vadd_square,
←sub_eq_zero_iff_eq, add_sub_assoc, dist_eq_norm_vsub V p₁ p₂,
←real_inner_self_eq_norm_square, sub_self] },
have hvi : ⟪v, v⟫ ≠ 0, by simpa using hv,
have hd : discrim ⟪v, v⟫ (2 * ⟪v, p₁ -ᵥ p₂⟫) 0 =
(2 * inner v (p₁ -ᵥ p₂)) * (2 * inner v (p₁ -ᵥ p₂)),
{ rw discrim, ring },
rw [quadratic_eq_zero_iff hvi hd, add_left_neg, zero_div, neg_mul_eq_neg_mul,
←mul_sub_right_distrib, sub_eq_add_neg, ←mul_two, mul_assoc, mul_div_assoc,
mul_div_mul_left, mul_div_assoc],
norm_num
end
open affine_subspace finite_dimensional
/-- Distances `r₁` `r₂` of `p` from two different points `c₁` `c₂` determine at
most two points `p₁` `p₂` in a two-dimensional subspace containing those points
(two circles intersect in at most two points). -/
lemma eq_of_dist_eq_of_dist_eq_of_mem_of_findim_eq_two {s : affine_subspace ℝ P}
[finite_dimensional ℝ s.direction] (hd : findim ℝ s.direction = 2) {c₁ c₂ p₁ p₂ p : P}
(hc₁s : c₁ ∈ s) (hc₂s : c₂ ∈ s) (hp₁s : p₁ ∈ s) (hp₂s : p₂ ∈ s) (hps : p ∈ s) {r₁ r₂ : ℝ}
(hc : c₁ ≠ c₂) (hp : p₁ ≠ p₂) (hp₁c₁ : dist p₁ c₁ = r₁) (hp₂c₁ : dist p₂ c₁ = r₁)
(hpc₁ : dist p c₁ = r₁) (hp₁c₂ : dist p₁ c₂ = r₂) (hp₂c₂ : dist p₂ c₂ = r₂)
(hpc₂ : dist p c₂ = r₂) : p = p₁ ∨ p = p₂ :=
begin
have ho : ⟪c₂ -ᵥ c₁, p₂ -ᵥ p₁⟫ = 0 :=
inner_vsub_vsub_of_dist_eq_of_dist_eq (by cc) (by cc),
have hop : ⟪c₂ -ᵥ c₁, p -ᵥ p₁⟫ = 0 :=
inner_vsub_vsub_of_dist_eq_of_dist_eq (by cc) (by cc),
let b : fin 2 → V := ![c₂ -ᵥ c₁, p₂ -ᵥ p₁],
have hb : linear_independent ℝ b,
{ refine linear_independent_of_ne_zero_of_inner_eq_zero _ _,
{ intro i,
fin_cases i; simp [b, hc.symm, hp.symm] },
{ intros i j hij,
fin_cases i; fin_cases j; try { exact false.elim (hij rfl) },
{ exact ho },
{ rw real_inner_comm, exact ho } } },
have hbs : submodule.span ℝ (set.range b) = s.direction,
{ refine eq_of_le_of_findim_eq _ _,
{ rw [submodule.span_le, set.range_subset_iff],
intro i,
fin_cases i,
{ exact vsub_mem_direction hc₂s hc₁s },
{ exact vsub_mem_direction hp₂s hp₁s } },
{ rw [findim_span_eq_card hb, fintype.card_fin, hd] } },
have hv : ∀ v ∈ s.direction, ∃ t₁ t₂ : ℝ, v = t₁ • (c₂ -ᵥ c₁) + t₂ • (p₂ -ᵥ p₁),
{ intros v hv,
have hr : set.range b = {c₂ -ᵥ c₁, p₂ -ᵥ p₁},
{ have hu : (finset.univ : finset (fin 2)) = {0, 1}, by dec_trivial,
rw [←fintype.coe_image_univ, hu],
simp,
refl },
rw [←hbs, hr, submodule.mem_span_insert] at hv,
rcases hv with ⟨t₁, v', hv', hv⟩,
rw submodule.mem_span_singleton at hv',
rcases hv' with ⟨t₂, rfl⟩,
exact ⟨t₁, t₂, hv⟩ },
rcases hv (p -ᵥ p₁) (vsub_mem_direction hps hp₁s) with ⟨t₁, t₂, hpt⟩,
simp only [hpt, inner_add_right, inner_smul_right, ho, mul_zero, add_zero, mul_eq_zero,
inner_self_eq_zero, vsub_eq_zero_iff_eq, hc.symm, or_false] at hop,
rw [hop, zero_smul, zero_add, ←eq_vadd_iff_vsub_eq] at hpt,
subst hpt,
have hp' : (p₂ -ᵥ p₁ : V) ≠ 0, { simp [hp.symm] },
have hp₂ : dist ((1 : ℝ) • (p₂ -ᵥ p₁) +ᵥ p₁) c₁ = r₁, { simp [hp₂c₁] },
rw [←hp₁c₁, dist_smul_vadd_eq_dist _ _ hp'] at hpc₁ hp₂,
simp only [one_ne_zero, false_or] at hp₂,
rw hp₂.symm at hpc₁,
cases hpc₁; simp [hpc₁]
end
/-- Distances `r₁` `r₂` of `p` from two different points `c₁` `c₂` determine at
most two points `p₁` `p₂` in two-dimensional space (two circles intersect in at
most two points). -/
lemma eq_of_dist_eq_of_dist_eq_of_findim_eq_two [finite_dimensional ℝ V] (hd : findim ℝ V = 2)
{c₁ c₂ p₁ p₂ p : P} {r₁ r₂ : ℝ} (hc : c₁ ≠ c₂) (hp : p₁ ≠ p₂) (hp₁c₁ : dist p₁ c₁ = r₁)
(hp₂c₁ : dist p₂ c₁ = r₁) (hpc₁ : dist p c₁ = r₁) (hp₁c₂ : dist p₁ c₂ = r₂)
(hp₂c₂ : dist p₂ c₂ = r₂) (hpc₂ : dist p c₂ = r₂) : p = p₁ ∨ p = p₂ :=
begin
have hd' : findim ℝ (⊤ : affine_subspace ℝ P).direction = 2,
{ rw [direction_top, findim_top],
exact hd },
exact eq_of_dist_eq_of_dist_eq_of_mem_of_findim_eq_two hd'
(mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _)
hc hp hp₁c₁ hp₂c₁ hpc₁ hp₁c₂ hp₂c₂ hpc₂
end
variables {V}
/-- The orthogonal projection of a point onto a nonempty affine
subspace, whose direction is complete, as an unbundled function. This
definition is only intended for use in setting up the bundled version
`orthogonal_projection` and should not be used once that is
defined. -/
def orthogonal_projection_fn {s : affine_subspace ℝ P} (hn : (s : set P).nonempty)
(hc : is_complete (s.direction : set V)) (p : P) : P :=
classical.some $ inter_eq_singleton_of_nonempty_of_is_compl
hn
(mk'_nonempty p s.direction.orthogonal)
((direction_mk' p s.direction.orthogonal).symm ▸ submodule.is_compl_orthogonal_of_is_complete_real hc)
/-- The intersection of the subspace and the orthogonal subspace
through the given point is the `orthogonal_projection_fn` of that
point onto the subspace. This lemma is only intended for use in
setting up the bundled version and should not be used once that is
defined. -/
lemma inter_eq_singleton_orthogonal_projection_fn {s : affine_subspace ℝ P}
(hn : (s : set P).nonempty) (hc : is_complete (s.direction : set V)) (p : P) :
(s : set P) ∩ (mk' p s.direction.orthogonal) = {orthogonal_projection_fn hn hc p} :=
classical.some_spec $ inter_eq_singleton_of_nonempty_of_is_compl
hn
(mk'_nonempty p s.direction.orthogonal)
((direction_mk' p s.direction.orthogonal).symm ▸ submodule.is_compl_orthogonal_of_is_complete_real hc)
/-- The `orthogonal_projection_fn` lies in the given subspace. This
lemma is only intended for use in setting up the bundled version and
should not be used once that is defined. -/
lemma orthogonal_projection_fn_mem {s : affine_subspace ℝ P} (hn : (s : set P).nonempty)
(hc : is_complete (s.direction : set V)) (p : P) : orthogonal_projection_fn hn hc p ∈ s :=
begin
rw [←mem_coe, ←set.singleton_subset_iff, ←inter_eq_singleton_orthogonal_projection_fn],
exact set.inter_subset_left _ _
end
/-- The `orthogonal_projection_fn` lies in the orthogonal
subspace. This lemma is only intended for use in setting up the
bundled version and should not be used once that is defined. -/
lemma orthogonal_projection_fn_mem_orthogonal {s : affine_subspace ℝ P}
(hn : (s : set P).nonempty) (hc : is_complete (s.direction : set V)) (p : P) :
orthogonal_projection_fn hn hc p ∈ mk' p s.direction.orthogonal :=
begin
rw [←mem_coe, ←set.singleton_subset_iff, ←inter_eq_singleton_orthogonal_projection_fn],
exact set.inter_subset_right _ _
end
/-- Subtracting `p` from its `orthogonal_projection_fn` produces a
result in the orthogonal direction. This lemma is only intended for
use in setting up the bundled version and should not be used once that
is defined. -/
lemma orthogonal_projection_fn_vsub_mem_direction_orthogonal {s : affine_subspace ℝ P}
(hn : (s : set P).nonempty) (hc : is_complete (s.direction : set V)) (p : P) :
orthogonal_projection_fn hn hc p -ᵥ p ∈ s.direction.orthogonal :=
direction_mk' p s.direction.orthogonal ▸
vsub_mem_direction (orthogonal_projection_fn_mem_orthogonal hn hc p) (self_mem_mk' _ _)
/-- The orthogonal projection of a point onto a nonempty affine
subspace, whose direction is complete. The corresponding linear map
(mapping a vector to the difference between the projections of two
points whose difference is that vector) is the `orthogonal_projection`
for real inner product spaces, onto the direction of the affine
subspace being projected onto. For most purposes,
`orthogonal_projection`, which removes the `nonempty` and
`is_complete` hypotheses and is the identity map when either of those
hypotheses fails, should be used instead. -/
def orthogonal_projection_of_nonempty_of_complete {s : affine_subspace ℝ P}
(hn : (s : set P).nonempty) (hc : is_complete (s.direction : set V)) : affine_map ℝ P P :=
{ to_fun := orthogonal_projection_fn hn hc,
linear := orthogonal_projection s.direction,
map_vadd' := λ p v, begin
have hs : (orthogonal_projection s.direction) v +ᵥ orthogonal_projection_fn hn hc p ∈ s :=
vadd_mem_of_mem_direction (orthogonal_projection_mem hc _)
(orthogonal_projection_fn_mem hn hc p),
have ho : (orthogonal_projection s.direction) v +ᵥ orthogonal_projection_fn hn hc p ∈
mk' (v +ᵥ p) s.direction.orthogonal,
{ rw [←vsub_right_mem_direction_iff_mem (self_mem_mk' _ _) _, direction_mk',
vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_comm, add_sub_assoc],
refine submodule.add_mem _ (orthogonal_projection_fn_vsub_mem_direction_orthogonal hn hc p) _,
rw submodule.mem_orthogonal',
intros w hw,
rw [←neg_sub, inner_neg_left, orthogonal_projection_inner_eq_zero _ _ w hw, neg_zero] },
have hm : (orthogonal_projection s.direction) v +ᵥ orthogonal_projection_fn hn hc p ∈
({orthogonal_projection_fn hn hc (v +ᵥ p)} : set P),
{ rw ←inter_eq_singleton_orthogonal_projection_fn hn hc (v +ᵥ p),
exact set.mem_inter hs ho },
rw set.mem_singleton_iff at hm,
exact hm.symm
end }
/-- The orthogonal projection of a point onto an affine subspace,
which is expected to be nonempty and complete. The corresponding
linear map (mapping a vector to the difference between the projections
of two points whose difference is that vector) is the
`orthogonal_projection` for real inner product spaces, onto the
direction of the affine subspace being projected onto. If the
subspace is empty or not complete, this uses the identity map
instead. -/
def orthogonal_projection (s : affine_subspace ℝ P) : affine_map ℝ P P :=
if h : (s : set P).nonempty ∧ is_complete (s.direction : set V) then
orthogonal_projection_of_nonempty_of_complete h.1 h.2 else affine_map.id ℝ P
/-- The definition of `orthogonal_projection` using `if`. -/
lemma orthogonal_projection_def (s : affine_subspace ℝ P) :
orthogonal_projection s = if h : (s : set P).nonempty ∧ is_complete (s.direction : set V) then
orthogonal_projection_of_nonempty_of_complete h.1 h.2 else affine_map.id ℝ P :=
rfl
@[simp] lemma orthogonal_projection_fn_eq {s : affine_subspace ℝ P} (hn : (s : set P).nonempty)
(hc : is_complete (s.direction : set V)) (p : P) :
orthogonal_projection_fn hn hc p = orthogonal_projection s p :=
by { rw [orthogonal_projection_def, dif_pos (and.intro hn hc)], refl }
/-- The linear map corresponding to `orthogonal_projection`. -/
@[simp] lemma orthogonal_projection_linear {s : affine_subspace ℝ P} (hn : (s : set P).nonempty) :
(orthogonal_projection s).linear = _root_.orthogonal_projection s.direction :=
begin
by_cases hc : is_complete (s.direction : set V),
{ rw [orthogonal_projection_def, dif_pos (and.intro hn hc)],
refl },
{ simp [orthogonal_projection_def, _root_.orthogonal_projection_def, hn, hc] }
end
@[simp] lemma orthogonal_projection_of_nonempty_of_complete_eq {s : affine_subspace ℝ P}
(hn : (s : set P).nonempty) (hc : is_complete (s.direction : set V)) (p : P) :
orthogonal_projection_of_nonempty_of_complete hn hc p = orthogonal_projection s p :=
by rw [orthogonal_projection_def, dif_pos (and.intro hn hc)]
/-- The intersection of the subspace and the orthogonal subspace
through the given point is the `orthogonal_projection` of that point
onto the subspace. -/
lemma inter_eq_singleton_orthogonal_projection {s : affine_subspace ℝ P}
(hn : (s : set P).nonempty) (hc : is_complete (s.direction : set V)) (p : P) :
(s : set P) ∩ (mk' p s.direction.orthogonal) = {orthogonal_projection s p} :=
begin
rw ←orthogonal_projection_fn_eq hn hc,
exact inter_eq_singleton_orthogonal_projection_fn hn hc p
end
/-- The `orthogonal_projection` lies in the given subspace. -/
lemma orthogonal_projection_mem {s : affine_subspace ℝ P} (hn : (s : set P).nonempty)
(hc : is_complete (s.direction : set V)) (p : P) : orthogonal_projection s p ∈ s :=
begin
rw ←orthogonal_projection_fn_eq hn hc,
exact orthogonal_projection_fn_mem hn hc p
end
/-- The `orthogonal_projection` lies in the orthogonal subspace. -/
lemma orthogonal_projection_mem_orthogonal (s : affine_subspace ℝ P) (p : P) :
orthogonal_projection s p ∈ mk' p s.direction.orthogonal :=
begin
rw orthogonal_projection_def,
split_ifs,
{ exact orthogonal_projection_fn_mem_orthogonal h.1 h.2 p },
{ exact self_mem_mk' _ _ }
end
/-- Subtracting a point in the given subspace from the
`orthogonal_projection` produces a result in the direction of the
given subspace. -/
lemma orthogonal_projection_vsub_mem_direction {s : affine_subspace ℝ P}
(hc : is_complete (s.direction : set V)) {p1 : P} (p2 : P) (hp1 : p1 ∈ s) :
orthogonal_projection s p2 -ᵥ p1 ∈ s.direction :=
vsub_mem_direction (orthogonal_projection_mem ⟨p1, hp1⟩ hc p2) hp1
/-- Subtracting the `orthogonal_projection` from a point in the given
subspace produces a result in the direction of the given subspace. -/
lemma vsub_orthogonal_projection_mem_direction {s : affine_subspace ℝ P}
(hc : is_complete (s.direction : set V)) {p1 : P} (p2 : P) (hp1 : p1 ∈ s) :
p1 -ᵥ orthogonal_projection s p2 ∈ s.direction :=
vsub_mem_direction hp1 (orthogonal_projection_mem ⟨p1, hp1⟩ hc p2)
/-- A point equals its orthogonal projection if and only if it lies in
the subspace. -/
lemma orthogonal_projection_eq_self_iff {s : affine_subspace ℝ P}
(hn : (s : set P).nonempty) (hc : is_complete (s.direction : set V)) {p : P} :
orthogonal_projection s p = p ↔ p ∈ s :=
begin
split,
{ exact λ h, h ▸ orthogonal_projection_mem hn hc p },
{ intro h,
have hp : p ∈ ((s : set P) ∩ mk' p s.direction.orthogonal) := ⟨h, self_mem_mk' p _⟩,
rw [inter_eq_singleton_orthogonal_projection hn hc p, set.mem_singleton_iff] at hp,
exact hp.symm }
end
/-- Orthogonal projection is idempotent. -/
@[simp] lemma orthogonal_projection_orthogonal_projection (s : affine_subspace ℝ P) (p : P) :
orthogonal_projection s (orthogonal_projection s p) = orthogonal_projection s p :=
begin
by_cases h : (s : set P).nonempty ∧ is_complete (s.direction : set V),
{ rw orthogonal_projection_eq_self_iff h.1 h.2,
exact orthogonal_projection_mem h.1 h.2 p },
{ simp [orthogonal_projection_def, h] }
end
/-- The distance to a point's orthogonal projection is 0 iff it lies in the subspace. -/
lemma dist_orthogonal_projection_eq_zero_iff {s : affine_subspace ℝ P}
(hn : (s : set P).nonempty) (hc : is_complete (s.direction : set V)) {p : P} :
dist p (orthogonal_projection s p) = 0 ↔ p ∈ s :=
by rw [dist_comm, dist_eq_zero, orthogonal_projection_eq_self_iff hn hc]
/-- The distance between a point and its orthogonal projection is
nonzero if it does not lie in the subspace. -/
lemma dist_orthogonal_projection_ne_zero_of_not_mem {s : affine_subspace ℝ P}
(hn : (s : set P).nonempty) (hc : is_complete (s.direction : set V)) {p : P} (hp : p ∉ s) :
dist p (orthogonal_projection s p) ≠ 0 :=
mt (dist_orthogonal_projection_eq_zero_iff hn hc).mp hp
/-- Subtracting `p` from its `orthogonal_projection` produces a result
in the orthogonal direction. -/
lemma orthogonal_projection_vsub_mem_direction_orthogonal (s : affine_subspace ℝ P) (p : P) :
orthogonal_projection s p -ᵥ p ∈ s.direction.orthogonal :=
begin
rw orthogonal_projection_def,
split_ifs,
{ exact orthogonal_projection_fn_vsub_mem_direction_orthogonal h.1 h.2 p },
{ simp }
end
/-- Subtracting the `orthogonal_projection` from `p` produces a result
in the orthogonal direction. -/
lemma vsub_orthogonal_projection_mem_direction_orthogonal (s : affine_subspace ℝ P) (p : P) :
p -ᵥ orthogonal_projection s p ∈ s.direction.orthogonal :=
direction_mk' p s.direction.orthogonal ▸
vsub_mem_direction (self_mem_mk' _ _) (orthogonal_projection_mem_orthogonal s p)
/-- Adding a vector to a point in the given subspace, then taking the
orthogonal projection, produces the original point if the vector was
in the orthogonal direction. -/
lemma orthogonal_projection_vadd_eq_self {s : affine_subspace ℝ P}
(hc : is_complete (s.direction : set V)) {p : P} (hp : p ∈ s) {v : V}
(hv : v ∈ s.direction.orthogonal) : orthogonal_projection s (v +ᵥ p) = p :=
begin
have h := vsub_orthogonal_projection_mem_direction_orthogonal s (v +ᵥ p),
rw [vadd_vsub_assoc, submodule.add_mem_iff_right _ hv] at h,
refine (eq_of_vsub_eq_zero _).symm,
refine submodule.disjoint_def.1 s.direction.orthogonal_disjoint _ _ h,
exact vsub_mem_direction hp (orthogonal_projection_mem ⟨p, hp⟩ hc (v +ᵥ p))
end
/-- Adding a vector to a point in the given subspace, then taking the
orthogonal projection, produces the original point if the vector is a
multiple of the result of subtracting a point's orthogonal projection
from that point. -/
lemma orthogonal_projection_vadd_smul_vsub_orthogonal_projection {s : affine_subspace ℝ P}
(hc : is_complete (s.direction : set V)) {p1 : P} (p2 : P) (r : ℝ) (hp : p1 ∈ s) :
orthogonal_projection s (r • (p2 -ᵥ orthogonal_projection s p2 : V) +ᵥ p1) = p1 :=
orthogonal_projection_vadd_eq_self hc hp
(submodule.smul_mem _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s _))
/-- The square of the distance from a point in `s` to `p2` equals the
sum of the squares of the distances of the two points to the
`orthogonal_projection`. -/
lemma dist_square_eq_dist_orthogonal_projection_square_add_dist_orthogonal_projection_square
{s : affine_subspace ℝ P} {p1 : P} (p2 : P) (hp1 : p1 ∈ s) :
dist p1 p2 * dist p1 p2 =
dist p1 (orthogonal_projection s p2) * dist p1 (orthogonal_projection s p2) +
dist p2 (orthogonal_projection s p2) * dist p2 (orthogonal_projection s p2) :=
begin
rw [metric_space.dist_comm p2 _, dist_eq_norm_vsub V p1 _, dist_eq_norm_vsub V p1 _,
dist_eq_norm_vsub V _ p2, ← vsub_add_vsub_cancel p1 (orthogonal_projection s p2) p2,
norm_add_square_eq_norm_square_add_norm_square_iff_real_inner_eq_zero],
rw orthogonal_projection_def,
split_ifs,
{ rw orthogonal_projection_of_nonempty_of_complete_eq,
exact submodule.inner_right_of_mem_orthogonal
(vsub_orthogonal_projection_mem_direction h.2 p2 hp1)
(orthogonal_projection_vsub_mem_direction_orthogonal s p2) },
{ simp }
end
/-- The square of the distance between two points constructed by
adding multiples of the same orthogonal vector to points in the same
subspace. -/
lemma dist_square_smul_orthogonal_vadd_smul_orthogonal_vadd {s : affine_subspace ℝ P}
{p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) (r1 r2 : ℝ) {v : V}
(hv : v ∈ s.direction.orthogonal) :
dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) * dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) =
dist p1 p2 * dist p1 p2 + (r1 - r2) * (r1 - r2) * (∥v∥ * ∥v∥) :=
calc dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) * dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2)
= ∥(p1 -ᵥ p2) + (r1 - r2) • v∥ * ∥(p1 -ᵥ p2) + (r1 - r2) • v∥
: by { rw [dist_eq_norm_vsub V (r1 • v +ᵥ p1), vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, sub_smul],
abel }
... = ∥p1 -ᵥ p2∥ * ∥p1 -ᵥ p2∥ + ∥(r1 - r2) • v∥ * ∥(r1 - r2) • v∥
: norm_add_square_eq_norm_square_add_norm_square_real
(submodule.inner_right_of_mem_orthogonal (vsub_mem_direction hp1 hp2)
(submodule.smul_mem _ _ hv))
... = ∥(p1 -ᵥ p2 : V)∥ * ∥(p1 -ᵥ p2 : V)∥ + abs (r1 - r2) * abs (r1 - r2) * ∥v∥ * ∥v∥
: by { rw [norm_smul, real.norm_eq_abs], ring }
... = dist p1 p2 * dist p1 p2 + (r1 - r2) * (r1 - r2) * (∥v∥ * ∥v∥)
: by { rw [dist_eq_norm_vsub V p1, abs_mul_abs_self, mul_assoc] }
/-- Reflection in an affine subspace, which is expected to be nonempty
and complete. The word "reflection" is sometimes understood to mean
specifically reflection in a codimension-one subspace, and sometimes
more generally to cover operations such as reflection in a point. The
definition here, of reflection in an affine subspace, is a more
general sense of the word that includes both those common cases. If
the subspace is empty or not complete, `orthogonal_projection` is
defined as the identity map, which results in `reflection` being the
identity map in that case as well. -/
def reflection (s : affine_subspace ℝ P) : P ≃ᵢ P :=
{ to_fun := λ p, (orthogonal_projection s p -ᵥ p) +ᵥ orthogonal_projection s p,
inv_fun := λ p, (orthogonal_projection s p -ᵥ p) +ᵥ orthogonal_projection s p,
left_inv := λ p, by simp [vsub_vadd_eq_vsub_sub, -orthogonal_projection_linear],
right_inv := λ p, by simp [vsub_vadd_eq_vsub_sub, -orthogonal_projection_linear],
isometry_to_fun := begin
dsimp only,
rw isometry_emetric_iff_metric,
intros p₁ p₂,
rw [←mul_self_inj_of_nonneg dist_nonneg dist_nonneg, dist_eq_norm_vsub V
((orthogonal_projection s p₁ -ᵥ p₁) +ᵥ orthogonal_projection s p₁),
dist_eq_norm_vsub V p₁, ←inner_self_eq_norm_square, ←inner_self_eq_norm_square],
by_cases h : (s : set P).nonempty ∧ is_complete (s.direction : set V),
{ calc
⟪(orthogonal_projection s p₁ -ᵥ p₁ +ᵥ orthogonal_projection s p₁ -ᵥ
(orthogonal_projection s p₂ -ᵥ p₂ +ᵥ orthogonal_projection s p₂)),
(orthogonal_projection s p₁ -ᵥ p₁ +ᵥ orthogonal_projection s p₁ -ᵥ
(orthogonal_projection s p₂ -ᵥ p₂ +ᵥ orthogonal_projection s p₂))⟫
= ⟪(_root_.orthogonal_projection s.direction (p₁ -ᵥ p₂)) +
_root_.orthogonal_projection s.direction (p₁ -ᵥ p₂) -
(p₁ -ᵥ p₂),
_root_.orthogonal_projection s.direction (p₁ -ᵥ p₂) +
_root_.orthogonal_projection s.direction (p₁ -ᵥ p₂) -
(p₁ -ᵥ p₂)⟫
: by rw [vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_comm, add_sub_assoc,
←vsub_vadd_eq_vsub_sub, vsub_vadd_comm, vsub_vadd_eq_vsub_sub, ←add_sub_assoc,
←affine_map.linear_map_vsub, orthogonal_projection_linear h.1]
... = -4 * inner (p₁ -ᵥ p₂ - (_root_.orthogonal_projection s.direction (p₁ -ᵥ p₂)))
(_root_.orthogonal_projection s.direction (p₁ -ᵥ p₂)) +
⟪p₁ -ᵥ p₂, p₁ -ᵥ p₂⟫
: by { simp [inner_sub_left, inner_sub_right, inner_add_left, inner_add_right,
real_inner_comm (p₁ -ᵥ p₂)],
ring }
... = -4 * 0 + ⟪p₁ -ᵥ p₂, p₁ -ᵥ p₂⟫
: by rw orthogonal_projection_inner_eq_zero s.direction _ _ (_root_.orthogonal_projection_mem h.2 _)
... = ⟪p₁ -ᵥ p₂, p₁ -ᵥ p₂⟫ : by simp },
{ simp [orthogonal_projection_def, h] }
end }
/-- The result of reflecting. -/
lemma reflection_apply (s : affine_subspace ℝ P) (p : P) :
reflection s p = (orthogonal_projection s p -ᵥ p) +ᵥ orthogonal_projection s p :=
rfl
/-- Reflection is its own inverse. -/
@[simp] lemma reflection_symm (s : affine_subspace ℝ P) : (reflection s).symm = reflection s :=
rfl
/-- Reflecting twice in the same subspace. -/
@[simp] lemma reflection_reflection (s : affine_subspace ℝ P) (p : P) :
reflection s (reflection s p) = p :=
(reflection s).left_inv p
/-- Reflection is involutive. -/
lemma reflection_involutive (s : affine_subspace ℝ P) : function.involutive (reflection s) :=
reflection_reflection s
/-- A point is its own reflection if and only if it is in the
subspace. -/
lemma reflection_eq_self_iff {s : affine_subspace ℝ P} (hn : (s : set P).nonempty)
(hc : is_complete (s.direction : set V)) (p : P) : reflection s p = p ↔ p ∈ s :=
begin
rw [←orthogonal_projection_eq_self_iff hn hc, reflection_apply],
split,
{ intro h,
rw [←@vsub_eq_zero_iff_eq V, vadd_vsub_assoc,
←two_smul ℝ (orthogonal_projection s p -ᵥ p), smul_eq_zero] at h,
norm_num at h,
exact h },
{ intro h,
simp [h] }
end
/-- Reflecting a point in two subspaces produces the same result if
and only if the point has the same orthogonal projection in each of
those subspaces. -/
lemma reflection_eq_iff_orthogonal_projection_eq (s₁ s₂ : affine_subspace ℝ P) (p : P) :
reflection s₁ p = reflection s₂ p ↔
orthogonal_projection s₁ p = orthogonal_projection s₂ p :=
begin
rw [reflection_apply, reflection_apply],
split,
{ intro h,
rw [←@vsub_eq_zero_iff_eq V, vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_comm,
add_sub_assoc, vsub_sub_vsub_cancel_right,
←two_smul ℝ (orthogonal_projection s₁ p -ᵥ orthogonal_projection s₂ p),
smul_eq_zero] at h,
norm_num at h,
exact h },
{ intro h,
rw h }
end
/-- The distance between `p₁` and the reflection of `p₂` equals that
between the reflection of `p₁` and `p₂`. -/
lemma dist_reflection (s : affine_subspace ℝ P) (p₁ p₂ : P) :
dist p₁ (reflection s p₂) = dist (reflection s p₁) p₂ :=
begin
conv_lhs { rw ←reflection_reflection s p₁ },
exact (reflection s).dist_eq _ _
end
/-- A point in the subspace is equidistant from another point and its
reflection. -/
lemma dist_reflection_eq_of_mem (s : affine_subspace ℝ P) {p₁ : P} (hp₁ : p₁ ∈ s) (p₂ : P) :
dist p₁ (reflection s p₂) = dist p₁ p₂ :=
begin
by_cases h : (s : set P).nonempty ∧ is_complete (s.direction : set V),
{ rw ←reflection_eq_self_iff h.1 h.2 p₁ at hp₁,
conv_lhs { rw ←hp₁ },
exact (reflection s).dist_eq _ _ },
{ simp [reflection_apply, orthogonal_projection_def, h] }
end
/-- The reflection of a point in a subspace is contained in any larger
subspace containing both the point and the subspace reflected in. -/
lemma reflection_mem_of_le_of_mem {s₁ s₂ : affine_subspace ℝ P} (hle : s₁ ≤ s₂) {p : P}
(hp : p ∈ s₂) : reflection s₁ p ∈ s₂ :=
begin
rw [reflection_apply],
by_cases h : (s₁ : set P).nonempty ∧ is_complete (s₁.direction : set V),
{ have ho : orthogonal_projection s₁ p ∈ s₂ := hle (orthogonal_projection_mem h.1 h.2 p),
exact vadd_mem_of_mem_direction (vsub_mem_direction ho hp) ho },
{ simpa [reflection_apply, orthogonal_projection_def, h] }
end
/-- Reflecting an orthogonal vector plus a point in the subspace
produces the negation of that vector plus the point. -/
lemma reflection_orthogonal_vadd {s : affine_subspace ℝ P}
(hc : is_complete (s.direction : set V)) {p : P} (hp : p ∈ s) {v : V}
(hv : v ∈ s.direction.orthogonal) : reflection s (v +ᵥ p) = -v +ᵥ p :=
begin
rw [reflection_apply, orthogonal_projection_vadd_eq_self hc hp hv, vsub_vadd_eq_vsub_sub],
simp
end
/-- Reflecting a vector plus a point in the subspace produces the
negation of that vector plus the point if the vector is a multiple of
the result of subtracting a point's orthogonal projection from that
point. -/
lemma reflection_vadd_smul_vsub_orthogonal_projection {s : affine_subspace ℝ P}
(hc : is_complete (s.direction : set V)) {p₁ : P} (p₂ : P) (r : ℝ) (hp₁ : p₁ ∈ s) :
reflection s (r • (p₂ -ᵥ orthogonal_projection s p₂) +ᵥ p₁) =
-(r • (p₂ -ᵥ orthogonal_projection s p₂)) +ᵥ p₁ :=
reflection_orthogonal_vadd hc hp₁
(submodule.smul_mem _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s _))
omit V
/-- A set of points is cospherical if they are equidistant from some
point. In two dimensions, this is the same thing as being
concyclic. -/
def cospherical (ps : set P) : Prop :=
∃ (center : P) (radius : ℝ), ∀ p ∈ ps, dist p center = radius
/-- The definition of `cospherical`. -/
lemma cospherical_def (ps : set P) :
cospherical ps ↔ ∃ (center : P) (radius : ℝ), ∀ p ∈ ps, dist p center = radius :=
iff.rfl
/-- A subset of a cospherical set is cospherical. -/
lemma cospherical_subset {ps₁ ps₂ : set P} (hs : ps₁ ⊆ ps₂) (hc : cospherical ps₂) :
cospherical ps₁ :=
begin
rcases hc with ⟨c, r, hcr⟩,
exact ⟨c, r, λ p hp, hcr p (hs hp)⟩
end
include V
/-- The empty set is cospherical. -/
lemma cospherical_empty : cospherical (∅ : set P) :=
begin
use add_torsor.nonempty.some,
simp,
end
omit V
/-- A single point is cospherical. -/
lemma cospherical_singleton (p : P) : cospherical ({p} : set P) :=
begin
use p,
simp
end
include V
/-- Two points are cospherical. -/
lemma cospherical_insert_singleton (p₁ p₂ : P) : cospherical ({p₁, p₂} : set P) :=
begin
use [(2⁻¹ : ℝ) • (p₂ -ᵥ p₁) +ᵥ p₁, (2⁻¹ : ℝ) * (dist p₂ p₁)],
intro p,
rw [set.mem_insert_iff, set.mem_singleton_iff],
rintro ⟨_|_⟩,
{ rw [dist_eq_norm_vsub V p₁, vsub_vadd_eq_vsub_sub, vsub_self, zero_sub, norm_neg, norm_smul,
dist_eq_norm_vsub V p₂],
simp },
{ rw [H, dist_eq_norm_vsub V p₂, vsub_vadd_eq_vsub_sub, dist_eq_norm_vsub V p₂],
conv_lhs { congr, congr, rw ←one_smul ℝ (p₂ -ᵥ p₁ : V) },
rw [←sub_smul, norm_smul],
norm_num }
end
/-- Any three points in a cospherical set are affinely independent. -/
lemma cospherical.affine_independent {s : set P} (hs : cospherical s) {p : fin 3 → P}
(hps : set.range p ⊆ s) (hpi : function.injective p) :
affine_independent ℝ p :=
begin
rw affine_independent_iff_not_collinear,
intro hc,
rw collinear_iff_of_mem ℝ (set.mem_range_self (0 : fin 3)) at hc,
rcases hc with ⟨v, hv⟩,
rw set.forall_range_iff at hv,
have hv0 : v ≠ 0,
{ intro h,
have he : p 1 = p 0, by simpa [h] using hv 1,
exact (dec_trivial : (1 : fin 3) ≠ 0) (hpi he) },
rcases hs with ⟨c, r, hs⟩,
have hs' := λ i, hs (p i) (set.mem_of_mem_of_subset (set.mem_range_self _) hps),
choose f hf using hv,
have hsd : ∀ i, dist ((f i • v) +ᵥ p 0) c = r,
{ intro i,
rw ←hf,
exact hs' i },
have hf0 : f 0 = 0,
{ have hf0' := hf 0,
rw [eq_comm, ←@vsub_eq_zero_iff_eq V, vadd_vsub, smul_eq_zero] at hf0',
simpa [hv0] using hf0' },
have hfi : function.injective f,
{ intros i j h,
have hi := hf i,
rw [h, ←hf j] at hi,
exact hpi hi },
simp_rw [←hsd 0, hf0, zero_smul, zero_vadd, dist_smul_vadd_eq_dist (p 0) c hv0] at hsd,
have hfn0 : ∀ i, i ≠ 0 → f i ≠ 0 := λ i, (hfi.ne_iff' hf0).2,
have hfn0' : ∀ i, i ≠ 0 → f i = (-2) * ⟪v, (p 0 -ᵥ c)⟫ / ⟪v, v⟫,
{ intros i hi,
have hsdi := hsd i,
simpa [hfn0, hi] using hsdi },
have hf12 : f 1 = f 2, { rw [hfn0' 1 dec_trivial, hfn0' 2 dec_trivial] },
exact (dec_trivial : (1 : fin 3) ≠ 2) (hfi hf12)
end
end euclidean_geometry
|
0ae8632a6b1329de81fb487fef40a4c1b76bc21b | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/number_theory/number_field/basic.lean | a426ce89fb1e7ae377fc27d88dba90aa92bcd792 | [
"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 | 7,481 | lean | /-
Copyright (c) 2021 Ashvni Narayanan. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Ashvni Narayanan, Anne Baanen
-/
import algebra.char_p.algebra
import ring_theory.dedekind_domain.integral_closure
/-!
# Number fields
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines a number field and the ring of integers corresponding to it.
## Main definitions
- `number_field` defines a number field as a field which has characteristic zero and is finite
dimensional over ℚ.
- `ring_of_integers` defines the ring of integers (or number ring) corresponding to a number field
as the integral closure of ℤ in the number field.
## Implementation notes
The definitions that involve a field of fractions choose a canonical field of fractions,
but are independent of that choice.
## References
* [D. Marcus, *Number Fields*][marcus1977number]
* [J.W.S. Cassels, A. Frölich, *Algebraic Number Theory*][cassels1967algebraic]
* [P. Samuel, *Algebraic Theory of Numbers*][samuel1970algebraic]
## Tags
number field, ring of integers
-/
/-- A number field is a field which has characteristic zero and is finite
dimensional over ℚ. -/
class number_field (K : Type*) [field K] : Prop :=
[to_char_zero : char_zero K]
[to_finite_dimensional : finite_dimensional ℚ K]
open function module
open_locale classical big_operators non_zero_divisors
/-- `ℤ` with its usual ring structure is not a field. -/
lemma int.not_is_field : ¬ is_field ℤ :=
λ h, int.not_even_one $ (h.mul_inv_cancel two_ne_zero).imp $ λ a, (by rw ← two_mul; exact eq.symm)
namespace number_field
variables (K L : Type*) [field K] [field L] [nf : number_field K]
include nf
-- See note [lower instance priority]
attribute [priority 100, instance] number_field.to_char_zero number_field.to_finite_dimensional
protected lemma is_algebraic : algebra.is_algebraic ℚ K := algebra.is_algebraic_of_finite _ _
omit nf
/-- The ring of integers (or number ring) corresponding to a number field
is the integral closure of ℤ in the number field. -/
def ring_of_integers := integral_closure ℤ K
localized "notation (name := ring_of_integers)
`𝓞` := number_field.ring_of_integers" in number_field
lemma mem_ring_of_integers (x : K) : x ∈ 𝓞 K ↔ is_integral ℤ x := iff.rfl
lemma is_integral_of_mem_ring_of_integers {K : Type*} [field K] {x : K} (hx : x ∈ 𝓞 K) :
is_integral ℤ (⟨x, hx⟩ : 𝓞 K) :=
begin
obtain ⟨P, hPm, hP⟩ := hx,
refine ⟨P, hPm, _⟩,
rw [← polynomial.aeval_def, ← subalgebra.coe_eq_zero, polynomial.aeval_subalgebra_coe,
polynomial.aeval_def, subtype.coe_mk, hP]
end
/-- Given an algebra between two fields, create an algebra between their two rings of integers.
For now, this is not an instance by default as it creates an equal-but-not-defeq diamond with
`algebra.id` when `K = L`. This is caused by `x = ⟨x, x.prop⟩` not being defeq on subtypes. This
will likely change in Lean 4. -/
def ring_of_integers_algebra [algebra K L] : algebra (𝓞 K) (𝓞 L) := ring_hom.to_algebra
{ to_fun := λ k, ⟨algebra_map K L k, is_integral.algebra_map k.2⟩,
map_zero' := subtype.ext $ by simp only [subtype.coe_mk, subalgebra.coe_zero, map_zero],
map_one' := subtype.ext $ by simp only [subtype.coe_mk, subalgebra.coe_one, map_one],
map_add' := λ x y, subtype.ext $ by simp only [map_add, subalgebra.coe_add, subtype.coe_mk],
map_mul' := λ x y, subtype.ext $ by simp only [subalgebra.coe_mul, map_mul, subtype.coe_mk] }
namespace ring_of_integers
variables {K}
instance [number_field K] : is_fraction_ring (𝓞 K) K :=
integral_closure.is_fraction_ring_of_finite_extension ℚ _
instance : is_integral_closure (𝓞 K) ℤ K :=
integral_closure.is_integral_closure _ _
instance [number_field K] : is_integrally_closed (𝓞 K) :=
integral_closure.is_integrally_closed_of_finite_extension ℚ
lemma is_integral_coe (x : 𝓞 K) : is_integral ℤ (x : K) :=
x.2
lemma map_mem {F L : Type*} [field L] [char_zero K] [char_zero L]
[alg_hom_class F ℚ K L] (f : F) (x : 𝓞 K) : f x ∈ 𝓞 L :=
(mem_ring_of_integers _ _).2 $ map_is_integral_int f $ ring_of_integers.is_integral_coe x
/-- The ring of integers of `K` are equivalent to any integral closure of `ℤ` in `K` -/
protected noncomputable def equiv (R : Type*) [comm_ring R] [algebra R K]
[is_integral_closure R ℤ K] : 𝓞 K ≃+* R :=
(is_integral_closure.equiv ℤ R K _).symm.to_ring_equiv
variable (K)
include nf
instance : char_zero (𝓞 K) := char_zero.of_module _ K
instance : is_noetherian ℤ (𝓞 K) := is_integral_closure.is_noetherian _ ℚ K _
/-- The ring of integers of a number field is not a field. -/
lemma not_is_field : ¬ is_field (𝓞 K) :=
begin
have h_inj : function.injective ⇑(algebra_map ℤ (𝓞 K)),
{ exact ring_hom.injective_int (algebra_map ℤ (𝓞 K)) },
intro hf,
exact int.not_is_field
(((is_integral_closure.is_integral_algebra ℤ K).is_field_iff_is_field h_inj).mpr hf)
end
instance : is_dedekind_domain (𝓞 K) :=
is_integral_closure.is_dedekind_domain ℤ ℚ K _
instance : free ℤ (𝓞 K) := is_integral_closure.module_free ℤ ℚ K (𝓞 K)
instance : is_localization (algebra.algebra_map_submonoid (𝓞 K) ℤ⁰) K :=
is_integral_closure.is_localization ℤ ℚ K (𝓞 K)
/-- A ℤ-basis of the ring of integers of `K`. -/
noncomputable def basis : basis (free.choose_basis_index ℤ (𝓞 K)) ℤ (𝓞 K) :=
free.choose_basis ℤ (𝓞 K)
end ring_of_integers
include nf
/-- A basis of `K` over `ℚ` that is also a basis of `𝓞 K` over `ℤ`. -/
noncomputable def integral_basis : basis (free.choose_basis_index ℤ (𝓞 K)) ℚ K :=
basis.localization_localization ℚ (non_zero_divisors ℤ) K (ring_of_integers.basis K)
@[simp]
lemma integral_basis_apply (i : free.choose_basis_index ℤ (𝓞 K)) :
integral_basis K i = algebra_map (𝓞 K) K (ring_of_integers.basis K i) :=
basis.localization_localization_apply ℚ (non_zero_divisors ℤ) K (ring_of_integers.basis K) i
lemma ring_of_integers.rank :
finite_dimensional.finrank ℤ (𝓞 K) = finite_dimensional.finrank ℚ K :=
is_integral_closure.rank ℤ ℚ K (𝓞 K)
end number_field
namespace rat
open number_field
instance number_field : number_field ℚ :=
{ to_char_zero := infer_instance,
to_finite_dimensional :=
-- The vector space structure of `ℚ` over itself can arise in multiple ways:
-- all fields are vector spaces over themselves (used in `rat.finite_dimensional`)
-- all char 0 fields have a canonical embedding of `ℚ` (used in `number_field`).
-- Show that these coincide:
by convert (infer_instance : finite_dimensional ℚ ℚ), }
/-- The ring of integers of `ℚ` as a number field is just `ℤ`. -/
noncomputable def ring_of_integers_equiv : ring_of_integers ℚ ≃+* ℤ :=
ring_of_integers.equiv ℤ
end rat
namespace adjoin_root
section
open_locale polynomial
local attribute [-instance] algebra_rat
/-- The quotient of `ℚ[X]` by the ideal generated by an irreducible polynomial of `ℚ[X]`
is a number field. -/
instance {f : ℚ[X]} [hf : fact (irreducible f)] : number_field (adjoin_root f) :=
{ to_char_zero := char_zero_of_injective_algebra_map (algebra_map ℚ _).injective,
to_finite_dimensional := by convert (adjoin_root.power_basis hf.out.ne_zero).finite_dimensional }
end
end adjoin_root
|
522a58becef034a38eb91903454ea9e6bd5fee0e | 32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7 | /stage0/src/Init/Core.lean | 8b9f71dd80ecd614a5eb49899f2f44af5f173b99 | [
"Apache-2.0"
] | permissive | walterhu1015/lean4 | b2c71b688975177402758924eaa513475ed6ce72 | 2214d81e84646a905d0b20b032c89caf89c737ad | refs/heads/master | 1,671,342,096,906 | 1,599,695,985,000 | 1,599,695,985,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 64,520 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
notation, basic datatypes and type classes
-/
prelude
notation `Prop` := Sort 0
reserve infixr ` $ `:1
notation f ` $ ` a := f a
/- Logical operations and relations -/
reserve prefix `¬`:40
reserve infixr ` ∧ `:35
reserve infixr ` /\ `:35
reserve infixr ` \/ `:30
reserve infixr ` ∨ `:30
reserve infix ` <-> `:20
reserve infix ` ↔ `:20
reserve infix ` = `:50
reserve infix ` == `:50
reserve infix ` != `:50
reserve infix ` ~= `:50
reserve infix ` ≅ `:50
reserve infix ` ≠ `:50
reserve infix ` ≈ `:50
reserve infixr ` ▸ `:75
/- types and Type constructors -/
reserve infixr ` × `:35
/- arithmetic operations -/
reserve infixl ` + `:65
reserve infixl ` - `:65
reserve infixl ` * `:70
reserve infixl ` / `:70
reserve infixl ` % `:70
reserve infixl ` %ₙ `:70
reserve prefix `-`:100
reserve infixr ` ^ `:80
reserve infixr ` ∘ `:90
reserve infix ` <= `:50
reserve infix ` ≤ `:50
reserve infix ` < `:50
reserve infix ` >= `:50
reserve infix ` ≥ `:50
reserve infix ` > `:50
/- boolean operations -/
reserve prefix `!`:40
reserve infixl ` && `:35
reserve infixl ` || `:30
/- other symbols -/
reserve infixl ` ++ `:65
reserve infixr ` :: `:67
/- Control -/
reserve infixr ` <|> `:2
reserve infixl ` >>= `:55
reserve infixr ` >=> `:55
reserve infixl ` <*> `:60
reserve infixl ` <* ` :60
reserve infixr ` *> ` :60
reserve infixr ` >> ` :60
reserve infixr ` <$> `:100
reserve infixl ` <&> `:100
universes u v w
/-- Auxiliary unsafe constant used by the Compiler when erasing proofs from code. -/
unsafe axiom lcProof {α : Prop} : α
/-- Auxiliary unsafe constant used by the Compiler to mark unreachable code. -/
unsafe axiom lcUnreachable {α : Sort u} : α
@[inline] def id {α : Sort u} (a : α) : α := a
def inline {α : Sort u} (a : α) : α := a
@[inline] def flip {α : Sort u} {β : Sort v} {φ : Sort w} (f : α → β → φ) : β → α → φ :=
fun b a => f a b
/-
The kernel definitional equality test (t =?= s) has special support for idDelta applications.
It implements the following rules
1) (idDelta t) =?= t
2) t =?= (idDelta t)
3) (idDelta t) =?= s IF (unfoldOf t) =?= s
4) t =?= idDelta s IF t =?= (unfoldOf s)
This is mechanism for controlling the delta reduction (aka unfolding) used in the kernel.
We use idDelta applications to address performance problems when Type checking
theorems generated by the equation Compiler.
-/
@[inline] def idDelta {α : Sort u} (a : α) : α :=
a
/-- Gadget for optional parameter support. -/
@[reducible] def optParam (α : Sort u) (default : α) : Sort u :=
α
/-- Gadget for marking output parameters in type classes. -/
@[reducible] def outParam (α : Sort u) : Sort u := α
/-- Auxiliary Declaration used to implement the notation (a : α) -/
@[reducible] def typedExpr (α : Sort u) (a : α) : α := a
/- `idRhs` is an auxiliary Declaration used in the equation Compiler to address performance
issues when proving equational theorems. The equation Compiler uses it as a marker. -/
@[macroInline, reducible] def idRhs (α : Sort u) (a : α) : α := a
/-- Auxiliary Declaration used to implement the named patterns `x@p` -/
@[reducible] def namedPattern {α : Sort u} (x a : α) : α := a
inductive PUnit : Sort u
| unit : PUnit
/-- An abbreviation for `PUnit.{0}`, its most common instantiation.
This Type should be preferred over `PUnit` where possible to avoid
unnecessary universe parameters. -/
abbrev Unit : Type := PUnit
@[matchPattern] abbrev Unit.unit : Unit := PUnit.unit
/- Remark: thunks have an efficient implementation in the runtime. -/
structure Thunk (α : Type u) : Type u :=
(fn : Unit → α)
attribute [extern "lean_mk_thunk"] Thunk.mk
@[noinline, extern "lean_thunk_pure"]
protected def Thunk.pure {α : Type u} (a : α) : Thunk α :=
⟨fun _ => a⟩
@[noinline, extern "lean_thunk_get_own"]
protected def Thunk.get {α : Type u} (x : @& Thunk α) : α :=
x.fn ()
@[noinline, extern "lean_thunk_map"]
protected def Thunk.map {α : Type u} {β : Type v} (f : α → β) (x : Thunk α) : Thunk β :=
⟨fun _ => f x.get⟩
@[noinline, extern "lean_thunk_bind"]
protected def Thunk.bind {α : Type u} {β : Type v} (x : Thunk α) (f : α → Thunk β) : Thunk β :=
⟨fun _ => (f x.get).get⟩
/- Remark: tasks have an efficient implementation in the runtime. -/
structure Task (α : Type u) : Type u :=
(fn : Unit → α)
attribute [extern "lean_mk_task"] Task.mk
@[noinline, extern "lean_task_pure"]
protected def Task.pure {α : Type u} (a : α) : Task α :=
⟨fun _ => a⟩
@[noinline, extern "lean_task_get_own"]
protected def Task.get {α : Type u} (x : @& Task α) : α :=
x.fn ()
@[noinline, extern "lean_task_map"]
protected def Task.map {α : Type u} {β : Type v} (f : α → β) (x : Task α) : Task β :=
⟨fun _ => f x.get⟩
@[noinline, extern "lean_task_bind"]
protected def Task.bind {α : Type u} {β : Type v} (x : Task α) (f : α → Task β) : Task β :=
⟨fun _ => (f x.get).get⟩
inductive True : Prop
| intro : True
inductive False : Prop
inductive Empty : Type
def Not (a : Prop) : Prop := a → False
prefix `¬` := Not
inductive Eq {α : Sort u} (a : α) : α → Prop
| refl {} : Eq a
@[elabAsEliminator, inline, reducible]
def Eq.ndrec.{u1, u2} {α : Sort u2} {a : α} {C : α → Sort u1} (m : C a) {b : α} (h : Eq a b) : C b :=
@Eq.rec α a (fun α _ => C α) m b h
@[elabAsEliminator, inline, reducible]
def Eq.ndrecOn.{u1, u2} {α : Sort u2} {a : α} {C : α → Sort u1} {b : α} (h : Eq a b) (m : C a) : C b :=
@Eq.rec α a (fun α _ => C α) m b h
/-
Initialize the Quotient Module, which effectively adds the following definitions:
constant Quot {α : Sort u} (r : α → α → Prop) : Sort u
constant Quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : Quot r
constant Quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) :
(∀ a b : α, r a b → Eq (f a) (f b)) → Quot r → β
constant Quot.ind {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} :
(∀ a : α, β (Quot.mk r a)) → ∀ q : Quot r, β q
-/
init_quot
inductive HEq {α : Sort u} (a : α) : ∀ {β : Sort u}, β → Prop
| refl {} : HEq a
structure Prod (α : Type u) (β : Type v) :=
(fst : α) (snd : β)
attribute [unbox] Prod
/-- Similar to `Prod`, but α and β can be propositions.
We use this Type internally to automatically generate the brecOn recursor. -/
structure PProd (α : Sort u) (β : Sort v) :=
(fst : α) (snd : β)
structure And (a b : Prop) : Prop :=
intro :: (left : a) (right : b)
structure Iff (a b : Prop) : Prop :=
intro :: (mp : a → b) (mpr : b → a)
/- Eq basic support -/
infix `=` := Eq
@[matchPattern] def rfl {α : Sort u} {a : α} : a = a := Eq.refl a
@[elabAsEliminator]
theorem Eq.subst {α : Sort u} {P : α → Prop} {a b : α} (h₁ : a = b) (h₂ : P a) : P b :=
Eq.ndrec h₂ h₁
infixr `▸` := Eq.subst
theorem Eq.trans {α : Sort u} {a b c : α} (h₁ : a = b) (h₂ : b = c) : a = c :=
h₂ ▸ h₁
theorem Eq.symm {α : Sort u} {a b : α} (h : a = b) : b = a :=
h ▸ rfl
infix `~=` := HEq
infix `≅` := HEq
@[matchPattern] def HEq.rfl {α : Sort u} {a : α} : a ≅ a := HEq.refl a
theorem eqOfHEq {α : Sort u} {a a' : α} (h : a ≅ a') : a = a' :=
have ∀ (α' : Sort u) (a' : α') (h₁ : @HEq α a α' a') (h₂ : α = α'), (Eq.recOn h₂ a : α') = a' :=
fun (α' : Sort u) (a' : α') (h₁ : @HEq α a α' a') => HEq.recOn h₁ (fun (h₂ : α = α) => rfl);
show (Eq.ndrecOn (Eq.refl α) a : α) = a' from
this α a' h (Eq.refl α)
inductive Sum (α : Type u) (β : Type v)
| inl (val : α) : Sum
| inr (val : β) : Sum
inductive PSum (α : Sort u) (β : Sort v)
| inl (val : α) : PSum
| inr (val : β) : PSum
inductive Or (a b : Prop) : Prop
| inl (h : a) : Or
| inr (h : b) : Or
def Or.introLeft {a : Prop} (b : Prop) (ha : a) : Or a b :=
Or.inl ha
def Or.introRight (a : Prop) {b : Prop} (hb : b) : Or a b :=
Or.inr hb
structure Sigma {α : Type u} (β : α → Type v) :=
mk :: (fst : α) (snd : β fst)
attribute [unbox] Sigma
structure PSigma {α : Sort u} (β : α → Sort v) :=
mk :: (fst : α) (snd : β fst)
inductive Bool : Type
| false : Bool
| true : Bool
/- Remark: Subtype must take a Sort instead of Type because of the axiom strongIndefiniteDescription. -/
structure Subtype {α : Sort u} (p : α → Prop) :=
(val : α) (property : p val)
inductive Exists {α : Sort u} (p : α → Prop) : Prop
| intro (w : α) (h : p w) : Exists
class inductive Decidable (p : Prop)
| isFalse (h : ¬p) : Decidable
| isTrue (h : p) : Decidable
abbrev DecidablePred {α : Sort u} (r : α → Prop) :=
∀ (a : α), Decidable (r a)
abbrev DecidableRel {α : Sort u} (r : α → α → Prop) :=
∀ (a b : α), Decidable (r a b)
abbrev DecidableEq (α : Sort u) :=
∀ (a b : α), Decidable (a = b)
def decEq {α : Sort u} [s : DecidableEq α] (a b : α) : Decidable (a = b) :=
s a b
inductive Option (α : Type u)
| none : Option
| some (val : α) : Option
attribute [unbox] Option
export Option (none some)
export Bool (false true)
inductive List (T : Type u)
| nil : List
| cons (hd : T) (tl : List) : List
infixr `::` := List.cons
inductive Nat
| zero : Nat
| succ (n : Nat) : Nat
/- Auxiliary axiom used to implement `sorry`.
TODO: add this theorem on-demand. That is,
we should only add it if after the first error. -/
axiom sorryAx (α : Sort u) (synthetic := true) : α
/- Declare builtin and reserved notation -/
class HasZero (α : Type u) := mk {} :: (zero : α)
class HasOne (α : Type u) := mk {} :: (one : α)
class HasAdd (α : Type u) := (add : α → α → α)
class HasMul (α : Type u) := (mul : α → α → α)
class HasNeg (α : Type u) := (neg : α → α)
class HasSub (α : Type u) := (sub : α → α → α)
class HasDiv (α : Type u) := (div : α → α → α)
class HasMod (α : Type u) := (mod : α → α → α)
class HasModN (α : Type u) := (modn : α → Nat → α)
class HasLessEq (α : Type u) := (LessEq : α → α → Prop)
class HasLess (α : Type u) := (Less : α → α → Prop)
class HasBeq (α : Type u) := (beq : α → α → Bool)
class HasAppend (α : Type u) := (append : α → α → α)
class HasOrelse (α : Type u) := (orelse : α → α → α)
class HasAndthen (α : Type u) := (andthen : α → α → α)
class HasEquiv (α : Sort u) := (Equiv : α → α → Prop)
class HasEmptyc (α : Type u) := (emptyc : α)
class HasPow (α : Type u) (β : Type v) :=
(pow : α → β → α)
infix `+` := HasAdd.add
infix `*` := HasMul.mul
infix `-` := HasSub.sub
infix `/` := HasDiv.div
infix `%` := HasMod.mod
infix `%ₙ` := HasModN.modn
prefix `-` := HasNeg.neg
infix `<=` := HasLessEq.LessEq
infix `≤` := HasLessEq.LessEq
infix `<` := HasLess.Less
infix `==` := HasBeq.beq
infix `++` := HasAppend.append
notation `∅` := HasEmptyc.emptyc
infix `≈` := HasEquiv.Equiv
infixr `^` := HasPow.pow
infixr `/\` := And
infixr `∧` := And
infixr `\/` := Or
infixr `∨` := Or
infix `<->` := Iff
infix `↔` := Iff
-- notation `exists` binders `, ` r:(scoped P, Exists P) := r
-- notation `∃` binders `, ` r:(scoped P, Exists P) := r
infixr `<|>` := HasOrelse.orelse
infixr `>>` := HasAndthen.andthen
@[reducible] def GreaterEq {α : Type u} [HasLessEq α] (a b : α) : Prop := HasLessEq.LessEq b a
@[reducible] def Greater {α : Type u} [HasLess α] (a b : α) : Prop := HasLess.Less b a
infix `>=` := GreaterEq
infix `≥` := GreaterEq
infix `>` := Greater
@[inline] def bit0 {α : Type u} [s : HasAdd α] (a : α) : α := a + a
@[inline] def bit1 {α : Type u} [s₁ : HasOne α] [s₂ : HasAdd α] (a : α) : α := (bit0 a) + 1
attribute [matchPattern] HasZero.zero HasOne.one bit0 bit1 HasAdd.add HasNeg.neg
/- Nat basic instances -/
@[extern "lean_nat_add"]
protected def Nat.add : (@& Nat) → (@& Nat) → Nat
| a, Nat.zero => a
| a, Nat.succ b => Nat.succ (Nat.add a b)
/- We mark the following definitions as pattern to make sure they can be used in recursive equations,
and reduced by the equation Compiler. -/
attribute [matchPattern] Nat.add Nat.add._main
instance : HasZero Nat := ⟨Nat.zero⟩
instance : HasOne Nat := ⟨Nat.succ (Nat.zero)⟩
instance : HasAdd Nat := ⟨Nat.add⟩
/- Auxiliary constant used by equation compiler. -/
constant hugeFuel : Nat := 10000
def std.priority.default : Nat := 1000
def std.priority.max : Nat := 0xFFFFFFFF
protected def Nat.prio := std.priority.default + 100
/-
Global declarations of right binding strength
If a Module reassigns these, it will be incompatible with other modules that adhere to these
conventions.
When hovering over a symbol, use "C-c C-k" to see how to input it.
-/
def std.prec.max : Nat := 1024 -- the strength of application, identifiers, (, [, etc.
def std.prec.arrow : Nat := 25
/-
The next def is "max + 10". It can be used e.g. for postfix operations that should
be stronger than application.
-/
def std.prec.maxPlus : Nat := std.prec.max + 10
infixr `×` := Prod
-- notation for n-ary tuples
/- Some type that is not a scalar value in our runtime. -/
structure NonScalar :=
(val : Nat)
/- Some type that is not a scalar value in our runtime and is universe polymorphic. -/
inductive PNonScalar : Type u
| mk (v : Nat) : PNonScalar
/- For numeric literals notation -/
class HasOfNat (α : Type u) :=
(ofNat : Nat → α)
export HasOfNat (ofNat)
instance : HasOfNat Nat :=
⟨id⟩
/- sizeof -/
class HasSizeof (α : Sort u) :=
(sizeof : α → Nat)
export HasSizeof (sizeof)
/-
Declare sizeof instances and theorems for types declared before HasSizeof.
From now on, the inductive Compiler will automatically generate sizeof instances and theorems.
-/
/- Every Type `α` has a default HasSizeof instance that just returns 0 for every element of `α` -/
protected def default.sizeof (α : Sort u) : α → Nat
| a => 0
instance defaultHasSizeof (α : Sort u) : HasSizeof α :=
⟨default.sizeof α⟩
protected def Nat.sizeof : Nat → Nat
| n => n
instance : HasSizeof Nat :=
⟨Nat.sizeof⟩
protected def Prod.sizeof {α : Type u} {β : Type v} [HasSizeof α] [HasSizeof β] : (Prod α β) → Nat
| ⟨a, b⟩ => 1 + sizeof a + sizeof b
instance (α : Type u) (β : Type v) [HasSizeof α] [HasSizeof β] : HasSizeof (Prod α β) :=
⟨Prod.sizeof⟩
protected def Sum.sizeof {α : Type u} {β : Type v} [HasSizeof α] [HasSizeof β] : (Sum α β) → Nat
| Sum.inl a => 1 + sizeof a
| Sum.inr b => 1 + sizeof b
instance (α : Type u) (β : Type v) [HasSizeof α] [HasSizeof β] : HasSizeof (Sum α β) :=
⟨Sum.sizeof⟩
protected def PSum.sizeof {α : Type u} {β : Type v} [HasSizeof α] [HasSizeof β] : (PSum α β) → Nat
| PSum.inl a => 1 + sizeof a
| PSum.inr b => 1 + sizeof b
instance (α : Type u) (β : Type v) [HasSizeof α] [HasSizeof β] : HasSizeof (PSum α β) :=
⟨PSum.sizeof⟩
protected def Sigma.sizeof {α : Type u} {β : α → Type v} [HasSizeof α] [∀ a, HasSizeof (β a)] : Sigma β → Nat
| ⟨a, b⟩ => 1 + sizeof a + sizeof b
instance (α : Type u) (β : α → Type v) [HasSizeof α] [∀ a, HasSizeof (β a)] : HasSizeof (Sigma β) :=
⟨Sigma.sizeof⟩
protected def PSigma.sizeof {α : Type u} {β : α → Type v} [HasSizeof α] [∀ a, HasSizeof (β a)] : PSigma β → Nat
| ⟨a, b⟩ => 1 + sizeof a + sizeof b
instance (α : Type u) (β : α → Type v) [HasSizeof α] [∀ a, HasSizeof (β a)] : HasSizeof (PSigma β) :=
⟨PSigma.sizeof⟩
protected def PUnit.sizeof : PUnit → Nat
| u => 1
instance : HasSizeof PUnit := ⟨PUnit.sizeof⟩
protected def Bool.sizeof : Bool → Nat
| b => 1
instance : HasSizeof Bool := ⟨Bool.sizeof⟩
protected def Option.sizeof {α : Type u} [HasSizeof α] : Option α → Nat
| none => 1
| some a => 1 + sizeof a
instance (α : Type u) [HasSizeof α] : HasSizeof (Option α) :=
⟨Option.sizeof⟩
protected def List.sizeof {α : Type u} [HasSizeof α] : List α → Nat
| List.nil => 1
| List.cons a l => 1 + sizeof a + List.sizeof l
instance (α : Type u) [HasSizeof α] : HasSizeof (List α) :=
⟨List.sizeof⟩
protected def Subtype.sizeof {α : Type u} [HasSizeof α] {p : α → Prop} : Subtype p → Nat
| ⟨a, _⟩ => sizeof a
instance {α : Type u} [HasSizeof α] (p : α → Prop) : HasSizeof (Subtype p) :=
⟨Subtype.sizeof⟩
theorem natAddZero (n : Nat) : n + 0 = n := rfl
theorem optParamEq (α : Sort u) (default : α) : optParam α default = α := rfl
/-- Like `by applyInstance`, but not dependent on the tactic framework. -/
@[reducible] def inferInstance {α : Type u} [i : α] : α := i
@[reducible, elabSimple] def inferInstanceAs (α : Type u) [i : α] : α := i
/- Boolean operators -/
@[macroInline] def cond {a : Type u} : Bool → a → a → a
| true, x, y => x
| false, x, y => y
@[inline] def condEq {β : Sort u} (b : Bool) (h₁ : b = true → β) (h₂ : b = false → β) : β :=
@Bool.casesOn (λ x => b = x → β) b h₂ h₁ rfl
@[macroInline] def or : Bool → Bool → Bool
| true, _ => true
| false, b => b
@[macroInline] def and : Bool → Bool → Bool
| false, _ => false
| true, b => b
@[macroInline] def not : Bool → Bool
| true => false
| false => true
@[macroInline] def xor : Bool → Bool → Bool
| true, b => not b
| false, b => b
prefix `!` := not
infix `||` := or
infix `&&` := and
@[extern c inline "#1 || #2"] def strictOr (b₁ b₂ : Bool) := b₁ || b₂
@[extern c inline "#1 && #2"] def strictAnd (b₁ b₂ : Bool) := b₁ && b₂
@[inline] def bne {α : Type u} [HasBeq α] (a b : α) : Bool :=
!(a == b)
infix `!=` := bne
/- Logical connectives an equality -/
def implies (a b : Prop) := a → b
theorem implies.trans {p q r : Prop} (h₁ : implies p q) (h₂ : implies q r) : implies p r :=
fun hp => h₂ (h₁ hp)
def trivial : True := ⟨⟩
@[macroInline] def False.elim {C : Sort u} (h : False) : C :=
False.rec (fun _ => C) h
@[macroInline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : ¬a) : b :=
False.elim (h₂ h₁)
theorem mt {a b : Prop} (h₁ : a → b) (h₂ : ¬b) : ¬a :=
fun ha => h₂ (h₁ ha)
theorem notFalse : ¬False := id
-- proof irrelevance is built in
theorem proofIrrel {a : Prop} (h₁ h₂ : a) : h₁ = h₂ := rfl
theorem id.def {α : Sort u} (a : α) : id a = a := rfl
@[macroInline] def Eq.mp {α β : Sort u} (h₁ : α = β) (h₂ : α) : β :=
Eq.recOn h₁ h₂
@[macroInline] def Eq.mpr {α β : Sort u} : (α = β) → β → α :=
fun h₁ h₂ => Eq.recOn (Eq.symm h₁) h₂
@[elabAsEliminator]
theorem Eq.substr {α : Sort u} {p : α → Prop} {a b : α} (h₁ : b = a) (h₂ : p a) : p b :=
Eq.subst (Eq.symm h₁) h₂
theorem congr {α : Sort u} {β : Sort v} {f₁ f₂ : α → β} {a₁ a₂ : α} (h₁ : f₁ = f₂) (h₂ : a₁ = a₂) : f₁ a₁ = f₂ a₂ :=
Eq.subst h₁ (Eq.subst h₂ rfl)
theorem congrFun {α : Sort u} {β : α → Sort v} {f g : ∀ x, β x} (h : f = g) (a : α) : f a = g a :=
Eq.subst h (Eq.refl (f a))
theorem congrArg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) (h : a₁ = a₂) : f a₁ = f a₂ :=
congr rfl h
theorem transRelLeft {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : r a b) (h₂ : b = c) : r a c :=
h₂ ▸ h₁
theorem transRelRight {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : a = b) (h₂ : r b c) : r a c :=
h₁.symm ▸ h₂
theorem ofEqTrue {p : Prop} (h : p = True) : p :=
h.symm ▸ trivial
theorem notOfEqFalse {p : Prop} (h : p = False) : ¬p :=
fun hp => h ▸ hp
@[macroInline] def cast {α β : Sort u} (h : α = β) (a : α) : β :=
Eq.rec a h
theorem castProofIrrel {α β : Sort u} (h₁ h₂ : α = β) (a : α) : cast h₁ a = cast h₂ a := rfl
theorem castEq {α : Sort u} (h : α = α) (a : α) : cast h a = a := rfl
@[reducible] def Ne {α : Sort u} (a b : α) := ¬(a = b)
infix `≠` := Ne
theorem Ne.def {α : Sort u} (a b : α) : a ≠ b = ¬ (a = b) := rfl
section Ne
variable {α : Sort u}
variables {a b : α} {p : Prop}
theorem Ne.intro (h : a = b → False) : a ≠ b := h
theorem Ne.elim (h : a ≠ b) : a = b → False := h
theorem Ne.irrefl (h : a ≠ a) : False := h rfl
theorem Ne.symm (h : a ≠ b) : b ≠ a :=
fun h₁ => h (h₁.symm)
theorem falseOfNe : a ≠ a → False := Ne.irrefl
theorem neFalseOfSelf : p → p ≠ False :=
fun (hp : p) (h : p = False) => h ▸ hp
theorem neTrueOfNot : ¬p → p ≠ True :=
fun (hnp : ¬p) (h : p = True) => (h ▸ hnp) trivial
theorem trueNeFalse : ¬True = False :=
neFalseOfSelf trivial
end Ne
theorem eqFalseOfNeTrue : ∀ {b : Bool}, b ≠ true → b = false
| true, h => False.elim (h rfl)
| false, h => rfl
theorem eqTrueOfNeFalse : ∀ {b : Bool}, b ≠ false → b = true
| true, h => rfl
| false, h => False.elim (h rfl)
theorem neFalseOfEqTrue : ∀ {b : Bool}, b = true → b ≠ false
| true, _ => fun h => Bool.noConfusion h
| false, h => Bool.noConfusion h
theorem neTrueOfEqFalse : ∀ {b : Bool}, b = false → b ≠ true
| true, h => Bool.noConfusion h
| false, _ => fun h => Bool.noConfusion h
section
variables {α β φ : Sort u} {a a' : α} {b b' : β} {c : φ}
@[elabAsEliminator]
theorem HEq.ndrec.{u1, u2} {α : Sort u2} {a : α} {C : ∀ {β : Sort u2}, β → Sort u1} (m : C a) {β : Sort u2} {b : β} (h : a ≅ b) : C b :=
@HEq.rec α a (fun β b _ => C b) m β b h
@[elabAsEliminator]
theorem HEq.ndrecOn.{u1, u2} {α : Sort u2} {a : α} {C : ∀ {β : Sort u2}, β → Sort u1} {β : Sort u2} {b : β} (h : a ≅ b) (m : C a) : C b :=
@HEq.rec α a (fun β b _ => C b) m β b h
theorem HEq.elim {α : Sort u} {a : α} {p : α → Sort v} {b : α} (h₁ : a ≅ b) (h₂ : p a) : p b :=
Eq.recOn (eqOfHEq h₁) h₂
theorem HEq.subst {p : ∀ (T : Sort u), T → Prop} (h₁ : a ≅ b) (h₂ : p α a) : p β b :=
HEq.ndrecOn h₁ h₂
theorem HEq.symm (h : a ≅ b) : b ≅ a :=
HEq.ndrecOn h (HEq.refl a)
theorem heqOfEq (h : a = a') : a ≅ a' :=
Eq.subst h (HEq.refl a)
theorem HEq.trans (h₁ : a ≅ b) (h₂ : b ≅ c) : a ≅ c :=
HEq.subst h₂ h₁
theorem heqOfHEqOfEq (h₁ : a ≅ b) (h₂ : b = b') : a ≅ b' :=
HEq.trans h₁ (heqOfEq h₂)
theorem heqOfEqOfHEq (h₁ : a = a') (h₂ : a' ≅ b) : a ≅ b :=
HEq.trans (heqOfEq h₁) h₂
def typeEqOfHEq (h : a ≅ b) : α = β :=
HEq.ndrecOn h (Eq.refl α)
end
theorem eqRecHEq {α : Sort u} {φ : α → Sort v} : ∀ {a a' : α} (h : a = a') (p : φ a), (Eq.recOn h p : φ a') ≅ p
| a, _, rfl, p => HEq.refl p
theorem ofHEqTrue {a : Prop} (h : a ≅ True) : a :=
ofEqTrue (eqOfHEq h)
theorem castHEq : ∀ {α β : Sort u} (h : α = β) (a : α), cast h a ≅ a
| α, _, rfl, a => HEq.refl a
variables {a b c d : Prop}
theorem And.elim (h₁ : a ∧ b) (h₂ : a → b → c) : c :=
And.rec h₂ h₁
theorem And.swap : a ∧ b → b ∧ a :=
fun ⟨ha, hb⟩ => ⟨hb, ha⟩
def And.symm := @And.swap
theorem Or.elim (h₁ : a ∨ b) (h₂ : a → c) (h₃ : b → c) : c :=
Or.rec h₂ h₃ h₁
theorem Or.swap (h : a ∨ b) : b ∨ a :=
Or.elim h Or.inr Or.inl
def Or.symm := @Or.swap
/- xor -/
def Xor (a b : Prop) : Prop := (a ∧ ¬ b) ∨ (b ∧ ¬ a)
@[recursor 5]
theorem Iff.elim (h₁ : (a → b) → (b → a) → c) (h₂ : a ↔ b) : c :=
Iff.rec h₁ h₂
theorem Iff.left : (a ↔ b) → a → b := Iff.mp
theorem Iff.right : (a ↔ b) → b → a := Iff.mpr
theorem iffIffImpliesAndImplies (a b : Prop) : (a ↔ b) ↔ (a → b) ∧ (b → a) :=
Iff.intro (fun h => And.intro h.mp h.mpr) (fun h => Iff.intro h.left h.right)
theorem Iff.refl (a : Prop) : a ↔ a :=
Iff.intro (fun h => h) (fun h => h)
theorem Iff.rfl {a : Prop} : a ↔ a :=
Iff.refl a
theorem Iff.trans (h₁ : a ↔ b) (h₂ : b ↔ c) : a ↔ c :=
Iff.intro
(fun ha => Iff.mp h₂ (Iff.mp h₁ ha))
(fun hc => Iff.mpr h₁ (Iff.mpr h₂ hc))
theorem Iff.symm (h : a ↔ b) : b ↔ a :=
Iff.intro (Iff.right h) (Iff.left h)
theorem Iff.comm : (a ↔ b) ↔ (b ↔ a) :=
Iff.intro Iff.symm Iff.symm
theorem Eq.toIff {a b : Prop} (h : a = b) : a ↔ b :=
Eq.recOn h Iff.rfl
theorem neqOfNotIff {a b : Prop} : ¬(a ↔ b) → a ≠ b :=
fun h₁ h₂ =>
have a ↔ b from Eq.subst h₂ (Iff.refl a);
absurd this h₁
theorem notIffNotOfIff (h₁ : a ↔ b) : ¬a ↔ ¬b :=
Iff.intro
(fun (hna : ¬ a) (hb : b) => hna (Iff.right h₁ hb))
(fun (hnb : ¬ b) (ha : a) => hnb (Iff.left h₁ ha))
theorem ofIffTrue (h : a ↔ True) : a :=
Iff.mp (Iff.symm h) trivial
theorem notOfIffFalse : (a ↔ False) → ¬a := Iff.mp
theorem iffTrueIntro (h : a) : a ↔ True :=
Iff.intro
(fun hl => trivial)
(fun hr => h)
theorem iffFalseIntro (h : ¬a) : a ↔ False :=
Iff.intro h (False.rec (fun _ => a))
theorem notNotIntro (ha : a) : ¬¬a :=
fun hna => hna ha
theorem notTrue : (¬ True) ↔ False :=
iffFalseIntro (notNotIntro trivial)
/- or resolution rulses -/
theorem resolveLeft {a b : Prop} (h : a ∨ b) (na : ¬ a) : b :=
Or.elim h (fun ha => absurd ha na) id
theorem negResolveLeft {a b : Prop} (h : ¬ a ∨ b) (ha : a) : b :=
Or.elim h (fun na => absurd ha na) id
theorem resolveRight {a b : Prop} (h : a ∨ b) (nb : ¬ b) : a :=
Or.elim h id (fun hb => absurd hb nb)
theorem negResolveRight {a b : Prop} (h : a ∨ ¬ b) (hb : b) : a :=
Or.elim h id (fun nb => absurd hb nb)
/- Exists -/
theorem Exists.elim {α : Sort u} {p : α → Prop} {b : Prop}
(h₁ : Exists (fun x => p x)) (h₂ : ∀ (a : α), p a → b) : b :=
Exists.rec h₂ h₁
/- Decidable -/
@[inlineIfReduce, nospecialize] def Decidable.decide (p : Prop) [h : Decidable p] : Bool :=
Decidable.casesOn h (fun h₁ => false) (fun h₂ => true)
export Decidable (isTrue isFalse decide)
instance beqOfEq {α : Type u} [DecidableEq α] : HasBeq α :=
⟨fun a b => decide (a = b)⟩
theorem decideTrueEqTrue (h : Decidable True) : @decide True h = true :=
match h with
| isTrue h => rfl
| isFalse h => False.elim (Iff.mp notTrue h)
theorem decideFalseEqFalse (h : Decidable False) : @decide False h = false :=
match h with
| isFalse h => rfl
| isTrue h => False.elim h
theorem decideEqTrue : ∀ {p : Prop} [s : Decidable p], p → decide p = true
| _, isTrue _, _ => rfl
| _, isFalse h₁, h₂ => absurd h₂ h₁
theorem decideEqFalse : ∀ {p : Prop} [s : Decidable p], ¬p → decide p = false
| _, isTrue h₁, h₂ => absurd h₁ h₂
| _, isFalse h, _ => rfl
theorem ofDecideEqTrue {p : Prop} [s : Decidable p] : decide p = true → p :=
fun h => match s with
| isTrue h₁ => h₁
| isFalse h₁ => absurd h (neTrueOfEqFalse (decideEqFalse h₁))
theorem ofDecideEqFalse {p : Prop} [s : Decidable p] : decide p = false → ¬p :=
fun h => match s with
| isTrue h₁ => absurd h (neFalseOfEqTrue (decideEqTrue h₁))
| isFalse h₁ => h₁
/-- Similar to `decide`, but uses an explicit instance -/
@[inline] def toBoolUsing {p : Prop} (d : Decidable p) : Bool :=
@decide p d
theorem toBoolUsingEqTrue {p : Prop} (d : Decidable p) (h : p) : toBoolUsing d = true :=
@decideEqTrue _ d h
theorem ofBoolUsingEqTrue {p : Prop} {d : Decidable p} (h : toBoolUsing d = true) : p :=
@ofDecideEqTrue _ d h
theorem ofBoolUsingEqFalse {p : Prop} {d : Decidable p} (h : toBoolUsing d = false) : ¬ p :=
@ofDecideEqFalse _ d h
instance : Decidable True :=
isTrue trivial
instance : Decidable False :=
isFalse notFalse
-- We use "dependent" if-then-else to be able to communicate the if-then-else condition
-- to the branches
@[macroInline] def dite {α : Sort u} (c : Prop) [h : Decidable c] : (c → α) → (¬ c → α) → α :=
fun t e => Decidable.casesOn h e t
/- if-then-else -/
@[macroInline] def ite {α : Sort u} (c : Prop) [h : Decidable c] (t e : α) : α :=
Decidable.casesOn h (fun hnc => e) (fun hc => t)
namespace Decidable
variables {p q : Prop}
def recOnTrue [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} (h₃ : p) (h₄ : h₁ h₃)
: (Decidable.recOn h h₂ h₁ : Sort u) :=
Decidable.casesOn h (fun h => False.rec _ (h h₃)) (fun h => h₄)
def recOnFalse [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} (h₃ : ¬p) (h₄ : h₂ h₃)
: (Decidable.recOn h h₂ h₁ : Sort u) :=
Decidable.casesOn h (fun h => h₄) (fun h => False.rec _ (h₃ h))
@[macroInline] def byCases {q : Sort u} [s : Decidable p] (h1 : p → q) (h2 : ¬p → q) : q :=
match s with
| isTrue h => h1 h
| isFalse h => h2 h
theorem em (p : Prop) [Decidable p] : p ∨ ¬p :=
byCases Or.inl Or.inr
theorem byContradiction [Decidable p] (h : ¬p → False) : p :=
byCases id (fun np => False.elim (h np))
theorem ofNotNot [Decidable p] : ¬ ¬ p → p :=
fun hnn => byContradiction (fun hn => absurd hn hnn)
theorem notNotIff (p) [Decidable p] : (¬ ¬ p) ↔ p :=
Iff.intro ofNotNot notNotIntro
theorem notAndIffOrNot (p q : Prop) [d₁ : Decidable p] [d₂ : Decidable q] : ¬ (p ∧ q) ↔ ¬ p ∨ ¬ q :=
Iff.intro
(fun h => match d₁, d₂ with
| isTrue h₁, isTrue h₂ => absurd (And.intro h₁ h₂) h
| _, isFalse h₂ => Or.inr h₂
| isFalse h₁, _ => Or.inl h₁)
(fun (h) ⟨hp, hq⟩ => Or.elim h (fun h => h hp) (fun h => h hq))
end Decidable
section
variables {p q : Prop}
@[inline] def decidableOfDecidableOfIff (hp : Decidable p) (h : p ↔ q) : Decidable q :=
if hp : p then isTrue (Iff.mp h hp)
else isFalse (Iff.mp (notIffNotOfIff h) hp)
@[inline] def decidableOfDecidableOfEq (hp : Decidable p) (h : p = q) : Decidable q :=
decidableOfDecidableOfIff hp h.toIff
end
section
variables {p q : Prop}
@[macroInline] instance [Decidable p] [Decidable q] : Decidable (p ∧ q) :=
if hp : p then
if hq : q then isTrue ⟨hp, hq⟩
else isFalse (fun h => hq (And.right h))
else isFalse (fun h => hp (And.left h))
@[macroInline] instance [Decidable p] [Decidable q] : Decidable (p ∨ q) :=
if hp : p then isTrue (Or.inl hp) else
if hq : q then isTrue (Or.inr hq) else
isFalse (fun h => Or.elim h hp hq)
instance [Decidable p] : Decidable (¬p) :=
if hp : p then isFalse (absurd hp) else isTrue hp
@[macroInline] instance implies.Decidable [Decidable p] [Decidable q] : Decidable (p → q) :=
if hp : p then
if hq : q then isTrue (fun h => hq)
else isFalse (fun h => absurd (h hp) hq)
else isTrue (fun h => absurd h hp)
instance [Decidable p] [Decidable q] : Decidable (p ↔ q) :=
if hp : p then
if hq : q then isTrue ⟨fun _ => hq, fun _ => hp⟩
else isFalse $ fun h => hq (h.1 hp)
else
if hq : q then isFalse $ fun h => hp (h.2 hq)
else isTrue $ ⟨fun h => absurd h hp, fun h => absurd h hq⟩
instance [Decidable p] [Decidable q] : Decidable (Xor p q) :=
if hp : p then
if hq : q then isFalse (fun h => Or.elim h (fun ⟨_, h⟩ => h hq : ¬(p ∧ ¬ q)) (fun ⟨_, h⟩ => h hp : ¬(q ∧ ¬ p)))
else isTrue $ Or.inl ⟨hp, hq⟩
else
if hq : q then isTrue $ Or.inr ⟨hq, hp⟩
else isFalse (fun h => Or.elim h (fun ⟨h, _⟩ => hp h : ¬(p ∧ ¬ q)) (fun ⟨h, _⟩ => hq h : ¬(q ∧ ¬ p)))
end
@[inline] instance {α : Sort u} [DecidableEq α] (a b : α) : Decidable (a ≠ b) :=
match decEq a b with
| isTrue h => isFalse $ fun h' => absurd h h'
| isFalse h => isTrue h
theorem Bool.falseNeTrue (h : false = true) : False :=
Bool.noConfusion h
@[inline] instance : DecidableEq Bool :=
fun a b => match a, b with
| false, false => isTrue rfl
| false, true => isFalse Bool.falseNeTrue
| true, false => isFalse (Ne.symm Bool.falseNeTrue)
| true, true => isTrue rfl
/- if-then-else expression theorems -/
theorem ifPos {c : Prop} [h : Decidable c] (hc : c) {α : Sort u} {t e : α} : (ite c t e) = t :=
match h with
| (isTrue hc) => rfl
| (isFalse hnc) => absurd hc hnc
theorem ifNeg {c : Prop} [h : Decidable c] (hnc : ¬c) {α : Sort u} {t e : α} : (ite c t e) = e :=
match h with
| (isTrue hc) => absurd hc hnc
| (isFalse hnc) => rfl
theorem difPos {c : Prop} [h : Decidable c] (hc : c) {α : Sort u} {t : c → α} {e : ¬ c → α} : (dite c t e) = t hc :=
match h with
| (isTrue hc) => rfl
| (isFalse hnc) => absurd hc hnc
theorem difNeg {c : Prop} [h : Decidable c] (hnc : ¬c) {α : Sort u} {t : c → α} {e : ¬ c → α} : (dite c t e) = e hnc :=
match h with
| (isTrue hc) => absurd hc hnc
| (isFalse hnc) => rfl
-- Remark: dite and ite are "defally equal" when we ignore the proofs.
theorem difEqIf (c : Prop) [h : Decidable c] {α : Sort u} (t : α) (e : α) : dite c (fun h => t) (fun h => e) = ite c t e :=
match h with
| (isTrue hc) => rfl
| (isFalse hnc) => rfl
instance {c t e : Prop} [dC : Decidable c] [dT : Decidable t] [dE : Decidable e] : Decidable (if c then t else e) :=
match dC with
| (isTrue hc) => dT
| (isFalse hc) => dE
instance {c : Prop} {t : c → Prop} {e : ¬c → Prop} [dC : Decidable c] [dT : ∀ h, Decidable (t h)] [dE : ∀ h, Decidable (e h)] : Decidable (if h : c then t h else e h) :=
match dC with
| (isTrue hc) => dT hc
| (isFalse hc) => dE hc
/-- Universe lifting operation -/
structure ULift.{r, s} (α : Type s) : Type (max s r) :=
up :: (down : α)
namespace ULift
/- Bijection between α and ULift.{v} α -/
theorem upDown {α : Type u} : ∀ (b : ULift.{v} α), up (down b) = b
| up a => rfl
theorem downUp {α : Type u} (a : α) : down (up.{v} a) = a := rfl
end ULift
/-- Universe lifting operation from Sort to Type -/
structure PLift (α : Sort u) : Type u :=
up :: (down : α)
namespace PLift
/- Bijection between α and PLift α -/
theorem upDown {α : Sort u} : ∀ (b : PLift α), up (down b) = b
| up a => rfl
theorem downUp {α : Sort u} (a : α) : down (up a) = a := rfl
end PLift
/- pointed types -/
structure PointedType :=
(type : Type u) (val : type)
/- Inhabited -/
class Inhabited (α : Sort u) :=
mk {} :: (default : α)
constant arbitrary (α : Sort u) [Inhabited α] : α :=
Inhabited.default α
instance Prop.Inhabited : Inhabited Prop :=
⟨True⟩
instance Fun.Inhabited (α : Sort u) {β : Sort v} [h : Inhabited β] : Inhabited (α → β) :=
Inhabited.casesOn h (fun b => ⟨fun a => b⟩)
instance Forall.Inhabited (α : Sort u) {β : α → Sort v} [∀ x, Inhabited (β x)] : Inhabited (∀ x, β x) :=
⟨fun a => arbitrary (β a)⟩
instance : Inhabited Bool := ⟨false⟩
instance : Inhabited True := ⟨trivial⟩
instance : Inhabited Nat := ⟨0⟩
instance : Inhabited NonScalar := ⟨⟨arbitrary _⟩⟩
instance : Inhabited PNonScalar.{u} := ⟨⟨arbitrary _⟩⟩
instance : Inhabited PointedType := ⟨{type := PUnit, val := ⟨⟩}⟩
class inductive Nonempty (α : Sort u) : Prop
| intro (val : α) : Nonempty
protected def Nonempty.elim {α : Sort u} {p : Prop} (h₁ : Nonempty α) (h₂ : α → p) : p :=
Nonempty.rec h₂ h₁
instance nonemptyOfInhabited {α : Sort u} [Inhabited α] : Nonempty α :=
⟨arbitrary α⟩
theorem nonemptyOfExists {α : Sort u} {p : α → Prop} : Exists (fun x => p x) → Nonempty α
| ⟨w, h⟩ => ⟨w⟩
/- Subsingleton -/
class inductive Subsingleton (α : Sort u) : Prop
| intro (h : ∀ (a b : α), a = b) : Subsingleton
protected def Subsingleton.elim {α : Sort u} [h : Subsingleton α] : ∀ (a b : α), a = b :=
Subsingleton.casesOn h (fun p => p)
protected def Subsingleton.helim {α β : Sort u} [h : Subsingleton α] (h : α = β) : ∀ (a : α) (b : β), a ≅ b :=
Eq.recOn h (fun a b => heqOfEq (Subsingleton.elim a b))
instance subsingletonProp (p : Prop) : Subsingleton p :=
⟨fun a b => proofIrrel a b⟩
instance (p : Prop) : Subsingleton (Decidable p) :=
Subsingleton.intro $ fun d₁ =>
match d₁ with
| (isTrue t₁) => fun d₂ =>
match d₂ with
| (isTrue t₂) => Eq.recOn (proofIrrel t₁ t₂) rfl
| (isFalse f₂) => absurd t₁ f₂
| (isFalse f₁) => fun d₂ =>
match d₂ with
| (isTrue t₂) => absurd t₂ f₁
| (isFalse f₂) => Eq.recOn (proofIrrel f₁ f₂) rfl
protected theorem recSubsingleton {p : Prop} [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u}
[h₃ : ∀ (h : p), Subsingleton (h₁ h)] [h₄ : ∀ (h : ¬p), Subsingleton (h₂ h)]
: Subsingleton (Decidable.casesOn h h₂ h₁) :=
match h with
| (isTrue h) => h₃ h
| (isFalse h) => h₄ h
section relation
variables {α : Sort u} {β : Sort v} (r : β → β → Prop)
def Reflexive := ∀ x, r x x
def Symmetric := ∀ {x y}, r x y → r y x
def Transitive := ∀ {x y z}, r x y → r y z → r x z
def Equivalence := Reflexive r ∧ Symmetric r ∧ Transitive r
def Total := ∀ x y, r x y ∨ r y x
def mkEquivalence (rfl : Reflexive r) (symm : Symmetric r) (trans : Transitive r) : Equivalence r :=
⟨rfl, @symm, @trans⟩
def Irreflexive := ∀ x, ¬ r x x
def AntiSymmetric := ∀ {x y}, r x y → r y x → x = y
def emptyRelation (a₁ a₂ : α) : Prop := False
def Subrelation (q r : β → β → Prop) := ∀ {x y}, q x y → r x y
def InvImage (f : α → β) : α → α → Prop :=
fun a₁ a₂ => r (f a₁) (f a₂)
theorem InvImage.Transitive (f : α → β) (h : Transitive r) : Transitive (InvImage r f) :=
fun (a₁ a₂ a₃ : α) (h₁ : InvImage r f a₁ a₂) (h₂ : InvImage r f a₂ a₃) => h h₁ h₂
theorem InvImage.Irreflexive (f : α → β) (h : Irreflexive r) : Irreflexive (InvImage r f) :=
fun (a : α) (h₁ : InvImage r f a a) => h (f a) h₁
inductive TC {α : Sort u} (r : α → α → Prop) : α → α → Prop
| base : ∀ a b, r a b → TC a b
| trans : ∀ a b c, TC a b → TC b c → TC a c
@[elabAsEliminator]
theorem TC.ndrec.{u1, u2} {α : Sort u} {r : α → α → Prop} {C : α → α → Prop}
(m₁ : ∀ (a b : α), r a b → C a b)
(m₂ : ∀ (a b c : α), TC r a b → TC r b c → C a b → C b c → C a c)
{a b : α} (h : TC r a b) : C a b :=
@TC.rec α r (fun a b _ => C a b) m₁ m₂ a b h
@[elabAsEliminator]
theorem TC.ndrecOn.{u1, u2} {α : Sort u} {r : α → α → Prop} {C : α → α → Prop}
{a b : α} (h : TC r a b)
(m₁ : ∀ (a b : α), r a b → C a b)
(m₂ : ∀ (a b c : α), TC r a b → TC r b c → C a b → C b c → C a c)
: C a b :=
@TC.rec α r (fun a b _ => C a b) m₁ m₂ a b h
end relation
section Binary
variables {α : Type u} {β : Type v}
variable (f : α → α → α)
def Commutative := ∀ a b, f a b = f b a
def Associative := ∀ a b c, f (f a b) c = f a (f b c)
def RightCommutative (h : β → α → β) := ∀ b a₁ a₂, h (h b a₁) a₂ = h (h b a₂) a₁
def LeftCommutative (h : α → β → β) := ∀ a₁ a₂ b, h a₁ (h a₂ b) = h a₂ (h a₁ b)
theorem leftComm : Commutative f → Associative f → LeftCommutative f :=
fun hcomm hassoc a b c =>
((Eq.symm (hassoc a b c)).trans (hcomm a b ▸ rfl : f (f a b) c = f (f b a) c)).trans (hassoc b a c)
theorem rightComm : Commutative f → Associative f → RightCommutative f :=
fun hcomm hassoc a b c =>
((hassoc a b c).trans (hcomm b c ▸ rfl : f a (f b c) = f a (f c b))).trans (Eq.symm (hassoc a c b))
end Binary
/- Subtype -/
namespace Subtype
def existsOfSubtype {α : Type u} {p : α → Prop} : { x // p x } → Exists (fun x => p x)
| ⟨a, h⟩ => ⟨a, h⟩
variables {α : Type u} {p : α → Prop}
theorem tagIrrelevant {a : α} (h1 h2 : p a) : mk a h1 = mk a h2 :=
rfl
protected theorem eq : ∀ {a1 a2 : {x // p x}}, val a1 = val a2 → a1 = a2
| ⟨x, h1⟩, ⟨.(x), h2⟩, rfl => rfl
theorem eta (a : {x // p x}) (h : p (val a)) : mk (val a) h = a :=
Subtype.eq rfl
instance {α : Type u} {p : α → Prop} {a : α} (h : p a) : Inhabited {x // p x} :=
⟨⟨a, h⟩⟩
instance {α : Type u} {p : α → Prop} [DecidableEq α] : DecidableEq {x : α // p x} :=
fun ⟨a, h₁⟩ ⟨b, h₂⟩ =>
if h : a = b then isTrue (Subtype.eq h)
else isFalse (fun h' => Subtype.noConfusion h' (fun h' => absurd h' h))
end Subtype
/- Sum -/
section
variables {α : Type u} {β : Type v}
instance Sum.inhabitedLeft [h : Inhabited α] : Inhabited (Sum α β) :=
⟨Sum.inl (arbitrary α)⟩
instance Sum.inhabitedRight [h : Inhabited β] : Inhabited (Sum α β) :=
⟨Sum.inr (arbitrary β)⟩
instance {α : Type u} {β : Type v} [DecidableEq α] [DecidableEq β] : DecidableEq (Sum α β) :=
fun a b =>
match a, b with
| (Sum.inl a), (Sum.inl b) =>
if h : a = b then isTrue (h ▸ rfl)
else isFalse (fun h' => Sum.noConfusion h' (fun h' => absurd h' h))
| (Sum.inr a), (Sum.inr b) =>
if h : a = b then isTrue (h ▸ rfl)
else isFalse (fun h' => Sum.noConfusion h' (fun h' => absurd h' h))
| (Sum.inr a), (Sum.inl b) => isFalse (fun h => Sum.noConfusion h)
| (Sum.inl a), (Sum.inr b) => isFalse (fun h => Sum.noConfusion h)
end
/- Product -/
section
variables {α : Type u} {β : Type v}
instance [Inhabited α] [Inhabited β] : Inhabited (Prod α β) :=
⟨(arbitrary α, arbitrary β)⟩
instance [DecidableEq α] [DecidableEq β] : DecidableEq (α × β) :=
fun ⟨a, b⟩ ⟨a', b'⟩ =>
match (decEq a a') with
| (isTrue e₁) =>
match (decEq b b') with
| (isTrue e₂) => isTrue (Eq.recOn e₁ (Eq.recOn e₂ rfl))
| (isFalse n₂) => isFalse (fun h => Prod.noConfusion h (fun e₁' e₂' => absurd e₂' n₂))
| (isFalse n₁) => isFalse (fun h => Prod.noConfusion h (fun e₁' e₂' => absurd e₁' n₁))
instance [HasBeq α] [HasBeq β] : HasBeq (α × β) :=
⟨fun ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ => a₁ == a₂ && b₁ == b₂⟩
instance [HasLess α] [HasLess β] : HasLess (α × β) :=
⟨fun s t => s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2)⟩
instance prodHasDecidableLt
[HasLess α] [HasLess β] [DecidableEq α] [DecidableEq β]
[∀ (a b : α), Decidable (a < b)] [∀ (a b : β), Decidable (a < b)]
: ∀ (s t : α × β), Decidable (s < t) :=
fun t s => Or.Decidable
theorem Prod.ltDef [HasLess α] [HasLess β] (s t : α × β) : (s < t) = (s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2)) :=
rfl
end
def Prod.map.{u₁, u₂, v₁, v₂} {α₁ : Type u₁} {α₂ : Type u₂} {β₁ : Type v₁} {β₂ : Type v₂}
(f : α₁ → α₂) (g : β₁ → β₂) : α₁ × β₁ → α₂ × β₂
| (a, b) => (f a, g b)
/- Dependent products -/
-- notation `Σ` binders `, ` r:(scoped p, Sigma p) := r
-- notation `Σ'` binders `, ` r:(scoped p, PSigma p) := r
theorem exOfPsig {α : Type u} {p : α → Prop} : (PSigma (fun x => p x)) → Exists (fun x => p x)
| ⟨x, hx⟩ => ⟨x, hx⟩
section
variables {α : Type u} {β : α → Type v}
protected theorem Sigma.eq : ∀ {p₁ p₂ : Sigma (fun a => β a)} (h₁ : p₁.1 = p₂.1), (Eq.recOn h₁ p₁.2 : β p₂.1) = p₂.2 → p₁ = p₂
| ⟨a, b⟩, ⟨.(a), .(b)⟩, rfl, rfl => rfl
end
section
variables {α : Sort u} {β : α → Sort v}
protected theorem PSigma.eq : ∀ {p₁ p₂ : PSigma β} (h₁ : p₁.1 = p₂.1), (Eq.recOn h₁ p₁.2 : β p₂.1) = p₂.2 → p₁ = p₂
| ⟨a, b⟩, ⟨.(a), .(b)⟩, rfl, rfl => rfl
end
/- Universe polymorphic unit -/
theorem punitEq (a b : PUnit) : a = b :=
PUnit.recOn a (PUnit.recOn b rfl)
theorem punitEqPUnit (a : PUnit) : a = () :=
punitEq a ()
instance : Subsingleton PUnit :=
Subsingleton.intro punitEq
instance : Inhabited PUnit :=
⟨⟨⟩⟩
instance : DecidableEq PUnit :=
fun a b => isTrue (punitEq a b)
/- Setoid -/
class Setoid (α : Sort u) :=
(r : α → α → Prop) (iseqv {} : Equivalence r)
instance setoidHasEquiv {α : Sort u} [Setoid α] : HasEquiv α :=
⟨Setoid.r⟩
namespace Setoid
variables {α : Sort u} [Setoid α]
theorem refl (a : α) : a ≈ a :=
match Setoid.iseqv α with
| ⟨hRefl, hSymm, hTrans⟩ => hRefl a
theorem symm {a b : α} (hab : a ≈ b) : b ≈ a :=
match Setoid.iseqv α with
| ⟨hRefl, hSymm, hTrans⟩ => hSymm hab
theorem trans {a b c : α} (hab : a ≈ b) (hbc : b ≈ c) : a ≈ c :=
match Setoid.iseqv α with
| ⟨hRefl, hSymm, hTrans⟩ => hTrans hab hbc
end Setoid
/- Propositional extensionality -/
axiom propext {a b : Prop} : (a ↔ b) → a = b
theorem eqTrueIntro {a : Prop} (h : a) : a = True :=
propext (iffTrueIntro h)
theorem eqFalseIntro {a : Prop} (h : ¬a) : a = False :=
propext (iffFalseIntro h)
/- Quotients -/
-- Iff can now be used to do substitutions in a calculation
theorem iffSubst {a b : Prop} {p : Prop → Prop} (h₁ : a ↔ b) (h₂ : p a) : p b :=
Eq.subst (propext h₁) h₂
namespace Quot
axiom sound : ∀ {α : Sort u} {r : α → α → Prop} {a b : α}, r a b → Quot.mk r a = Quot.mk r b
attribute [elabAsEliminator] lift ind
protected theorem liftBeta {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) (c : ∀ a b, r a b → f a = f b) (a : α) : lift f c (Quot.mk r a) = f a :=
rfl
protected theorem indBeta {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} (p : ∀ a, β (Quot.mk r a)) (a : α) : (ind p (Quot.mk r a) : β (Quot.mk r a)) = p a :=
rfl
@[reducible, elabAsEliminator, inline]
protected def liftOn {α : Sort u} {β : Sort v} {r : α → α → Prop} (q : Quot r) (f : α → β) (c : ∀ a b, r a b → f a = f b) : β :=
lift f c q
@[elabAsEliminator]
protected theorem inductionOn {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} (q : Quot r) (h : ∀ a, β (Quot.mk r a)) : β q :=
ind h q
theorem existsRep {α : Sort u} {r : α → α → Prop} (q : Quot r) : Exists (fun a => (Quot.mk r a) = q) :=
Quot.inductionOn q (fun a => ⟨a, rfl⟩)
section
variable {α : Sort u}
variable {r : α → α → Prop}
variable {β : Quot r → Sort v}
@[reducible, macroInline]
protected def indep (f : ∀ a, β (Quot.mk r a)) (a : α) : PSigma β :=
⟨Quot.mk r a, f a⟩
protected theorem indepCoherent (f : ∀ a, β (Quot.mk r a))
(h : ∀ (a b : α) (p : r a b), (Eq.rec (f a) (sound p) : β (Quot.mk r b)) = f b)
: ∀ a b, r a b → Quot.indep f a = Quot.indep f b :=
fun a b e => PSigma.eq (sound e) (h a b e)
protected theorem liftIndepPr1
(f : ∀ a, β (Quot.mk r a)) (h : ∀ (a b : α) (p : r a b), (Eq.rec (f a) (sound p) : β (Quot.mk r b)) = f b)
(q : Quot r) : (lift (Quot.indep f) (Quot.indepCoherent f h) q).1 = q :=
Quot.ind (fun (a : α) => Eq.refl (Quot.indep f a).1) q
@[reducible, elabAsEliminator, inline]
protected def rec
(f : ∀ a, β (Quot.mk r a)) (h : ∀ (a b : α) (p : r a b), (Eq.rec (f a) (sound p) : β (Quot.mk r b)) = f b)
(q : Quot r) : β q :=
Eq.ndrecOn (Quot.liftIndepPr1 f h q) ((lift (Quot.indep f) (Quot.indepCoherent f h) q).2)
@[reducible, elabAsEliminator, inline]
protected def recOn
(q : Quot r) (f : ∀ a, β (Quot.mk r a)) (h : ∀ (a b : α) (p : r a b), (Eq.rec (f a) (sound p) : β (Quot.mk r b)) = f b) : β q :=
Quot.rec f h q
@[reducible, elabAsEliminator, inline]
protected def recOnSubsingleton
[h : ∀ a, Subsingleton (β (Quot.mk r a))] (q : Quot r) (f : ∀ a, β (Quot.mk r a)) : β q :=
Quot.rec f (fun a b h => Subsingleton.elim _ (f b)) q
@[reducible, elabAsEliminator, inline]
protected def hrecOn
(q : Quot r) (f : ∀ a, β (Quot.mk r a)) (c : ∀ (a b : α) (p : r a b), f a ≅ f b) : β q :=
Quot.recOn q f $
fun a b p => eqOfHEq $
have p₁ : (Eq.rec (f a) (sound p) : β (Quot.mk r b)) ≅ f a := eqRecHEq (sound p) (f a);
HEq.trans p₁ (c a b p)
end
end Quot
def Quotient {α : Sort u} (s : Setoid α) :=
@Quot α Setoid.r
namespace Quotient
@[inline]
protected def mk {α : Sort u} [s : Setoid α] (a : α) : Quotient s :=
Quot.mk Setoid.r a
def sound {α : Sort u} [s : Setoid α] {a b : α} : a ≈ b → Quotient.mk a = Quotient.mk b :=
Quot.sound
@[reducible, elabAsEliminator]
protected def lift {α : Sort u} {β : Sort v} [s : Setoid α] (f : α → β) : (∀ a b, a ≈ b → f a = f b) → Quotient s → β :=
Quot.lift f
@[elabAsEliminator]
protected theorem ind {α : Sort u} [s : Setoid α] {β : Quotient s → Prop} : (∀ a, β (Quotient.mk a)) → ∀ q, β q :=
Quot.ind
@[reducible, elabAsEliminator, inline]
protected def liftOn {α : Sort u} {β : Sort v} [s : Setoid α] (q : Quotient s) (f : α → β) (c : ∀ a b, a ≈ b → f a = f b) : β :=
Quot.liftOn q f c
@[elabAsEliminator]
protected theorem inductionOn {α : Sort u} [s : Setoid α] {β : Quotient s → Prop} (q : Quotient s) (h : ∀ a, β (Quotient.mk a)) : β q :=
Quot.inductionOn q h
theorem existsRep {α : Sort u} [s : Setoid α] (q : Quotient s) : Exists (fun (a : α) => Quotient.mk a = q) :=
Quot.existsRep q
section
variable {α : Sort u}
variable [s : Setoid α]
variable {β : Quotient s → Sort v}
@[inline]
protected def rec
(f : ∀ a, β (Quotient.mk a)) (h : ∀ (a b : α) (p : a ≈ b), (Eq.rec (f a) (Quotient.sound p) : β (Quotient.mk b)) = f b)
(q : Quotient s) : β q :=
Quot.rec f h q
@[reducible, elabAsEliminator, inline]
protected def recOn
(q : Quotient s) (f : ∀ a, β (Quotient.mk a)) (h : ∀ (a b : α) (p : a ≈ b), (Eq.rec (f a) (Quotient.sound p) : β (Quotient.mk b)) = f b) : β q :=
Quot.recOn q f h
@[reducible, elabAsEliminator, inline]
protected def recOnSubsingleton
[h : ∀ a, Subsingleton (β (Quotient.mk a))] (q : Quotient s) (f : ∀ a, β (Quotient.mk a)) : β q :=
@Quot.recOnSubsingleton _ _ _ h q f
@[reducible, elabAsEliminator, inline]
protected def hrecOn
(q : Quotient s) (f : ∀ a, β (Quotient.mk a)) (c : ∀ (a b : α) (p : a ≈ b), f a ≅ f b) : β q :=
Quot.hrecOn q f c
end
section
universes uA uB uC
variables {α : Sort uA} {β : Sort uB} {φ : Sort uC}
variables [s₁ : Setoid α] [s₂ : Setoid β]
@[reducible, elabAsEliminator, inline]
protected def lift₂
(f : α → β → φ)(c : ∀ a₁ a₂ b₁ b₂, a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂)
(q₁ : Quotient s₁) (q₂ : Quotient s₂) : φ :=
Quotient.lift
(fun (a₁ : α) => Quotient.lift (f a₁) (fun (a b : β) => c a₁ a a₁ b (Setoid.refl a₁)) q₂)
(fun (a b : α) (h : a ≈ b) =>
@Quotient.ind β s₂
(fun (a1 : Quotient s₂) =>
(Quotient.lift (f a) (fun (a1 b : β) => c a a1 a b (Setoid.refl a)) a1)
=
(Quotient.lift (f b) (fun (a b1 : β) => c b a b b1 (Setoid.refl b)) a1))
(fun (a' : β) => c a a' b a' h (Setoid.refl a'))
q₂)
q₁
@[reducible, elabAsEliminator, inline]
protected def liftOn₂
(q₁ : Quotient s₁) (q₂ : Quotient s₂) (f : α → β → φ) (c : ∀ a₁ a₂ b₁ b₂, a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) : φ :=
Quotient.lift₂ f c q₁ q₂
@[elabAsEliminator]
protected theorem ind₂ {φ : Quotient s₁ → Quotient s₂ → Prop} (h : ∀ a b, φ (Quotient.mk a) (Quotient.mk b)) (q₁ : Quotient s₁) (q₂ : Quotient s₂) : φ q₁ q₂ :=
Quotient.ind (fun a₁ => Quotient.ind (fun a₂ => h a₁ a₂) q₂) q₁
@[elabAsEliminator]
protected theorem inductionOn₂
{φ : Quotient s₁ → Quotient s₂ → Prop} (q₁ : Quotient s₁) (q₂ : Quotient s₂) (h : ∀ a b, φ (Quotient.mk a) (Quotient.mk b)) : φ q₁ q₂ :=
Quotient.ind (fun a₁ => Quotient.ind (fun a₂ => h a₁ a₂) q₂) q₁
@[elabAsEliminator]
protected theorem inductionOn₃
[s₃ : Setoid φ]
{δ : Quotient s₁ → Quotient s₂ → Quotient s₃ → Prop} (q₁ : Quotient s₁) (q₂ : Quotient s₂) (q₃ : Quotient s₃) (h : ∀ a b c, δ (Quotient.mk a) (Quotient.mk b) (Quotient.mk c))
: δ q₁ q₂ q₃ :=
Quotient.ind (fun a₁ => Quotient.ind (fun a₂ => Quotient.ind (fun a₃ => h a₁ a₂ a₃) q₃) q₂) q₁
end
section Exact
variable {α : Sort u}
private def rel [s : Setoid α] (q₁ q₂ : Quotient s) : Prop :=
Quotient.liftOn₂ q₁ q₂
(fun a₁ a₂ => a₁ ≈ a₂)
(fun a₁ a₂ b₁ b₂ a₁b₁ a₂b₂ =>
propext (Iff.intro
(fun a₁a₂ => Setoid.trans (Setoid.symm a₁b₁) (Setoid.trans a₁a₂ a₂b₂))
(fun b₁b₂ => Setoid.trans a₁b₁ (Setoid.trans b₁b₂ (Setoid.symm a₂b₂)))))
private theorem rel.refl [s : Setoid α] : ∀ (q : Quotient s), rel q q :=
fun q => Quot.inductionOn q (fun a => Setoid.refl a)
private theorem eqImpRel [s : Setoid α] {q₁ q₂ : Quotient s} : q₁ = q₂ → rel q₁ q₂ :=
fun h => Eq.ndrecOn h (rel.refl q₁)
theorem exact [s : Setoid α] {a b : α} : Quotient.mk a = Quotient.mk b → a ≈ b :=
fun h => eqImpRel h
end Exact
section
universes uA uB uC
variables {α : Sort uA} {β : Sort uB}
variables [s₁ : Setoid α] [s₂ : Setoid β]
@[reducible, elabAsEliminator]
protected def recOnSubsingleton₂
{φ : Quotient s₁ → Quotient s₂ → Sort uC} [h : ∀ a b, Subsingleton (φ (Quotient.mk a) (Quotient.mk b))]
(q₁ : Quotient s₁) (q₂ : Quotient s₂) (f : ∀ a b, φ (Quotient.mk a) (Quotient.mk b)) : φ q₁ q₂:=
@Quotient.recOnSubsingleton _ s₁ (fun q => φ q q₂) (fun a => Quotient.ind (fun b => h a b) q₂) q₁
(fun a => Quotient.recOnSubsingleton q₂ (fun b => f a b))
end
end Quotient
section
variable {α : Type u}
variable (r : α → α → Prop)
inductive EqvGen : α → α → Prop
| rel : ∀ x y, r x y → EqvGen x y
| refl : ∀ x, EqvGen x x
| symm : ∀ x y, EqvGen x y → EqvGen y x
| trans : ∀ x y z, EqvGen x y → EqvGen y z → EqvGen x z
theorem EqvGen.isEquivalence : Equivalence (@EqvGen α r) :=
mkEquivalence _ EqvGen.refl EqvGen.symm EqvGen.trans
def EqvGen.Setoid : Setoid α :=
Setoid.mk _ (EqvGen.isEquivalence r)
theorem Quot.exact {a b : α} (H : Quot.mk r a = Quot.mk r b) : EqvGen r a b :=
@Quotient.exact _ (EqvGen.Setoid r) a b (@congrArg _ _ _ _
(Quot.lift (@Quotient.mk _ (EqvGen.Setoid r)) (fun x y h => Quot.sound (EqvGen.rel x y h))) H)
theorem Quot.eqvGenSound {r : α → α → Prop} {a b : α} (H : EqvGen r a b) : Quot.mk r a = Quot.mk r b :=
EqvGen.recOn H
(fun x y h => Quot.sound h)
(fun x => rfl)
(fun x y _ IH => Eq.symm IH)
(fun x y z _ _ IH₁ IH₂ => Eq.trans IH₁ IH₂)
end
instance {α : Sort u} {s : Setoid α} [d : ∀ (a b : α), Decidable (a ≈ b)] : DecidableEq (Quotient s) :=
fun (q₁ q₂ : Quotient s) =>
Quotient.recOnSubsingleton₂ q₁ q₂
(fun a₁ a₂ =>
match (d a₁ a₂) with
| (isTrue h₁) => isTrue (Quotient.sound h₁)
| (isFalse h₂) => isFalse (fun h => absurd (Quotient.exact h) h₂))
/- Function extensionality -/
namespace Function
variables {α : Sort u} {β : α → Sort v}
def Equiv (f₁ f₂ : ∀ (x : α), β x) : Prop := ∀ x, f₁ x = f₂ x
protected theorem Equiv.refl (f : ∀ (x : α), β x) : Equiv f f :=
fun x => rfl
protected theorem Equiv.symm {f₁ f₂ : ∀ (x : α), β x} : Equiv f₁ f₂ → Equiv f₂ f₁ :=
fun h x => Eq.symm (h x)
protected theorem Equiv.trans {f₁ f₂ f₃ : ∀ (x : α), β x} : Equiv f₁ f₂ → Equiv f₂ f₃ → Equiv f₁ f₃ :=
fun h₁ h₂ x => Eq.trans (h₁ x) (h₂ x)
protected theorem Equiv.isEquivalence (α : Sort u) (β : α → Sort v) : Equivalence (@Function.Equiv α β) :=
mkEquivalence (@Function.Equiv α β) (@Equiv.refl α β) (@Equiv.symm α β) (@Equiv.trans α β)
end Function
section
open Quotient
variables {α : Sort u} {β : α → Sort v}
@[instance]
private def funSetoid (α : Sort u) (β : α → Sort v) : Setoid (∀ (x : α), β x) :=
Setoid.mk (@Function.Equiv α β) (Function.Equiv.isEquivalence α β)
private def extfunApp (f : Quotient $ funSetoid α β) : ∀ (x : α), β x :=
fun x =>
Quot.liftOn f
(fun (f : ∀ (x : α), β x) => f x)
(fun f₁ f₂ h => h x)
theorem funext {f₁ f₂ : ∀ (x : α), β x} (h : ∀ x, f₁ x = f₂ x) : f₁ = f₂ :=
show extfunApp (Quotient.mk f₁) = extfunApp (Quotient.mk f₂) from
congrArg extfunApp (sound h)
end
instance Forall.Subsingleton {α : Sort u} {β : α → Sort v} [∀ a, Subsingleton (β a)] : Subsingleton (∀ a, β a) :=
⟨fun f₁ f₂ => funext (fun a => Subsingleton.elim (f₁ a) (f₂ a))⟩
/- General operations on functions -/
namespace Function
universes u₁ u₂ u₃ u₄
variables {α : Sort u₁} {β : Sort u₂} {φ : Sort u₃} {δ : Sort u₄} {ζ : Sort u₁}
@[inline, reducible] def comp (f : β → φ) (g : α → β) : α → φ :=
fun x => f (g x)
infixr ` ∘ ` := Function.comp
@[inline, reducible] def onFun (f : β → β → φ) (g : α → β) : α → α → φ :=
fun x y => f (g x) (g y)
@[inline, reducible] def combine (f : α → β → φ) (op : φ → δ → ζ) (g : α → β → δ)
: α → β → ζ :=
fun x y => op (f x y) (g x y)
@[inline, reducible] def const (β : Sort u₂) (a : α) : β → α :=
fun x => a
@[inline, reducible] def swap {φ : α → β → Sort u₃} (f : ∀ x y, φ x y) : ∀ y x, φ x y :=
fun y x => f x y
end Function
/- Squash -/
def Squash (α : Type u) := Quot (fun (a b : α) => True)
def Squash.mk {α : Type u} (x : α) : Squash α := Quot.mk _ x
theorem Squash.ind {α : Type u} {β : Squash α → Prop} (h : ∀ (a : α), β (Squash.mk a)) : ∀ (q : Squash α), β q :=
Quot.ind h
@[inline] def Squash.lift {α β} [Subsingleton β] (s : Squash α) (f : α → β) : β :=
Quot.lift f (fun a b _ => Subsingleton.elim _ _) s
instance Squash.Subsingleton {α} : Subsingleton (Squash α) :=
⟨Squash.ind (fun (a : α) => Squash.ind (fun (b : α) => Quot.sound trivial))⟩
namespace Lean
/- Kernel reduction hints -/
/--
When the kernel tries to reduce a term `Lean.reduceBool c`, it will invoke the Lean interpreter to evaluate `c`.
The kernel will not use the interpreter if `c` is not a constant.
This feature is useful for performing proofs by reflection.
Remark: the Lean frontend allows terms of the from `Lean.reduceBool t` where `t` is a term not containing
free variables. The frontend automatically declares a fresh auxiliary constant `c` and replaces the term with
`Lean.reduceBool c`. The main motivation is that the code for `t` will be pre-compiled.
Warning: by using this feature, the Lean compiler and interpreter become part of your trusted code base.
This is extra 30k lines of code. More importantly, you will probably not be able to check your developement using
external type checkers (e.g., Trepplein) that do not implement this feature.
Keep in mind that if you are using Lean as programming language, you are already trusting the Lean compiler and interpreter.
So, you are mainly losing the capability of type checking your developement using external checkers.
Recall that the compiler trusts the correctness of all `[implementedBy ...]` and `[extern ...]` annotations.
If an extern function is executed, then the trusted code base will also include the implementation of the associated
foreign function.
-/
constant reduceBool (b : Bool) : Bool := b
/--
Similar to `Lean.reduceBool` for closed `Nat` terms.
Remark: we do not have plans for supporting a generic `reduceValue {α} (a : α) : α := a`.
The main issue is that it is non-trivial to convert an arbitrary runtime object back into a Lean expression.
We believe `Lean.reduceBool` enables most interesting applications (e.g., proof by reflection). -/
constant reduceNat (n : Nat) : Nat := n
axiom ofReduceBool (a b : Bool) (h : reduceBool a = b) : a = b
axiom ofReduceNat (a b : Nat) (h : reduceNat a = b) : a = b
end Lean
/- Classical reasoning support -/
namespace Classical
axiom choice {α : Sort u} : Nonempty α → α
noncomputable def indefiniteDescription {α : Sort u} (p : α → Prop)
(h : Exists (fun x => p x)) : {x // p x} :=
choice $ let ⟨x, px⟩ := h; ⟨⟨x, px⟩⟩
noncomputable def choose {α : Sort u} {p : α → Prop} (h : Exists (fun x => p x)) : α :=
(indefiniteDescription p h).val
theorem chooseSpec {α : Sort u} {p : α → Prop} (h : Exists (fun x => p x)) : p (choose h) :=
(indefiniteDescription p h).property
/- Diaconescu's theorem: excluded middle from choice, Function extensionality and propositional extensionality. -/
theorem em (p : Prop) : p ∨ ¬p :=
let U (x : Prop) : Prop := x = True ∨ p;
let V (x : Prop) : Prop := x = False ∨ p;
have exU : Exists (fun x => U x) from ⟨True, Or.inl rfl⟩;
have exV : Exists (fun x => V x) from ⟨False, Or.inl rfl⟩;
let u : Prop := choose exU;
let v : Prop := choose exV;
have uDef : U u from chooseSpec exU;
have vDef : V v from chooseSpec exV;
have notUvOrP : u ≠ v ∨ p from
Or.elim uDef
(fun hut =>
Or.elim vDef
(fun hvf =>
have hne : u ≠ v from hvf.symm ▸ hut.symm ▸ trueNeFalse;
Or.inl hne)
Or.inr)
Or.inr;
have pImpliesUv : p → u = v from
fun hp =>
have hpred : U = V from
funext $ fun x =>
have hl : (x = True ∨ p) → (x = False ∨ p) from
fun a => Or.inr hp;
have hr : (x = False ∨ p) → (x = True ∨ p) from
fun a => Or.inr hp;
show (x = True ∨ p) = (x = False ∨ p) from
propext (Iff.intro hl hr);
have h₀ : ∀ exU exV, @choose _ U exU = @choose _ V exV from
hpred ▸ fun exU exV => rfl;
show u = v from h₀ _ _;
Or.elim notUvOrP
(fun (hne : u ≠ v) => Or.inr (mt pImpliesUv hne))
Or.inl
theorem existsTrueOfNonempty {α : Sort u} : Nonempty α → Exists (fun (x : α) => True)
| ⟨x⟩ => ⟨x, trivial⟩
noncomputable def inhabitedOfNonempty {α : Sort u} (h : Nonempty α) : Inhabited α :=
⟨choice h⟩
noncomputable def inhabitedOfExists {α : Sort u} {p : α → Prop} (h : Exists (fun x => p x)) :
Inhabited α :=
inhabitedOfNonempty (Exists.elim h (fun w hw => ⟨w⟩))
/- all propositions are Decidable -/
noncomputable def propDecidable (a : Prop) : Decidable a :=
choice $ Or.elim (em a)
(fun ha => ⟨isTrue ha⟩)
(fun hna => ⟨isFalse hna⟩)
noncomputable def decidableInhabited (a : Prop) : Inhabited (Decidable a) :=
⟨propDecidable a⟩
noncomputable def typeDecidableEq (α : Sort u) : DecidableEq α :=
fun x y => propDecidable (x = y)
noncomputable def typeDecidable (α : Sort u) : PSum α (α → False) :=
match (propDecidable (Nonempty α)) with
| (isTrue hp) => PSum.inl (@arbitrary _ (inhabitedOfNonempty hp))
| (isFalse hn) => PSum.inr (fun a => absurd (Nonempty.intro a) hn)
noncomputable def strongIndefiniteDescription {α : Sort u} (p : α → Prop)
(h : Nonempty α) : {x : α // Exists (fun (y : α) => p y) → p x} :=
@dite _ (Exists (fun (x : α) => p x)) (propDecidable _)
(fun (hp : Exists (fun (x : α) => p x)) =>
show {x : α // Exists (fun (y : α) => p y) → p x} from
let xp := indefiniteDescription _ hp;
⟨xp.val, fun h' => xp.property⟩)
(fun hp => ⟨choice h, fun h => absurd h hp⟩)
/- the Hilbert epsilon Function -/
noncomputable def epsilon {α : Sort u} [h : Nonempty α] (p : α → Prop) : α :=
(strongIndefiniteDescription p h).val
theorem epsilonSpecAux {α : Sort u} (h : Nonempty α) (p : α → Prop)
: Exists (fun y => p y) → p (@epsilon α h p) :=
(strongIndefiniteDescription p h).property
theorem epsilonSpec {α : Sort u} {p : α → Prop} (hex : Exists (fun y => p y)) :
p (@epsilon α (nonemptyOfExists hex) p) :=
epsilonSpecAux (nonemptyOfExists hex) p hex
theorem epsilonSingleton {α : Sort u} (x : α) : @epsilon α ⟨x⟩ (fun y => y = x) = x :=
@epsilonSpec α (fun y => y = x) ⟨x, rfl⟩
/- the axiom of choice -/
theorem axiomOfChoice {α : Sort u} {β : α → Sort v} {r : ∀ x, β x → Prop} (h : ∀ x, Exists (fun y => r x y)) :
Exists (fun (f : ∀ x, β x) => ∀ x, r x (f x)) :=
⟨_, fun x => chooseSpec (h x)⟩
theorem skolem {α : Sort u} {b : α → Sort v} {p : ∀ x, b x → Prop} :
(∀ x, Exists (fun y => p x y)) ↔ Exists (fun (f : ∀ x, b x) => ∀ x, p x (f x)) :=
⟨axiomOfChoice, fun ⟨f, hw⟩ (x) => ⟨f x, hw x⟩⟩
theorem propComplete (a : Prop) : a = True ∨ a = False :=
Or.elim (em a)
(fun t => Or.inl (eqTrueIntro t))
(fun f => Or.inr (eqFalseIntro f))
-- this supercedes byCases in Decidable
theorem byCases {p q : Prop} (hpq : p → q) (hnpq : ¬p → q) : q :=
@Decidable.byCases _ _ (propDecidable _) hpq hnpq
-- this supercedes byContradiction in Decidable
theorem byContradiction {p : Prop} (h : ¬p → False) : p :=
@Decidable.byContradiction _ (propDecidable _) h
end Classical
|
378b6785e4af14f8ed86a85026b324af38892694 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/compiler/uset.lean | 9562cd7105011e9f0ec2d66df3cd90fd50170132 | [
"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 | 189 | lean | structure Point where
x : USize
y : UInt32
@[noinline] def Point.right (p : Point) : Point :=
{ p with x := p.x + 1 }
def main : IO Unit :=
IO.println (Point.right ⟨0, 0⟩).x
|
67fe142ec4b9ddf907162808f57fe9f33b1badcc | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/algebra/char_p/subring.lean | c5194ae4dcfb514ffb75a77cc15f726f5a7f057f | [] | 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,776 | lean | /-
Copyright (c) 2020 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.char_p.basic
import Mathlib.ring_theory.subring
import Mathlib.PostPort
universes u
namespace Mathlib
/-!
# Characteristic of subrings
-/
namespace char_p
protected instance subsemiring (R : Type u) [semiring R] (p : ℕ) [char_p R p] (S : subsemiring R) : char_p (↥S) p :=
mk
fun (x : ℕ) =>
iff.symm
(iff.trans (iff.symm (cast_eq_zero_iff R p x))
{ mp :=
fun (h : ↑x = 0) =>
subtype.eq
((fun (this : coe_fn (subsemiring.subtype S) ↑x = 0) => this)
(eq.mpr
(id
(Eq._oldrec (Eq.refl (coe_fn (subsemiring.subtype S) ↑x = 0))
(ring_hom.map_nat_cast (subsemiring.subtype S) x)))
(eq.mpr (id (Eq._oldrec (Eq.refl (↑x = 0)) h)) (Eq.refl 0)))),
mpr :=
fun (h : ↑x = 0) =>
ring_hom.map_nat_cast (subsemiring.subtype S) x ▸
eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn (subsemiring.subtype S) ↑x = 0)) h))
(eq.mpr
(id
(Eq._oldrec (Eq.refl (coe_fn (subsemiring.subtype S) 0 = 0))
(ring_hom.map_zero (subsemiring.subtype S))))
(Eq.refl 0)) })
protected instance subring (R : Type u) [ring R] (p : ℕ) [char_p R p] (S : subring R) : char_p (↥S) p :=
mk
fun (x : ℕ) =>
iff.symm
(iff.trans (iff.symm (cast_eq_zero_iff R p x))
{ mp :=
fun (h : ↑x = 0) =>
subtype.eq
((fun (this : coe_fn (subring.subtype S) ↑x = 0) => this)
(eq.mpr
(id
(Eq._oldrec (Eq.refl (coe_fn (subring.subtype S) ↑x = 0))
(ring_hom.map_nat_cast (subring.subtype S) x)))
(eq.mpr (id (Eq._oldrec (Eq.refl (↑x = 0)) h)) (Eq.refl 0)))),
mpr :=
fun (h : ↑x = 0) =>
ring_hom.map_nat_cast (subring.subtype S) x ▸
eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn (subring.subtype S) ↑x = 0)) h))
(eq.mpr
(id
(Eq._oldrec (Eq.refl (coe_fn (subring.subtype S) 0 = 0)) (ring_hom.map_zero (subring.subtype S))))
(Eq.refl 0)) })
protected instance subring' (R : Type u) [comm_ring R] (p : ℕ) [char_p R p] (S : subring R) : char_p (↥S) p :=
char_p.subring R p S
|
d2a36e7ee496b68f517560ba75493e593094a3c1 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/init/meta/well_founded_tactics.lean | ba91174caf2141b09647119c8768e6fa5d2f20a5 | [] | 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,531 | 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 Mathlib.PrePort
import Mathlib.Lean3Lib.init.meta.default
import Mathlib.Lean3Lib.init.data.sigma.lex
import Mathlib.Lean3Lib.init.data.nat.lemmas
import Mathlib.Lean3Lib.init.data.list.instances
import Mathlib.Lean3Lib.init.data.list.qsort
universes u v
namespace Mathlib
/- TODO(Leo): move this lemma, or delete it after we add algebraic normalizer. -/
theorem nat.lt_add_of_zero_lt_left (a : ℕ) (b : ℕ) (h : 0 < b) : a < a + b :=
(fun (this : a + 0 < a + b) => this) (nat.add_lt_add_left h a)
/- TODO(Leo): move this lemma, or delete it after we add algebraic normalizer. -/
theorem nat.zero_lt_one_add (a : ℕ) : 0 < 1 + a := sorry
/- TODO(Leo): move this lemma, or delete it after we add algebraic normalizer. -/
theorem nat.lt_add_right (a : ℕ) (b : ℕ) (c : ℕ) : a < b → a < b + c :=
fun (h : a < b) => lt_of_lt_of_le h (nat.le_add_right b c)
/- TODO(Leo): move this lemma, or delete it after we add algebraic normalizer. -/
theorem nat.lt_add_left (a : ℕ) (b : ℕ) (c : ℕ) : a < b → a < c + b :=
fun (h : a < b) => lt_of_lt_of_le h (nat.le_add_left b c)
protected def psum.alt.sizeof {α : Type u} {β : Type v} [SizeOf α] [SizeOf β] : psum α β → ℕ :=
sorry
protected def psum.has_sizeof_alt (α : Type u) (β : Type v) [SizeOf α] [SizeOf β] : SizeOf (psum α β) :=
{ sizeOf := psum.alt.sizeof }
|
13b61e77800168c4bd9b70bd245224164209e8ad | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/topology/category/Top/opens.lean | 8146312c116d9bf03a4aa1dc63c5e5c0f77d1086 | [
"Apache-2.0"
] | permissive | dupuisf/mathlib | 62de4ec6544bf3b79086afd27b6529acfaf2c1bb | 8582b06b0a5d06c33ee07d0bdf7c646cae22cf36 | refs/heads/master | 1,669,494,854,016 | 1,595,692,409,000 | 1,595,692,409,000 | 272,046,630 | 0 | 0 | Apache-2.0 | 1,592,066,143,000 | 1,592,066,142,000 | null | UTF-8 | Lean | false | false | 3,862 | 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
open category_theory
open topological_space
open opposite
universe u
namespace topological_space.opens
variables {X Y Z : Top.{u}}
instance opens_category : category.{u} (opens X) :=
{ hom := λ U V, ulift (plift (U ≤ V)),
id := λ X, ⟨ ⟨ le_refl X ⟩ ⟩,
comp := λ X Y Z f g, ⟨ ⟨ le_trans f.down.down g.down.down ⟩ ⟩ }
def to_Top (X : Top.{u}) : opens X ⥤ Top :=
{ obj := λ U, ⟨U.val, infer_instance⟩,
map := λ U V i, ⟨λ x, ⟨x.1, i.down.down x.2⟩,
(embedding.continuous_iff embedding_subtype_coe).2 continuous_induced_dom⟩ }
/-- `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, i.down.down 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
section
variable (X)
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 } }
@[simp] lemma map_id_hom_app (U) : (map_id X).hom.app U = eq_to_hom (map_id_obj U) := rfl
@[simp] lemma map_id_inv_app (U) : (map_id X).inv.app U = eq_to_hom (map_id_obj U).symm := rfl
end
@[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_obj_unop (f : X ⟶ Y) (g : Y ⟶ Z) (U) :
(map (f ≫ g)).obj (unop U) = (map f).obj ((map g).obj (unop U)) :=
by simp
@[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
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 } }
@[simp] lemma map_comp_hom_app (f : X ⟶ Y) (g : Y ⟶ Z) (U) :
(map_comp f g).hom.app U = eq_to_hom (map_comp_obj f g U) := rfl
@[simp] lemma map_comp_inv_app (f : X ⟶ Y) (g : Y ⟶ Z) (U) :
(map_comp f g).inv.app U = eq_to_hom (map_comp_obj f g U).symm := rfl
-- 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
|
0770da5efbf1cae0d2903cbf7db762277130868f | 130c49f47783503e462c16b2eff31933442be6ff | /stage0/src/Lean/Elab/InfoTree.lean | 3379a5be60ccb2cf24366bfac6e41f170856c77c | [
"Apache-2.0"
] | permissive | Hazel-Brown/lean4 | 8aa5860e282435ffc30dcdfccd34006c59d1d39c | 79e6732fc6bbf5af831b76f310f9c488d44e7a16 | refs/heads/master | 1,689,218,208,951 | 1,629,736,869,000 | 1,629,736,896,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 15,246 | lean | /-
Copyright (c) 2020 Wojciech Nawrocki. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Wojciech Nawrocki, Leonardo de Moura, Sebastian Ullrich
-/
import Lean.Data.Position
import Lean.Expr
import Lean.Message
import Lean.Data.Json
import Lean.Meta.Basic
import Lean.Meta.PPGoal
namespace Lean.Elab
open Std (PersistentArray PersistentArray.empty PersistentHashMap)
/- Context after executing `liftTermElabM`.
Note that the term information collected during elaboration may contain metavariables, and their
assignments are stored at `mctx`. -/
structure ContextInfo where
env : Environment
fileMap : FileMap
mctx : MetavarContext := {}
options : Options := {}
currNamespace : Name := Name.anonymous
openDecls : List OpenDecl := []
deriving Inhabited
/-- An elaboration step -/
structure ElabInfo where
elaborator : Name
stx : Syntax
deriving Inhabited
structure TermInfo extends ElabInfo where
lctx : LocalContext -- The local context when the term was elaborated.
expectedType? : Option Expr
expr : Expr
isBinder : Bool := false
deriving Inhabited
structure CommandInfo extends ElabInfo where
deriving Inhabited
inductive CompletionInfo where
| dot (termInfo : TermInfo) (field? : Option Syntax) (expectedType? : Option Expr)
| id (stx : Syntax) (id : Name) (danglingDot : Bool) (lctx : LocalContext) (expectedType? : Option Expr)
| namespaceId (stx : Syntax)
| option (stx : Syntax)
| endSection (stx : Syntax) (scopeNames : List String)
| tactic (stx : Syntax) (goals : List MVarId)
-- TODO `import`
def CompletionInfo.stx : CompletionInfo → Syntax
| dot i .. => i.stx
| id stx .. => stx
| namespaceId stx => stx
| option stx => stx
| endSection stx .. => stx
| tactic stx .. => stx
structure FieldInfo where
/-- Name of the projection. -/
projName : Name
/-- Name of the field as written. -/
fieldName : Name
lctx : LocalContext
val : Expr
stx : Syntax
deriving Inhabited
/- We store the list of goals before and after the execution of a tactic.
We also store the metavariable context at each time since, we want to unassigned metavariables
at tactic execution time to be displayed as `?m...`. -/
structure TacticInfo extends ElabInfo where
mctxBefore : MetavarContext
goalsBefore : List MVarId
mctxAfter : MetavarContext
goalsAfter : List MVarId
deriving Inhabited
structure MacroExpansionInfo where
lctx : LocalContext -- The local context when the macro was expanded.
stx : Syntax
output : Syntax
deriving Inhabited
inductive Info where
| ofTacticInfo (i : TacticInfo)
| ofTermInfo (i : TermInfo)
| ofCommandInfo (i : CommandInfo)
| ofMacroExpansionInfo (i : MacroExpansionInfo)
| ofFieldInfo (i : FieldInfo)
| ofCompletionInfo (i : CompletionInfo)
deriving Inhabited
inductive InfoTree where
| context (i : ContextInfo) (t : InfoTree) -- The context object is created by `liftTermElabM` at `Command.lean`
| node (i : Info) (children : PersistentArray InfoTree) -- The children contains information for nested term elaboration and tactic evaluation
| ofJson (j : Json) -- For user data
| hole (mvarId : MVarId) -- The elaborator creates holes (aka metavariables) for tactics and postponed terms
deriving Inhabited
partial def InfoTree.findInfo? (p : Info → Bool) (t : InfoTree) : Option Info :=
match t with
| context _ t => findInfo? p t
| node i ts =>
if p i then
some i
else
ts.findSome? (findInfo? p)
| _ => none
structure InfoState where
enabled : Bool := false
assignment : PersistentHashMap MVarId InfoTree := {} -- map from holeId to InfoTree
trees : PersistentArray InfoTree := {}
deriving Inhabited
class MonadInfoTree (m : Type → Type) where
getInfoState : m InfoState
modifyInfoState : (InfoState → InfoState) → m Unit
export MonadInfoTree (getInfoState modifyInfoState)
instance [MonadLift m n] [MonadInfoTree m] : MonadInfoTree n where
getInfoState := liftM (getInfoState : m _)
modifyInfoState f := liftM (modifyInfoState f : m _)
partial def InfoTree.substitute (tree : InfoTree) (assignment : PersistentHashMap MVarId InfoTree) : InfoTree :=
match tree with
| node i c => node i <| c.map (substitute · assignment)
| context i t => context i (substitute t assignment)
| ofJson j => ofJson j
| hole id => match assignment.find? id with
| none => hole id
| some tree => substitute tree assignment
def ContextInfo.runMetaM (info : ContextInfo) (lctx : LocalContext) (x : MetaM α) : IO α := do
let x := x.run { lctx := lctx } { mctx := info.mctx }
let ((a, _), _) ← x.toIO { options := info.options, currNamespace := info.currNamespace, openDecls := info.openDecls } { env := info.env }
return a
def ContextInfo.toPPContext (info : ContextInfo) (lctx : LocalContext) : PPContext :=
{ env := info.env, mctx := info.mctx, lctx := lctx,
opts := info.options, currNamespace := info.currNamespace, openDecls := info.openDecls }
def ContextInfo.ppSyntax (info : ContextInfo) (lctx : LocalContext) (stx : Syntax) : IO Format := do
ppTerm (info.toPPContext lctx) stx
private def formatStxRange (ctx : ContextInfo) (stx : Syntax) : Format := do
let pos := stx.getPos?.getD 0
let endPos := stx.getTailPos?.getD pos
return f!"{fmtPos pos stx.getHeadInfo}-{fmtPos endPos stx.getTailInfo}"
where fmtPos pos info :=
let pos := format <| ctx.fileMap.toPosition pos
match info with
| SourceInfo.original .. => pos
| _ => f!"{pos}†"
private def formatElabInfo (ctx : ContextInfo) (info : ElabInfo) : Format :=
if info.elaborator.isAnonymous then
formatStxRange ctx info.stx
else
f!"{formatStxRange ctx info.stx} @ {info.elaborator}"
def TermInfo.runMetaM (info : TermInfo) (ctx : ContextInfo) (x : MetaM α) : IO α :=
ctx.runMetaM info.lctx x
def TermInfo.format (ctx : ContextInfo) (info : TermInfo) : IO Format := do
info.runMetaM ctx do
try
return f!"{← Meta.ppExpr info.expr} : {← Meta.ppExpr (← Meta.inferType info.expr)} @ {formatElabInfo ctx info.toElabInfo}"
catch _ =>
return f!"{← Meta.ppExpr info.expr} : <failed-to-infer-type> @ {formatElabInfo ctx info.toElabInfo}"
def CompletionInfo.format (ctx : ContextInfo) (info : CompletionInfo) : IO Format :=
match info with
| CompletionInfo.dot i (expectedType? := expectedType?) .. => return f!"[.] {← i.format ctx} : {expectedType?}"
| CompletionInfo.id stx _ _ lctx expectedType? => ctx.runMetaM lctx do return f!"[.] {stx} : {expectedType?} @ {formatStxRange ctx info.stx}"
| _ => return f!"[.] {info.stx} @ {formatStxRange ctx info.stx}"
def CommandInfo.format (ctx : ContextInfo) (info : CommandInfo) : IO Format := do
return f!"command @ {formatElabInfo ctx info.toElabInfo}"
def FieldInfo.format (ctx : ContextInfo) (info : FieldInfo) : IO Format := do
ctx.runMetaM info.lctx do
return f!"{info.fieldName} : {← Meta.ppExpr (← Meta.inferType info.val)} := {← Meta.ppExpr info.val} @ {formatStxRange ctx info.stx}"
def ContextInfo.ppGoals (ctx : ContextInfo) (goals : List MVarId) : IO Format :=
if goals.isEmpty then
return "no goals"
else
ctx.runMetaM {} (return Std.Format.prefixJoin "\n" (← goals.mapM Meta.ppGoal))
def TacticInfo.format (ctx : ContextInfo) (info : TacticInfo) : IO Format := do
let ctxB := { ctx with mctx := info.mctxBefore }
let ctxA := { ctx with mctx := info.mctxAfter }
let goalsBefore ← ctxB.ppGoals info.goalsBefore
let goalsAfter ← ctxA.ppGoals info.goalsAfter
return f!"Tactic @ {formatElabInfo ctx info.toElabInfo}\n{info.stx}\nbefore {goalsBefore}\nafter {goalsAfter}"
def MacroExpansionInfo.format (ctx : ContextInfo) (info : MacroExpansionInfo) : IO Format := do
let stx ← ctx.ppSyntax info.lctx info.stx
let output ← ctx.ppSyntax info.lctx info.output
return f!"Macro expansion\n{stx}\n===>\n{output}"
def Info.format (ctx : ContextInfo) : Info → IO Format
| ofTacticInfo i => i.format ctx
| ofTermInfo i => i.format ctx
| ofCommandInfo i => i.format ctx
| ofMacroExpansionInfo i => i.format ctx
| ofFieldInfo i => i.format ctx
| ofCompletionInfo i => i.format ctx
def Info.toElabInfo? : Info → Option ElabInfo
| ofTacticInfo i => some i.toElabInfo
| ofTermInfo i => some i.toElabInfo
| ofCommandInfo i => some i.toElabInfo
| ofMacroExpansionInfo i => none
| ofFieldInfo i => none
| ofCompletionInfo i => none
/--
Helper function for propagating the tactic metavariable context to its children nodes.
We need this function because we preserve `TacticInfo` nodes during backtracking *and* their
children. Moreover, we backtrack the metavariable context to undo metavariable assignments.
`TacticInfo` nodes save the metavariable context before/after the tactic application, and
can be pretty printed without any extra information. This is not the case for `TermInfo` nodes.
Without this function, the formatting method would often fail when processing `TermInfo` nodes
that are children of `TacticInfo` nodes that have been preserved during backtracking.
Saving the metavariable context at `TermInfo` nodes is also not a good option because
at `TermInfo` creation time, the metavariable context often miss information, e.g.,
a TC problem has not been resolved, a postponed subterm has not been elaborated, etc.
See `Term.SavedState.restore`.
-/
def Info.updateContext? : Option ContextInfo → Info → Option ContextInfo
| some ctx, ofTacticInfo i => some { ctx with mctx := i.mctxAfter }
| ctx?, _ => ctx?
partial def InfoTree.format (tree : InfoTree) (ctx? : Option ContextInfo := none) : IO Format := do
match tree with
| ofJson j => return toString j
| hole id => return toString id
| context i t => format t i
| node i cs => match ctx? with
| none => return "<context-not-available>"
| some ctx =>
let fmt ← i.format ctx
if cs.size == 0 then
return fmt
else
let ctx? := i.updateContext? ctx?
return f!"{fmt}{Std.Format.nestD <| Std.Format.prefixJoin (Std.format "\n") (← cs.toList.mapM fun c => format c ctx?)}"
section
variable [Monad m] [MonadInfoTree m]
@[inline] private def modifyInfoTrees (f : PersistentArray InfoTree → PersistentArray InfoTree) : m Unit :=
modifyInfoState fun s => { s with trees := f s.trees }
def getResetInfoTrees : m (PersistentArray InfoTree) := do
let trees := (← getInfoState).trees
modifyInfoTrees fun _ => {}
return trees
def pushInfoTree (t : InfoTree) : m Unit := do
if (← getInfoState).enabled then
modifyInfoTrees fun ts => ts.push t
def pushInfoLeaf (t : Info) : m Unit := do
if (← getInfoState).enabled then
pushInfoTree <| InfoTree.node (children := {}) t
def addCompletionInfo (info : CompletionInfo) : m Unit := do
pushInfoLeaf <| Info.ofCompletionInfo info
def resolveGlobalConstNoOverloadWithInfo [MonadResolveName m] [MonadEnv m] [MonadError m] (id : Syntax) (expectedType? : Option Expr := none) : m Name := do
let n ← resolveGlobalConstNoOverload id
if (← getInfoState).enabled then
-- we do not store a specific elaborator since identifiers are special-cased by the server anyway
pushInfoLeaf <| Info.ofTermInfo { elaborator := Name.anonymous, lctx := LocalContext.empty, expr := (← mkConstWithLevelParams n), stx := id, expectedType? }
return n
def resolveGlobalConstWithInfos [MonadResolveName m] [MonadEnv m] [MonadError m] (id : Syntax) (expectedType? : Option Expr := none) : m (List Name) := do
let ns ← resolveGlobalConst id
if (← getInfoState).enabled then
for n in ns do
pushInfoLeaf <| Info.ofTermInfo { elaborator := Name.anonymous, lctx := LocalContext.empty, expr := (← mkConstWithLevelParams n), stx := id, expectedType? }
return ns
def withInfoContext' [MonadFinally m] (x : m α) (mkInfo : α → m (Sum Info MVarId)) : m α := do
if (← getInfoState).enabled then
let treesSaved ← getResetInfoTrees
Prod.fst <$> MonadFinally.tryFinally' x fun a? => do
match a? with
| none => modifyInfoTrees fun _ => treesSaved
| some a =>
let info ← mkInfo a
modifyInfoTrees fun trees =>
match info with
| Sum.inl info => treesSaved.push <| InfoTree.node info trees
| Sum.inr mvaId => treesSaved.push <| InfoTree.hole mvaId
else
x
def withInfoTreeContext [MonadFinally m] (x : m α) (mkInfoTree : PersistentArray InfoTree → m InfoTree) : m α := do
if (← getInfoState).enabled then
let treesSaved ← getResetInfoTrees
Prod.fst <$> MonadFinally.tryFinally' x fun _ => do
let st ← getInfoState
let tree ← mkInfoTree st.trees
modifyInfoTrees fun _ => treesSaved.push tree
else
x
@[inline] def withInfoContext [MonadFinally m] (x : m α) (mkInfo : m Info) : m α := do
withInfoTreeContext x (fun trees => do return InfoTree.node (← mkInfo) trees)
def withSaveInfoContext [MonadFinally m] [MonadEnv m] [MonadOptions m] [MonadMCtx m] [MonadResolveName m] [MonadFileMap m] (x : m α) : m α := do
if (← getInfoState).enabled then
let treesSaved ← getResetInfoTrees
Prod.fst <$> MonadFinally.tryFinally' x fun _ => do
let st ← getInfoState
let trees ← st.trees.mapM fun tree => do
let tree := tree.substitute st.assignment
InfoTree.context {
env := (← getEnv), fileMap := (← getFileMap), mctx := (← getMCtx), currNamespace := (← getCurrNamespace), openDecls := (← getOpenDecls), options := (← getOptions)
} tree
modifyInfoTrees fun _ => treesSaved ++ trees
else
x
def getInfoHoleIdAssignment? (mvarId : MVarId) : m (Option InfoTree) :=
return (← getInfoState).assignment[mvarId]
def assignInfoHoleId (mvarId : MVarId) (infoTree : InfoTree) : m Unit := do
assert! (← getInfoHoleIdAssignment? mvarId).isNone
modifyInfoState fun s => { s with assignment := s.assignment.insert mvarId infoTree }
end
def withMacroExpansionInfo [MonadFinally m] [Monad m] [MonadInfoTree m] [MonadLCtx m] (stx output : Syntax) (x : m α) : m α :=
let mkInfo : m Info := do
return Info.ofMacroExpansionInfo {
lctx := (← getLCtx)
stx, output
}
withInfoContext x mkInfo
@[inline] def withInfoHole [MonadFinally m] [Monad m] [MonadInfoTree m] (mvarId : MVarId) (x : m α) : m α := do
if (← getInfoState).enabled then
let treesSaved ← getResetInfoTrees
Prod.fst <$> MonadFinally.tryFinally' x fun a? => modifyInfoState fun s =>
if s.trees.size > 0 then
{ s with trees := treesSaved, assignment := s.assignment.insert mvarId s.trees[s.trees.size - 1] }
else
{ s with trees := treesSaved }
else
x
def enableInfoTree [MonadInfoTree m] (flag := true) : m Unit :=
modifyInfoState fun s => { s with enabled := flag }
def getInfoTrees [MonadInfoTree m] [Monad m] : m (PersistentArray InfoTree) :=
return (← getInfoState).trees
end Lean.Elab
|
80c045895dfd5cdc157541848bec239e2a2ad922 | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/topology/Top/stalks.lean | 8dcb8b4c59819b776fc2adc590b310dfb5e50f6b | [
"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 | 3,565 | 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.Top.open_nhds
import topology.Top.presheaf
import category_theory.limits.limits
universes v u v' u'
open category_theory
open Top
open category_theory.limits
open topological_space
variables {C : Type u} [𝒞 : category.{v+1} C]
include 𝒞
variables [has_colimits.{v} C]
variables {X Y Z : Top.{v}}
namespace Top.presheaf
variables (C)
/-- Stalks are functorial with respect to morphisms of presheaves over a fixed `X`. -/
def stalk_functor (x : X) : X.presheaf C ⥤ C :=
((whiskering_left _ _ C).obj (open_nhds.inclusion x).op) ⋙ colim
variables {C}
/--
The stalk of a presheaf `F` at a point `x` is calculated as the colimit of the functor
nbhds x ⥤ opens F.X ⥤ C
-/
def stalk (ℱ : X.presheaf C) (x : X) : C :=
(stalk_functor C x).obj ℱ -- -- colimit (nbhds_inclusion x ⋙ ℱ)
@[simp] lemma stalk_functor_obj (ℱ : X.presheaf C) (x : X) : (stalk_functor C x).obj ℱ = ℱ.stalk x := rfl
variables (C)
def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) : (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x :=
begin
-- This is a hack; Lean doesn't like to elaborate the term written directly.
transitivity,
swap,
exact colimit.pre _ (open_nhds.map f x).op,
exact colim.map (whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) ℱ),
end
-- Here are two other potential solutions, suggested by @fpvandoorn at
-- https://github.com/leanprover-community/mathlib/pull/1018#discussion_r283978240
-- However, I can't get the subsequent two proofs to work with either one.
-- def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) : (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x :=
-- colim.map ((functor.associator _ _ _).inv ≫
-- whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) ℱ) ≫
-- colimit.pre ((open_nhds.inclusion x).op ⋙ ℱ) (open_nhds.map f x).op
-- def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) : (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x :=
-- (colim.map (whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) ℱ) :
-- colim.obj ((open_nhds.inclusion (f x) ⋙ opens.map f).op ⋙ ℱ) ⟶ _) ≫
-- colimit.pre ((open_nhds.inclusion x).op ⋙ ℱ) (open_nhds.map f x).op
namespace stalk_pushforward
local attribute [tidy] tactic.op_induction'
@[simp] lemma id (ℱ : X.presheaf C) (x : X) :
ℱ.stalk_pushforward C (𝟙 X) x = (stalk_functor C x).map ((pushforward.id ℱ).hom) :=
begin
dsimp [stalk_pushforward, stalk_functor],
ext1,
tactic.op_induction',
cases j, cases j_val,
rw [colim.ι_map_assoc, colim.ι_map, colimit.ι_pre, whisker_left.app, whisker_right.app,
pushforward.id_hom_app, eq_to_hom_map, eq_to_hom_refl],
dsimp,
rw [category_theory.functor.map_id]
end
@[simp] lemma comp (ℱ : X.presheaf C) (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) :
ℱ.stalk_pushforward C (f ≫ g) x =
((f _* ℱ).stalk_pushforward C g (f x)) ≫ (ℱ.stalk_pushforward C f x) :=
begin
dsimp [stalk_pushforward, stalk_functor, pushforward],
ext U,
op_induction U,
cases U,
cases U_val,
simp only [colim.ι_map_assoc, colimit.ι_pre_assoc, colimit.ι_pre,
whisker_right.app, category.assoc],
dsimp,
simp only [category.id_comp, category_theory.functor.map_id],
-- FIXME A simp lemma which unfortunately doesn't fire:
rw [category_theory.functor.map_id],
dsimp,
simp,
end
end stalk_pushforward
end Top.presheaf
|
5727a9dd1df90a25be545a84c1cf1746b6f42043 | 9d2e3d5a2e2342a283affd97eead310c3b528a24 | /src/for_mathlib/manifolds.lean | c49ad523ab7d63eb7a88a22b10dfc203b386b1b7 | [] | permissive | Vtec234/lftcm2020 | ad2610ab614beefe44acc5622bb4a7fff9a5ea46 | bbbd4c8162f8c2ef602300ab8fdeca231886375d | refs/heads/master | 1,668,808,098,623 | 1,594,989,081,000 | 1,594,990,079,000 | 280,423,039 | 0 | 0 | MIT | 1,594,990,209,000 | 1,594,990,209,000 | null | UTF-8 | Lean | false | false | 10,486 | lean | /- Missing bits that should be added to mathlib after the workshop and after cleaning them up -/
import geometry.manifold.times_cont_mdiff
import geometry.manifold.real_instances
open set
open_locale big_operators
instance : has_zero (Icc (0 : ℝ) 1) := ⟨⟨(0 : ℝ), ⟨le_refl _, zero_le_one⟩⟩⟩
instance : has_one (Icc (0 : ℝ) 1) := ⟨⟨(1 : ℝ), ⟨zero_le_one, le_refl _⟩⟩⟩
@[simp] lemma homeomorph_mk_coe {α : Type*} {β : Type*} [topological_space α] [topological_space β]
(a : equiv α β) (b c) : ((homeomorph.mk a b c) : α → β) = a :=
rfl
@[simp] lemma homeomorph_mk_coe_symm {α : Type*} {β : Type*} [topological_space α] [topological_space β]
(a : equiv α β) (b c) : ((homeomorph.mk a b c).symm : β → α) = a.symm :=
rfl
namespace metric
lemma is_closed_sphere {α : Type*} [metric_space α] {x : α} {r : ℝ} :
is_closed (sphere x r) :=
is_closed_eq (continuous_id.dist continuous_const) continuous_const
end metric
section fderiv_id
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
variables {E : Type*} [normed_group E] [normed_space 𝕜 E]
lemma fderiv_id' {x : E} : fderiv 𝕜 (λ (x : E), x) x = continuous_linear_map.id 𝕜 E :=
fderiv_id
end fderiv_id
section times_cont_diff_sum
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E]
{F : Type*} [normed_group F] [normed_space 𝕜 F]
{G : Type*} [normed_group G] [normed_space 𝕜 G]
{ι : Type*} {f : ι → E → F} {s : finset ι} {n : with_top ℕ} {t : set E} {x : E}
/- When adding it to mathlib, make `x` explicit in times_cont_diff_within_at.comp -/
/-- The sum of two `C^n`functions on a domain is `C^n`. -/
lemma times_cont_diff_within_at.add {n : with_top ℕ} {s : set E} {f g : E → F}
(hf : times_cont_diff_within_at 𝕜 n f s x) (hg : times_cont_diff_within_at 𝕜 n g s x) :
times_cont_diff_within_at 𝕜 n (λx, f x + g x) s x :=
begin
have A : times_cont_diff 𝕜 n (λp : F × F, p.1 + p.2),
{ apply is_bounded_linear_map.times_cont_diff,
exact is_bounded_linear_map.add is_bounded_linear_map.fst is_bounded_linear_map.snd },
have B : times_cont_diff_within_at 𝕜 n (λp : F × F, p.1 + p.2) univ (prod.mk (f x) (g x)) :=
A.times_cont_diff_at.times_cont_diff_within_at,
exact @times_cont_diff_within_at.comp _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ x B (hf.prod hg) (subset_preimage_univ),
end
/-- The sum of two `C^n`functions on a domain is `C^n`. -/
lemma times_cont_diff_at.add {n : with_top ℕ} {f g : E → F}
(hf : times_cont_diff_at 𝕜 n f x) (hg : times_cont_diff_at 𝕜 n g x) :
times_cont_diff_at 𝕜 n (λx, f x + g x) x :=
begin
simp [← times_cont_diff_within_at_univ] at *,
exact hf.add hg
end
lemma times_cont_diff_within_at.sum (h : ∀ i ∈ s, times_cont_diff_within_at 𝕜 n (λ x, f i x) t x) :
times_cont_diff_within_at 𝕜 n (λ x, (∑ i in s, f i x)) t x :=
begin
classical,
induction s using finset.induction_on with i s is IH,
{ simp [times_cont_diff_within_at_const] },
{ simp only [is, finset.sum_insert, not_false_iff],
exact (h _ (finset.mem_insert_self i s)).add (IH (λ j hj, h _ (finset.mem_insert_of_mem hj))) }
end
lemma times_cont_diff_at.sum (h : ∀ i ∈ s, times_cont_diff_at 𝕜 n (λ x, f i x) x) :
times_cont_diff_at 𝕜 n (λ x, (∑ i in s, f i x)) x :=
begin
simp [← times_cont_diff_within_at_univ] at *,
exact times_cont_diff_within_at.sum h
end
lemma times_cont_diff_on.sum (h : ∀ i ∈ s, times_cont_diff_on 𝕜 n (λ x, f i x) t) :
times_cont_diff_on 𝕜 n (λ x, (∑ i in s, f i x)) t :=
λ x hx, times_cont_diff_within_at.sum (λ i hi, h i hi x hx)
lemma times_cont_diff.sum (h : ∀ i ∈ s, times_cont_diff 𝕜 n (λ x, f i x)) :
times_cont_diff 𝕜 n (λ x, (∑ i in s, f i x)) :=
begin
simp [← times_cont_diff_on_univ] at *,
exact times_cont_diff_on.sum h
end
lemma times_cont_diff.comp_times_cont_diff_within_at {g : F → G} {f : E → F} (h : times_cont_diff 𝕜 n g)
(hf : times_cont_diff_within_at 𝕜 n f t x) :
times_cont_diff_within_at 𝕜 n (g ∘ f) t x :=
begin
have : times_cont_diff_within_at 𝕜 n g univ (f x) :=
h.times_cont_diff_at.times_cont_diff_within_at,
exact this.comp hf (subset_univ _),
end
end times_cont_diff_sum
section pi_Lp_smooth
variables
{𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{ι : Type*} [fintype ι]
{p : ℝ} {hp : 1 ≤ p} {α : ι → Type*} {n : with_top ℕ} (i : ι)
[∀i, normed_group (α i)] [∀i, normed_space 𝕜 (α i)]
{E : Type*} [normed_group E] [normed_space 𝕜 E] {f : E → pi_Lp p hp α} {s : set E} {x : E}
lemma pi_Lp.norm_coord_le_norm (x : pi_Lp p hp α) (i : ι) : ∥x i∥ ≤ ∥x∥ :=
calc
∥x i∥ ≤ (∥x i∥ ^ p) ^ (1/p) :
begin
have : p ≠ 0 := ne_of_gt (lt_of_lt_of_le zero_lt_one hp),
rw [← real.rpow_mul (norm_nonneg _), mul_one_div_cancel this, real.rpow_one],
end
... ≤ _ :
begin
have A : ∀ j, 0 ≤ ∥x j∥ ^ p := λ j, real.rpow_nonneg_of_nonneg (norm_nonneg _) _,
simp only [pi_Lp.norm_eq, one_mul, linear_map.coe_mk],
apply real.rpow_le_rpow (A i),
{ exact finset.single_le_sum (λ j hj, A j) (finset.mem_univ _) },
{ exact div_nonneg zero_le_one (lt_of_lt_of_le zero_lt_one hp) }
end
lemma pi_Lp.times_cont_diff_coord :
times_cont_diff 𝕜 n (λ x : pi_Lp p hp α, x i) :=
let F : pi_Lp p hp α →ₗ[𝕜] α i :=
{ to_fun := λ x, x i, map_add' := λ x y, rfl, map_smul' := λ x c, rfl } in
(F.mk_continuous 1 (λ x, by simpa using pi_Lp.norm_coord_le_norm x i)).times_cont_diff
lemma pi_Lp.times_cont_diff_within_at_iff_coord :
times_cont_diff_within_at 𝕜 n f s x ↔ ∀ i, times_cont_diff_within_at 𝕜 n (λ x, (f x) i) s x:=
begin
classical,
split,
{ assume h i,
exact (pi_Lp.times_cont_diff_coord i).comp_times_cont_diff_within_at h, },
{ assume h,
let F : Π (i : ι), α i →ₗ[𝕜] pi_Lp p hp α := λ i,
{ to_fun := λ y, function.update 0 i y,
map_add' := begin
assume y y',
ext j,
by_cases h : j = i,
{ rw h, simp },
{ simp [h], }
end,
map_smul' := begin
assume c x,
ext j,
by_cases h : j = i,
{ rw h, simp },
{ simp [h], }
end },
let G : Π (i : ι), α i →L[𝕜] pi_Lp p hp α := λ i,
begin
have p_ne_0 : p ≠ 0 := ne_of_gt (lt_of_lt_of_le zero_lt_one hp),
refine (F i).mk_continuous 1 (λ x, _),
have : (λ j, ∥function.update 0 i x j∥ ^ p) = (λ j, if j = i then ∥x∥ ^ p else 0),
{ ext j,
by_cases h : j = i,
{ rw h, simp },
{ simp [h, p_ne_0] } },
simp only [pi_Lp.norm_eq, this, one_mul, finset.mem_univ, if_true, linear_map.coe_mk, finset.sum_ite_eq'],
rw [← real.rpow_mul (norm_nonneg _), mul_one_div_cancel p_ne_0, real.rpow_one]
end,
have : times_cont_diff_within_at 𝕜 n (λ x, (∑ (i : ι), G i ((f x) i))) s x,
{ apply times_cont_diff_within_at.sum (λ i hi, _),
exact (G i).times_cont_diff.comp_times_cont_diff_within_at (h i) },
convert this,
ext x j,
simp,
change f x j = (∑ (i : ι), function.update 0 i (f x i)) j,
rw finset.sum_apply,
have : ∀ i, function.update 0 i (f x i) j = (if j = i then f x j else 0),
{ assume i,
by_cases h : j = i,
{ rw h, simp },
{ simp [h] } },
simp [this] }
end
lemma pi_Lp.times_cont_diff_at_iff_coord :
times_cont_diff_at 𝕜 n f x ↔ ∀ i, times_cont_diff_at 𝕜 n (λ x, (f x) i) x :=
by simp [← times_cont_diff_within_at_univ, pi_Lp.times_cont_diff_within_at_iff_coord]
lemma pi_Lp.times_cont_diff_on_iff_coord :
times_cont_diff_on 𝕜 n f s ↔ ∀ i, times_cont_diff_on 𝕜 n (λ x, (f x) i) s :=
by { simp_rw [times_cont_diff_on, pi_Lp.times_cont_diff_within_at_iff_coord], tauto }
lemma pi_Lp.times_cont_diff_iff_coord :
times_cont_diff 𝕜 n f ↔ ∀ i, times_cont_diff 𝕜 n (λ x, (f x) i) :=
by simp [← times_cont_diff_on_univ, pi_Lp.times_cont_diff_on_iff_coord]
end pi_Lp_smooth
lemma inducing.continuous_on_iff
{α : Type*} {β : Type*} {γ : Type*}
[topological_space α] [topological_space β] [topological_space γ]
{f : α → β} {g : β → γ} (hg : inducing g) {s : set α} :
continuous_on f s ↔ continuous_on (g ∘ f) s :=
begin
simp only [continuous_on_iff_continuous_restrict, restrict_eq],
conv_rhs { rw [function.comp.assoc, ← (inducing.continuous_iff hg)] },
end
lemma embedding.continuous_on_iff
{α : Type*} {β : Type*} {γ : Type*}
[topological_space α] [topological_space β] [topological_space γ]
{f : α → β} {g : β → γ} (hg : embedding g) {s : set α} :
continuous_on f s ↔ continuous_on (g ∘ f) s :=
inducing.continuous_on_iff hg.1
section tangent_map
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E]
{H : Type*} [topological_space H] {I : model_with_corners 𝕜 E H}
{M : Type*} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M]
{s : set M} {x : M}
variables {E' : Type*} [normed_group E'] [normed_space 𝕜 E']
{H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'}
{M' : Type*} [topological_space M'] [charted_space H' M'] [smooth_manifold_with_corners I' M']
@[simp, mfld_simps] lemma tangent_map_id : tangent_map I I (id : M → M) = id :=
by { ext1 p, simp [tangent_map] }
lemma tangent_map_within_id {p : tangent_bundle I M}
(hs : unique_mdiff_within_at I s (tangent_bundle.proj I M p)) :
tangent_map_within I I (id : M → M) s p = p :=
begin
simp only [tangent_map_within, id.def],
rw mfderiv_within_id,
{ rcases p, refl },
{ exact hs }
end
lemma mfderiv_within_congr {f f₁ : M → M'} (hs : unique_mdiff_within_at I s x)
(hL : ∀ x ∈ s, f₁ x = f x) (hx : f₁ x = f x) :
mfderiv_within I I' f₁ s x = (mfderiv_within I I' f s x : _) :=
filter.eventually_eq.mfderiv_within_eq hs (filter.eventually_eq_of_mem (self_mem_nhds_within) hL) hx
lemma tangent_map_within_congr {f g : M → M'} {s : set M}
(h : ∀ x ∈ s, f x = g x)
(p : tangent_bundle I M) (hp : p.1 ∈ s) (hs : unique_mdiff_within_at I s p.1) :
tangent_map_within I I' f s p = tangent_map_within I I' g s p :=
begin
simp only [tangent_map_within, h p.fst hp, true_and, prod.mk.inj_iff, eq_self_iff_true],
congr' 1,
exact mfderiv_within_congr hs h (h _ hp)
end
end tangent_map
|
cf2a40e7934890aebb732d9fa8fe59fb5d1f58f4 | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/data/sym2.lean | 3cdd885d24a0ff794483082ceab1be54926c369b | [
"Apache-2.0"
] | permissive | dupuisf/mathlib | 62de4ec6544bf3b79086afd27b6529acfaf2c1bb | 8582b06b0a5d06c33ee07d0bdf7c646cae22cf36 | refs/heads/master | 1,669,494,854,016 | 1,595,692,409,000 | 1,595,692,409,000 | 272,046,630 | 0 | 0 | Apache-2.0 | 1,592,066,143,000 | 1,592,066,142,000 | null | UTF-8 | Lean | false | false | 9,481 | lean | /-
Copyright (c) 2020 Kyle Miller All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Kyle Miller.
-/
import tactic.linarith
import data.sym
open function
open sym
/-!
# The symmetric square
This file defines the symmetric square, which is `α × α` modulo
swapping. This is also known as the type of unordered pairs.
More generally, the symmetric square is the second symmetric power
(see `data.sym`). The equivalence is `sym2.equiv_sym`.
From the point of view that an unordered pair is equivalent to a
multiset of cardinality two (see `sym2.equiv_multiset`), there is a
`has_mem` instance `sym2.mem`, which is a `Prop`-valued membership
test. Given `a ∈ z` for `z : sym2 α`, it does not appear to be
possible, in general, to *computably* give the other element in the
pair. For this, `sym2.vmem a z` is a `Type`-valued membership test
that gives a way to obtain the other element with `sym2.vmem.other`.
Recall that an undirected graph (allowing self loops, but no multiple
edges) is equivalent to a symmetric relation on the vertex type `α`.
Given a symmetric relation on `α`, the corresponding edge set is
constructed by `sym2.from_rel`.
## Notation
The symmetric square has a setoid instance, so `⟦(a, b)⟧` denotes a
term of the symmetric square.
## Tags
symmetric square, unordered pairs, symmetric powers
-/
namespace sym2
variables {α : Type*}
/--
This is the relation capturing the notion of pairs equivalent up to permutations.
-/
inductive rel (α : Type*) : (α × α) → (α × α) → Prop
| refl (x y : α) : rel (x, y) (x, y)
| swap (x y : α) : rel (x, y) (y, x)
attribute [refl] rel.refl
@[symm] lemma rel.symm {x y : α × α} : rel α x y → rel α y x :=
by { rintro ⟨_,_⟩, exact a, apply rel.swap }
@[trans] lemma rel.trans {x y z : α × α} : rel α x y → rel α y z → rel α x z :=
by { intros a b, cases_matching* rel _ _ _; apply rel.refl <|> apply rel.swap }
lemma rel.is_equivalence : equivalence (rel α) := by tidy; apply rel.trans; assumption
instance rel.setoid (α : Type*) : setoid (α × α) := ⟨rel α, rel.is_equivalence⟩
end sym2
/--
`sym2 α` is the symmetric square of `α`, which, in other words, is the
type of unordered pairs.
It is equivalent in a natural way to multisets of cardinality 2 (see
`sym2.equiv_multiset`).
-/
@[reducible]
def sym2 (α : Type*) := quotient (sym2.rel.setoid α)
namespace sym2
universe u
variables {α : Type u}
lemma eq_swap {a b : α} : ⟦(a, b)⟧ = ⟦(b, a)⟧ :=
by { rw quotient.eq, apply rel.swap }
lemma congr_right (a b c : α) : ⟦(a, b)⟧ = ⟦(a, c)⟧ ↔ b = c :=
by { split; intro h, { rw quotient.eq at h, cases h; refl }, rw h }
/--
The functor `sym2` is functorial, and this function constructs the induced maps.
-/
def map {α β : Type*} (f : α → β) : sym2 α → sym2 β :=
quotient.map (prod.map f f)
(by { rintros _ _ h, cases h, { refl }, apply rel.swap })
@[simp]
lemma map_id : sym2.map (@id α) = id := by tidy
lemma map_comp {α β γ : Type*} {g : β → γ} {f : α → β} :
sym2.map (g ∘ f) = sym2.map g ∘ sym2.map f := by tidy
section membership
/-! ### Declarations about membership -/
/--
This is a predicate that determines whether a given term is a member of a term of the
symmetric square. From this point of view, the symmetric square is the subtype of
cardinality-two multisets on `α`.
-/
def mem (x : α) (z : sym2 α) : Prop :=
∃ (y : α), z = ⟦(x, y)⟧
instance : has_mem α (sym2 α) := ⟨mem⟩
lemma mk_has_mem (x y : α) : x ∈ ⟦(x, y)⟧ := ⟨y, rfl⟩
/--
This is a type-valued version of the membership predicate `mem` that contains the other
element `y` of `z` such that `z = ⟦(x, y)⟧`. It is a subsingleton already,
so there is no need to apply `trunc` to the type.
-/
@[nolint has_inhabited_instance]
def vmem (x : α) (z : sym2 α) : Type u :=
{y : α // z = ⟦(x, y)⟧}
instance (x : α) (z : sym2 α) : subsingleton {y : α // z = ⟦(x, y)⟧} :=
⟨by { rintros ⟨a, ha⟩ ⟨b, hb⟩, rw [ha, congr_right] at hb, tidy }⟩
/--
The `vmem` version of `mk_has_mem`.
-/
def mk_has_vmem (x y : α) : vmem x ⟦(x, y)⟧ :=
⟨y, rfl⟩
instance {a : α} {z : sym2 α} : has_lift (vmem a z) (mem a z) := ⟨λ h, ⟨h.val, h.property⟩⟩
/--
Given an element of a term of the symmetric square (using `vmem`), retrieve the other element.
-/
def vmem.other {a : α} {p : sym2 α} (h : vmem a p) : α := h.val
/--
The defining property of the other element is that it can be used to
reconstruct the term of the symmetric square.
-/
lemma vmem_other_spec {a : α} {z : sym2 α} (h : vmem a z) :
z = ⟦(a, h.other)⟧ := by { delta vmem.other, tidy }
/--
This is the `mem`-based version of `other`.
-/
noncomputable def mem.other {a : α} {z : sym2 α} (h : a ∈ z) : α :=
classical.some h
lemma mem_other_spec {a : α} {z : sym2 α} (h : a ∈ z) :
⟦(a, h.other)⟧ = z := by erw ← classical.some_spec h
lemma other_is_mem_other {a : α} {z : sym2 α} (h : vmem a z) (h' : a ∈ z) :
h.other = mem.other h' := by rw [← congr_right a, ← vmem_other_spec h, mem_other_spec]
lemma eq_iff {x y z w : α} :
⟦(x, y)⟧ = ⟦(z, w)⟧ ↔ (x = z ∧ y = w) ∨ (x = w ∧ y = z) :=
begin
split; intro h,
{ rw quotient.eq at h, cases h; tidy },
{ cases h; rw [h.1, h.2], rw eq_swap }
end
lemma mem_iff {a b c : α} : a ∈ ⟦(b, c)⟧ ↔ a = b ∨ a = c :=
{ mp := by { rintro ⟨_, h⟩, rw eq_iff at h, tidy },
mpr := by { rintro ⟨_⟩; subst a, { apply mk_has_mem }, rw eq_swap, apply mk_has_mem } }
end membership
/--
A type `α` is naturally included in the diagonal of `α × α`, and this function gives the image
of this diagonal in `sym2 α`.
-/
def diag (x : α) : sym2 α := ⟦(x, x)⟧
/--
A predicate for testing whether an element of `sym2 α` is on the diagonal.
-/
def is_diag (z : sym2 α) : Prop := z ∈ set.range (@diag α)
lemma is_diag_iff_proj_eq (z : α × α) : is_diag ⟦z⟧ ↔ z.1 = z.2 :=
begin
cases z with a, split,
{ rintro ⟨_, h⟩, erw eq_iff at h, cc },
{ rintro ⟨⟩, use a, refl },
end
instance is_diag.decidable_pred (α : Type u) [decidable_eq α] : decidable_pred (@is_diag α) :=
by { intro z, induction z, { erw is_diag_iff_proj_eq, apply_instance }, apply subsingleton.elim }
section relations
/-! ### Declarations about symmetric relations -/
variables {r : α → α → Prop}
/--
Symmetric relations define a set on `sym2 α` by taking all those pairs
of elements that are related.
-/
def from_rel (sym : symmetric r) : set (sym2 α) :=
λ z, quotient.rec_on z (λ z, r z.1 z.2) (by { rintros _ _ ⟨_,_⟩, tidy })
@[simp]
lemma from_rel_proj_prop {sym : symmetric r} {z : α × α} :
⟦z⟧ ∈ from_rel sym ↔ r z.1 z.2 := by tidy
@[simp]
lemma from_rel_prop {sym : symmetric r} {a b : α} :
⟦(a, b)⟧ ∈ from_rel sym ↔ r a b := by simp only [from_rel_proj_prop]
lemma from_rel_irreflexive {sym : symmetric r} :
irreflexive r ↔ ∀ {z}, z ∈ from_rel sym → ¬is_diag z :=
{ mp := by { intros h z hr hd, induction z,
erw is_diag_iff_proj_eq at hd, erw from_rel_proj_prop at hr, tidy },
mpr := by { intros h x hr, rw ← @from_rel_prop _ _ sym at hr, exact h hr ⟨x, rfl⟩ }}
end relations
section sym_equiv
/-! ### Equivalence to the second symmetric power -/
local attribute [instance] vector.perm.is_setoid
private def from_vector {α : Type*} : vector α 2 → α × α
| ⟨[a, b], h⟩ := (a, b)
private lemma perm_card_two_iff {α : Type*} {a₁ b₁ a₂ b₂ : α} :
[a₁, b₁].perm [a₂, b₂] ↔ (a₁ = a₂ ∧ b₁ = b₂) ∨ (a₁ = b₂ ∧ b₁ = a₂) :=
{ mp := by { simp [← multiset.coe_eq_coe, ← multiset.cons_coe, multiset.cons_eq_cons]; tidy },
mpr := by { intro h, cases h; rw [h.1, h.2], apply list.perm.swap', refl } }
/--
The symmetric square is equivalent to length-2 vectors up to permutations.
-/
def sym2_equiv_sym' {α : Type*} : equiv (sym2 α) (sym' α 2) :=
{ to_fun := quotient.map
(λ (x : α × α), ⟨[x.1, x.2], rfl⟩)
(by { rintros _ _ ⟨_⟩, { refl }, apply list.perm.swap', refl }),
inv_fun := quotient.map from_vector (begin
rintros ⟨x, hx⟩ ⟨y, hy⟩ h,
cases x with _ x, { simp at hx; tauto },
cases x with _ x, { simp at hx; norm_num at hx },
cases x with _ x, swap, { exfalso, simp at hx; linarith [hx] },
cases y with _ y, { simp at hy; tauto },
cases y with _ y, { simp at hy; norm_num at hy },
cases y with _ y, swap, { exfalso, simp at hy; linarith [hy] },
rcases perm_card_two_iff.mp h with ⟨rfl,rfl⟩|⟨rfl,rfl⟩, { refl },
apply sym2.rel.swap,
end),
left_inv := by tidy,
right_inv := λ x, begin
induction x,
{ cases x with x hx,
cases x with _ x, { simp at hx; tauto },
cases x with _ x, { simp at hx; norm_num at hx },
cases x with _ x, swap, { exfalso, simp at hx; linarith [hx] },
refl },
refl,
end }
/--
The symmetric square is equivalent to the second symmetric power.
-/
def equiv_sym (α : Type*) : sym2 α ≃ sym α 2 :=
equiv.trans sym2_equiv_sym' (sym_equiv_sym' α 2).symm
/--
The symmetric square is equivalent to multisets of cardinality
two. (This is currently a synonym for `equiv_sym`, but it's provided
in case the definition for `sym` changes.)
-/
def equiv_multiset (α : Type*) : sym2 α ≃ {s : multiset α // s.card = 2} :=
equiv_sym α
end sym_equiv
end sym2
|
cd885cf9544d88584ed07b825af13194107906f4 | 618003631150032a5676f229d13a079ac875ff77 | /src/data/setoid/partition.lean | d7aef47f009acb9ed88115d222754c8bf4158d9c | [
"Apache-2.0"
] | permissive | awainverse/mathlib | 939b68c8486df66cfda64d327ad3d9165248c777 | ea76bd8f3ca0a8bf0a166a06a475b10663dec44a | refs/heads/master | 1,659,592,962,036 | 1,590,987,592,000 | 1,590,987,592,000 | 268,436,019 | 1 | 0 | Apache-2.0 | 1,590,990,500,000 | 1,590,990,500,000 | null | UTF-8 | Lean | false | false | 8,349 | lean | import data.setoid.basic
import data.set.lattice
/-!
# Equivalence relations: partitions
This file comprises properties of equivalence relations viewed as partitions.
## Tags
setoid, equivalence, iseqv, relation, equivalence relation, partition, equivalence class
-/
namespace setoid
variables {α : Type*}
/-- If x ∈ α is in 2 elements of a set of sets partitioning α, those 2 sets are equal. -/
lemma eq_of_mem_eqv_class {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b)
{x b b'} (hc : b ∈ c) (hb : x ∈ b) (hc' : b' ∈ c) (hb' : x ∈ b') :
b = b' :=
(H x).unique2 hc hb hc' hb'
/-- Makes an equivalence relation from a set of sets partitioning α. -/
def mk_classes (c : set (set α)) (H : ∀ a, ∃! b ∈ c, a ∈ b) :
setoid α :=
⟨λ x y, ∀ s ∈ c, x ∈ s → y ∈ s, ⟨λ _ _ _ hx, hx,
λ x y h s hs hy, (H x).elim2 $ λ t ht hx _,
have s = t, from eq_of_mem_eqv_class H hs hy ht (h t ht hx),
this.symm ▸ hx,
λ x y z h1 h2 s hs hx, (H y).elim2 $ λ t ht hy _, (H z).elim2 $ λ t' ht' hz _,
have hst : s = t, from eq_of_mem_eqv_class H hs (h1 _ hs hx) ht hy,
have htt' : t = t', from eq_of_mem_eqv_class H ht (h2 _ ht hy) ht' hz,
(hst.trans htt').symm ▸ hz⟩⟩
/-- Makes the equivalence classes of an equivalence relation. -/
def classes (r : setoid α) : set (set α) :=
{s | ∃ y, s = {x | r.rel x y}}
lemma mem_classes (r : setoid α) (y) : {x | r.rel x y} ∈ r.classes := ⟨y, rfl⟩
/-- Two equivalence relations are equal iff all their equivalence classes are equal. -/
lemma eq_iff_classes_eq {r₁ r₂ : setoid α} :
r₁ = r₂ ↔ ∀ x, {y | r₁.rel x y} = {y | r₂.rel x y} :=
⟨λ h x, h ▸ rfl, λ h, ext' $ λ x, set.ext_iff.1 $ h x⟩
lemma rel_iff_exists_classes (r : setoid α) {x y} :
r.rel x y ↔ ∃ c ∈ r.classes, x ∈ c ∧ y ∈ c :=
⟨λ h, ⟨_, r.mem_classes y, h, r.refl' y⟩,
λ ⟨c, ⟨z, hz⟩, hx, hy⟩, by { subst c, exact r.trans' hx (r.symm' hy) }⟩
/-- Two equivalence relations are equal iff their equivalence classes are equal. -/
lemma classes_inj {r₁ r₂ : setoid α} :
r₁ = r₂ ↔ r₁.classes = r₂.classes :=
⟨λ h, h ▸ rfl, λ h, ext' $ λ a b, by simp only [rel_iff_exists_classes, exists_prop, h] ⟩
/-- The empty set is not an equivalence class. -/
lemma empty_not_mem_classes {r : setoid α} : ∅ ∉ r.classes :=
λ ⟨y, hy⟩, set.not_mem_empty y $ hy.symm ▸ r.refl' y
/-- Equivalence classes partition the type. -/
lemma classes_eqv_classes {r : setoid α} (a) : ∃! b ∈ r.classes, a ∈ b :=
exists_unique.intro2 {x | r.rel x a} (r.mem_classes a) (r.refl' _) $
begin
rintros _ ⟨y, rfl⟩ ha,
ext x,
exact ⟨λ hx, r.trans' hx (r.symm' ha), λ hx, r.trans' hx ha⟩
end
/-- If x ∈ α is in 2 equivalence classes, the equivalence classes are equal. -/
lemma eq_of_mem_classes {r : setoid α} {x b} (hc : b ∈ r.classes)
(hb : x ∈ b) {b'} (hc' : b' ∈ r.classes) (hb' : x ∈ b') : b = b' :=
eq_of_mem_eqv_class classes_eqv_classes hc hb hc' hb'
/-- The elements of a set of sets partitioning α are the equivalence classes of the
equivalence relation defined by the set of sets. -/
lemma eq_eqv_class_of_mem {c : set (set α)}
(H : ∀ a, ∃! b ∈ c, a ∈ b) {s y} (hs : s ∈ c) (hy : y ∈ s) :
s = {x | (mk_classes c H).rel x y} :=
set.ext $ λ x,
⟨λ hs', symm' (mk_classes c H) $ λ b' hb' h', eq_of_mem_eqv_class H hs hy hb' h' ▸ hs',
λ hx, (H x).elim2 $ λ b' hc' hb' h',
(eq_of_mem_eqv_class H hs hy hc' $ hx b' hc' hb').symm ▸ hb'⟩
/-- The equivalence classes of the equivalence relation defined by a set of sets
partitioning α are elements of the set of sets. -/
lemma eqv_class_mem {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {y} :
{x | (mk_classes c H).rel x y} ∈ c :=
(H y).elim2 $ λ b hc hy hb, eq_eqv_class_of_mem H hc hy ▸ hc
/-- Distinct elements of a set of sets partitioning α are disjoint. -/
lemma eqv_classes_disjoint {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) :
set.pairwise_disjoint c :=
λ b₁ h₁ b₂ h₂ h, set.disjoint_left.2 $
λ x hx1 hx2, (H x).elim2 $ λ b hc hx hb, h $ eq_of_mem_eqv_class H h₁ hx1 h₂ hx2
/-- A set of disjoint sets covering α partition α (classical). -/
lemma eqv_classes_of_disjoint_union {c : set (set α)}
(hu : set.sUnion c = @set.univ α) (H : set.pairwise_disjoint c) (a) :
∃! b ∈ c, a ∈ b :=
let ⟨b, hc, ha⟩ := set.mem_sUnion.1 $ show a ∈ _, by rw hu; exact set.mem_univ a in
exists_unique.intro2 b hc ha $ λ b' hc' ha', H.elim hc' hc a ha' ha
/-- Makes an equivalence relation from a set of disjoints sets covering α. -/
def setoid_of_disjoint_union {c : set (set α)} (hu : set.sUnion c = @set.univ α)
(H : set.pairwise_disjoint c) : setoid α :=
setoid.mk_classes c $ eqv_classes_of_disjoint_union hu H
/-- The equivalence relation made from the equivalence classes of an equivalence
relation r equals r. -/
theorem mk_classes_classes (r : setoid α) :
mk_classes r.classes classes_eqv_classes = r :=
ext' $ λ x y, ⟨λ h, r.symm' (h {z | r.rel z x} (r.mem_classes x) $ r.refl' x),
λ h b hb hx, eq_of_mem_classes (r.mem_classes x) (r.refl' x) hb hx ▸ r.symm' h⟩
section partition
/-- A collection `c : set (set α)` of sets is a partition of `α` into pairwise
disjoint sets if `∅ ∉ c` and each element `a : α` belongs to a unique set `b ∈ c`. -/
def is_partition (c : set (set α)) :=
∅ ∉ c ∧ ∀ a, ∃! b ∈ c, a ∈ b
/-- A partition of `α` does not contain the empty set. -/
lemma nonempty_of_mem_partition {c : set (set α)} (hc : is_partition c) {s} (h : s ∈ c) :
s.nonempty :=
set.ne_empty_iff_nonempty.1 $ λ hs0, hc.1 $ hs0 ▸ h
/-- All elements of a partition of α are the equivalence class of some y ∈ α. -/
lemma exists_of_mem_partition {c : set (set α)} (hc : is_partition c) {s} (hs : s ∈ c) :
∃ y, s = {x | (mk_classes c hc.2).rel x y} :=
let ⟨y, hy⟩ := nonempty_of_mem_partition hc hs in
⟨y, eq_eqv_class_of_mem hc.2 hs hy⟩
/-- The equivalence classes of the equivalence relation defined by a partition of α equal
the original partition. -/
theorem classes_mk_classes (c : set (set α)) (hc : is_partition c) :
(mk_classes c hc.2).classes = c :=
set.ext $ λ s,
⟨λ ⟨y, hs⟩, (hc.2 y).elim2 $ λ b hm hb hy,
by rwa (show s = b, from hs.symm ▸ set.ext
(λ x, ⟨λ hx, symm' (mk_classes c hc.2) hx b hm hb,
λ hx b' hc' hx', eq_of_mem_eqv_class hc.2 hm hx hc' hx' ▸ hb⟩)),
exists_of_mem_partition hc⟩
/-- Defining `≤` on partitions as the `≤` defined on their induced equivalence relations. -/
instance partition.le : has_le (subtype (@is_partition α)) :=
⟨λ x y, mk_classes x.1 x.2.2 ≤ mk_classes y.1 y.2.2⟩
/-- Defining a partial order on partitions as the partial order on their induced
equivalence relations. -/
instance partition.partial_order : partial_order (subtype (@is_partition α)) :=
{ le := (≤),
lt := λ x y, x ≤ y ∧ ¬y ≤ x,
le_refl := λ _, @le_refl (setoid α) _ _,
le_trans := λ _ _ _, @le_trans (setoid α) _ _ _ _,
lt_iff_le_not_le := λ _ _, iff.rfl,
le_antisymm := λ x y hx hy, let h := @le_antisymm (setoid α) _ _ _ hx hy in by
rw [subtype.ext, ←classes_mk_classes x.1 x.2, ←classes_mk_classes y.1 y.2, h] }
variables (α)
/-- The order-preserving bijection between equivalence relations and partitions of sets. -/
def partition.order_iso :
((≤) : setoid α → setoid α → Prop) ≃o (@setoid.partition.partial_order α).le :=
{ to_fun := λ r, ⟨r.classes, empty_not_mem_classes, classes_eqv_classes⟩,
inv_fun := λ x, mk_classes x.1 x.2.2,
left_inv := mk_classes_classes,
right_inv := λ x, by rw [subtype.ext, ←classes_mk_classes x.1 x.2],
ord' := λ x y, by conv {to_lhs, rw [←mk_classes_classes x, ←mk_classes_classes y]}; refl }
variables {α}
/-- A complete lattice instance for partitions; there is more infrastructure for the
equivalent complete lattice on equivalence relations. -/
instance partition.complete_lattice : complete_lattice (subtype (@is_partition α)) :=
galois_insertion.lift_complete_lattice $ @order_iso.to_galois_insertion
_ (subtype (@is_partition α)) _ (partial_order.to_preorder _) $ partition.order_iso α
end partition
end setoid
|
3a72ad38392ac1215a7bde010e5f2ca67562ee06 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Meta/Tactic/Acyclic.lean | 2d6c581507219258568940aa0220b3694d9e4040 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 1,941 | 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.Meta.MatchUtil
import Lean.Meta.Tactic.Simp.Main
namespace Lean.MVarId
open Meta
private def isTarget (lhs rhs : Expr) : MetaM Bool := do
if !lhs.isFVar || !lhs.occurs rhs then
return false
else
return (← whnf rhs).isConstructorApp (← getEnv)
/--
Close the given goal if `h` is a proof for an equality such as `as = a :: as`.
Inductive datatypes in Lean are acyclic.
-/
def acyclic (mvarId : MVarId) (h : Expr) : MetaM Bool := mvarId.withContext do
let type ← whnfD (← inferType h)
trace[Meta.Tactic.acyclic] "type: {type}"
let some (_, lhs, rhs) := type.eq? | return false
if (← isTarget lhs rhs) then
go h lhs rhs
else if (← isTarget rhs lhs) then
go (← mkEqSymm h) rhs lhs
else
return false
where
go (h lhs rhs : Expr) : MetaM Bool := do
try
let sizeOf_lhs ← mkAppM ``sizeOf #[lhs]
let sizeOf_rhs ← mkAppM ``sizeOf #[rhs]
let sizeOfEq ← mkLT sizeOf_lhs sizeOf_rhs
let hlt ← mkFreshExprSyntheticOpaqueMVar sizeOfEq
-- TODO: we only need the `sizeOf` simp theorems
match (← simpTarget hlt.mvarId! { config.arith := true, simpTheorems := #[ (← getSimpTheorems) ] }).1 with
| some _ => return false
| none =>
let heq ← mkCongrArg sizeOf_lhs.appFn! (← mkEqSymm h)
let hlt_self ← mkAppM ``Nat.lt_of_lt_of_eq #[hlt, heq]
let hlt_irrelf ← mkAppM ``Nat.lt_irrefl #[sizeOf_lhs]
mvarId.assign (← mkFalseElim (← mvarId.getType) (mkApp hlt_irrelf hlt_self))
trace[Meta.Tactic.acyclic] "succeeded"
return true
catch ex =>
trace[Meta.Tactic.acyclic] "failed with\n{ex.toMessageData}"
return false
builtin_initialize
registerTraceClass `Meta.Tactic.acyclic
end Lean.MVarId
|
af0837d913c3092ded20fc9154461e0eee601ada | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/linear_algebra/affine_space/finite_dimensional.lean | ddee8772f37b162315ebc6865f1afe559c3cab2e | [
"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 | 16,024 | lean | /-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers
-/
import linear_algebra.affine_space.independent
import linear_algebra.finite_dimensional
/-!
# Finite-dimensional subspaces of affine spaces.
This file provides a few results relating to finite-dimensional
subspaces of affine spaces.
## Main definitions
* `collinear` defines collinear sets of points as those that span a
subspace of dimension at most 1.
-/
noncomputable theory
open_locale big_operators classical affine
section affine_space'
variables (k : Type*) {V : Type*} {P : Type*} [field k] [add_comm_group V] [module k V]
[affine_space V P]
variables {ι : Type*}
include V
open affine_subspace finite_dimensional vector_space
/-- The `vector_span` of a finite set is finite-dimensional. -/
lemma finite_dimensional_vector_span_of_finite {s : set P} (h : set.finite s) :
finite_dimensional k (vector_span k s) :=
span_of_finite k $ h.vsub h
/-- The `vector_span` of a family indexed by a `fintype` is
finite-dimensional. -/
instance finite_dimensional_vector_span_of_fintype [fintype ι] (p : ι → P) :
finite_dimensional k (vector_span k (set.range p)) :=
finite_dimensional_vector_span_of_finite k (set.finite_range _)
/-- The `vector_span` of a subset of a family indexed by a `fintype`
is finite-dimensional. -/
instance finite_dimensional_vector_span_image_of_fintype [fintype ι] (p : ι → P)
(s : set ι) : finite_dimensional k (vector_span k (p '' s)) :=
finite_dimensional_vector_span_of_finite k ((set.finite.of_fintype _).image _)
/-- The direction of the affine span of a finite set is
finite-dimensional. -/
lemma finite_dimensional_direction_affine_span_of_finite {s : set P} (h : set.finite s) :
finite_dimensional k (affine_span k s).direction :=
(direction_affine_span k s).symm ▸ finite_dimensional_vector_span_of_finite k h
/-- The direction of the affine span of a family indexed by a
`fintype` is finite-dimensional. -/
instance finite_dimensional_direction_affine_span_of_fintype [fintype ι] (p : ι → P) :
finite_dimensional k (affine_span k (set.range p)).direction :=
finite_dimensional_direction_affine_span_of_finite k (set.finite_range _)
/-- The direction of the affine span of a subset of a family indexed
by a `fintype` is finite-dimensional. -/
instance finite_dimensional_direction_affine_span_image_of_fintype [fintype ι] (p : ι → P)
(s : set ι) : finite_dimensional k (affine_span k (p '' s)).direction :=
finite_dimensional_direction_affine_span_of_finite k ((set.finite.of_fintype _).image _)
variables {k}
/-- The `vector_span` of a finite subset of an affinely independent
family has dimension one less than its cardinality. -/
lemma findim_vector_span_image_finset_of_affine_independent {p : ι → P}
(hi : affine_independent k p) {s : finset ι} {n : ℕ} (hc : finset.card s = n + 1) :
findim k (vector_span k (p '' ↑s)) = n :=
begin
have hi' := affine_independent_of_subset_affine_independent
(affine_independent_set_of_affine_independent hi) (set.image_subset_range p ↑s),
have hc' : fintype.card (p '' ↑s) = n + 1,
{ rwa [set.card_image_of_injective ↑s (injective_of_affine_independent hi), fintype.card_coe] },
have hn : (p '' ↑s).nonempty,
{ simp [hc, ←finset.card_pos] },
rcases hn with ⟨p₁, hp₁⟩,
rw affine_independent_set_iff_linear_independent_vsub k hp₁ at hi',
have hfr : (p '' ↑s \ {p₁}).finite := ((set.finite_mem_finset _).image _).subset
(set.diff_subset _ _),
haveI := hfr.fintype,
have hf : set.finite ((λ (p : P), p -ᵥ p₁) '' (p '' ↑s \ {p₁})) := hfr.image _,
haveI := hf.fintype,
have hc : hf.to_finset.card = n,
{ rw [hf.card_to_finset,
set.card_image_of_injective (p '' ↑s \ {p₁}) (vsub_left_injective _)],
have hd : insert p₁ (p '' ↑s \ {p₁}) = p '' ↑s,
{ rw [set.insert_diff_singleton, set.insert_eq_of_mem hp₁] },
have hc'' : fintype.card ↥(insert p₁ (p '' ↑s \ {p₁})) = n + 1,
{ convert hc' },
rw set.card_insert (p '' ↑s \ {p₁}) (λ h, ((set.mem_diff p₁).2 h).2 rfl) at hc'',
simpa using hc'' },
rw [vector_span_eq_span_vsub_set_right_ne k hp₁, findim_span_set_eq_card _ hi', ←hc],
congr
end
/-- The `vector_span` of a finite affinely independent family has
dimension one less than its cardinality. -/
lemma findim_vector_span_of_affine_independent [fintype ι] {p : ι → P}
(hi : affine_independent k p) {n : ℕ} (hc : fintype.card ι = n + 1) :
findim k (vector_span k (set.range p)) = n :=
begin
rw ←finset.card_univ at hc,
rw [←set.image_univ, ←finset.coe_univ],
exact findim_vector_span_image_finset_of_affine_independent hi hc
end
/-- If the `vector_span` of a finite subset of an affinely independent
family lies in a submodule with dimension one less than its
cardinality, it equals that submodule. -/
lemma vector_span_image_finset_eq_of_le_of_affine_independent_of_card_eq_findim_add_one
{p : ι → P} (hi : affine_independent k p) {s : finset ι} {sm : submodule k V}
[finite_dimensional k sm] (hle : vector_span k (p '' ↑s) ≤ sm)
(hc : finset.card s = findim k sm + 1) : vector_span k (p '' ↑s) = sm :=
eq_of_le_of_findim_eq hle $ findim_vector_span_image_finset_of_affine_independent hi hc
/-- If the `vector_span` of a finite affinely independent
family lies in a submodule with dimension one less than its
cardinality, it equals that submodule. -/
lemma vector_span_eq_of_le_of_affine_independent_of_card_eq_findim_add_one [fintype ι]
{p : ι → P} (hi : affine_independent k p) {sm : submodule k V} [finite_dimensional k sm]
(hle : vector_span k (set.range p) ≤ sm) (hc : fintype.card ι = findim k sm + 1) :
vector_span k (set.range p) = sm :=
eq_of_le_of_findim_eq hle $ findim_vector_span_of_affine_independent hi hc
/-- If the `affine_span` of a finite subset of an affinely independent
family lies in an affine subspace whose direction has dimension one
less than its cardinality, it equals that subspace. -/
lemma affine_span_image_finset_eq_of_le_of_affine_independent_of_card_eq_findim_add_one
{p : ι → P} (hi : affine_independent k p) {s : finset ι} {sp : affine_subspace k P}
[finite_dimensional k sp.direction] (hle : affine_span k (p '' ↑s) ≤ sp)
(hc : finset.card s = findim k sp.direction + 1) : affine_span k (p '' ↑s) = sp :=
begin
have hn : (p '' ↑s).nonempty, { simp [hc, ←finset.card_pos] },
refine eq_of_direction_eq_of_nonempty_of_le _ ((affine_span_nonempty k _).2 hn) hle,
have hd := direction_le hle,
rw direction_affine_span at ⊢ hd,
exact vector_span_image_finset_eq_of_le_of_affine_independent_of_card_eq_findim_add_one hi hd hc
end
/-- If the `affine_span` of a finite affinely independent family lies
in an affine subspace whose direction has dimension one less than its
cardinality, it equals that subspace. -/
lemma affine_span_eq_of_le_of_affine_independent_of_card_eq_findim_add_one [fintype ι]
{p : ι → P} (hi : affine_independent k p) {sp : affine_subspace k P}
[finite_dimensional k sp.direction] (hle : affine_span k (set.range p) ≤ sp)
(hc : fintype.card ι = findim k sp.direction + 1) : affine_span k (set.range p) = sp :=
begin
rw ←finset.card_univ at hc,
rw [←set.image_univ, ←finset.coe_univ] at ⊢ hle,
exact affine_span_image_finset_eq_of_le_of_affine_independent_of_card_eq_findim_add_one hi hle hc
end
/-- The `vector_span` of a finite affinely independent family whose
cardinality is one more than that of the finite-dimensional space is
`⊤`. -/
lemma vector_span_eq_top_of_affine_independent_of_card_eq_findim_add_one [finite_dimensional k V]
[fintype ι] {p : ι → P} (hi : affine_independent k p) (hc : fintype.card ι = findim k V + 1) :
vector_span k (set.range p) = ⊤ :=
eq_top_of_findim_eq $ findim_vector_span_of_affine_independent hi hc
/-- The `affine_span` of a finite affinely independent family whose
cardinality is one more than that of the finite-dimensional space is
`⊤`. -/
lemma affine_span_eq_top_of_affine_independent_of_card_eq_findim_add_one [finite_dimensional k V]
[fintype ι] {p : ι → P} (hi : affine_independent k p) (hc : fintype.card ι = findim k V + 1) :
affine_span k (set.range p) = ⊤ :=
begin
rw [←findim_top, ←direction_top k V P] at hc,
exact affine_span_eq_of_le_of_affine_independent_of_card_eq_findim_add_one hi le_top hc
end
variables (k)
/-- The `vector_span` of `n + 1` points in an indexed family has
dimension at most `n`. -/
lemma findim_vector_span_image_finset_le (p : ι → P) (s : finset ι) {n : ℕ}
(hc : finset.card s = n + 1) : findim k (vector_span k (p '' ↑s)) ≤ n :=
begin
have hn : (p '' ↑s).nonempty,
{ simp [hc, ←finset.card_pos] },
rcases hn with ⟨p₁, hp₁⟩,
rw [vector_span_eq_span_vsub_set_right_ne k hp₁],
have hfp₁ : (p '' ↑s \ {p₁}).finite :=
((finset.finite_to_set _).image _).subset (set.diff_subset _ _),
haveI := hfp₁.fintype,
have hf : ((λ p, p -ᵥ p₁) '' (p '' ↑s \ {p₁})).finite := hfp₁.image _,
haveI := hf.fintype,
convert le_trans (findim_span_le_card ((λ p, p -ᵥ p₁) '' (p '' ↑s \ {p₁}))) _,
have hm : p₁ ∉ p '' ↑s \ {p₁}, by simp,
haveI := set.fintype_insert' (p '' ↑s \ {p₁}) hm,
rw [set.to_finset_card, set.card_image_of_injective (p '' ↑s \ {p₁}) (vsub_left_injective p₁),
←add_le_add_iff_right 1, ←set.card_fintype_insert' _ hm],
have h : fintype.card (↑(s.image p) : set P) ≤ n + 1,
{ rw [fintype.card_coe, ←hc],
exact finset.card_image_le },
convert h,
simp [hp₁]
end
/-- The `vector_span` of an indexed family of `n + 1` points has
dimension at most `n`. -/
lemma findim_vector_span_range_le [fintype ι] (p : ι → P) {n : ℕ}
(hc : fintype.card ι = n + 1) : findim k (vector_span k (set.range p)) ≤ n :=
begin
rw [←set.image_univ, ←finset.coe_univ],
rw ←finset.card_univ at hc,
exact findim_vector_span_image_finset_le _ _ _ hc
end
/-- `n + 1` points are affinely independent if and only if their
`vector_span` has dimension `n`. -/
lemma affine_independent_iff_findim_vector_span_eq [fintype ι] (p : ι → P) {n : ℕ}
(hc : fintype.card ι = n + 1) :
affine_independent k p ↔ findim k (vector_span k (set.range p)) = n :=
begin
have hn : nonempty ι, by simp [←fintype.card_pos_iff, hc],
cases hn with i₁,
rw [affine_independent_iff_linear_independent_vsub _ _ i₁,
linear_independent_iff_card_eq_findim_span, eq_comm,
vector_span_range_eq_span_range_vsub_right_ne k p i₁],
congr',
rw ←finset.card_univ at hc,
rw fintype.subtype_card,
simp [finset.filter_ne', finset.card_erase_of_mem, hc]
end
/-- `n + 1` points are affinely independent if and only if their
`vector_span` has dimension at least `n`. -/
lemma affine_independent_iff_le_findim_vector_span [fintype ι] (p : ι → P) {n : ℕ}
(hc : fintype.card ι = n + 1) :
affine_independent k p ↔ n ≤ findim k (vector_span k (set.range p)) :=
begin
rw affine_independent_iff_findim_vector_span_eq k p hc,
split,
{ rintro rfl,
refl },
{ exact λ hle, le_antisymm (findim_vector_span_range_le k p hc) hle }
end
/-- `n + 2` points are affinely independent if and only if their
`vector_span` does not have dimension at most `n`. -/
lemma affine_independent_iff_not_findim_vector_span_le [fintype ι] (p : ι → P) {n : ℕ}
(hc : fintype.card ι = n + 2) :
affine_independent k p ↔ ¬ findim k (vector_span k (set.range p)) ≤ n :=
by rw [affine_independent_iff_le_findim_vector_span k p hc, ←nat.lt_iff_add_one_le, lt_iff_not_ge]
/-- `n + 2` points have a `vector_span` with dimension at most `n` if
and only if they are not affinely independent. -/
lemma findim_vector_span_le_iff_not_affine_independent [fintype ι] (p : ι → P) {n : ℕ}
(hc : fintype.card ι = n + 2) :
findim k (vector_span k (set.range p)) ≤ n ↔ ¬ affine_independent k p :=
(not_iff_comm.1 (affine_independent_iff_not_findim_vector_span_le k p hc).symm).symm
/-- A set of points is collinear if their `vector_span` has dimension
at most `1`. -/
def collinear (s : set P) : Prop := dim k (vector_span k s) ≤ 1
/-- The definition of `collinear`. -/
lemma collinear_iff_dim_le_one (s : set P) : collinear k s ↔ dim k (vector_span k s) ≤ 1 :=
iff.rfl
/-- A set of points, whose `vector_span` is finite-dimensional, is
collinear if and only if their `vector_span` has dimension at most
`1`. -/
lemma collinear_iff_findim_le_one (s : set P) [finite_dimensional k (vector_span k s)] :
collinear k s ↔ findim k (vector_span k s) ≤ 1 :=
begin
have h := collinear_iff_dim_le_one k s,
rw ←findim_eq_dim at h,
exact_mod_cast h
end
variables (P)
/-- The empty set is collinear. -/
lemma collinear_empty : collinear k (∅ : set P) :=
begin
rw [collinear_iff_dim_le_one, vector_span_empty],
simp
end
variables {P}
/-- A single point is collinear. -/
lemma collinear_singleton (p : P) : collinear k ({p} : set P) :=
begin
rw [collinear_iff_dim_le_one, vector_span_singleton],
simp
end
/-- Given a point `p₀` in a set of points, that set is collinear if and
only if the points can all be expressed as multiples of the same
vector, added to `p₀`. -/
lemma collinear_iff_of_mem {s : set P} {p₀ : P} (h : p₀ ∈ s) :
collinear k s ↔ ∃ v : V, ∀ p ∈ s, ∃ r : k, p = r • v +ᵥ p₀ :=
begin
simp_rw [collinear_iff_dim_le_one, dim_submodule_le_one_iff', submodule.le_span_singleton_iff],
split,
{ rintro ⟨v₀, hv⟩,
use v₀,
intros p hp,
obtain ⟨r, hr⟩ := hv (p -ᵥ p₀) (vsub_mem_vector_span k hp h),
use r,
rw eq_vadd_iff_vsub_eq,
exact hr.symm },
{ rintro ⟨v, hp₀v⟩,
use v,
intros w hw,
have hs : vector_span k s ≤ k ∙ v,
{ rw [vector_span_eq_span_vsub_set_right k h, submodule.span_le, set.subset_def],
intros x hx,
rw [set_like.mem_coe, submodule.mem_span_singleton],
rw set.mem_image at hx,
rcases hx with ⟨p, hp, rfl⟩,
rcases hp₀v p hp with ⟨r, rfl⟩,
use r,
simp },
have hw' := set_like.le_def.1 hs hw,
rwa submodule.mem_span_singleton at hw' }
end
/-- A set of points is collinear if and only if they can all be
expressed as multiples of the same vector, added to the same base
point. -/
lemma collinear_iff_exists_forall_eq_smul_vadd (s : set P) :
collinear k s ↔ ∃ (p₀ : P) (v : V), ∀ p ∈ s, ∃ r : k, p = r • v +ᵥ p₀ :=
begin
rcases set.eq_empty_or_nonempty s with rfl | ⟨⟨p₁, hp₁⟩⟩,
{ simp [collinear_empty] },
{ rw collinear_iff_of_mem k hp₁,
split,
{ exact λ h, ⟨p₁, h⟩ },
{ rintros ⟨p, v, hv⟩,
use v,
intros p₂ hp₂,
rcases hv p₂ hp₂ with ⟨r, rfl⟩,
rcases hv p₁ hp₁ with ⟨r₁, rfl⟩,
use r - r₁,
simp [vadd_vadd, ←add_smul] } }
end
/-- Two points are collinear. -/
lemma collinear_insert_singleton (p₁ p₂ : P) : collinear k ({p₁, p₂} : set P) :=
begin
rw collinear_iff_exists_forall_eq_smul_vadd,
use [p₁, p₂ -ᵥ p₁],
intros p hp,
rw [set.mem_insert_iff, set.mem_singleton_iff] at hp,
cases hp,
{ use 0,
simp [hp] },
{ use 1,
simp [hp] }
end
/-- Three points are affinely independent if and only if they are not
collinear. -/
lemma affine_independent_iff_not_collinear (p : fin 3 → P) :
affine_independent k p ↔ ¬ collinear k (set.range p) :=
by rw [collinear_iff_findim_le_one,
affine_independent_iff_not_findim_vector_span_le k p (fintype.card_fin 3)]
/-- Three points are collinear if and only if they are not affinely
independent. -/
lemma collinear_iff_not_affine_independent (p : fin 3 → P) :
collinear k (set.range p) ↔ ¬ affine_independent k p :=
by rw [collinear_iff_findim_le_one,
findim_vector_span_le_iff_not_affine_independent k p (fintype.card_fin 3)]
end affine_space'
|
716b75efe2163c1499b097038df430f7fb37d0d6 | efa51dd2edbbbbd6c34bd0ce436415eb405832e7 | /20161026_ICTAC_Tutorial/ex12.lean | 6c6197ce380e35c2fec314db14ca4c2339b2567b | [
"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 | 468 | lean | /- Applications -/
constants A B C : Type
constant f : A → B
constant g : B → C
constant h : A → A
constants (a : A) (b : B)
check (λ x : A, x) a -- A
check (λ x : A, b) a -- B
check (λ x : A, b) (h a) -- B
check (λ x : A, g (f x)) (h (h a)) -- C
check (λ (v : B → C) (u : A → B) x, v (u x)) g f a -- C
check (λ (Q R S : Type) (v : R → S) (u : Q → R) (x : Q),
v (u x)) A B C g f a -- C
|
b717db77ee3dc899e64bc465ee05cc8fb335893d | 4727251e0cd73359b15b664c3170e5d754078599 | /src/algebraic_geometry/Spec.lean | 817af71b7c2a602a8becd4535a977c27b5c0cd21 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 10,825 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Justus Springer
-/
import algebraic_geometry.locally_ringed_space
import algebraic_geometry.structure_sheaf
import logic.equiv.transfer_instance
import ring_theory.localization.localization_localization
import topology.sheaves.sheaf_condition.sites
import topology.sheaves.functors
/-!
# $Spec$ as a functor to locally ringed spaces.
We define the functor $Spec$ from commutative rings to locally ringed spaces.
## Implementation notes
We define $Spec$ in three consecutive steps, each with more structure than the last:
1. `Spec.to_Top`, valued in the category of topological spaces,
2. `Spec.to_SheafedSpace`, valued in the category of sheafed spaces and
3. `Spec.to_LocallyRingedSpace`, valued in the category of locally ringed spaces.
Additionally, we provide `Spec.to_PresheafedSpace` as a composition of `Spec.to_SheafedSpace` with
a forgetful functor.
## Related results
The adjunction `Γ ⊣ Spec` is constructed in `algebraic_geometry/Gamma_Spec_adjunction.lean`.
-/
noncomputable theory
universes u v
namespace algebraic_geometry
open opposite
open category_theory
open structure_sheaf Spec (structure_sheaf)
/--
The spectrum of a commutative ring, as a topological space.
-/
def Spec.Top_obj (R : CommRing) : Top := Top.of (prime_spectrum R)
/--
The induced map of a ring homomorphism on the ring spectra, as a morphism of topological spaces.
-/
def Spec.Top_map {R S : CommRing} (f : R ⟶ S) :
Spec.Top_obj S ⟶ Spec.Top_obj R :=
prime_spectrum.comap f
@[simp] lemma Spec.Top_map_id (R : CommRing) :
Spec.Top_map (𝟙 R) = 𝟙 (Spec.Top_obj R) :=
prime_spectrum.comap_id
lemma Spec.Top_map_comp {R S T : CommRing} (f : R ⟶ S) (g : S ⟶ T) :
Spec.Top_map (f ≫ g) = Spec.Top_map g ≫ Spec.Top_map f :=
prime_spectrum.comap_comp _ _
/--
The spectrum, as a contravariant functor from commutative rings to topological spaces.
-/
@[simps] def Spec.to_Top : CommRingᵒᵖ ⥤ Top :=
{ obj := λ R, Spec.Top_obj (unop R),
map := λ R S f, Spec.Top_map f.unop,
map_id' := λ R, by rw [unop_id, Spec.Top_map_id],
map_comp' := λ R S T f g, by rw [unop_comp, Spec.Top_map_comp] }
/--
The spectrum of a commutative ring, as a `SheafedSpace`.
-/
@[simps] def Spec.SheafedSpace_obj (R : CommRing) : SheafedSpace CommRing :=
{ carrier := Spec.Top_obj R,
presheaf := (structure_sheaf R).1,
is_sheaf := (structure_sheaf R).2 }
/--
The induced map of a ring homomorphism on the ring spectra, as a morphism of sheafed spaces.
-/
@[simps] def Spec.SheafedSpace_map {R S : CommRing.{u}} (f : R ⟶ S) :
Spec.SheafedSpace_obj S ⟶ Spec.SheafedSpace_obj R :=
{ base := Spec.Top_map f,
c :=
{ app := λ U, comap f (unop U) ((topological_space.opens.map (Spec.Top_map f)).obj (unop U))
(λ p, id),
naturality' := λ U V i, ring_hom.ext $ λ s, subtype.eq $ funext $ λ p, rfl } }
@[simp] lemma Spec.SheafedSpace_map_id {R : CommRing} :
Spec.SheafedSpace_map (𝟙 R) = 𝟙 (Spec.SheafedSpace_obj R) :=
PresheafedSpace.ext _ _ (Spec.Top_map_id R) $ nat_trans.ext _ _ $ funext $ λ U,
begin
dsimp,
erw [PresheafedSpace.id_c_app, comap_id], swap,
{ rw [Spec.Top_map_id, topological_space.opens.map_id_obj_unop] },
simpa,
end
lemma Spec.SheafedSpace_map_comp {R S T : CommRing} (f : R ⟶ S) (g : S ⟶ T) :
Spec.SheafedSpace_map (f ≫ g) = Spec.SheafedSpace_map g ≫ Spec.SheafedSpace_map f :=
PresheafedSpace.ext _ _ (Spec.Top_map_comp f g) $ nat_trans.ext _ _ $ funext $ λ U,
by { dsimp, rw category_theory.functor.map_id, rw category.comp_id, erw comap_comp f g, refl }
/--
Spec, as a contravariant functor from commutative rings to sheafed spaces.
-/
@[simps] def Spec.to_SheafedSpace : CommRingᵒᵖ ⥤ SheafedSpace CommRing :=
{ obj := λ R, Spec.SheafedSpace_obj (unop R),
map := λ R S f, Spec.SheafedSpace_map f.unop,
map_id' := λ R, by rw [unop_id, Spec.SheafedSpace_map_id],
map_comp' := λ R S T f g, by rw [unop_comp, Spec.SheafedSpace_map_comp] }
/--
Spec, as a contravariant functor from commutative rings to presheafed spaces.
-/
def Spec.to_PresheafedSpace : CommRingᵒᵖ ⥤ PresheafedSpace CommRing :=
Spec.to_SheafedSpace ⋙ SheafedSpace.forget_to_PresheafedSpace
@[simp] lemma Spec.to_PresheafedSpace_obj (R : CommRingᵒᵖ) :
Spec.to_PresheafedSpace.obj R = (Spec.SheafedSpace_obj (unop R)).to_PresheafedSpace := rfl
lemma Spec.to_PresheafedSpace_obj_op (R : CommRing) :
Spec.to_PresheafedSpace.obj (op R) = (Spec.SheafedSpace_obj R).to_PresheafedSpace := rfl
@[simp] lemma Spec.to_PresheafedSpace_map (R S : CommRingᵒᵖ) (f : R ⟶ S) :
Spec.to_PresheafedSpace.map f = Spec.SheafedSpace_map f.unop := rfl
lemma Spec.to_PresheafedSpace_map_op (R S : CommRing) (f : R ⟶ S) :
Spec.to_PresheafedSpace.map f.op = Spec.SheafedSpace_map f := rfl
lemma Spec.basic_open_hom_ext {X : RingedSpace} {R : CommRing} {α β : X ⟶ Spec.SheafedSpace_obj R}
(w : α.base = β.base) (h : ∀ r : R, let U := prime_spectrum.basic_open r in
(to_open R U ≫ α.c.app (op U)) ≫ X.presheaf.map (eq_to_hom (by rw w)) =
to_open R U ≫ β.c.app (op U)) : α = β :=
begin
ext1,
{ apply ((Top.sheaf.pushforward β.base).obj X.sheaf).hom_ext _
prime_spectrum.is_basis_basic_opens,
intro r,
apply (structure_sheaf.to_basic_open_epi R r).1,
simpa using h r },
exact w,
end
/--
The spectrum of a commutative ring, as a `LocallyRingedSpace`.
-/
@[simps] def Spec.LocallyRingedSpace_obj (R : CommRing) : LocallyRingedSpace :=
{ local_ring := λ x, @@ring_equiv.local_ring _
(show local_ring (localization.at_prime _), by apply_instance) _
(iso.CommRing_iso_to_ring_equiv $ stalk_iso R x).symm,
.. Spec.SheafedSpace_obj R }
@[elementwise]
lemma stalk_map_to_stalk {R S : CommRing} (f : R ⟶ S) (p : prime_spectrum S) :
to_stalk R (prime_spectrum.comap f p) ≫
PresheafedSpace.stalk_map (Spec.SheafedSpace_map f) p =
f ≫ to_stalk S p :=
begin
erw [← to_open_germ S ⊤ ⟨p, trivial⟩, ← to_open_germ R ⊤ ⟨prime_spectrum.comap f p, trivial⟩,
category.assoc, PresheafedSpace.stalk_map_germ (Spec.SheafedSpace_map f) ⊤ ⟨p, trivial⟩,
Spec.SheafedSpace_map_c_app, to_open_comp_comap_assoc],
refl
end
/--
Under the isomorphisms `stalk_iso`, the map `stalk_map (Spec.SheafedSpace_map f) p` corresponds
to the induced local ring homomorphism `localization.local_ring_hom`.
-/
@[elementwise]
lemma local_ring_hom_comp_stalk_iso {R S : CommRing} (f : R ⟶ S) (p : prime_spectrum S) :
(stalk_iso R (prime_spectrum.comap f p)).hom ≫
@category_struct.comp _ _
(CommRing.of (localization.at_prime (prime_spectrum.comap f p).as_ideal))
(CommRing.of (localization.at_prime p.as_ideal)) _
(localization.local_ring_hom (prime_spectrum.comap f p).as_ideal p.as_ideal f rfl)
(stalk_iso S p).inv =
PresheafedSpace.stalk_map (Spec.SheafedSpace_map f) p :=
(stalk_iso R (prime_spectrum.comap f p)).eq_inv_comp.mp $ (stalk_iso S p).comp_inv_eq.mpr $
localization.local_ring_hom_unique _ _ _ _ $ λ x, by
rw [stalk_iso_hom, stalk_iso_inv, comp_apply, comp_apply, localization_to_stalk_of,
stalk_map_to_stalk_apply, stalk_to_fiber_ring_hom_to_stalk]
/--
The induced map of a ring homomorphism on the prime spectra, as a morphism of locally ringed spaces.
-/
@[simps] def Spec.LocallyRingedSpace_map {R S : CommRing} (f : R ⟶ S) :
Spec.LocallyRingedSpace_obj S ⟶ Spec.LocallyRingedSpace_obj R :=
subtype.mk (Spec.SheafedSpace_map f) $ λ p, is_local_ring_hom.mk $ λ a ha,
begin
-- Here, we are showing that the map on prime spectra induced by `f` is really a morphism of
-- *locally* ringed spaces, i.e. that the induced map on the stalks is a local ring homomorphism.
rw ← local_ring_hom_comp_stalk_iso_apply at ha,
replace ha := (stalk_iso S p).hom.is_unit_map ha,
rw coe_inv_hom_id at ha,
replace ha := is_local_ring_hom.map_nonunit _ ha,
convert ring_hom.is_unit_map (stalk_iso R (prime_spectrum.comap f p)).inv ha,
rw coe_hom_inv_id,
end
@[simp] lemma Spec.LocallyRingedSpace_map_id (R : CommRing) :
Spec.LocallyRingedSpace_map (𝟙 R) = 𝟙 (Spec.LocallyRingedSpace_obj R) :=
subtype.ext $ by { rw [Spec.LocallyRingedSpace_map_coe, Spec.SheafedSpace_map_id], refl }
lemma Spec.LocallyRingedSpace_map_comp {R S T : CommRing} (f : R ⟶ S) (g : S ⟶ T) :
Spec.LocallyRingedSpace_map (f ≫ g) =
Spec.LocallyRingedSpace_map g ≫ Spec.LocallyRingedSpace_map f :=
subtype.ext $ by { rw [Spec.LocallyRingedSpace_map_coe, Spec.SheafedSpace_map_comp], refl }
/--
Spec, as a contravariant functor from commutative rings to locally ringed spaces.
-/
@[simps] def Spec.to_LocallyRingedSpace : CommRingᵒᵖ ⥤ LocallyRingedSpace :=
{ obj := λ R, Spec.LocallyRingedSpace_obj (unop R),
map := λ R S f, Spec.LocallyRingedSpace_map f.unop,
map_id' := λ R, by rw [unop_id, Spec.LocallyRingedSpace_map_id],
map_comp' := λ R S T f g, by rw [unop_comp, Spec.LocallyRingedSpace_map_comp] }
section Spec_Γ
open algebraic_geometry.LocallyRingedSpace
/-- The counit morphism `R ⟶ Γ(Spec R)` given by `algebraic_geometry.structure_sheaf.to_open`. -/
@[simps] def to_Spec_Γ (R : CommRing) : R ⟶ Γ.obj (op (Spec.to_LocallyRingedSpace.obj (op R))) :=
structure_sheaf.to_open R ⊤
instance is_iso_to_Spec_Γ (R : CommRing) : is_iso (to_Spec_Γ R) :=
by { cases R, apply structure_sheaf.is_iso_to_global }
@[reassoc]
lemma Spec_Γ_naturality {R S : CommRing} (f : R ⟶ S) :
f ≫ to_Spec_Γ S = to_Spec_Γ R ≫ Γ.map (Spec.to_LocallyRingedSpace.map f.op).op :=
by { ext, symmetry, apply localization.local_ring_hom_to_map }
/-- The counit (`Spec_Γ_identity.inv.op`) of the adjunction `Γ ⊣ Spec` is an isomorphism. -/
@[simps hom_app inv_app] def Spec_Γ_identity : Spec.to_LocallyRingedSpace.right_op ⋙ Γ ≅ 𝟭 _ :=
iso.symm $ nat_iso.of_components (λ R, as_iso (to_Spec_Γ R) : _) (λ _ _, Spec_Γ_naturality)
end Spec_Γ
/-- The stalk map of `Spec M⁻¹R ⟶ Spec R` is an iso for each `p : Spec M⁻¹R`. -/
lemma Spec_map_localization_is_iso (R : CommRing) (M : submonoid R)
(x : prime_spectrum (localization M)) :
is_iso (PresheafedSpace.stalk_map (Spec.to_PresheafedSpace.map
(CommRing.of_hom (algebra_map R (localization M))).op) x) :=
begin
erw ← local_ring_hom_comp_stalk_iso,
apply_with is_iso.comp_is_iso { instances := ff },
apply_instance,
apply_with is_iso.comp_is_iso { instances := ff },
/- I do not know why this is defeq to the goal, but I'm happy to accept that it is. -/
exact (show is_iso (is_localization.localization_localization_at_prime_iso_localization
M x.as_ideal).to_ring_equiv.to_CommRing_iso.hom, by apply_instance),
apply_instance
end
end algebraic_geometry
|
b5ef0000664aa4752e9ebf79319c88b8f6e73eff | 2a70b774d16dbdf5a533432ee0ebab6838df0948 | /_target/deps/mathlib/src/algebra/group_power/lemmas.lean | 5530254fe31ccd23fd5880a8c564b69a371b60c8 | [
"Apache-2.0"
] | permissive | hjvromen/lewis | 40b035973df7c77ebf927afab7878c76d05ff758 | 105b675f73630f028ad5d890897a51b3c1146fb0 | refs/heads/master | 1,677,944,636,343 | 1,676,555,301,000 | 1,676,555,301,000 | 327,553,599 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 28,073 | lean | /-
Copyright (c) 2015 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Robert Y. Lewis
-/
import algebra.group_power.basic
import algebra.opposites
import data.list.basic
import data.int.cast
import data.equiv.basic
import data.equiv.mul_add
import deprecated.group
/-!
# Lemmas about power operations on monoids and groups
This file contains lemmas about `monoid.pow`, `group.pow`, `nsmul`, `gsmul`
which require additional imports besides those available in `.basic`.
-/
universes u v w x y z u₁ u₂
variables {M : Type u} {N : Type v} {G : Type w} {H : Type x} {A : Type y} {B : Type z}
{R : Type u₁} {S : Type u₂}
/-!
### (Additive) monoid
-/
section monoid
variables [monoid M] [monoid N] [add_monoid A] [add_monoid B]
@[simp] theorem nsmul_one [has_one A] : ∀ n : ℕ, n •ℕ (1 : A) = n :=
add_monoid_hom.eq_nat_cast
⟨λ n, n •ℕ (1 : A), zero_nsmul _, λ _ _, add_nsmul _ _ _⟩
(one_nsmul _)
@[simp, priority 500]
theorem list.prod_repeat (a : M) (n : ℕ) : (list.repeat a n).prod = a ^ n :=
begin
induction n with n ih,
{ refl },
{ rw [list.repeat_succ, list.prod_cons, ih], refl, }
end
@[simp, priority 500]
theorem list.sum_repeat : ∀ (a : A) (n : ℕ), (list.repeat a n).sum = n •ℕ a :=
@list.prod_repeat (multiplicative A) _
@[simp, norm_cast] lemma units.coe_pow (u : units M) (n : ℕ) : ((u ^ n : units M) : M) = u ^ n :=
(units.coe_hom M).map_pow u n
lemma is_unit_of_pow_eq_one (x : M) (n : ℕ) (hx : x ^ n = 1) (hn : 0 < n) :
is_unit x :=
begin
cases n, { exact (nat.not_lt_zero _ hn).elim },
refine ⟨⟨x, x ^ n, _, _⟩, rfl⟩,
{ rwa [pow_succ] at hx },
{ rwa [pow_succ'] at hx }
end
end monoid
theorem nat.nsmul_eq_mul (m n : ℕ) : m •ℕ n = m * n :=
by induction m with m ih; [rw [zero_nsmul, zero_mul],
rw [succ_nsmul', ih, nat.succ_mul]]
section group
variables [group G] [group H] [add_group A] [add_group B]
open int
local attribute [ematch] le_of_lt
open nat
theorem gsmul_one [has_one A] (n : ℤ) : n •ℤ (1 : A) = n :=
by cases n; simp
lemma gpow_add_one (a : G) : ∀ n : ℤ, a ^ (n + 1) = a ^ n * a
| (of_nat n) := by simp [← int.coe_nat_succ, pow_succ']
| -[1+0] := by simp [int.neg_succ_of_nat_eq]
| -[1+(n+1)] := by rw [int.neg_succ_of_nat_eq, gpow_neg, neg_add, neg_add_cancel_right, gpow_neg,
← int.coe_nat_succ, gpow_coe_nat, gpow_coe_nat, pow_succ _ (n + 1), mul_inv_rev,
inv_mul_cancel_right]
theorem add_one_gsmul : ∀ (a : A) (i : ℤ), (i + 1) •ℤ a = i •ℤ a + a :=
@gpow_add_one (multiplicative A) _
lemma gpow_sub_one (a : G) (n : ℤ) : a ^ (n - 1) = a ^ n * a⁻¹ :=
calc a ^ (n - 1) = a ^ (n - 1) * a * a⁻¹ : (mul_inv_cancel_right _ _).symm
... = a^n * a⁻¹ : by rw [← gpow_add_one, sub_add_cancel]
lemma gpow_add (a : G) (m n : ℤ) : a ^ (m + n) = a ^ m * a ^ n :=
begin
induction n using int.induction_on with n ihn n ihn,
case hz : { simp },
{ simp only [← add_assoc, gpow_add_one, ihn, mul_assoc] },
{ rw [gpow_sub_one, ← mul_assoc, ← ihn, ← gpow_sub_one, add_sub_assoc] }
end
lemma mul_self_gpow (b : G) (m : ℤ) : b*b^m = b^(m+1) :=
by { conv_lhs {congr, rw ← gpow_one b }, rw [← gpow_add, add_comm] }
lemma mul_gpow_self (b : G) (m : ℤ) : b^m*b = b^(m+1) :=
by { conv_lhs {congr, skip, rw ← gpow_one b }, rw [← gpow_add, add_comm] }
theorem add_gsmul : ∀ (a : A) (i j : ℤ), (i + j) •ℤ a = i •ℤ a + j •ℤ a :=
@gpow_add (multiplicative A) _
lemma gpow_sub (a : G) (m n : ℤ) : a ^ (m - n) = a ^ m * (a ^ n)⁻¹ :=
by rw [sub_eq_add_neg, gpow_add, gpow_neg]
lemma sub_gsmul (m n : ℤ) (a : A) : (m - n) •ℤ a = m •ℤ a - n •ℤ a :=
by simpa only [sub_eq_add_neg] using @gpow_sub (multiplicative A) _ _ _ _
theorem gpow_one_add (a : G) (i : ℤ) : a ^ (1 + i) = a * a ^ i :=
by rw [gpow_add, gpow_one]
theorem one_add_gsmul : ∀ (a : A) (i : ℤ), (1 + i) •ℤ a = a + i •ℤ a :=
@gpow_one_add (multiplicative A) _
theorem gpow_mul_comm (a : G) (i j : ℤ) : a ^ i * a ^ j = a ^ j * a ^ i :=
by rw [← gpow_add, ← gpow_add, add_comm]
theorem gsmul_add_comm : ∀ (a : A) (i j), i •ℤ a + j •ℤ a = j •ℤ a + i •ℤ a :=
@gpow_mul_comm (multiplicative A) _
theorem gpow_mul (a : G) (m n : ℤ) : a ^ (m * n) = (a ^ m) ^ n :=
int.induction_on n (by simp) (λ n ihn, by simp [mul_add, gpow_add, ihn])
(λ n ihn, by simp only [mul_sub, gpow_sub, ihn, mul_one, gpow_one])
theorem gsmul_mul' : ∀ (a : A) (m n : ℤ), m * n •ℤ a = n •ℤ (m •ℤ a) :=
@gpow_mul (multiplicative A) _
theorem gpow_mul' (a : G) (m n : ℤ) : a ^ (m * n) = (a ^ n) ^ m :=
by rw [mul_comm, gpow_mul]
theorem gsmul_mul (a : A) (m n : ℤ) : m * n •ℤ a = m •ℤ (n •ℤ a) :=
by rw [mul_comm, gsmul_mul']
theorem gpow_bit0 (a : G) (n : ℤ) : a ^ bit0 n = a ^ n * a ^ n := gpow_add _ _ _
theorem bit0_gsmul (a : A) (n : ℤ) : bit0 n •ℤ a = n •ℤ a + n •ℤ a := gpow_add _ _ _
theorem gpow_bit1 (a : G) (n : ℤ) : a ^ bit1 n = a ^ n * a ^ n * a :=
by rw [bit1, gpow_add, gpow_bit0, gpow_one]
theorem bit1_gsmul : ∀ (a : A) (n : ℤ), bit1 n •ℤ a = n •ℤ a + n •ℤ a + a :=
@gpow_bit1 (multiplicative A) _
@[simp] theorem monoid_hom.map_gpow (f : G →* H) (a : G) (n : ℤ) : f (a ^ n) = f a ^ n :=
by cases n; [exact f.map_pow _ _, exact (f.map_inv _).trans (congr_arg _ $ f.map_pow _ _)]
@[simp] theorem add_monoid_hom.map_gsmul (f : A →+ B) (a : A) (n : ℤ) : f (n •ℤ a) = n •ℤ f a :=
f.to_multiplicative.map_gpow a n
@[simp, norm_cast] lemma units.coe_gpow (u : units G) (n : ℤ) : ((u ^ n : units G) : G) = u ^ n :=
(units.coe_hom G).map_gpow u n
end group
section ordered_add_comm_group
variables [ordered_add_comm_group A]
/-! Lemmas about `gsmul` under ordering, placed here (rather than in `algebra.group_power.basic`
with their friends) because they require facts from `data.int.basic`-/
open int
lemma gsmul_pos {a : A} (ha : 0 < a) {k : ℤ} (hk : (0:ℤ) < k) : 0 < k •ℤ a :=
begin
lift k to ℕ using int.le_of_lt hk,
apply nsmul_pos ha,
exact coe_nat_pos.mp hk,
end
theorem gsmul_le_gsmul {a : A} {n m : ℤ} (ha : 0 ≤ a) (h : n ≤ m) : n •ℤ a ≤ m •ℤ a :=
calc n •ℤ a = n •ℤ a + 0 : (add_zero _).symm
... ≤ n •ℤ a + (m - n) •ℤ a : add_le_add_left (gsmul_nonneg ha (sub_nonneg.mpr h)) _
... = m •ℤ a : by { rw [← add_gsmul], simp }
theorem gsmul_lt_gsmul {a : A} {n m : ℤ} (ha : 0 < a) (h : n < m) : n •ℤ a < m •ℤ a :=
calc n •ℤ a = n •ℤ a + 0 : (add_zero _).symm
... < n •ℤ a + (m - n) •ℤ a : add_lt_add_left (gsmul_pos ha (sub_pos.mpr h)) _
... = m •ℤ a : by { rw [← add_gsmul], simp }
end ordered_add_comm_group
section linear_ordered_add_comm_group
variable [linear_ordered_add_comm_group A]
theorem gsmul_le_gsmul_iff {a : A} {n m : ℤ} (ha : 0 < a) : n •ℤ a ≤ m •ℤ a ↔ n ≤ m :=
begin
refine ⟨λ h, _, gsmul_le_gsmul $ le_of_lt ha⟩,
by_contra H,
exact lt_irrefl _ (lt_of_lt_of_le (gsmul_lt_gsmul ha (not_le.mp H)) h)
end
theorem gsmul_lt_gsmul_iff {a : A} {n m : ℤ} (ha : 0 < a) : n •ℤ a < m •ℤ a ↔ n < m :=
begin
refine ⟨λ h, _, gsmul_lt_gsmul ha⟩,
by_contra H,
exact lt_irrefl _ (lt_of_le_of_lt (gsmul_le_gsmul (le_of_lt ha) $ not_lt.mp H) h)
end
theorem nsmul_le_nsmul_iff {a : A} {n m : ℕ} (ha : 0 < a) : n •ℕ a ≤ m •ℕ a ↔ n ≤ m :=
begin
refine ⟨λ h, _, nsmul_le_nsmul $ le_of_lt ha⟩,
by_contra H,
exact lt_irrefl _ (lt_of_lt_of_le (nsmul_lt_nsmul ha (not_le.mp H)) h)
end
theorem nsmul_lt_nsmul_iff {a : A} {n m : ℕ} (ha : 0 < a) : n •ℕ a < m •ℕ a ↔ n < m :=
begin
refine ⟨λ h, _, nsmul_lt_nsmul ha⟩,
by_contra H,
exact lt_irrefl _ (lt_of_le_of_lt (nsmul_le_nsmul (le_of_lt ha) $ not_lt.mp H) h)
end
end linear_ordered_add_comm_group
@[simp] lemma with_bot.coe_nsmul [add_monoid A] (a : A) (n : ℕ) :
((nsmul n a : A) : with_bot A) = nsmul n a :=
add_monoid_hom.map_nsmul ⟨(coe : A → with_bot A), with_bot.coe_zero, with_bot.coe_add⟩ a n
theorem nsmul_eq_mul' [semiring R] (a : R) (n : ℕ) : n •ℕ a = a * n :=
by induction n with n ih; [rw [zero_nsmul, nat.cast_zero, mul_zero],
rw [succ_nsmul', ih, nat.cast_succ, mul_add, mul_one]]
@[simp] theorem nsmul_eq_mul [semiring R] (n : ℕ) (a : R) : n •ℕ a = n * a :=
by rw [nsmul_eq_mul', (n.cast_commute a).eq]
theorem mul_nsmul_left [semiring R] (a b : R) (n : ℕ) : n •ℕ (a * b) = a * (n •ℕ b) :=
by rw [nsmul_eq_mul', nsmul_eq_mul', mul_assoc]
theorem mul_nsmul_assoc [semiring R] (a b : R) (n : ℕ) : n •ℕ (a * b) = n •ℕ a * b :=
by rw [nsmul_eq_mul, nsmul_eq_mul, mul_assoc]
@[simp, norm_cast] theorem nat.cast_pow [semiring R] (n m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m :=
by induction m with m ih; [exact nat.cast_one, rw [pow_succ', pow_succ', nat.cast_mul, ih]]
@[simp, norm_cast] theorem int.coe_nat_pow (n m : ℕ) : ((n ^ m : ℕ) : ℤ) = n ^ m :=
by induction m with m ih; [exact int.coe_nat_one, rw [pow_succ', pow_succ', int.coe_nat_mul, ih]]
theorem int.nat_abs_pow (n : ℤ) (k : ℕ) : int.nat_abs (n ^ k) = (int.nat_abs n) ^ k :=
by induction k with k ih; [refl, rw [pow_succ', int.nat_abs_mul, pow_succ', ih]]
-- The next four lemmas allow us to replace multiplication by a numeral with a `gsmul` expression.
-- They are used by the `noncomm_ring` tactic, to normalise expressions before passing to `abel`.
lemma bit0_mul [ring R] {n r : R} : bit0 n * r = gsmul 2 (n * r) :=
by { dsimp [bit0], rw [add_mul, add_gsmul, one_gsmul], }
lemma mul_bit0 [ring R] {n r : R} : r * bit0 n = gsmul 2 (r * n) :=
by { dsimp [bit0], rw [mul_add, add_gsmul, one_gsmul], }
lemma bit1_mul [ring R] {n r : R} : bit1 n * r = gsmul 2 (n * r) + r :=
by { dsimp [bit1], rw [add_mul, bit0_mul, one_mul], }
lemma mul_bit1 [ring R] {n r : R} : r * bit1 n = gsmul 2 (r * n) + r :=
by { dsimp [bit1], rw [mul_add, mul_bit0, mul_one], }
@[simp] theorem gsmul_eq_mul [ring R] (a : R) : ∀ n, n •ℤ a = n * a
| (n : ℕ) := nsmul_eq_mul _ _
| -[1+ n] := show -(_ •ℕ _)=-_*_, by rw [neg_mul_eq_neg_mul_symm, nsmul_eq_mul, nat.cast_succ]
theorem gsmul_eq_mul' [ring R] (a : R) (n : ℤ) : n •ℤ a = a * n :=
by rw [gsmul_eq_mul, (n.cast_commute a).eq]
theorem mul_gsmul_left [ring R] (a b : R) (n : ℤ) : n •ℤ (a * b) = a * (n •ℤ b) :=
by rw [gsmul_eq_mul', gsmul_eq_mul', mul_assoc]
theorem mul_gsmul_assoc [ring R] (a b : R) (n : ℤ) : n •ℤ (a * b) = n •ℤ a * b :=
by rw [gsmul_eq_mul, gsmul_eq_mul, mul_assoc]
@[simp]
lemma gsmul_int_int (a b : ℤ) : a •ℤ b = a * b := by simp [gsmul_eq_mul]
lemma gsmul_int_one (n : ℤ) : n •ℤ 1 = n := by simp
@[simp, norm_cast] theorem int.cast_pow [ring R] (n : ℤ) (m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m :=
by induction m with m ih; [exact int.cast_one,
rw [pow_succ, pow_succ, int.cast_mul, ih]]
lemma neg_one_pow_eq_pow_mod_two [ring R] {n : ℕ} : (-1 : R) ^ n = (-1) ^ (n % 2) :=
by rw [← nat.mod_add_div n 2, pow_add, pow_mul]; simp [pow_two]
section ordered_semiring
variable [ordered_semiring R]
/-- Bernoulli's inequality. This version works for semirings but requires
an additional hypothesis `0 ≤ a * a`. -/
theorem one_add_mul_le_pow' {a : R} (Hsqr : 0 ≤ a * a) (H : 0 ≤ 1 + a) :
∀ (n : ℕ), 1 + n •ℕ a ≤ (1 + a) ^ n
| 0 := le_of_eq $ add_zero _
| (n+1) :=
calc 1 + (n + 1) •ℕ a ≤ (1 + a) * (1 + n •ℕ a) :
by simpa [succ_nsmul, mul_add, add_mul, mul_nsmul_left, add_comm, add_left_comm]
using nsmul_nonneg Hsqr n
... ≤ (1 + a)^(n+1) : mul_le_mul_of_nonneg_left (one_add_mul_le_pow' n) H
private lemma pow_lt_pow_of_lt_one_aux {a : R} (h : 0 < a) (ha : a < 1) (i : ℕ) :
∀ k : ℕ, a ^ (i + k + 1) < a ^ i
| 0 :=
begin
simp only [add_zero],
rw ←one_mul (a^i), exact mul_lt_mul ha (le_refl _) (pow_pos h _) zero_le_one
end
| (k+1) :=
begin
rw ←one_mul (a^i),
apply mul_lt_mul ha _ _ zero_le_one,
{ apply le_of_lt, apply pow_lt_pow_of_lt_one_aux },
{ show 0 < a ^ (i + (k + 1) + 0), apply pow_pos h }
end
private lemma pow_le_pow_of_le_one_aux {a : R} (h : 0 ≤ a) (ha : a ≤ 1) (i : ℕ) :
∀ k : ℕ, a ^ (i + k) ≤ a ^ i
| 0 := by simp
| (k+1) := by rw [←add_assoc, ←one_mul (a^i)];
exact mul_le_mul ha (pow_le_pow_of_le_one_aux _) (pow_nonneg h _) zero_le_one
lemma pow_lt_pow_of_lt_one {a : R} (h : 0 < a) (ha : a < 1)
{i j : ℕ} (hij : i < j) : a ^ j < a ^ i :=
let ⟨k, hk⟩ := nat.exists_eq_add_of_lt hij in
by rw hk; exact pow_lt_pow_of_lt_one_aux h ha _ _
lemma pow_lt_pow_iff_of_lt_one {a : R} {n m : ℕ} (hpos : 0 < a) (h : a < 1) :
a ^ m < a ^ n ↔ n < m :=
begin
have : strict_mono (λ (n : order_dual ℕ), a ^ (id n : ℕ)) := λ m n, pow_lt_pow_of_lt_one hpos h,
exact this.lt_iff_lt
end
lemma pow_le_pow_of_le_one {a : R} (h : 0 ≤ a) (ha : a ≤ 1)
{i j : ℕ} (hij : i ≤ j) : a ^ j ≤ a ^ i :=
let ⟨k, hk⟩ := nat.exists_eq_add_of_le hij in
by rw hk; exact pow_le_pow_of_le_one_aux h ha _ _
lemma pow_le_one {x : R} : ∀ (n : ℕ) (h0 : 0 ≤ x) (h1 : x ≤ 1), x ^ n ≤ 1
| 0 h0 h1 := le_refl (1 : R)
| (n+1) h0 h1 := mul_le_one h1 (pow_nonneg h0 _) (pow_le_one n h0 h1)
end ordered_semiring
section linear_ordered_semiring
variables [linear_ordered_semiring R]
lemma sign_cases_of_C_mul_pow_nonneg {C r : R} (h : ∀ n : ℕ, 0 ≤ C * r ^ n) :
C = 0 ∨ (0 < C ∧ 0 ≤ r) :=
begin
have : 0 ≤ C, by simpa only [pow_zero, mul_one] using h 0,
refine this.eq_or_lt.elim (λ h, or.inl h.symm) (λ hC, or.inr ⟨hC, _⟩),
refine nonneg_of_mul_nonneg_left _ hC,
simpa only [pow_one] using h 1
end
end linear_ordered_semiring
section linear_ordered_ring
variables [linear_ordered_ring R]
@[simp] lemma abs_pow (a : R) (n : ℕ) : abs (a ^ n) = abs a ^ n :=
abs_hom.to_monoid_hom.map_pow a n
@[simp] theorem pow_bit1_neg_iff {a : R} {n : ℕ} : a ^ bit1 n < 0 ↔ a < 0 :=
⟨λ h, not_le.1 $ λ h', not_le.2 h $ pow_nonneg h' _,
λ h, mul_neg_of_neg_of_pos h (pow_bit0_pos h.ne _)⟩
@[simp] theorem pow_bit1_nonneg_iff {a : R} {n : ℕ} : 0 ≤ a ^ bit1 n ↔ 0 ≤ a :=
le_iff_le_iff_lt_iff_lt.2 pow_bit1_neg_iff
@[simp] theorem pow_bit1_nonpos_iff {a : R} {n : ℕ} : a ^ bit1 n ≤ 0 ↔ a ≤ 0 :=
by simp only [le_iff_lt_or_eq, pow_bit1_neg_iff, pow_eq_zero_iff (bit1_pos (zero_le n))]
@[simp] theorem pow_bit1_pos_iff {a : R} {n : ℕ} : 0 < a ^ bit1 n ↔ 0 < a :=
lt_iff_lt_of_le_iff_le pow_bit1_nonpos_iff
lemma strict_mono_pow_bit1 (n : ℕ) : strict_mono (λ a : R, a ^ bit1 n) :=
begin
intros a b hab,
cases le_total a 0 with ha ha,
{ cases le_or_lt b 0 with hb hb,
{ rw [← neg_lt_neg_iff, ← neg_pow_bit1, ← neg_pow_bit1],
exact pow_lt_pow_of_lt_left (neg_lt_neg hab) (neg_nonneg.2 hb) (bit1_pos (zero_le n)) },
{ exact (pow_bit1_nonpos_iff.2 ha).trans_lt (pow_bit1_pos_iff.2 hb) } },
{ exact pow_lt_pow_of_lt_left hab ha (bit1_pos (zero_le n)) }
end
/-- Bernoulli's inequality for `n : ℕ`, `-2 ≤ a`. -/
theorem one_add_mul_le_pow {a : R} (H : -2 ≤ a) : ∀ (n : ℕ), 1 + n •ℕ a ≤ (1 + a) ^ n
| 0 := le_of_eq $ add_zero _
| 1 := by simp
| (n+2) :=
have H' : 0 ≤ 2 + a,
from neg_le_iff_add_nonneg'.1 H,
have 0 ≤ n •ℕ (a * a * (2 + a)) + a * a,
from add_nonneg (nsmul_nonneg (mul_nonneg (mul_self_nonneg a) H') n)
(mul_self_nonneg a),
calc 1 + (n + 2) •ℕ a ≤ 1 + (n + 2) •ℕ a + (n •ℕ (a * a * (2 + a)) + a * a) :
(le_add_iff_nonneg_right _).2 this
... = (1 + a) * (1 + a) * (1 + n •ℕ a) :
by { simp only [add_mul, mul_add, mul_two, mul_one, one_mul, succ_nsmul, nsmul_add,
mul_nsmul_assoc, (mul_nsmul_left _ _ _).symm],
ac_refl }
... ≤ (1 + a) * (1 + a) * (1 + a)^n :
mul_le_mul_of_nonneg_left (one_add_mul_le_pow n) (mul_self_nonneg (1 + a))
... = (1 + a)^(n + 2) : by simp only [pow_succ, mul_assoc]
/-- Bernoulli's inequality reformulated to estimate `a^n`. -/
theorem one_add_sub_mul_le_pow {a : R} (H : -1 ≤ a) (n : ℕ) : 1 + n •ℕ (a - 1) ≤ a ^ n :=
have -2 ≤ a - 1, by rwa [bit0, neg_add, ← sub_eq_add_neg, sub_le_sub_iff_right],
by simpa only [add_sub_cancel'_right] using one_add_mul_le_pow this n
end linear_ordered_ring
namespace int
lemma units_pow_two (u : units ℤ) : u ^ 2 = 1 :=
(pow_two u).symm ▸ units_mul_self u
lemma units_pow_eq_pow_mod_two (u : units ℤ) (n : ℕ) : u ^ n = u ^ (n % 2) :=
by conv {to_lhs, rw ← nat.mod_add_div n 2}; rw [pow_add, pow_mul, units_pow_two, one_pow, mul_one]
@[simp] lemma nat_abs_pow_two (x : ℤ) : (x.nat_abs ^ 2 : ℤ) = x ^ 2 :=
by rw [pow_two, int.nat_abs_mul_self', pow_two]
lemma abs_le_self_pow_two (a : ℤ) : (int.nat_abs a : ℤ) ≤ a ^ 2 :=
by { rw [← int.nat_abs_pow_two a, pow_two], norm_cast, apply nat.le_mul_self }
lemma le_self_pow_two (b : ℤ) : b ≤ b ^ 2 := le_trans (le_nat_abs) (abs_le_self_pow_two _)
end int
variables (M G A)
/-- Monoid homomorphisms from `multiplicative ℕ` are defined by the image
of `multiplicative.of_add 1`. -/
def powers_hom [monoid M] : M ≃ (multiplicative ℕ →* M) :=
{ to_fun := λ x, ⟨λ n, x ^ n.to_add, pow_zero x, λ m n, pow_add x m n⟩,
inv_fun := λ f, f (multiplicative.of_add 1),
left_inv := pow_one,
right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_pow, ← of_add_nsmul] } }
/-- Monoid homomorphisms from `multiplicative ℤ` are defined by the image
of `multiplicative.of_add 1`. -/
def gpowers_hom [group G] : G ≃ (multiplicative ℤ →* G) :=
{ to_fun := λ x, ⟨λ n, x ^ n.to_add, gpow_zero x, λ m n, gpow_add x m n⟩,
inv_fun := λ f, f (multiplicative.of_add 1),
left_inv := gpow_one,
right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_gpow, ← of_add_gsmul ] } }
/-- Additive homomorphisms from `ℕ` are defined by the image of `1`. -/
def multiples_hom [add_monoid A] : A ≃ (ℕ →+ A) :=
{ to_fun := λ x, ⟨λ n, n •ℕ x, zero_nsmul x, λ m n, add_nsmul _ _ _⟩,
inv_fun := λ f, f 1,
left_inv := one_nsmul,
right_inv := λ f, add_monoid_hom.ext_nat $ one_nsmul (f 1) }
/-- Additive homomorphisms from `ℤ` are defined by the image of `1`. -/
def gmultiples_hom [add_group A] : A ≃ (ℤ →+ A) :=
{ to_fun := λ x, ⟨λ n, n •ℤ x, zero_gsmul x, λ m n, add_gsmul _ _ _⟩,
inv_fun := λ f, f 1,
left_inv := one_gsmul,
right_inv := λ f, add_monoid_hom.ext_int $ one_gsmul (f 1) }
variables {M G A}
@[simp] lemma powers_hom_apply [monoid M] (x : M) (n : multiplicative ℕ) :
powers_hom M x n = x ^ n.to_add := rfl
@[simp] lemma powers_hom_symm_apply [monoid M] (f : multiplicative ℕ →* M) :
(powers_hom M).symm f = f (multiplicative.of_add 1) := rfl
@[simp] lemma gpowers_hom_apply [group G] (x : G) (n : multiplicative ℤ) :
gpowers_hom G x n = x ^ n.to_add := rfl
@[simp] lemma gpowers_hom_symm_apply [group G] (f : multiplicative ℤ →* G) :
(gpowers_hom G).symm f = f (multiplicative.of_add 1) := rfl
@[simp] lemma multiples_hom_apply [add_monoid A] (x : A) (n : ℕ) :
multiples_hom A x n = n •ℕ x := rfl
@[simp] lemma multiples_hom_symm_apply [add_monoid A] (f : ℕ →+ A) :
(multiples_hom A).symm f = f 1 := rfl
@[simp] lemma gmultiples_hom_apply [add_group A] (x : A) (n : ℤ) :
gmultiples_hom A x n = n •ℤ x := rfl
@[simp] lemma gmultiples_hom_symm_apply [add_group A] (f : ℤ →+ A) :
(gmultiples_hom A).symm f = f 1 := rfl
lemma monoid_hom.apply_mnat [monoid M] (f : multiplicative ℕ →* M) (n : multiplicative ℕ) :
f n = (f (multiplicative.of_add 1)) ^ n.to_add :=
by rw [← powers_hom_symm_apply, ← powers_hom_apply, equiv.apply_symm_apply]
@[ext] lemma monoid_hom.ext_mnat [monoid M] ⦃f g : multiplicative ℕ →* M⦄
(h : f (multiplicative.of_add 1) = g (multiplicative.of_add 1)) : f = g :=
monoid_hom.ext $ λ n, by rw [f.apply_mnat, g.apply_mnat, h]
lemma monoid_hom.apply_mint [group M] (f : multiplicative ℤ →* M) (n : multiplicative ℤ) :
f n = (f (multiplicative.of_add 1)) ^ n.to_add :=
by rw [← gpowers_hom_symm_apply, ← gpowers_hom_apply, equiv.apply_symm_apply]
@[ext] lemma monoid_hom.ext_mint [group M] ⦃f g : multiplicative ℤ →* M⦄
(h : f (multiplicative.of_add 1) = g (multiplicative.of_add 1)) : f = g :=
monoid_hom.ext $ λ n, by rw [f.apply_mint, g.apply_mint, h]
lemma add_monoid_hom.apply_nat [add_monoid M] (f : ℕ →+ M) (n : ℕ) :
f n = n •ℕ (f 1) :=
by rw [← multiples_hom_symm_apply, ← multiples_hom_apply, equiv.apply_symm_apply]
/-! `add_monoid_hom.ext_nat` is defined in `data.nat.cast` -/
lemma add_monoid_hom.apply_int [add_group M] (f : ℤ →+ M) (n : ℤ) :
f n = n •ℤ (f 1) :=
by rw [← gmultiples_hom_symm_apply, ← gmultiples_hom_apply, equiv.apply_symm_apply]
/-! `add_monoid_hom.ext_int` is defined in `data.int.cast` -/
variables (M G A)
/-- If `M` is commutative, `powers_hom` is a multiplicative equivalence. -/
def powers_mul_hom [comm_monoid M] : M ≃* (multiplicative ℕ →* M) :=
{ map_mul' := λ a b, monoid_hom.ext $ by simp [mul_pow],
..powers_hom M}
/-- If `M` is commutative, `gpowers_hom` is a multiplicative equivalence. -/
def gpowers_mul_hom [comm_group G] : G ≃* (multiplicative ℤ →* G) :=
{ map_mul' := λ a b, monoid_hom.ext $ by simp [mul_gpow],
..gpowers_hom G}
/-- If `M` is commutative, `multiples_hom` is an additive equivalence. -/
def multiples_add_hom [add_comm_monoid A] : A ≃+ (ℕ →+ A) :=
{ map_add' := λ a b, add_monoid_hom.ext $ by simp [nsmul_add],
..multiples_hom A}
/-- If `M` is commutative, `gmultiples_hom` is an additive equivalence. -/
def gmultiples_add_hom [add_comm_group A] : A ≃+ (ℤ →+ A) :=
{ map_add' := λ a b, add_monoid_hom.ext $ by simp [gsmul_add],
..gmultiples_hom A}
variables {M G A}
@[simp] lemma powers_mul_hom_apply [comm_monoid M] (x : M) (n : multiplicative ℕ) :
powers_mul_hom M x n = x ^ n.to_add := rfl
@[simp] lemma powers_mul_hom_symm_apply [comm_monoid M] (f : multiplicative ℕ →* M) :
(powers_mul_hom M).symm f = f (multiplicative.of_add 1) := rfl
@[simp] lemma gpowers_mul_hom_apply [comm_group G] (x : G) (n : multiplicative ℤ) :
gpowers_mul_hom G x n = x ^ n.to_add := rfl
@[simp] lemma gpowers_mul_hom_symm_apply [comm_group G] (f : multiplicative ℤ →* G) :
(gpowers_mul_hom G).symm f = f (multiplicative.of_add 1) := rfl
@[simp] lemma multiples_add_hom_apply [add_comm_monoid A] (x : A) (n : ℕ) :
multiples_add_hom A x n = n •ℕ x := rfl
@[simp] lemma multiples_add_hom_symm_apply [add_comm_monoid A] (f : ℕ →+ A) :
(multiples_add_hom A).symm f = f 1 := rfl
@[simp] lemma gmultiples_add_hom_apply [add_comm_group A] (x : A) (n : ℤ) :
gmultiples_add_hom A x n = n •ℤ x := rfl
@[simp] lemma gmultiples_add_hom_symm_apply [add_comm_group A] (f : ℤ →+ A) :
(gmultiples_add_hom A).symm f = f 1 := rfl
/-!
### Commutativity (again)
Facts about `semiconj_by` and `commute` that require `gpow` or `gsmul`, or the fact that integer
multiplication equals semiring multiplication.
-/
namespace semiconj_by
section
variables [semiring R] {a x y : R}
@[simp] lemma cast_nat_mul_right (h : semiconj_by a x y) (n : ℕ) : semiconj_by a ((n : R) * x) (n * y) :=
semiconj_by.mul_right (nat.commute_cast _ _) h
@[simp] lemma cast_nat_mul_left (h : semiconj_by a x y) (n : ℕ) : semiconj_by ((n : R) * a) x y :=
semiconj_by.mul_left (nat.cast_commute _ _) h
@[simp] lemma cast_nat_mul_cast_nat_mul (h : semiconj_by a x y) (m n : ℕ) :
semiconj_by ((m : R) * a) (n * x) (n * y) :=
(h.cast_nat_mul_left m).cast_nat_mul_right n
end
variables [monoid M] [group G] [ring R]
@[simp] lemma units_gpow_right {a : M} {x y : units M} (h : semiconj_by a x y) :
∀ m : ℤ, semiconj_by a (↑(x^m)) (↑(y^m))
| (n : ℕ) := by simp only [gpow_coe_nat, units.coe_pow, h, pow_right]
| -[1+n] := by simp only [gpow_neg_succ_of_nat, units.coe_pow, units_inv_right, h, pow_right]
variables {a b x y x' y' : R}
@[simp] lemma cast_int_mul_right (h : semiconj_by a x y) (m : ℤ) :
semiconj_by a ((m : ℤ) * x) (m * y) :=
semiconj_by.mul_right (int.commute_cast _ _) h
@[simp] lemma cast_int_mul_left (h : semiconj_by a x y) (m : ℤ) : semiconj_by ((m : R) * a) x y :=
semiconj_by.mul_left (int.cast_commute _ _) h
@[simp] lemma cast_int_mul_cast_int_mul (h : semiconj_by a x y) (m n : ℤ) :
semiconj_by ((m : R) * a) (n * x) (n * y) :=
(h.cast_int_mul_left m).cast_int_mul_right n
end semiconj_by
namespace commute
section
variables [semiring R] {a b : R}
@[simp] theorem cast_nat_mul_right (h : commute a b) (n : ℕ) : commute a ((n : R) * b) :=
h.cast_nat_mul_right n
@[simp] theorem cast_nat_mul_left (h : commute a b) (n : ℕ) : commute ((n : R) * a) b :=
h.cast_nat_mul_left n
@[simp] theorem cast_nat_mul_cast_nat_mul (h : commute a b) (m n : ℕ) :
commute ((m : R) * a) (n * b) :=
h.cast_nat_mul_cast_nat_mul m n
@[simp] theorem self_cast_nat_mul (n : ℕ) : commute a (n * a) :=
(commute.refl a).cast_nat_mul_right n
@[simp] theorem cast_nat_mul_self (n : ℕ) : commute ((n : R) * a) a :=
(commute.refl a).cast_nat_mul_left n
@[simp] theorem self_cast_nat_mul_cast_nat_mul (m n : ℕ) : commute ((m : R) * a) (n * a) :=
(commute.refl a).cast_nat_mul_cast_nat_mul m n
end
variables [monoid M] [group G] [ring R]
@[simp] lemma units_gpow_right {a : M} {u : units M} (h : commute a u) (m : ℤ) :
commute a (↑(u^m)) :=
h.units_gpow_right m
@[simp] lemma units_gpow_left {u : units M} {a : M} (h : commute ↑u a) (m : ℤ) :
commute (↑(u^m)) a :=
(h.symm.units_gpow_right m).symm
variables {a b : R}
@[simp] lemma cast_int_mul_right (h : commute a b) (m : ℤ) : commute a (m * b) :=
h.cast_int_mul_right m
@[simp] lemma cast_int_mul_left (h : commute a b) (m : ℤ) : commute ((m : R) * a) b :=
h.cast_int_mul_left m
lemma cast_int_mul_cast_int_mul (h : commute a b) (m n : ℤ) : commute ((m : R) * a) (n * b) :=
h.cast_int_mul_cast_int_mul m n
variables (a) (m n : ℤ)
@[simp] theorem self_cast_int_mul : commute a (n * a) := (commute.refl a).cast_int_mul_right n
@[simp] theorem cast_int_mul_self : commute ((n : R) * a) a := (commute.refl a).cast_int_mul_left n
theorem self_cast_int_mul_cast_int_mul : commute ((m : R) * a) (n * a) :=
(commute.refl a).cast_int_mul_cast_int_mul m n
end commute
section multiplicative
open multiplicative
@[simp] lemma nat.to_add_pow (a : multiplicative ℕ) (b : ℕ) : to_add (a ^ b) = to_add a * b :=
begin
induction b with b ih,
{ erw [pow_zero, to_add_one, mul_zero] },
{ simp [*, pow_succ, add_comm, nat.mul_succ] }
end
@[simp] lemma nat.of_add_mul (a b : ℕ) : of_add (a * b) = of_add a ^ b :=
(nat.to_add_pow _ _).symm
@[simp] lemma int.to_add_pow (a : multiplicative ℤ) (b : ℕ) : to_add (a ^ b) = to_add a * b :=
by induction b; simp [*, mul_add, pow_succ, add_comm]
@[simp] lemma int.to_add_gpow (a : multiplicative ℤ) (b : ℤ) : to_add (a ^ b) = to_add a * b :=
int.induction_on b (by simp)
(by simp [gpow_add, mul_add] {contextual := tt})
(by simp [gpow_add, mul_add, sub_eq_add_neg] {contextual := tt})
@[simp] lemma int.of_add_mul (a b : ℤ) : of_add (a * b) = of_add a ^ b :=
(int.to_add_gpow _ _).symm
end multiplicative
namespace units
variables [monoid M]
lemma conj_pow (u : units M) (x : M) (n : ℕ) : (↑u * x * ↑(u⁻¹))^n = u * x^n * ↑(u⁻¹) :=
(divp_eq_iff_mul_eq.2 ((u.mk_semiconj_by x).pow_right n).eq.symm).symm
lemma conj_pow' (u : units M) (x : M) (n : ℕ) : (↑(u⁻¹) * x * u)^n = ↑(u⁻¹) * x^n * u:=
(u⁻¹).conj_pow x n
open opposite
/-- Moving to the opposite monoid commutes with taking powers. -/
@[simp] lemma op_pow (x : M) (n : ℕ) : op (x ^ n) = (op x) ^ n :=
begin
induction n with n h,
{ simp },
{ rw [pow_succ', op_mul, h, pow_succ] }
end
@[simp] lemma unop_pow (x : Mᵒᵖ) (n : ℕ) : unop (x ^ n) = (unop x) ^ n :=
begin
induction n with n h,
{ simp },
{ rw [pow_succ', unop_mul, h, pow_succ] }
end
end units
|
d55dff06057b994ba7702fefb8cbb692c14ff6fb | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/set_theory/game.lean | 8ffe071e3d7ac54e0f8bc5f1db2ef4a21755df1b | [
"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 | 5,341 | lean | /-
Copyright (c) 2019 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton, Mario Carneiro, Isabel Longbottom, Scott Morrison
-/
import set_theory.pgame
/-!
# Combinatorial games.
In this file we define the quotient of pre-games by the equivalence relation `p ≈ q ↔ p ≤ q ∧ q ≤
p`, and construct an instance `add_comm_group game`, as well as an instance `partial_order game`
(although note carefully the warning that the `<` field in this instance is not the usual relation
on combinatorial games).
-/
universes u
local infix ` ≈ ` := pgame.equiv
instance pgame.setoid : setoid pgame :=
⟨λ x y, x ≈ y,
λ x, pgame.equiv_refl _,
λ x y, pgame.equiv_symm,
λ x y z, pgame.equiv_trans⟩
/-- The type of combinatorial games. In ZFC, a combinatorial game is constructed from
two sets of combinatorial games that have been constructed at an earlier
stage. To do this in type theory, we say that a combinatorial pre-game is built
inductively from two families of combinatorial games indexed over any type
in Type u. The resulting type `pgame.{u}` lives in `Type (u+1)`,
reflecting that it is a proper class in ZFC.
A combinatorial game is then constructed by quotienting by the equivalence
`x ≈ y ↔ x ≤ y ∧ y ≤ x`. -/
def game := quotient pgame.setoid
open pgame
namespace game
/-- The relation `x ≤ y` on games. -/
def le : game → game → Prop :=
quotient.lift₂ (λ x y, x ≤ y) (λ x₁ y₁ x₂ y₂ hx hy, propext (le_congr hx hy))
instance : has_le game :=
{ le := le }
@[refl] theorem le_refl : ∀ x : game, x ≤ x :=
by { rintro ⟨x⟩, apply pgame.le_refl }
@[trans] theorem le_trans : ∀ x y z : game, x ≤ y → y ≤ z → x ≤ z :=
by { rintro ⟨x⟩ ⟨y⟩ ⟨z⟩, apply pgame.le_trans }
theorem le_antisymm : ∀ x y : game, x ≤ y → y ≤ x → x = y :=
by { rintro ⟨x⟩ ⟨y⟩ h₁ h₂, apply quot.sound, exact ⟨h₁, h₂⟩ }
/-- The relation `x < y` on games. -/
-- We don't yet make this into an instance, because it will conflict with the (incorrect) notion
-- of `<` provided by `partial_order` later.
def lt : game → game → Prop :=
quotient.lift₂ (λ x y, x < y) (λ x₁ y₁ x₂ y₂ hx hy, propext (lt_congr hx hy))
theorem not_le : ∀ {x y : game}, ¬ (x ≤ y) ↔ (lt y x) :=
by { rintro ⟨x⟩ ⟨y⟩, exact not_le }
instance : has_zero game := ⟨⟦0⟧⟩
instance : has_one game := ⟨⟦1⟧⟩
/-- The negation of `{L | R}` is `{-R | -L}`. -/
def neg : game → game :=
quot.lift (λ x, ⟦-x⟧) (λ x y h, quot.sound (@neg_congr x y h))
instance : has_neg game :=
{ neg := neg }
/-- The sum of `x = {xL | xR}` and `y = {yL | yR}` is `{xL + y, x + yL | xR + y, x + yR}`. -/
def add : game → game → game :=
quotient.lift₂ (λ x y : pgame, ⟦x + y⟧) (λ x₁ y₁ x₂ y₂ hx hy, quot.sound (pgame.add_congr hx hy))
instance : has_add game := ⟨add⟩
theorem add_assoc : ∀ (x y z : game), (x + y) + z = x + (y + z) :=
begin
rintros ⟨x⟩ ⟨y⟩ ⟨z⟩,
apply quot.sound,
exact add_assoc_equiv
end
instance : add_semigroup game.{u} :=
{ add_assoc := add_assoc,
..game.has_add }
theorem add_zero : ∀ (x : game), x + 0 = x :=
begin
rintro ⟨x⟩,
apply quot.sound,
apply add_zero_equiv
end
theorem zero_add : ∀ (x : game), 0 + x = x :=
begin
rintro ⟨x⟩,
apply quot.sound,
apply zero_add_equiv
end
instance : add_monoid game :=
{ add_zero := add_zero,
zero_add := zero_add,
..game.has_zero,
..game.add_semigroup }
theorem add_left_neg : ∀ (x : game), (-x) + x = 0 :=
begin
rintro ⟨x⟩,
apply quot.sound,
apply add_left_neg_equiv
end
instance : add_group game :=
{ add_left_neg := add_left_neg,
..game.has_neg,
..game.add_monoid }
theorem add_comm : ∀ (x y : game), x + y = y + x :=
begin
rintros ⟨x⟩ ⟨y⟩,
apply quot.sound,
exact add_comm_equiv
end
instance : add_comm_semigroup game :=
{ add_comm := add_comm,
..game.add_semigroup }
instance : add_comm_group game :=
{ ..game.add_comm_semigroup,
..game.add_group }
theorem add_le_add_left : ∀ (a b : game), a ≤ b → ∀ (c : game), c + a ≤ c + b :=
begin rintro ⟨a⟩ ⟨b⟩ h ⟨c⟩, apply pgame.add_le_add_left h, end
-- While it is very tempting to define a `partial_order` on games, and prove
-- that games form an `ordered_comm_group`, it is a bit dangerous.
-- The relations `≤` and `<` on games do not satisfy
-- `lt_iff_le_not_le : ∀ a b : α, a < b ↔ (a ≤ b ∧ ¬ b ≤ a)`
-- (Consider `a = 0`, `b = star`.)
-- (`lt_iff_le_not_le` is satisfied by surreal numbers, however.)
-- Thus we can not use `<` when defining a `partial_order`.
-- Because of this issue, we define the `partial_order` and `ordered_comm_group` instances,
-- but do not actually mark them as instances, for safety.
/-- The `<` operation provided by this partial order is not the usual `<` on games! -/
def game_partial_order : partial_order game :=
{ le_refl := le_refl,
le_trans := le_trans,
le_antisymm := le_antisymm,
..game.has_le }
local attribute [instance] game_partial_order
/-- The `<` operation provided by this `ordered_comm_group` is not the usual `<` on games! -/
def ordered_comm_group_game : ordered_comm_group game :=
ordered_comm_group.mk' add_le_add_left
end game
|
ccac8acbd941f2019bd7afb4ea80940bfb0a09c3 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/field_theory/mv_polynomial.lean | eee5c1a2fd341f2fe24e70e754d68bda5c9badbe | [
"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 | 9,538 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl
Multivariate functions of the form `α^n → α` are isomorphic to multivariate polynomials in
`n` variables.
-/
import linear_algebra.finsupp_vector_space
import field_theory.finite
noncomputable theory
open_locale classical
open set linear_map submodule
open_locale big_operators
namespace mv_polynomial
universes u v
variables {σ : Type u} {α : Type v}
section
variables (σ α) [field α] (m : ℕ)
def restrict_total_degree : submodule α (mv_polynomial σ α) :=
finsupp.supported _ _ {n | n.sum (λn e, e) ≤ m }
lemma mem_restrict_total_degree (p : mv_polynomial σ α) :
p ∈ restrict_total_degree σ α m ↔ p.total_degree ≤ m :=
begin
rw [total_degree, finset.sup_le_iff],
refl
end
end
section
variables (σ α)
def restrict_degree (m : ℕ) [field α] : submodule α (mv_polynomial σ α) :=
finsupp.supported _ _ {n | ∀i, n i ≤ m }
end
lemma mem_restrict_degree [field α] (p : mv_polynomial σ α) (n : ℕ) :
p ∈ restrict_degree σ α n ↔ (∀s ∈ p.support, ∀i, (s : σ →₀ ℕ) i ≤ n) :=
begin
rw [restrict_degree, finsupp.mem_supported],
refl
end
lemma mem_restrict_degree_iff_sup [field α] (p : mv_polynomial σ α) (n : ℕ) :
p ∈ restrict_degree σ α n ↔ ∀i, p.degrees.count i ≤ n :=
begin
simp only [mem_restrict_degree, degrees, multiset.count_sup, finsupp.count_to_multiset,
finset.sup_le_iff],
exact ⟨assume h n s hs, h s hs n, assume h s hs n, h n s hs⟩
end
lemma map_range_eq_map {β : Type*} [comm_ring α] [comm_ring β] (p : mv_polynomial σ α)
(f : α →+* β) :
finsupp.map_range f f.map_zero p = map f p :=
begin
rw [← finsupp.sum_single p, finsupp.sum],
-- It's not great that we need to use an `erw` here,
-- but hopefully it will become smoother when we move entirely away from `is_semiring_hom`.
erw [finsupp.map_range_finset_sum (f : α →+ β)],
rw [← p.support.sum_hom (map f)],
{ refine finset.sum_congr rfl (assume n _, _),
rw [finsupp.map_range_single, ← monomial, ← monomial, map_monomial], refl, },
apply_instance
end
section
variables (σ α)
lemma is_basis_monomials [field α] :
is_basis α ((λs, (monomial s 1 : mv_polynomial σ α))) :=
suffices is_basis α (λ (sa : Σ _, unit), (monomial sa.1 1 : mv_polynomial σ α)),
begin
apply is_basis.comp this (λ (s : σ →₀ ℕ), ⟨s, punit.star⟩),
split,
{ intros x y hxy,
simpa using hxy },
{ intros x,
rcases x with ⟨x₁, x₂⟩,
use x₁,
rw punit_eq punit.star x₂ }
end,
begin
apply finsupp.is_basis_single (λ _ _, (1 : α)),
intro _,
apply is_basis_singleton_one,
end
end
end mv_polynomial
namespace mv_polynomial
universe u
variables (σ : Type u) (α : Type u) [field α]
open_locale classical
lemma dim_mv_polynomial : vector_space.dim α (mv_polynomial σ α) = cardinal.mk (σ →₀ ℕ) :=
by rw [← cardinal.lift_inj, ← (is_basis_monomials σ α).mk_eq_dim]
end mv_polynomial
namespace mv_polynomial
variables {α : Type*} {σ : Type*}
variables [field α] [fintype α] [fintype σ]
def indicator (a : σ → α) : mv_polynomial σ α :=
∏ n, (1 - (X n - C (a n))^(fintype.card α - 1))
lemma eval_indicator_apply_eq_one (a : σ → α) :
eval a (indicator a) = 1 :=
have 0 < fintype.card α - 1,
begin
rw [← finite_field.card_units, fintype.card_pos_iff],
exact ⟨1⟩
end,
by simp only [indicator, (finset.univ.prod_hom (eval a)).symm, ring_hom.map_sub,
is_ring_hom.map_one (eval a), is_monoid_hom.map_pow (eval a), eval_X, eval_C,
sub_self, zero_pow this, sub_zero, finset.prod_const_one]
lemma eval_indicator_apply_eq_zero (a b : σ → α) (h : a ≠ b) :
eval a (indicator b) = 0 :=
have ∃i, a i ≠ b i, by rwa [(≠), function.funext_iff, not_forall] at h,
begin
rcases this with ⟨i, hi⟩,
simp only [indicator, (finset.univ.prod_hom (eval a)).symm, ring_hom.map_sub,
is_ring_hom.map_one (eval a), is_monoid_hom.map_pow (eval a), eval_X, eval_C,
sub_self, finset.prod_eq_zero_iff],
refine ⟨i, finset.mem_univ _, _⟩,
rw [finite_field.pow_card_sub_one_eq_one, sub_self],
rwa [(≠), sub_eq_zero],
end
lemma degrees_indicator (c : σ → α) :
degrees (indicator c) ≤ ∑ s : σ, (fintype.card α - 1) •ℕ {s} :=
begin
rw [indicator],
refine le_trans (degrees_prod _ _) (finset.sum_le_sum $ assume s hs, _),
refine le_trans (degrees_sub _ _) _,
rw [degrees_one, ← bot_eq_zero, bot_sup_eq],
refine le_trans (degrees_pow _ _) (nsmul_le_nsmul_of_le_right _ _),
refine le_trans (degrees_sub _ _) _,
rw [degrees_C, ← bot_eq_zero, sup_bot_eq],
exact degrees_X _
end
lemma indicator_mem_restrict_degree (c : σ → α) :
indicator c ∈ restrict_degree σ α (fintype.card α - 1) :=
begin
rw [mem_restrict_degree_iff_sup, indicator],
assume n,
refine le_trans (multiset.count_le_of_le _ $ degrees_indicator _) (le_of_eq _),
rw [← finset.univ.sum_hom (multiset.count n)],
simp only [is_add_monoid_hom.map_nsmul (multiset.count n), multiset.singleton_eq_singleton,
nsmul_eq_mul, nat.cast_id],
transitivity,
refine finset.sum_eq_single n _ _,
{ assume b hb ne, rw [multiset.count_cons_of_ne ne.symm, multiset.count_zero, mul_zero] },
{ assume h, exact (h $ finset.mem_univ _).elim },
{ rw [multiset.count_cons_self, multiset.count_zero, mul_one] }
end
section
variables (α σ)
def evalₗ : mv_polynomial σ α →ₗ[α] (σ → α) → α :=
⟨ λp e, eval e p,
assume p q, (by { ext x, rw ring_hom.map_add, refl, }),
assume a p, funext $ assume e, by rw [smul_eq_C_mul, ring_hom.map_mul, eval_C]; refl ⟩
end
lemma evalₗ_apply (p : mv_polynomial σ α) (e : σ → α) : evalₗ α σ p e = eval e p :=
rfl
lemma map_restrict_dom_evalₗ : (restrict_degree σ α (fintype.card α - 1)).map (evalₗ α σ) = ⊤ :=
begin
refine top_unique (submodule.le_def'.2 $ assume e _, mem_map.2 _),
refine ⟨∑ n : σ → α, e n • indicator n, _, _⟩,
{ exact sum_mem _ (assume c _, smul_mem _ _ (indicator_mem_restrict_degree _)) },
{ ext n,
simp only [linear_map.map_sum, @finset.sum_apply (σ → α) (λ_, α) _ _ _ _ _,
pi.smul_apply, linear_map.map_smul],
simp only [evalₗ_apply],
transitivity,
refine finset.sum_eq_single n _ _,
{ assume b _ h,
rw [eval_indicator_apply_eq_zero _ _ h.symm, smul_zero] },
{ assume h, exact (h $ finset.mem_univ n).elim },
{ rw [eval_indicator_apply_eq_one, smul_eq_mul, mul_one] } }
end
end mv_polynomial
namespace mv_polynomial
universe u
variables (σ : Type u) (α : Type u) [fintype σ] [field α] [fintype α]
@[derive [add_comm_group, vector_space α, inhabited]]
def R : Type u := restrict_degree σ α (fintype.card α - 1)
noncomputable instance decidable_restrict_degree (m : ℕ) :
decidable_pred (λn, n ∈ {n : σ →₀ ℕ | ∀i, n i ≤ m }) :=
by simp only [set.mem_set_of_eq]; apply_instance
lemma dim_R : vector_space.dim α (R σ α) = fintype.card (σ → α) :=
calc vector_space.dim α (R σ α) =
vector_space.dim α (↥{s : σ →₀ ℕ | ∀ (n : σ), s n ≤ fintype.card α - 1} →₀ α) :
linear_equiv.dim_eq
(finsupp.supported_equiv_finsupp {s : σ →₀ ℕ | ∀n:σ, s n ≤ fintype.card α - 1 })
... = cardinal.mk {s : σ →₀ ℕ | ∀ (n : σ), s n ≤ fintype.card α - 1} :
by rw [finsupp.dim_eq, dim_of_field, mul_one]
... = cardinal.mk {s : σ → ℕ | ∀ (n : σ), s n < fintype.card α } :
begin
refine quotient.sound ⟨equiv.subtype_congr finsupp.equiv_fun_on_fintype $ assume f, _⟩,
refine forall_congr (assume n, nat.le_sub_right_iff_add_le _),
exact fintype.card_pos_iff.2 ⟨0⟩
end
... = cardinal.mk (σ → {n // n < fintype.card α}) :
quotient.sound ⟨@equiv.subtype_pi_equiv_pi σ (λ_, ℕ) (λs n, n < fintype.card α)⟩
... = cardinal.mk (σ → fin (fintype.card α)) :
quotient.sound ⟨equiv.arrow_congr (equiv.refl σ) (equiv.fin_equiv_subtype _).symm⟩
... = cardinal.mk (σ → α) :
begin
refine (trunc.induction_on (fintype.equiv_fin α) $ assume (e : α ≃ fin (fintype.card α)), _),
refine quotient.sound ⟨equiv.arrow_congr (equiv.refl σ) e.symm⟩
end
... = fintype.card (σ → α) : cardinal.fintype_card _
def evalᵢ : R σ α →ₗ[α] (σ → α) → α :=
((evalₗ α σ).comp (restrict_degree σ α (fintype.card α - 1)).subtype)
lemma range_evalᵢ : (evalᵢ σ α).range = ⊤ :=
begin
rw [evalᵢ, linear_map.range_comp, range_subtype],
exact map_restrict_dom_evalₗ
end
lemma ker_evalₗ : (evalᵢ σ α).ker = ⊥ :=
begin
refine injective_of_surjective _ _ _ (range_evalᵢ _ _),
{ rw [dim_R], exact cardinal.nat_lt_omega _ },
{ rw [dim_R, dim_fun, dim_of_field, mul_one] }
end
lemma eq_zero_of_eval_eq_zero (p : mv_polynomial σ α)
(h : ∀v:σ → α, eval v p = 0) (hp : p ∈ restrict_degree σ α (fintype.card α - 1)) :
p = 0 :=
let p' : R σ α := ⟨p, hp⟩ in
have p' ∈ (evalᵢ σ α).ker := by { rw [mem_ker], ext v, exact h v },
show p'.1 = (0 : R σ α).1,
begin
rw [ker_evalₗ, mem_bot] at this,
rw [this]
end
end mv_polynomial
namespace mv_polynomial
variables (σ : Type*) (R : Type*) [comm_ring R] (p : ℕ)
instance [char_p R p] : char_p (mv_polynomial σ R) p :=
{ cast_eq_zero_iff := λ n, by rw [← C_eq_coe_nat, ← C_0, C_inj, char_p.cast_eq_zero_iff R p] }
end mv_polynomial
|
2cb8dad6a89ca073337dfed38bebfd0885e927d7 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/topology/spectral/hom.lean | 9a939f0bc670cad208c7e01543bac3301e8cfd2e | [
"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 | 5,812 | 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 topology.continuous_function.basic
/-!
# Spectral maps
This file defines spectral maps. A map is spectral when it's continuous and the preimage of a
compact open set is compact open.
## Main declarations
* `is_spectral_map`: Predicate for a map to be spectral.
* `spectral_map`: Bundled spectral maps.
* `spectral_map_class`: Typeclass for a type to be a type of spectral maps.
## TODO
Once we have `spectral_space`, `is_spectral_map` should move to `topology.spectral.basic`.
-/
open function order_dual
variables {F α β γ δ : Type*}
section unbundled
variables [topological_space α] [topological_space β] [topological_space γ] {f : α → β} {s : set β}
/-- A function between topological spaces is spectral if it is continuous and the preimage of every
compact open set is compact open. -/
structure is_spectral_map (f : α → β) extends continuous f : Prop :=
(compact_preimage_of_open ⦃s : set β⦄ : is_open s → is_compact s → is_compact (f ⁻¹' s))
lemma is_compact.preimage_of_open (hf : is_spectral_map f) (h₀ : is_compact s) (h₁ : is_open s) :
is_compact (f ⁻¹' s) :=
hf.compact_preimage_of_open h₁ h₀
lemma is_spectral_map.continuous {f : α → β} (hf : is_spectral_map f) : continuous f :=
hf.to_continuous
lemma is_spectral_map_id : is_spectral_map (@id α) := ⟨continuous_id, λ s _, id⟩
lemma is_spectral_map.comp {f : β → γ} {g : α → β} (hf : is_spectral_map f)
(hg : is_spectral_map g) :
is_spectral_map (f ∘ g) :=
⟨hf.continuous.comp hg.continuous,
λ s hs₀ hs₁, (hs₁.preimage_of_open hf hs₀).preimage_of_open hg (hs₀.preimage hf.continuous)⟩
end unbundled
/-- The type of spectral maps from `α` to `β`. -/
structure spectral_map (α β : Type*) [topological_space α] [topological_space β] :=
(to_fun : α → β)
(spectral' : is_spectral_map to_fun)
/-- `spectral_map_class F α β` states that `F` is a type of spectral maps.
You should extend this class when you extend `spectral_map`. -/
class spectral_map_class (F : Type*) (α β : out_param $ Type*) [topological_space α]
[topological_space β]
extends fun_like F α (λ _, β) :=
(map_spectral (f : F) : is_spectral_map f)
export spectral_map_class (map_spectral)
attribute [simp] map_spectral
@[priority 100] -- See note [lower instance priority]
instance spectral_map_class.to_continuous_map_class [topological_space α] [topological_space β]
[spectral_map_class F α β] :
continuous_map_class F α β :=
{ map_continuous := λ f, (map_spectral f).continuous,
..‹spectral_map_class F α β› }
instance [topological_space α] [topological_space β] [spectral_map_class F α β] :
has_coe_t F (spectral_map α β) :=
⟨λ f, ⟨_, map_spectral f⟩⟩
/-! ### Spectral maps -/
namespace spectral_map
variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
/-- Reinterpret a `spectral_map` as a `continuous_map`. -/
def to_continuous_map (f : spectral_map α β) : continuous_map α β := ⟨_, f.spectral'.continuous⟩
instance : spectral_map_class (spectral_map α β) α β :=
{ coe := spectral_map.to_fun,
coe_injective' := λ f g h, by { cases f, cases g, congr' },
map_spectral := λ f, f.spectral' }
/-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun`
directly. -/
instance : has_coe_to_fun (spectral_map α β) (λ _, α → β) := fun_like.has_coe_to_fun
@[simp] lemma to_fun_eq_coe {f : spectral_map α β} : f.to_fun = (f : α → β) := rfl
@[ext] lemma ext {f g : spectral_map α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h
/-- Copy of a `spectral_map` with a new `to_fun` equal to the old one. Useful to fix definitional
equalities. -/
protected def copy (f : spectral_map α β) (f' : α → β) (h : f' = f) : spectral_map α β :=
⟨f', h.symm.subst f.spectral'⟩
variables (α)
/-- `id` as a `spectral_map`. -/
protected def id : spectral_map α α := ⟨id, is_spectral_map_id⟩
instance : inhabited (spectral_map α α) := ⟨spectral_map.id α⟩
@[simp] lemma coe_id : ⇑(spectral_map.id α) = id := rfl
variables {α}
@[simp] lemma id_apply (a : α) : spectral_map.id α a = a := rfl
/-- Composition of `spectral_map`s as a `spectral_map`. -/
def comp (f : spectral_map β γ) (g : spectral_map α β) : spectral_map α γ :=
⟨f.to_continuous_map.comp g.to_continuous_map, f.spectral'.comp g.spectral'⟩
@[simp] lemma coe_comp (f : spectral_map β γ) (g : spectral_map α β) : (f.comp g : α → γ) = f ∘ g :=
rfl
@[simp] lemma comp_apply (f : spectral_map β γ) (g : spectral_map α β) (a : α) :
(f.comp g) a = f (g a) := rfl
@[simp] lemma coe_comp_continuous_map (f : spectral_map β γ) (g : spectral_map α β) :
(f.comp g : continuous_map α γ) = (f : continuous_map β γ).comp g := rfl
@[simp] lemma comp_assoc (f : spectral_map γ δ) (g : spectral_map β γ) (h : spectral_map α β) :
(f.comp g).comp h = f.comp (g.comp h) := rfl
@[simp] lemma comp_id (f : spectral_map α β) : f.comp (spectral_map.id α) = f :=
ext $ λ a, rfl
@[simp] lemma id_comp (f : spectral_map α β) : (spectral_map.id β).comp f = f :=
ext $ λ a, rfl
lemma cancel_right {g₁ g₂ : spectral_map β γ} {f : spectral_map α β} (hf : surjective f) :
g₁.comp f = g₂.comp f ↔ g₁ = g₂ :=
⟨λ h, ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩
lemma cancel_left {g : spectral_map β γ} {f₁ f₂ : spectral_map α β} (hg : injective g) :
g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ :=
⟨λ h, ext $ λ a, hg $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩
end spectral_map
|
364265b62554da4dcef7ad1aff0328ee75a32653 | 57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d | /src/Lean/Elab/Log.lean | 8eac22779c12f40ca9ed560f45fa48f50b42a03d | [
"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 | 3,184 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Elab.Util
import Lean.Util.Sorry
import Lean.Elab.Exception
namespace Lean.Elab
class MonadFileMap (m : Type → Type) where
getFileMap : m FileMap
export MonadFileMap (getFileMap)
class MonadLog (m : Type → Type) extends MonadFileMap m where
getRef : m Syntax
getFileName : m String
logMessage : Message → m Unit
export MonadLog (getFileName logMessage)
instance (m n) [MonadLift m n] [MonadLog m] : MonadLog n where
getRef := liftM (MonadLog.getRef : m _)
getFileMap := liftM (getFileMap : m _)
getFileName := liftM (getFileName : m _)
logMessage := fun msg => liftM (logMessage msg : m _ )
variable {m : Type → Type} [Monad m] [MonadLog m] [AddMessageContext m]
def getRefPos : m String.Pos := do
let ref ← MonadLog.getRef
return ref.getPos?.getD 0
def getRefPosition : m Position := do
let fileMap ← getFileMap
return fileMap.toPosition (← getRefPos)
def logAt (ref : Syntax) (msgData : MessageData) (severity : MessageSeverity := MessageSeverity.error): m Unit :=
unless severity == MessageSeverity.error && msgData.hasSyntheticSorry do
let ref := replaceRef ref (← MonadLog.getRef)
let pos := ref.getPos?.getD 0
let endPos := ref.getTailPos?.getD pos
let fileMap ← getFileMap
let msgData ← addMessageContext msgData
logMessage { fileName := (← getFileName), pos := fileMap.toPosition pos, endPos := fileMap.toPosition endPos, data := msgData, severity := severity }
def logErrorAt (ref : Syntax) (msgData : MessageData) : m Unit :=
logAt ref msgData MessageSeverity.error
def logWarningAt (ref : Syntax) (msgData : MessageData) : m Unit :=
logAt ref msgData MessageSeverity.warning
def logInfoAt (ref : Syntax) (msgData : MessageData) : m Unit :=
logAt ref msgData MessageSeverity.information
def log (msgData : MessageData) (severity : MessageSeverity := MessageSeverity.error): m Unit := do
let ref ← MonadLog.getRef
logAt ref msgData severity
def logError (msgData : MessageData) : m Unit :=
log msgData MessageSeverity.error
def logWarning (msgData : MessageData) : m Unit :=
log msgData MessageSeverity.warning
def logInfo (msgData : MessageData) : m Unit :=
log msgData MessageSeverity.information
def logException [MonadLiftT IO m] (ex : Exception) : m Unit := do
match ex with
| Exception.error ref msg => logErrorAt ref msg
| Exception.internal id _ =>
unless isAbortExceptionId id do
let name ← id.getName
logError m!"internal exception: {name}"
def logTrace (cls : Name) (msgData : MessageData) : m Unit := do
logInfo (MessageData.tagged cls msgData)
@[inline] def trace [MonadOptions m] (cls : Name) (msg : Unit → MessageData) : m Unit := do
if checkTraceOption (← getOptions) cls then
logTrace cls (msg ())
def logDbgTrace [MonadOptions m] (msg : MessageData) : m Unit := do
trace `Elab.debug fun _ => msg
def logUnknownDecl (declName : Name) : m Unit :=
logError m!"unknown declaration '{declName}'"
end Lean.Elab
|
c01a08d664871c910a305191af845f103e41eb5c | aa5a655c05e5359a70646b7154e7cac59f0b4132 | /src/Lean/Util/Recognizers.lean | ff969f7469aa262581dbb637ea17dd0e9311d8da | [
"Apache-2.0"
] | permissive | lambdaxymox/lean4 | ae943c960a42247e06eff25c35338268d07454cb | 278d47c77270664ef29715faab467feac8a0f446 | refs/heads/master | 1,677,891,867,340 | 1,612,500,005,000 | 1,612,500,005,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,619 | 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.Environment
namespace Lean
namespace Expr
@[inline] def const? (e : Expr) : Option (Name × List Level) :=
match e with
| Expr.const n us _ => some (n, us)
| _ => none
@[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 not? (p : Expr) : Option Expr :=
p.app1? ``Not
@[inline] def heq? (p : Expr) : Option (Expr × Expr × Expr × Expr) :=
p.app4? ``HEq
def natAdd? (e : Expr) : Option (Expr × Expr) :=
e.app2? ``Nat.add
@[inline] def arrow? : Expr → Option (Expr × Expr)
| Expr.forallE _ α β _ => if β.hasLooseBVars then none else some (α, β)
| _ => none
def isEq (e : Expr) :=
e.isAppOfArity ``Eq 3
def isHEq (e : Expr) :=
e.isAppOfArity ``HEq 4
partial def listLit? (e : Expr) : Option (Expr × List Expr) :=
let rec loop (e : Expr) (acc : List Expr) :=
if e.isAppOfArity ``List.nil 1 then
some (e.appArg!, acc.reverse)
else if e.isAppOfArity ``List.cons 3 then
loop e.appArg! (e.appFn!.appArg! :: acc)
else
none
loop e []
def arrayLit? (e : Expr) : Option (Expr × 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
private def getConstructorVal? (env : Environment) (ctorName : Name) : Option ConstructorVal := do
match env.find? ctorName with
| some (ConstantInfo.ctorInfo v) => v
| _ => none
def isConstructorApp? (env : Environment) (e : Expr) : Option ConstructorVal :=
match e with
| Expr.lit (Literal.natVal n) _ => if n == 0 then getConstructorVal? env `Nat.zero else getConstructorVal? env `Nat.succ
| _ =>
match e.getAppFn with
| Expr.const n _ _ => match getConstructorVal? env n with
| some v => if v.numParams + v.numFields == e.getAppNumArgs then some v else none
| none => none
| _ => none
def isConstructorApp (env : Environment) (e : Expr) : Bool :=
e.isConstructorApp? env |>.isSome
def constructorApp? (env : Environment) (e : Expr) : Option (ConstructorVal × Array Expr) :=
match e with
| Expr.lit (Literal.natVal n) _ =>
if n == 0 then do
let v ← getConstructorVal? env `Nat.zero
pure (v, #[])
else do
let v ← getConstructorVal? env `Nat.succ
pure (v, #[mkNatLit (n-1)])
| _ =>
match e.getAppFn with
| Expr.const n _ _ => do
let v ← getConstructorVal? env n
if v.numParams + v.numFields == e.getAppNumArgs then
pure (v, e.getAppArgs)
else
none
| _ => none
end Expr
end Lean
|
724f63cf1d4bfeca0a2f6be7c416bed5cb2182f9 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /stage0/src/Init/Data/Array/BasicAux.lean | 0fe2149a68ce2d70e50dafddf5444918c6c4d49d | [
"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,180 | 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
-/
prelude
import Init.Data.Array.Basic
import Init.Data.Nat.Linear
import Init.NotationExtra
theorem Array.of_push_eq_push {as bs : Array α} (h : as.push a = bs.push b) : as = bs ∧ a = b := by
simp [push] at h
have ⟨h₁, h₂⟩ := List.of_concat_eq_concat h
cases as; cases bs
simp_all
private theorem List.size_toArrayAux (as : List α) (bs : Array α) : (as.toArrayAux bs).size = as.length + bs.size := by
induction as generalizing bs with
| nil => simp [toArrayAux]
| cons a as ih => simp_arith [toArrayAux, *]
private theorem List.of_toArrayAux_eq_toArrayAux {as bs : List α} {cs ds : Array α} (h : as.toArrayAux cs = bs.toArrayAux ds) (hlen : cs.size = ds.size) : as = bs ∧ cs = ds := by
match as, bs with
| [], [] => simp [toArrayAux] at h; simp [h]
| a::as, [] => simp [toArrayAux] at h; rw [← h] at hlen; simp_arith [size_toArrayAux] at hlen
| [], b::bs => simp [toArrayAux] at h; rw [h] at hlen; simp_arith [size_toArrayAux] at hlen
| a::as, b::bs =>
simp [toArrayAux] at h
have : (cs.push a).size = (ds.push b).size := by simp [*]
have ⟨ih₁, ih₂⟩ := of_toArrayAux_eq_toArrayAux h this
simp [ih₁]
have := Array.of_push_eq_push ih₂
simp [this]
@[simp] theorem List.toArray_eq_toArray_eq (as bs : List α) : (as.toArray = bs.toArray) = (as = bs) := by
apply propext; apply Iff.intro
· intro h; simp [toArray] at h; have := of_toArrayAux_eq_toArrayAux h rfl; exact this.1
· intro h; rw [h]
def Array.mapM' [Monad m] (f : α → m β) (as : Array α) : m { bs : Array β // bs.size = as.size } :=
go 0 ⟨mkEmpty as.size, rfl⟩ (by simp_arith)
where
go (i : Nat) (acc : { bs : Array β // bs.size = i }) (hle : i ≤ as.size) : m { bs : Array β // bs.size = as.size } := do
if h : i = as.size then
return h ▸ acc
else
have hlt : i < as.size := Nat.lt_of_le_of_ne hle h
let b ← f as[i]
go (i+1) ⟨acc.val.push b, by simp [acc.property]⟩ hlt
termination_by go i _ _ => as.size - i
|
ffaaf76626fbd6822db24f04a0c7e82ef31cf9de | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/topology/sheaves/sheafify.lean | 7adc5d90beb8774ee5a993bf6862d4c2bda64a52 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 4,525 | 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 topology.sheaves.local_predicate
import topology.sheaves.stalks
/-!
# Sheafification of `Type` valued presheaves
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We construct the sheafification of a `Type` valued presheaf,
as the subsheaf of dependent functions into the stalks
consisting of functions which are locally germs.
We show that the stalks of the sheafification are isomorphic to the original stalks,
via `stalk_to_fiber` which evaluates a germ of a dependent function at a point.
We construct a morphism `to_sheafify` from a presheaf to (the underlying presheaf of)
its sheafification, given by sending a section to its collection of germs.
## Future work
Show that the map induced on stalks by `to_sheafify` is the inverse of `stalk_to_fiber`.
Show sheafification is a functor from presheaves to sheaves,
and that it is the left adjoint of the forgetful functor,
following <https://stacks.math.columbia.edu/tag/007X>.
-/
universes v
noncomputable theory
open Top
open opposite
open topological_space
variables {X : Top.{v}} (F : presheaf (Type v) X)
namespace Top.presheaf
namespace sheafify
/--
The prelocal predicate on functions into the stalks, asserting that the function is equal to a germ.
-/
def is_germ : prelocal_predicate (λ x, F.stalk x) :=
{ pred := λ U f, ∃ (g : F.obj (op U)), ∀ x : U, f x = F.germ x g,
res := λ V U i f ⟨g, p⟩, ⟨F.map i.op g, λ x, (p (i x)).trans (F.germ_res_apply _ _ _).symm⟩, }
/--
The local predicate on functions into the stalks,
asserting that the function is locally equal to a germ.
-/
def is_locally_germ : local_predicate (λ x, F.stalk x) := (is_germ F).sheafify
end sheafify
/--
The sheafification of a `Type` valued presheaf, defined as the functions into the stalks which
are locally equal to germs.
-/
def sheafify : sheaf (Type v) X :=
subsheaf_to_Types (sheafify.is_locally_germ F)
/--
The morphism from a presheaf to its sheafification,
sending each section to its germs.
(This forms the unit of the adjunction.)
-/
def to_sheafify : F ⟶ F.sheafify.1 :=
{ app := λ U f, ⟨λ x, F.germ x f, prelocal_predicate.sheafify_of ⟨f, λ x, rfl⟩⟩,
naturality' := λ U U' f, by { ext x ⟨u, m⟩, exact germ_res_apply F f.unop ⟨u, m⟩ x } }
/--
The natural morphism from the stalk of the sheafification to the original stalk.
In `sheafify_stalk_iso` we show this is an isomorphism.
-/
def stalk_to_fiber (x : X) : F.sheafify.presheaf.stalk x ⟶ F.stalk x :=
stalk_to_fiber (sheafify.is_locally_germ F) x
lemma stalk_to_fiber_surjective (x : X) : function.surjective (F.stalk_to_fiber x) :=
begin
apply stalk_to_fiber_surjective,
intro t,
obtain ⟨U, m, s, rfl⟩ := F.germ_exist _ t,
{ use ⟨U, m⟩,
fsplit,
{ exact λ y, F.germ y s, },
{ exact ⟨prelocal_predicate.sheafify_of ⟨s, (λ _, rfl)⟩, rfl⟩, }, },
end
lemma stalk_to_fiber_injective (x : X) : function.injective (F.stalk_to_fiber x) :=
begin
apply stalk_to_fiber_injective,
intros,
rcases hU ⟨x, U.2⟩ with ⟨U', mU, iU, gU, wU⟩,
rcases hV ⟨x, V.2⟩ with ⟨V', mV, iV, gV, wV⟩,
have wUx := wU ⟨x, mU⟩,
dsimp at wUx, erw wUx at e, clear wUx,
have wVx := wV ⟨x, mV⟩,
dsimp at wVx, erw wVx at e, clear wVx,
rcases F.germ_eq x mU mV gU gV e with ⟨W, mW, iU', iV', e'⟩,
dsimp at e',
use ⟨W ⊓ (U' ⊓ V'), ⟨mW, mU, mV⟩⟩,
refine ⟨_, _, _⟩,
{ change W ⊓ (U' ⊓ V') ⟶ U.obj,
exact (opens.inf_le_right _ _) ≫ (opens.inf_le_left _ _) ≫ iU, },
{ change W ⊓ (U' ⊓ V') ⟶ V.obj,
exact (opens.inf_le_right _ _) ≫ (opens.inf_le_right _ _) ≫ iV, },
{ intro w,
dsimp,
specialize wU ⟨w.1, w.2.2.1⟩,
dsimp at wU,
specialize wV ⟨w.1, w.2.2.2⟩,
dsimp at wV,
erw [wU, ←F.germ_res iU' ⟨w, w.2.1⟩, wV, ←F.germ_res iV' ⟨w, w.2.1⟩,
category_theory.types_comp_apply, category_theory.types_comp_apply, e'] },
end
/--
The isomorphism betweeen a stalk of the sheafification and the original stalk.
-/
def sheafify_stalk_iso (x : X) : F.sheafify.presheaf.stalk x ≅ F.stalk x :=
(equiv.of_bijective _ ⟨stalk_to_fiber_injective _ _, stalk_to_fiber_surjective _ _⟩).to_iso
-- PROJECT functoriality, and that sheafification is the left adjoint of the forgetful functor.
end Top.presheaf
|
59d1ed2e221a811579917897f6c684d5f5dd19fc | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/data/matrix/dmatrix.lean | dba9388a8436560b6194204177dfc513775eaa7d | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 5,530 | lean | /-
Copyright (c) 2021 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import data.fintype.basic
/-!
# Matrices
-/
universes u u' v w z
/-- `dmatrix m n` is the type of dependently typed matrices
whose rows are indexed by the fintype `m` and
whose columns are indexed by the fintype `n`. -/
@[nolint unused_arguments]
def dmatrix (m : Type u) (n : Type u') [fintype m] [fintype n] (α : m → n → Type v) :
Type (max u u' v) :=
Π i j, α i j
variables {l m n o : Type*} [fintype l] [fintype m] [fintype n] [fintype o]
variables {α : m → n → Type v}
namespace dmatrix
section ext
variables {M N : dmatrix m n α}
theorem ext_iff : (∀ i j, M i j = N i j) ↔ M = N :=
⟨λ h, funext $ λ i, funext $ h i, λ h, by simp [h]⟩
@[ext] theorem ext : (∀ i j, M i j = N i j) → M = N :=
ext_iff.mp
end ext
/-- `M.map f` is the dmatrix obtained by applying `f` to each entry of the matrix `M`. -/
def map (M : dmatrix m n α) {β : m → n → Type w} (f : Π ⦃i j⦄, α i j → β i j) :
dmatrix m n β := λ i j, f (M i j)
@[simp]
lemma map_apply {M : dmatrix m n α} {β : m → n → Type w} {f : Π ⦃i j⦄, α i j → β i j}
{i : m} {j : n} : M.map f i j = f (M i j) :=
rfl
@[simp]
lemma map_map {M : dmatrix m n α} {β : m → n → Type w} {γ : m → n → Type z}
{f : Π ⦃i j⦄, α i j → β i j} {g : Π ⦃i j⦄, β i j → γ i j} :
(M.map f).map g = M.map (λ i j x, g (f x)) :=
by { ext, simp, }
/-- The transpose of a dmatrix. -/
def transpose (M : dmatrix m n α) : dmatrix n m (λ j i, α i j)
| x y := M y x
localized "postfix `ᵀ`:1500 := dmatrix.transpose" in dmatrix
/-- `dmatrix.col u` is the column matrix whose entries are given by `u`. -/
def col {α : m → Type v} (w : Π i, α i) : dmatrix m unit (λ i j, α i)
| x y := w x
/-- `dmatrix.row u` is the row matrix whose entries are given by `u`. -/
def row {α : n → Type v} (v : Π j, α j) : dmatrix unit n (λ i j, α j)
| x y := v y
instance [∀ i j, inhabited (α i j)] : inhabited (dmatrix m n α) := pi.inhabited _
instance [∀ i j, has_add (α i j)] : has_add (dmatrix m n α) := pi.has_add
instance [∀ i j, add_semigroup (α i j)] : add_semigroup (dmatrix m n α) := pi.add_semigroup
instance [∀ i j, add_comm_semigroup (α i j)] : add_comm_semigroup (dmatrix m n α) :=
pi.add_comm_semigroup
instance [∀ i j, has_zero (α i j)] : has_zero (dmatrix m n α) := pi.has_zero
instance [∀ i j, add_monoid (α i j)] : add_monoid (dmatrix m n α) := pi.add_monoid
instance [∀ i j, add_comm_monoid (α i j)] : add_comm_monoid (dmatrix m n α) := pi.add_comm_monoid
instance [∀ i j, has_neg (α i j)] : has_neg (dmatrix m n α) := pi.has_neg
instance [∀ i j, has_sub (α i j)] : has_sub (dmatrix m n α) := pi.has_sub
instance [∀ i j, add_group (α i j)] : add_group (dmatrix m n α) := pi.add_group
instance [∀ i j, add_comm_group (α i j)] : add_comm_group (dmatrix m n α) := pi.add_comm_group
instance [∀ i j, unique (α i j)] : unique (dmatrix m n α) := pi.unique
instance [∀ i j, subsingleton (α i j)] : subsingleton (dmatrix m n α) := pi.subsingleton
@[simp] theorem zero_apply [∀ i j, has_zero (α i j)] (i j) : (0 : dmatrix m n α) i j = 0 := rfl
@[simp] theorem neg_apply [∀ i j, has_neg (α i j)] (M : dmatrix m n α) (i j) :
(- M) i j = - M i j :=
rfl
@[simp] theorem add_apply [∀ i j, has_add (α i j)] (M N : dmatrix m n α) (i j) :
(M + N) i j = M i j + N i j :=
rfl
@[simp] theorem sub_apply [∀ i j, has_sub (α i j)] (M N : dmatrix m n α) (i j) :
(M - N) i j = M i j - N i j :=
rfl
@[simp] lemma map_zero [∀ i j, has_zero (α i j)] {β : m → n → Type w} [∀ i j, has_zero (β i j)]
{f : Π ⦃i j⦄, α i j → β i j} (h : ∀ i j, f (0 : α i j) = 0) :
(0 : dmatrix m n α).map f = 0 :=
by { ext, simp [h], }
lemma map_add [∀ i j, add_monoid (α i j)] {β : m → n → Type w} [∀ i j, add_monoid (β i j)]
(f : Π ⦃i j⦄, α i j →+ β i j) (M N : dmatrix m n α) :
(M + N).map (λ i j, @f i j) = M.map (λ i j, @f i j) + N.map (λ i j, @f i j) :=
by { ext, simp, }
lemma map_sub [∀ i j, add_group (α i j)] {β : m → n → Type w} [∀ i j, add_group (β i j)]
(f : Π ⦃i j⦄, α i j →+ β i j) (M N : dmatrix m n α) :
(M - N).map (λ i j, @f i j) = M.map (λ i j, @f i j) - N.map (λ i j, @f i j) :=
by { ext, simp }
-- TODO[gh-6025]: make this an instance once safe to do so
lemma subsingleton_of_empty_left [is_empty m] : subsingleton (dmatrix m n α) :=
⟨λ M N, by { ext, exact is_empty_elim i }⟩
-- TODO[gh-6025]: make this an instance once safe to do so
lemma subsingleton_of_empty_right [is_empty n] : subsingleton (dmatrix m n α) :=
⟨λ M N, by { ext, exact is_empty_elim j }⟩
end dmatrix
/-- The `add_monoid_hom` between spaces of dependently typed matrices
induced by an `add_monoid_hom` between their coefficients. -/
def add_monoid_hom.map_dmatrix
[∀ i j, add_monoid (α i j)] {β : m → n → Type w} [∀ i j, add_monoid (β i j)]
(f : Π ⦃i j⦄, α i j →+ β i j) :
dmatrix m n α →+ dmatrix m n β :=
{ to_fun := λ M, M.map (λ i j, @f i j),
map_zero' := by simp,
map_add' := dmatrix.map_add f, }
@[simp] lemma add_monoid_hom.map_dmatrix_apply
[∀ i j, add_monoid (α i j)] {β : m → n → Type w} [∀ i j, add_monoid (β i j)]
(f : Π ⦃i j⦄, α i j →+ β i j) (M : dmatrix m n α) :
add_monoid_hom.map_dmatrix f M = M.map (λ i j, @f i j) :=
rfl
|
8aa9a1a5a09abc788abe9ab40022854e328866c2 | c3f2fcd060adfa2ca29f924839d2d925e8f2c685 | /library/logic/quantifiers.lean | d05f5f23802d637e1c399a251adb262d5d54e905 | [
"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 | 3,249 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: logic.quantifiers
Authors: Leonardo de Moura, Jeremy Avigad
Universal and existential quantifiers. See also init.logic.
-/
open inhabited nonempty
theorem not_forall_not_of_exists {A : Type} {p : A → Prop} (H : ∃x, p x) : ¬∀x, ¬p x :=
assume H1 : ∀x, ¬p x,
obtain (w : A) (Hw : p w), from H,
absurd Hw (H1 w)
theorem not_exists_not_of_forall {A : Type} {p : A → Prop} (H2 : ∀x, p x) : ¬∃x, ¬p x :=
assume H1 : ∃x, ¬p x,
obtain (w : A) (Hw : ¬p w), from H1,
absurd (H2 w) Hw
theorem forall_congr {A : Type} {φ ψ : A → Prop} (H : ∀x, φ x ↔ ψ x) : (∀x, φ x) ↔ (∀x, ψ x) :=
iff.intro
(assume Hl, take x, iff.elim_left (H x) (Hl x))
(assume Hr, take x, iff.elim_right (H x) (Hr x))
theorem exists_congr {A : Type} {φ ψ : A → Prop} (H : ∀x, φ x ↔ ψ x) : (∃x, φ x) ↔ (∃x, ψ x) :=
iff.intro
(assume Hex, obtain w Pw, from Hex,
exists.intro w (iff.elim_left (H w) Pw))
(assume Hex, obtain w Qw, from Hex,
exists.intro w (iff.elim_right (H w) Qw))
theorem forall_true_iff_true (A : Type) : (∀x : A, true) ↔ true :=
iff.intro (assume H, trivial) (assume H, take x, trivial)
theorem forall_p_iff_p (A : Type) [H : inhabited A] (p : Prop) : (∀x : A, p) ↔ p :=
iff.intro (assume Hl, inhabited.destruct H (take x, Hl x)) (assume Hr, take x, Hr)
theorem exists_p_iff_p (A : Type) [H : inhabited A] (p : Prop) : (∃x : A, p) ↔ p :=
iff.intro
(assume Hl, obtain a Hp, from Hl, Hp)
(assume Hr, inhabited.destruct H (take a, exists.intro a Hr))
theorem forall_and_distribute {A : Type} (φ ψ : A → Prop) :
(∀x, φ x ∧ ψ x) ↔ (∀x, φ x) ∧ (∀x, ψ x) :=
iff.intro
(assume H, and.intro (take x, and.elim_left (H x)) (take x, and.elim_right (H x)))
(assume H, take x, and.intro (and.elim_left H x) (and.elim_right H x))
theorem exists_or_distribute {A : Type} (φ ψ : A → Prop) :
(∃x, φ x ∨ ψ x) ↔ (∃x, φ x) ∨ (∃x, ψ x) :=
iff.intro
(assume H, obtain (w : A) (Hw : φ w ∨ ψ w), from H,
or.elim Hw
(assume Hw1 : φ w, or.inl (exists.intro w Hw1))
(assume Hw2 : ψ w, or.inr (exists.intro w Hw2)))
(assume H, or.elim H
(assume H1, obtain (w : A) (Hw : φ w), from H1,
exists.intro w (or.inl Hw))
(assume H2, obtain (w : A) (Hw : ψ w), from H2,
exists.intro w (or.inr Hw)))
theorem nonempty_of_exists {A : Type} {P : A → Prop} (H : ∃x, P x) : nonempty A :=
obtain w Hw, from H, nonempty.intro w
section
open decidable eq.ops
variables {A : Type} (P : A → Prop) (a : A) [H : decidable (P a)]
include H
definition decidable_forall_eq [instance] : decidable (∀ x, x = a → P x) :=
decidable.rec_on H
(λ pa, inl (λ x heq, eq.rec_on (eq.rec_on heq rfl) pa))
(λ npa, inr (λ h, absurd (h a rfl) npa))
definition decidable_exists_eq [instance] : decidable (∃ x, x = a ∧ P x) :=
decidable.rec_on H
(λ pa, inl (exists.intro a (and.intro rfl pa)))
(λ npa, inr (λ h,
obtain (w : A) (Hw : w = a ∧ P w), from h,
absurd (and.rec_on Hw (λ h₁ h₂, h₁ ▸ h₂)) npa))
end
|
d9a9f31d9db6abf243b9c4c1d480bfb7197faf52 | ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5 | /tests/compiler/t2.lean | f2cb76c560e2742928626b9f8034260befa6d961 | [
"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 | 2,978 | lean | #lang lean4
/- Benchmark for new code generator -/
inductive Expr
| Val : Int → Expr
| Var : String → Expr
| Add : Expr → Expr → Expr
| Mul : Expr → Expr → Expr
| Pow : Expr → Expr → Expr
| Ln : Expr → Expr
namespace Expr
partial def pown : Int → Int → Int
| a, 0 => 1
| a, 1 => a
| a, n =>
let b := pown a (n / 2);
b * b * (if n % 2 = 0 then 1 else a)
partial def add : Expr → Expr → Expr
| Val n, Val m => Val (n + m)
| Val 0, f => f
| f, Val 0 => f
| f, Val n => add (Val n) f
| Val n, Add (Val m) f => add (Val (n+m)) f
| f, Add (Val n) g => add (Val n) (add f g)
| Add f g, h => add f (add g h)
| f, g => Add f g
partial def mul : Expr → Expr → Expr
| Val n, Val m => Val (n*m)
| Val 0, _ => Val 0
| _, Val 0 => Val 0
| Val 1, f => f
| f, Val 1 => f
| f, Val n => mul (Val n) f
| Val n, Mul (Val m) f => mul (Val (n*m)) f
| f, Mul (Val n) g => mul (Val n) (mul f g)
| Mul f g, h => mul f (mul g h)
| f, g => Mul f g
def pow : Expr → Expr → Expr
| Val m, Val n => Val (pown m n)
| _, Val 0 => Val 1
| f, Val 1 => f
| Val 0, _ => Val 0
| f, g => Pow f g
def ln : Expr → Expr
| Val 1 => Val 0
| f => Ln f
def d (x : String) : Expr → Expr
| Val _ => Val 0
| Var y => if x = y then Val 1 else Val 0
| Add f g => add (d x f) (d x g)
| Mul f g => add (mul f (d x g)) (mul g (d x f))
| Pow f g => mul (pow f g) (add (mul (mul g (d x f)) (pow f (Val (-1)))) (mul (ln f) (d x g)))
| Ln f => mul (d x f) (pow f (Val (-1)))
def count : Expr → Nat
| Val _ => 1
| Var _ => 1
| Add f g => count f + count g
| Mul f g => count f + count g
| Pow f g => count f + count g
| Ln f => count f
protected def Expr.toString : Expr → String
| Val n => toString n
| Var x => x
| Add f g => "(" ++ Expr.toString f ++ " + " ++ Expr.toString g ++ ")"
| Mul f g => "(" ++ Expr.toString f ++ " * " ++ Expr.toString g ++ ")"
| Pow f g => "(" ++ Expr.toString f ++ " ^ " ++ Expr.toString g ++ ")"
| Ln f => "ln(" ++ Expr.toString f ++ ")"
instance : ToString Expr :=
⟨Expr.toString⟩
def nestAux (s : Nat) (f : Nat → Expr → IO Expr) : Nat → Expr → IO Expr
| 0, x => pure x
| m@(n+1), x => f (s - m) x >>= nestAux s f n
def nest (f : Nat → Expr → IO Expr) (n : Nat) (e : Expr) : IO Expr :=
nestAux n f n e
def deriv (i : Nat) (f : Expr) : IO Expr :=
do
let d := d "x" f;
IO.println (toString (i+1) ++ " count: " ++ (toString $ count d));
pure d
end Expr
def main (xs : List String) : IO UInt32 :=
do let x := Expr.Var "x"
let f := Expr.pow x x
discard <| Expr.nest Expr.deriv 7 f
pure 0
-- setOption profiler True
-- #eval main []
|
b27468276af218f97e0f4692654e15dcfe30e600 | d1a52c3f208fa42c41df8278c3d280f075eb020c | /src/Lean/Elab/Deriving/BEq.lean | ac3caf9193be6467279240a3aac21b48236361a2 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | cipher1024/lean4 | 6e1f98bb58e7a92b28f5364eb38a14c8d0aae393 | 69114d3b50806264ef35b57394391c3e738a9822 | refs/heads/master | 1,642,227,983,603 | 1,642,011,696,000 | 1,642,011,696,000 | 228,607,691 | 0 | 0 | Apache-2.0 | 1,576,584,269,000 | 1,576,584,268,000 | null | UTF-8 | Lean | false | false | 5,093 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Transform
import Lean.Elab.Deriving.Basic
import Lean.Elab.Deriving.Util
namespace Lean.Elab.Deriving.BEq
open Lean.Parser.Term
open Meta
def mkBEqHeader (ctx : Context) (indVal : InductiveVal) : TermElabM Header := do
mkHeader ctx `BEq 2 indVal
def mkMatch (ctx : Context) (header : Header) (indVal : InductiveVal) (auxFunName : Name) : TermElabM Syntax := do
let discrs ← mkDiscrs header indVal
let alts ← mkAlts
`(match $[$discrs],* with $alts:matchAlt*)
where
mkElseAlt : TermElabM Syntax := do
let mut patterns := #[]
-- add `_` pattern for indices
for i in [:indVal.numIndices] do
patterns := patterns.push (← `(_))
patterns := patterns.push (← `(_))
patterns := patterns.push (← `(_))
let altRhs ← `(false)
`(matchAltExpr| | $[$patterns:term],* => $altRhs:term)
mkAlts : TermElabM (Array Syntax) := do
let mut alts := #[]
for ctorName in indVal.ctors do
let ctorInfo ← getConstInfoCtor ctorName
let alt ← forallTelescopeReducing ctorInfo.type fun xs type => do
let type ← Core.betaReduce type -- we 'beta-reduce' to eliminate "artificial" dependencies
let mut patterns := #[]
-- add `_` pattern for indices
for i in [:indVal.numIndices] do
patterns := patterns.push (← `(_))
let mut ctorArgs1 := #[]
let mut ctorArgs2 := #[]
let mut rhs ← `(true)
-- add `_` for inductive parameters, they are inaccessible
for i in [:indVal.numParams] do
ctorArgs1 := ctorArgs1.push (← `(_))
ctorArgs2 := ctorArgs2.push (← `(_))
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
if (← inferType x).isAppOf indVal.name then
rhs ← `($rhs && $(mkIdent auxFunName):ident $a:ident $b:ident)
else
rhs ← `($rhs && $a:ident == $b:ident)
patterns := patterns.push (← `(@$(mkIdent ctorName):ident $ctorArgs1:term*))
patterns := patterns.push (← `(@$(mkIdent ctorName):ident $ctorArgs2:term*))
`(matchAltExpr| | $[$patterns:term],* => $rhs:term)
alts := alts.push alt
alts := alts.push (← mkElseAlt)
return alts
def mkAuxFunction (ctx : Context) (i : Nat) : TermElabM Syntax := do
let auxFunName ← ctx.auxFunNames[i]
let indVal ← ctx.typeInfos[i]
let header ← mkBEqHeader ctx indVal
let mut body ← mkMatch ctx header indVal auxFunName
if ctx.usePartial then
let letDecls ← mkLocalInstanceLetDecls ctx `BEq header.argNames
body ← mkLet letDecls body
let binders := header.binders
if ctx.usePartial then
`(private partial def $(mkIdent auxFunName):ident $binders:explicitBinder* : Bool := $body:term)
else
`(private def $(mkIdent auxFunName):ident $binders:explicitBinder* : Bool := $body:term)
def mkMutualBlock (ctx : Context) : TermElabM Syntax := do
let mut auxDefs := #[]
for i in [:ctx.typeInfos.size] do
auxDefs := auxDefs.push (← mkAuxFunction ctx i)
`(mutual
set_option match.ignoreUnusedAlts true
$auxDefs:command*
end)
private def mkBEqInstanceCmds (declNames : Array Name) : TermElabM (Array Syntax) := do
let ctx ← mkContext "beq" declNames[0]
let cmds := #[← mkMutualBlock ctx] ++ (← mkInstanceCmds ctx `BEq declNames)
trace[Elab.Deriving.beq] "\n{cmds}"
return cmds
private def mkBEqEnumFun (ctx : Context) (name : Name) : TermElabM Syntax := do
let auxFunName ← ctx.auxFunNames[0]
`(private def $(mkIdent auxFunName):ident (x y : $(mkIdent name)) : Bool := x.toCtorIdx == y.toCtorIdx)
private def mkBEqEnumCmd (name : Name): TermElabM (Array Syntax) := do
let ctx ← mkContext "beq" name
let cmds := #[← mkBEqEnumFun ctx name] ++ (← mkInstanceCmds ctx `BEq #[name])
trace[Elab.Deriving.beq] "\n{cmds}"
return cmds
open Command
def mkBEqInstanceHandler (declNames : Array Name) : CommandElabM Bool := do
if declNames.size == 1 && (← isEnumType declNames[0]) then
let cmds ← liftTermElabM none <| mkBEqEnumCmd declNames[0]
cmds.forM elabCommand
return true
else if (← declNames.allM isInductive) && declNames.size > 0 then
let cmds ← liftTermElabM none <| mkBEqInstanceCmds declNames
cmds.forM elabCommand
return true
else
return false
builtin_initialize
registerBuiltinDerivingHandler `BEq mkBEqInstanceHandler
registerTraceClass `Elab.Deriving.beq
end Lean.Elab.Deriving.BEq
|
71792d364d809e3b077eed07e41171b422a94503 | c45b34bfd44d8607a2e8762c926e3cfaa7436201 | /uexp/src/uexp/rules/ex2sigmod92.lean | d064200e2ac177954e82b7be6f11cbba81e39011 | [
"BSD-2-Clause"
] | permissive | Shamrock-Frost/Cosette | b477c442c07e45082348a145f19ebb35a7f29392 | 24cbc4adebf627f13f5eac878f04ffa20d1209af | refs/heads/master | 1,619,721,304,969 | 1,526,082,841,000 | 1,526,082,841,000 | 121,695,605 | 1 | 0 | null | 1,518,737,210,000 | 1,518,737,210,000 | null | UTF-8 | Lean | false | false | 2,097 | lean | import ..sql
import ..tactics
import ..u_semiring
import ..extra_constants
import ..UDP
import ..cosette_tactics
open Expr
open Proj
open Pred
open SQL
variable i1000 : const datatypes.int
theorem rule :
forall (Γ scm_itm scm_itp : Schema)
(rel_itm : relation scm_itm)
(rel_itp : relation scm_itp)
(itm_itemno : Column datatypes.int scm_itm)
(itm_type : Column datatypes.int scm_itm)
(itp_itemno : Column datatypes.int scm_itp)
(itp_np : Column datatypes.int scm_itp)
(ik : isKey itm_itemno rel_itm),
denoteSQL
(SELECT1 (combine (right⋅left⋅right)
(combine (right⋅right⋅itm_type)
(right⋅right⋅itm_itemno)))
FROM1 (product (DISTINCT (SELECT1 (combine (right⋅itp_itemno)
(right⋅itp_np))
FROM1 (table rel_itp)
WHERE (castPred (combine (right⋅itp_np)
(e2p (constantExpr i1000)))
predicates.gt)))
(table rel_itm))
WHERE (equal (uvariable (right⋅left⋅left))
(uvariable (right⋅right⋅itm_itemno))) : SQL Γ _) =
denoteSQL
(DISTINCT (SELECT1 (combine (right⋅left⋅itp_np)
(combine (right⋅right⋅itm_type)
(right⋅right⋅itm_itemno)))
FROM1 (product (table rel_itp)
(table rel_itm))
WHERE (and (castPred (combine (right⋅left⋅itp_np)
(e2p (constantExpr i1000)))
predicates.gt)
(equal (uvariable (right⋅left⋅itp_itemno))
(uvariable (right⋅right⋅itm_itemno))))) : SQL Γ _) :=
begin
intros,
unfold_all_denotations,
funext,
unfold pair,
simp,
sorry
end |
210115b3c9db63b6c9dbebce0384dccf99497431 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/data/equiv/ring.lean | 90a380861c9ea216c39ea3dc6a4a404fd8566385 | [
"Apache-2.0"
] | permissive | waynemunro/mathlib | e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552 | 065a70810b5480d584033f7bbf8e0409480c2118 | refs/heads/master | 1,693,417,182,397 | 1,634,644,781,000 | 1,634,644,781,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 16,774 | 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, Callum Sutton, Yury Kudryashov
-/
import data.equiv.mul_add
import algebra.field
import algebra.opposites
import algebra.big_operators.basic
/-!
# (Semi)ring equivs
In this file we define extension of `equiv` called `ring_equiv`, which is a datatype representing an
isomorphism of `semiring`s, `ring`s, `division_ring`s, or `field`s. We also introduce the
corresponding group of automorphisms `ring_aut`.
## Notations
* ``infix ` ≃+* `:25 := ring_equiv``
The extended equiv have coercions to functions, and the coercion is the canonical notation when
treating the isomorphism as maps.
## Implementation notes
The fields for `ring_equiv` now avoid the unbundled `is_mul_hom` and `is_add_hom`, as these are
deprecated.
Definition of multiplication in the groups of automorphisms agrees with function composition,
multiplication in `equiv.perm`, and multiplication in `category_theory.End`, not with
`category_theory.comp`.
## Tags
equiv, mul_equiv, add_equiv, ring_equiv, mul_aut, add_aut, ring_aut
-/
open_locale big_operators
variables {R : Type*} {S : Type*} {S' : Type*}
set_option old_structure_cmd true
/-- An equivalence between two (semi)rings that preserves the algebraic structure. -/
structure ring_equiv (R S : Type*) [has_mul R] [has_add R] [has_mul S] [has_add S]
extends R ≃ S, R ≃* S, R ≃+ S
infix ` ≃+* `:25 := ring_equiv
/-- The "plain" equivalence of types underlying an equivalence of (semi)rings. -/
add_decl_doc ring_equiv.to_equiv
/-- The equivalence of additive monoids underlying an equivalence of (semi)rings. -/
add_decl_doc ring_equiv.to_add_equiv
/-- The equivalence of multiplicative monoids underlying an equivalence of (semi)rings. -/
add_decl_doc ring_equiv.to_mul_equiv
namespace ring_equiv
section basic
variables [has_mul R] [has_add R] [has_mul S] [has_add S] [has_mul S'] [has_add S']
instance : has_coe_to_fun (R ≃+* S) := ⟨_, ring_equiv.to_fun⟩
@[simp] lemma to_fun_eq_coe (f : R ≃+* S) : f.to_fun = f := rfl
/-- A ring isomorphism preserves multiplication. -/
@[simp] lemma map_mul (e : R ≃+* S) (x y : R) : e (x * y) = e x * e y := e.map_mul' x y
/-- A ring isomorphism preserves addition. -/
@[simp] lemma map_add (e : R ≃+* S) (x y : R) : e (x + y) = e x + e y := e.map_add' x y
/-- Two ring isomorphisms agree if they are defined by the
same underlying function. -/
@[ext] lemma ext {f g : R ≃+* S} (h : ∀ x, f x = g x) : f = g :=
begin
have h₁ : f.to_equiv = g.to_equiv := equiv.ext h,
cases f, cases g, congr,
{ exact (funext h) },
{ exact congr_arg equiv.inv_fun h₁ }
end
@[simp] theorem coe_mk (e e' h₁ h₂ h₃ h₄) :
⇑(⟨e, e', h₁, h₂, h₃, h₄⟩ : R ≃+* S) = e := rfl
@[simp] theorem mk_coe (e : R ≃+* S) (e' h₁ h₂ h₃ h₄) :
(⟨e, e', h₁, h₂, h₃, h₄⟩ : R ≃+* S) = e := ext $ λ _, rfl
protected lemma congr_arg {f : R ≃+* S} : Π {x x' : R}, x = x' → f x = f x'
| _ _ rfl := rfl
protected lemma congr_fun {f g : R ≃+* S} (h : f = g) (x : R) : f x = g x := h ▸ rfl
lemma ext_iff {f g : R ≃+* S} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, ext⟩
instance has_coe_to_mul_equiv : has_coe (R ≃+* S) (R ≃* S) := ⟨ring_equiv.to_mul_equiv⟩
instance has_coe_to_add_equiv : has_coe (R ≃+* S) (R ≃+ S) := ⟨ring_equiv.to_add_equiv⟩
lemma to_add_equiv_eq_coe (f : R ≃+* S) : f.to_add_equiv = ↑f := rfl
lemma to_mul_equiv_eq_coe (f : R ≃+* S) : f.to_mul_equiv = ↑f := rfl
@[simp, norm_cast] lemma coe_to_mul_equiv (f : R ≃+* S) : ⇑(f : R ≃* S) = f := rfl
@[simp, norm_cast] lemma coe_to_add_equiv (f : R ≃+* S) : ⇑(f : R ≃+ S) = f := rfl
/-- The `ring_equiv` between two semirings with a unique element. -/
def ring_equiv_of_unique_of_unique {M N}
[unique M] [unique N] [has_add M] [has_mul M] [has_add N] [has_mul N] : M ≃+* N :=
{ ..add_equiv.add_equiv_of_unique_of_unique,
..mul_equiv.mul_equiv_of_unique_of_unique}
instance {M N} [unique M] [unique N] [has_add M] [has_mul M] [has_add N] [has_mul N] :
unique (M ≃+* N) :=
{ default := ring_equiv_of_unique_of_unique,
uniq := λ _, ext $ λ x, subsingleton.elim _ _ }
variable (R)
/-- The identity map is a ring isomorphism. -/
@[refl] protected def refl : R ≃+* R := { .. mul_equiv.refl R, .. add_equiv.refl R }
@[simp] lemma refl_apply (x : R) : ring_equiv.refl R x = x := rfl
@[simp] lemma coe_add_equiv_refl : (ring_equiv.refl R : R ≃+ R) = add_equiv.refl R := rfl
@[simp] lemma coe_mul_equiv_refl : (ring_equiv.refl R : R ≃* R) = mul_equiv.refl R := rfl
instance : inhabited (R ≃+* R) := ⟨ring_equiv.refl R⟩
variables {R}
/-- The inverse of a ring isomorphism is a ring isomorphism. -/
@[symm] protected def symm (e : R ≃+* S) : S ≃+* R :=
{ .. e.to_mul_equiv.symm, .. e.to_add_equiv.symm }
/-- See Note [custom simps projection] -/
def simps.symm_apply (e : R ≃+* S) : S → R := e.symm
initialize_simps_projections ring_equiv (to_fun → apply, inv_fun → symm_apply)
@[simp] lemma symm_symm (e : R ≃+* S) : e.symm.symm = e := ext $ λ x, rfl
lemma symm_bijective : function.bijective (ring_equiv.symm : (R ≃+* S) → (S ≃+* R)) :=
equiv.bijective ⟨ring_equiv.symm, ring_equiv.symm, symm_symm, symm_symm⟩
@[simp] lemma mk_coe' (e : R ≃+* S) (f h₁ h₂ h₃ h₄) :
(ring_equiv.mk f ⇑e h₁ h₂ h₃ h₄ : S ≃+* R) = e.symm :=
symm_bijective.injective $ ext $ λ x, rfl
@[simp] lemma symm_mk (f : R → S) (g h₁ h₂ h₃ h₄) :
(mk f g h₁ h₂ h₃ h₄).symm =
{ to_fun := g, inv_fun := f, ..(mk f g h₁ h₂ h₃ h₄).symm} := rfl
/-- Transitivity of `ring_equiv`. -/
@[trans] protected def trans (e₁ : R ≃+* S) (e₂ : S ≃+* S') : R ≃+* S' :=
{ .. (e₁.to_mul_equiv.trans e₂.to_mul_equiv), .. (e₁.to_add_equiv.trans e₂.to_add_equiv) }
@[simp] lemma trans_apply (e₁ : R ≃+* S) (e₂ : S ≃+* S') (a : R) :
e₁.trans e₂ a = e₂ (e₁ a) := rfl
protected lemma bijective (e : R ≃+* S) : function.bijective e := e.to_equiv.bijective
protected lemma injective (e : R ≃+* S) : function.injective e := e.to_equiv.injective
protected lemma surjective (e : R ≃+* S) : function.surjective e := e.to_equiv.surjective
@[simp] lemma apply_symm_apply (e : R ≃+* S) : ∀ x, e (e.symm x) = x := e.to_equiv.apply_symm_apply
@[simp] lemma symm_apply_apply (e : R ≃+* S) : ∀ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply
lemma image_eq_preimage (e : R ≃+* S) (s : set R) : e '' s = e.symm ⁻¹' s :=
e.to_equiv.image_eq_preimage s
end basic
section opposite
open opposite
/-- A ring iso `α ≃+* β` can equivalently be viewed as a ring iso `αᵒᵖ ≃+* βᵒᵖ`. -/
@[simps]
protected def op {α β} [has_add α] [has_mul α] [has_add β] [has_mul β] :
(α ≃+* β) ≃ (αᵒᵖ ≃+* βᵒᵖ) :=
{ to_fun := λ f, { ..f.to_add_equiv.op, ..f.to_mul_equiv.op},
inv_fun := λ f, { ..(add_equiv.op.symm f.to_add_equiv), ..(mul_equiv.op.symm f.to_mul_equiv) },
left_inv := λ f, by { ext, refl },
right_inv := λ f, by { ext, refl } }
/-- The 'unopposite' of a ring iso `αᵒᵖ ≃+* βᵒᵖ`. Inverse to `ring_equiv.op`. -/
@[simp] protected def unop {α β} [has_add α] [has_mul α] [has_add β] [has_mul β] :
(αᵒᵖ ≃+* βᵒᵖ) ≃ (α ≃+* β) := ring_equiv.op.symm
section comm_semiring
variables (R) [comm_semiring R]
/-- A commutative ring is isomorphic to its opposite. -/
def to_opposite : R ≃+* Rᵒᵖ :=
{ map_add' := λ x y, rfl,
map_mul' := λ x y, mul_comm (op y) (op x),
..equiv_to_opposite }
@[simp]
lemma to_opposite_apply (r : R) : to_opposite R r = op r := rfl
@[simp]
lemma to_opposite_symm_apply (r : Rᵒᵖ) : (to_opposite R).symm r = unop r := rfl
end comm_semiring
end opposite
section non_unital_semiring
variables [non_unital_non_assoc_semiring R] [non_unital_non_assoc_semiring S]
(f : R ≃+* S) (x y : R)
/-- A ring isomorphism sends zero to zero. -/
@[simp] lemma map_zero : f 0 = 0 := (f : R ≃+ S).map_zero
variable {x}
@[simp] lemma map_eq_zero_iff : f x = 0 ↔ x = 0 := (f : R ≃+ S).map_eq_zero_iff
lemma map_ne_zero_iff : f x ≠ 0 ↔ x ≠ 0 := (f : R ≃+ S).map_ne_zero_iff
end non_unital_semiring
section semiring
variables [non_assoc_semiring R] [non_assoc_semiring S] (f : R ≃+* S) (x y : R)
/-- A ring isomorphism sends one to one. -/
@[simp] lemma map_one : f 1 = 1 := (f : R ≃* S).map_one
variable {x}
@[simp] lemma map_eq_one_iff : f x = 1 ↔ x = 1 := (f : R ≃* S).map_eq_one_iff
lemma map_ne_one_iff : f x ≠ 1 ↔ x ≠ 1 := (f : R ≃* S).map_ne_one_iff
/-- Produce a ring isomorphism from a bijective ring homomorphism. -/
noncomputable def of_bijective (f : R →+* S) (hf : function.bijective f) : R ≃+* S :=
{ .. equiv.of_bijective f hf, .. f }
@[simp] lemma coe_of_bijective (f : R →+* S) (hf : function.bijective f) :
(of_bijective f hf : R → S) = f := rfl
lemma of_bijective_apply (f : R →+* S) (hf : function.bijective f) (x : R) :
of_bijective f hf x = f x := rfl
end semiring
section
variables [ring R] [ring S] (f : R ≃+* S) (x y : R)
@[simp] lemma map_neg : f (-x) = -f x := (f : R ≃+ S).map_neg x
@[simp] lemma map_sub : f (x - y) = f x - f y := (f : R ≃+ S).map_sub x y
@[simp] lemma map_neg_one : f (-1) = -1 := f.map_one ▸ f.map_neg 1
end
section semiring_hom
variables [non_assoc_semiring R] [non_assoc_semiring S] [non_assoc_semiring S']
/-- Reinterpret a ring equivalence as a ring homomorphism. -/
def to_ring_hom (e : R ≃+* S) : R →+* S :=
{ .. e.to_mul_equiv.to_monoid_hom, .. e.to_add_equiv.to_add_monoid_hom }
lemma to_ring_hom_injective : function.injective (to_ring_hom : (R ≃+* S) → R →+* S) :=
λ f g h, ring_equiv.ext (ring_hom.ext_iff.1 h)
instance has_coe_to_ring_hom : has_coe (R ≃+* S) (R →+* S) := ⟨ring_equiv.to_ring_hom⟩
lemma to_ring_hom_eq_coe (f : R ≃+* S) : f.to_ring_hom = ↑f := rfl
@[simp, norm_cast] lemma coe_to_ring_hom (f : R ≃+* S) : ⇑(f : R →+* S) = f := rfl
lemma coe_ring_hom_inj_iff {R S : Type*} [non_assoc_semiring R] [non_assoc_semiring S]
(f g : R ≃+* S) :
f = g ↔ (f : R →+* S) = g :=
⟨congr_arg _, λ h, ext $ ring_hom.ext_iff.mp h⟩
/-- Reinterpret a ring equivalence as a monoid homomorphism. -/
abbreviation to_monoid_hom (e : R ≃+* S) : R →* S := e.to_ring_hom.to_monoid_hom
/-- Reinterpret a ring equivalence as an `add_monoid` homomorphism. -/
abbreviation to_add_monoid_hom (e : R ≃+* S) : R →+ S := e.to_ring_hom.to_add_monoid_hom
/-- The two paths coercion can take to an `add_monoid_hom` are equivalent -/
lemma to_add_monoid_hom_commutes (f : R ≃+* S) :
(f : R →+* S).to_add_monoid_hom = (f : R ≃+ S).to_add_monoid_hom :=
rfl
/-- The two paths coercion can take to an `monoid_hom` are equivalent -/
lemma to_monoid_hom_commutes (f : R ≃+* S) :
(f : R →+* S).to_monoid_hom = (f : R ≃* S).to_monoid_hom :=
rfl
/-- The two paths coercion can take to an `equiv` are equivalent -/
lemma to_equiv_commutes (f : R ≃+* S) :
(f : R ≃+ S).to_equiv = (f : R ≃* S).to_equiv :=
rfl
@[simp]
lemma to_ring_hom_refl : (ring_equiv.refl R).to_ring_hom = ring_hom.id R := rfl
@[simp]
lemma to_monoid_hom_refl : (ring_equiv.refl R).to_monoid_hom = monoid_hom.id R := rfl
@[simp]
lemma to_add_monoid_hom_refl : (ring_equiv.refl R).to_add_monoid_hom = add_monoid_hom.id R := rfl
@[simp]
lemma to_ring_hom_apply_symm_to_ring_hom_apply (e : R ≃+* S) :
∀ (y : S), e.to_ring_hom (e.symm.to_ring_hom y) = y :=
e.to_equiv.apply_symm_apply
@[simp]
lemma symm_to_ring_hom_apply_to_ring_hom_apply (e : R ≃+* S) :
∀ (x : R), e.symm.to_ring_hom (e.to_ring_hom x) = x :=
equiv.symm_apply_apply (e.to_equiv)
@[simp]
lemma to_ring_hom_trans (e₁ : R ≃+* S) (e₂ : S ≃+* S') :
(e₁.trans e₂).to_ring_hom = e₂.to_ring_hom.comp e₁.to_ring_hom := rfl
@[simp]
lemma to_ring_hom_comp_symm_to_ring_hom (e : R ≃+* S) :
e.to_ring_hom.comp e.symm.to_ring_hom = ring_hom.id _ :=
by { ext, simp }
@[simp]
lemma symm_to_ring_hom_comp_to_ring_hom (e : R ≃+* S) :
e.symm.to_ring_hom.comp e.to_ring_hom = ring_hom.id _ :=
by { ext, simp }
/--
Construct an equivalence of rings from homomorphisms in both directions, which are inverses.
-/
def of_hom_inv (hom : R →+* S) (inv : S →+* R)
(hom_inv_id : inv.comp hom = ring_hom.id R) (inv_hom_id : hom.comp inv = ring_hom.id S) :
R ≃+* S :=
{ inv_fun := inv,
left_inv := λ x, ring_hom.congr_fun hom_inv_id x,
right_inv := λ x, ring_hom.congr_fun inv_hom_id x,
..hom }
@[simp]
lemma of_hom_inv_apply (hom : R →+* S) (inv : S →+* R) (hom_inv_id inv_hom_id) (r : R) :
(of_hom_inv hom inv hom_inv_id inv_hom_id) r = hom r := rfl
@[simp]
lemma of_hom_inv_symm_apply (hom : R →+* S) (inv : S →+* R) (hom_inv_id inv_hom_id) (s : S) :
(of_hom_inv hom inv hom_inv_id inv_hom_id).symm s = inv s := rfl
end semiring_hom
section big_operators
lemma map_list_prod [semiring R] [semiring S] (f : R ≃+* S) (l : list R) :
f l.prod = (l.map f).prod := f.to_ring_hom.map_list_prod l
lemma map_list_sum [non_assoc_semiring R] [non_assoc_semiring S] (f : R ≃+* S) (l : list R) :
f l.sum = (l.map f).sum := f.to_ring_hom.map_list_sum l
lemma map_multiset_prod [comm_semiring R] [comm_semiring S] (f : R ≃+* S) (s : multiset R) :
f s.prod = (s.map f).prod := f.to_ring_hom.map_multiset_prod s
lemma map_multiset_sum [non_assoc_semiring R] [non_assoc_semiring S]
(f : R ≃+* S) (s : multiset R) : f s.sum = (s.map f).sum := f.to_ring_hom.map_multiset_sum s
lemma map_prod {α : Type*} [comm_semiring R] [comm_semiring S] (g : R ≃+* S) (f : α → R)
(s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) :=
g.to_ring_hom.map_prod f s
lemma map_sum {α : Type*} [non_assoc_semiring R] [non_assoc_semiring S]
(g : R ≃+* S) (f : α → R) (s : finset α) : g (∑ x in s, f x) = ∑ x in s, g (f x) :=
g.to_ring_hom.map_sum f s
end big_operators
section division_ring
variables {K K' : Type*} [division_ring K] [division_ring K']
(g : K ≃+* K') (x y : K)
lemma map_inv : g x⁻¹ = (g x)⁻¹ := g.to_ring_hom.map_inv x
lemma map_div : g (x / y) = g x / g y := g.to_ring_hom.map_div x y
end division_ring
section group_power
variables [semiring R] [semiring S]
@[simp] lemma map_pow (f : R ≃+* S) (a) :
∀ n : ℕ, f (a ^ n) = (f a) ^ n :=
f.to_ring_hom.map_pow a
end group_power
end ring_equiv
namespace mul_equiv
/-- Gives a `ring_equiv` from a `mul_equiv` preserving addition.-/
def to_ring_equiv {R : Type*} {S : Type*} [has_add R] [has_add S] [has_mul R] [has_mul S]
(h : R ≃* S) (H : ∀ x y : R, h (x + y) = h x + h y) : R ≃+* S :=
{..h.to_equiv, ..h, ..add_equiv.mk' h.to_equiv H }
end mul_equiv
namespace ring_equiv
variables [has_add R] [has_add S] [has_mul R] [has_mul S]
@[simp] theorem trans_symm (e : R ≃+* S) : e.trans e.symm = ring_equiv.refl R := ext e.3
@[simp] theorem symm_trans (e : R ≃+* S) : e.symm.trans e = ring_equiv.refl S := ext e.4
/-- If two rings are isomorphic, and the second is an integral domain, then so is the first. -/
protected lemma is_integral_domain {A : Type*} (B : Type*) [ring A] [ring B]
(hB : is_integral_domain B) (e : A ≃+* B) : is_integral_domain A :=
{ mul_comm := λ x y, have e.symm (e x * e y) = e.symm (e y * e x), by rw hB.mul_comm, by simpa,
eq_zero_or_eq_zero_of_mul_eq_zero := λ x y hxy,
have e x * e y = 0, by rw [← e.map_mul, hxy, e.map_zero],
(hB.eq_zero_or_eq_zero_of_mul_eq_zero _ _ this).imp (λ hx, by simpa using congr_arg e.symm hx)
(λ hy, by simpa using congr_arg e.symm hy),
exists_pair_ne := ⟨e.symm 0, e.symm 1,
by { haveI : nontrivial B := hB.to_nontrivial, exact e.symm.injective.ne zero_ne_one }⟩ }
/-- If two rings are isomorphic, and the second is an integral domain, then so is the first. -/
protected lemma integral_domain
{A : Type*} (B : Type*) [comm_ring A] [comm_ring B] [integral_domain B]
(e : A ≃+* B) : integral_domain A :=
{ .. e.is_integral_domain B (integral_domain.to_is_integral_domain B) }
end ring_equiv
namespace equiv
variables (K : Type*) [division_ring K]
/-- In a division ring `K`, the unit group `units K`
is equivalent to the subtype of nonzero elements. -/
-- TODO: this might already exist elsewhere for `group_with_zero`
-- deduplicate or generalize
def units_equiv_ne_zero : units K ≃ {a : K | a ≠ 0} :=
⟨λ a, ⟨a.1, a.ne_zero⟩, λ a, units.mk0 _ a.2, λ ⟨_, _, _, _⟩, units.ext rfl, λ ⟨_, _⟩, rfl⟩
variable {K}
@[simp]
lemma coe_units_equiv_ne_zero (a : units K) :
((units_equiv_ne_zero K a) : K) = a := rfl
end equiv
|
2ea3c894284d2078ac39dfb71e65ecd1e6196d92 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/limits/shapes/constructions/finite_products_of_binary_products.lean | c5423187feb8e7146d380ac538c21a0858106ecd | [] | 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 | 5,325 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.limits.shapes.finite_products
import Mathlib.category_theory.limits.shapes.binary_products
import Mathlib.category_theory.limits.preserves.shapes.products
import Mathlib.category_theory.limits.preserves.shapes.binary_products
import Mathlib.category_theory.limits.shapes.pullbacks
import Mathlib.category_theory.pempty
import Mathlib.data.equiv.fin
import Mathlib.PostPort
universes v u u'
namespace Mathlib
/-!
# Constructing finite products from binary products and terminal.
If a category has binary products and a terminal object then it has finite products.
If a functor preserves binary products and the terminal object then it preserves finite products.
# TODO
Provide the dual results.
Show the analogous results for functors which reflect or create (co)limits.
-/
namespace category_theory
/--
Given `n+1` objects of `C`, a fan for the last `n` with point `c₁.X` and a binary fan on `c₁.X` and
`f 0`, we can build a fan for all `n+1`.
In `extend_fan_is_limit` we show that if the two given fans are limits, then this fan is also a
limit.
-/
@[simp] theorem extend_fan_X {C : Type u} [category C] {n : ℕ} {f : ulift (fin (n + 1)) → C} (c₁ : limits.fan fun (i : ulift (fin n)) => f (ulift.up (fin.succ (ulift.down i)))) (c₂ : limits.binary_fan (f (ulift.up 0)) (limits.cone.X c₁)) : limits.cone.X (extend_fan c₁ c₂) = limits.cone.X c₂ :=
Eq.refl (limits.cone.X (extend_fan c₁ c₂))
/--
Show that if the two given fans in `extend_fan` are limits, then the constructed fan is also a
limit.
-/
def extend_fan_is_limit {C : Type u} [category C] {n : ℕ} (f : ulift (fin (n + 1)) → C) {c₁ : limits.fan fun (i : ulift (fin n)) => f (ulift.up (fin.succ (ulift.down i)))} {c₂ : limits.binary_fan (f (ulift.up 0)) (limits.cone.X c₁)} (t₁ : limits.is_limit c₁) (t₂ : limits.is_limit c₂) : limits.is_limit (extend_fan c₁ c₂) :=
limits.is_limit.mk
fun (s : limits.cone (discrete.functor f)) =>
subtype.val
(limits.binary_fan.is_limit.lift' t₂ (nat_trans.app (limits.cone.π s) (ulift.up 0))
(limits.is_limit.lift t₁
(limits.cone.mk (limits.cone.X s)
(discrete.nat_trans
fun (i : discrete (ulift (fin n))) =>
nat_trans.app (limits.cone.π s) (ulift.up (fin.succ (ulift.down i)))))))
/--
If `C` has a terminal object and binary products, then it has a product for objects indexed by
`ulift (fin n)`.
This is a helper lemma for `has_finite_products_of_has_binary_and_terminal`, which is more general
than this.
-/
/--
If `C` has a terminal object and binary products, then it has limits of shape
`discrete (ulift (fin n))` for any `n : ℕ`.
This is a helper lemma for `has_finite_products_of_has_binary_and_terminal`, which is more general
than this.
-/
/-- If `C` has a terminal object and binary products, then it has finite products. -/
theorem has_finite_products_of_has_binary_and_terminal {C : Type u} [category C] [limits.has_binary_products C] [limits.has_terminal C] : limits.has_finite_products C := sorry
/--
If `F` preserves the terminal object and binary products, then it preserves products indexed by
`ulift (fin n)` for any `n`.
-/
def preserves_fin_of_preserves_binary_and_terminal {C : Type u} [category C] {D : Type u'} [category D] (F : C ⥤ D) [limits.preserves_limits_of_shape (discrete limits.walking_pair) F] [limits.preserves_limits_of_shape (discrete pempty) F] [limits.has_finite_products C] (n : ℕ) (f : ulift (fin n) → C) : limits.preserves_limit (discrete.functor f) F :=
sorry
/--
If `F` preserves the terminal object and binary products, then it preserves limits of shape
`discrete (ulift (fin n))`.
-/
def preserves_ulift_fin_of_preserves_binary_and_terminal {C : Type u} [category C] {D : Type u'} [category D] (F : C ⥤ D) [limits.preserves_limits_of_shape (discrete limits.walking_pair) F] [limits.preserves_limits_of_shape (discrete pempty) F] [limits.has_finite_products C] (n : ℕ) : limits.preserves_limits_of_shape (discrete (ulift (fin n))) F :=
limits.preserves_limits_of_shape.mk
fun (K : discrete (ulift (fin n)) ⥤ C) =>
let this : discrete.functor (functor.obj K) ≅ K :=
discrete.nat_iso
fun (i : discrete (discrete (ulift (fin n)))) => iso.refl (functor.obj (discrete.functor (functor.obj K)) i);
limits.preserves_limit_of_iso_diagram F this
/-- If `F` preserves the terminal object and binary products then it preserves finite products. -/
def preserves_finite_products_of_preserves_binary_and_terminal {C : Type u} [category C] {D : Type u'} [category D] (F : C ⥤ D) [limits.preserves_limits_of_shape (discrete limits.walking_pair) F] [limits.preserves_limits_of_shape (discrete pempty) F] [limits.has_finite_products C] (J : Type v) [fintype J] : limits.preserves_limits_of_shape (discrete J) F :=
trunc.rec_on_subsingleton (fintype.equiv_fin J)
fun (e : J ≃ fin (fintype.card J)) =>
limits.preserves_limits_of_shape_of_equiv
(equivalence.symm (discrete.equivalence (equiv.trans e (equiv.symm equiv.ulift)))) F
|
19b93a1a1afebd7e1dfd9410b790bd1ac06b3324 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/linear_algebra/affine_space/affine_subspace.lean | b65614f1633c21a9ff5a4bc72677e5d33939c78a | [
"Apache-2.0"
] | permissive | urkud/mathlib | eab80095e1b9f1513bfb7f25b4fa82fa4fd02989 | 6379d39e6b5b279df9715f8011369a301b634e41 | refs/heads/master | 1,658,425,342,662 | 1,658,078,703,000 | 1,658,078,703,000 | 186,910,338 | 0 | 0 | Apache-2.0 | 1,568,512,083,000 | 1,557,958,709,000 | Lean | UTF-8 | Lean | false | false | 55,497 | lean | /-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers
-/
import data.set.intervals.unordered_interval
import linear_algebra.affine_space.affine_equiv
/-!
# Affine spaces
This file defines affine subspaces (over modules) and the affine span of a set of points.
## Main definitions
* `affine_subspace k P` is the type of affine subspaces. Unlike
affine spaces, affine subspaces are allowed to be empty, and lemmas
that do not apply to empty affine subspaces have `nonempty`
hypotheses. There is a `complete_lattice` structure on affine
subspaces.
* `affine_subspace.direction` gives the `submodule` spanned by the
pairwise differences of points in an `affine_subspace`. There are
various lemmas relating to the set of vectors in the `direction`,
and relating the lattice structure on affine subspaces to that on
their directions.
* `affine_span` gives the affine subspace spanned by a set of points,
with `vector_span` giving its direction. `affine_span` is defined
in terms of `span_points`, which gives an explicit description of
the points contained in the affine span; `span_points` itself should
generally only be used when that description is required, with
`affine_span` being the main definition for other purposes. Two
other descriptions of the affine span are proved equivalent: it is
the `Inf` of affine subspaces containing the points, and (if
`[nontrivial k]`) it contains exactly those points that are affine
combinations of points in the given set.
## Implementation notes
`out_param` is used in the definiton of `add_torsor V P` to make `V` an implicit argument (deduced
from `P`) in most cases; `include V` is needed in many cases for `V`, and type classes using it, to
be added as implicit arguments to individual lemmas. As for modules, `k` is an explicit argument
rather than implied by `P` or `V`.
This file only provides purely algebraic definitions and results.
Those depending on analysis or topology are defined elsewhere; see
`analysis.normed_space.add_torsor` and `topology.algebra.affine`.
## References
* https://en.wikipedia.org/wiki/Affine_space
* https://en.wikipedia.org/wiki/Principal_homogeneous_space
-/
noncomputable theory
open_locale big_operators classical affine
open set
section
variables (k : Type*) {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V]
variables [affine_space V P]
include V
/-- The submodule spanning the differences of a (possibly empty) set
of points. -/
def vector_span (s : set P) : submodule k V := submodule.span k (s -ᵥ s)
/-- The definition of `vector_span`, for rewriting. -/
lemma vector_span_def (s : set P) : vector_span k s = submodule.span k (s -ᵥ s) :=
rfl
/-- `vector_span` is monotone. -/
lemma vector_span_mono {s₁ s₂ : set P} (h : s₁ ⊆ s₂) : vector_span k s₁ ≤ vector_span k s₂ :=
submodule.span_mono (vsub_self_mono h)
variables (P)
/-- The `vector_span` of the empty set is `⊥`. -/
@[simp] lemma vector_span_empty : vector_span k (∅ : set P) = (⊥ : submodule k V) :=
by rw [vector_span_def, vsub_empty, submodule.span_empty]
variables {P}
/-- The `vector_span` of a single point is `⊥`. -/
@[simp] lemma vector_span_singleton (p : P) : vector_span k ({p} : set P) = ⊥ :=
by simp [vector_span_def]
/-- The `s -ᵥ s` lies within the `vector_span k s`. -/
lemma vsub_set_subset_vector_span (s : set P) : s -ᵥ s ⊆ ↑(vector_span k s) :=
submodule.subset_span
/-- Each pairwise difference is in the `vector_span`. -/
lemma vsub_mem_vector_span {s : set P} {p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) :
p1 -ᵥ p2 ∈ vector_span k s :=
vsub_set_subset_vector_span k s (vsub_mem_vsub hp1 hp2)
/-- The points in the affine span of a (possibly empty) set of
points. Use `affine_span` instead to get an `affine_subspace k P`. -/
def span_points (s : set P) : set P :=
{p | ∃ p1 ∈ s, ∃ v ∈ (vector_span k s), p = v +ᵥ p1}
/-- A point in a set is in its affine span. -/
lemma mem_span_points (p : P) (s : set P) : p ∈ s → p ∈ span_points k s
| hp := ⟨p, hp, 0, submodule.zero_mem _, (zero_vadd V p).symm⟩
/-- A set is contained in its `span_points`. -/
lemma subset_span_points (s : set P) : s ⊆ span_points k s :=
λ p, mem_span_points k p s
/-- The `span_points` of a set is nonempty if and only if that set
is. -/
@[simp] lemma span_points_nonempty (s : set P) :
(span_points k s).nonempty ↔ s.nonempty :=
begin
split,
{ contrapose,
rw [set.not_nonempty_iff_eq_empty, set.not_nonempty_iff_eq_empty],
intro h,
simp [h, span_points] },
{ exact λ h, h.mono (subset_span_points _ _) }
end
/-- Adding a point in the affine span and a vector in the spanning
submodule produces a point in the affine span. -/
lemma vadd_mem_span_points_of_mem_span_points_of_mem_vector_span {s : set P} {p : P} {v : V}
(hp : p ∈ span_points k s) (hv : v ∈ vector_span k s) : v +ᵥ p ∈ span_points k s :=
begin
rcases hp with ⟨p2, ⟨hp2, ⟨v2, ⟨hv2, hv2p⟩⟩⟩⟩,
rw [hv2p, vadd_vadd],
use [p2, hp2, v + v2, (vector_span k s).add_mem hv hv2, rfl]
end
/-- Subtracting two points in the affine span produces a vector in the
spanning submodule. -/
lemma vsub_mem_vector_span_of_mem_span_points_of_mem_span_points {s : set P} {p1 p2 : P}
(hp1 : p1 ∈ span_points k s) (hp2 : p2 ∈ span_points k s) :
p1 -ᵥ p2 ∈ vector_span k s :=
begin
rcases hp1 with ⟨p1a, ⟨hp1a, ⟨v1, ⟨hv1, hv1p⟩⟩⟩⟩,
rcases hp2 with ⟨p2a, ⟨hp2a, ⟨v2, ⟨hv2, hv2p⟩⟩⟩⟩,
rw [hv1p, hv2p, vsub_vadd_eq_vsub_sub (v1 +ᵥ p1a), vadd_vsub_assoc, add_comm, add_sub_assoc],
have hv1v2 : v1 - v2 ∈ vector_span k s,
{ rw sub_eq_add_neg,
apply (vector_span k s).add_mem hv1,
rw ←neg_one_smul k v2,
exact (vector_span k s).smul_mem (-1 : k) hv2 },
refine (vector_span k s).add_mem _ hv1v2,
exact vsub_mem_vector_span k hp1a hp2a
end
end
/-- An `affine_subspace k P` is a subset of an `affine_space V P`
that, if not empty, has an affine space structure induced by a
corresponding subspace of the `module k V`. -/
structure affine_subspace (k : Type*) {V : Type*} (P : Type*) [ring k] [add_comm_group V]
[module k V] [affine_space V P] :=
(carrier : set P)
(smul_vsub_vadd_mem : ∀ (c : k) {p1 p2 p3 : P}, p1 ∈ carrier → p2 ∈ carrier → p3 ∈ carrier →
c • (p1 -ᵥ p2 : V) +ᵥ p3 ∈ carrier)
namespace submodule
variables {k V : Type*} [ring k] [add_comm_group V] [module k V]
/-- Reinterpret `p : submodule k V` as an `affine_subspace k V`. -/
def to_affine_subspace (p : submodule k V) : affine_subspace k V :=
{ carrier := p,
smul_vsub_vadd_mem := λ c p₁ p₂ p₃ h₁ h₂ h₃, p.add_mem (p.smul_mem _ (p.sub_mem h₁ h₂)) h₃ }
end submodule
namespace affine_subspace
variables (k : Type*) {V : Type*} (P : Type*) [ring k] [add_comm_group V] [module k V]
[affine_space V P]
include V
-- TODO Refactor to use `instance : set_like (affine_subspace k P) P :=` instead
instance : has_coe (affine_subspace k P) (set P) := ⟨carrier⟩
instance : has_mem P (affine_subspace k P) := ⟨λ p s, p ∈ (s : set P)⟩
/-- A point is in an affine subspace coerced to a set if and only if
it is in that affine subspace. -/
@[simp] lemma mem_coe (p : P) (s : affine_subspace k P) :
p ∈ (s : set P) ↔ p ∈ s :=
iff.rfl
variables {k P}
/-- The direction of an affine subspace is the submodule spanned by
the pairwise differences of points. (Except in the case of an empty
affine subspace, where the direction is the zero submodule, every
vector in the direction is the difference of two points in the affine
subspace.) -/
def direction (s : affine_subspace k P) : submodule k V := vector_span k (s : set P)
/-- The direction equals the `vector_span`. -/
lemma direction_eq_vector_span (s : affine_subspace k P) :
s.direction = vector_span k (s : set P) :=
rfl
/-- Alternative definition of the direction when the affine subspace
is nonempty. This is defined so that the order on submodules (as used
in the definition of `submodule.span`) can be used in the proof of
`coe_direction_eq_vsub_set`, and is not intended to be used beyond
that proof. -/
def direction_of_nonempty {s : affine_subspace k P} (h : (s : set P).nonempty) :
submodule k V :=
{ carrier := (s : set P) -ᵥ s,
zero_mem' := begin
cases h with p hp,
exact (vsub_self p) ▸ vsub_mem_vsub hp hp
end,
add_mem' := begin
intros a b ha hb,
rcases ha with ⟨p1, p2, hp1, hp2, rfl⟩,
rcases hb with ⟨p3, p4, hp3, hp4, rfl⟩,
rw [←vadd_vsub_assoc],
refine vsub_mem_vsub _ hp4,
convert s.smul_vsub_vadd_mem 1 hp1 hp2 hp3,
rw one_smul
end,
smul_mem' := begin
intros c v hv,
rcases hv with ⟨p1, p2, hp1, hp2, rfl⟩,
rw [←vadd_vsub (c • (p1 -ᵥ p2)) p2],
refine vsub_mem_vsub _ hp2,
exact s.smul_vsub_vadd_mem c hp1 hp2 hp2
end }
/-- `direction_of_nonempty` gives the same submodule as
`direction`. -/
lemma direction_of_nonempty_eq_direction {s : affine_subspace k P} (h : (s : set P).nonempty) :
direction_of_nonempty h = s.direction :=
le_antisymm (vsub_set_subset_vector_span k s) (submodule.span_le.2 set.subset.rfl)
/-- The set of vectors in the direction of a nonempty affine subspace
is given by `vsub_set`. -/
lemma coe_direction_eq_vsub_set {s : affine_subspace k P} (h : (s : set P).nonempty) :
(s.direction : set V) = (s : set P) -ᵥ s :=
direction_of_nonempty_eq_direction h ▸ rfl
/-- A vector is in the direction of a nonempty affine subspace if and
only if it is the subtraction of two vectors in the subspace. -/
lemma mem_direction_iff_eq_vsub {s : affine_subspace k P} (h : (s : set P).nonempty) (v : V) :
v ∈ s.direction ↔ ∃ p1 ∈ s, ∃ p2 ∈ s, v = p1 -ᵥ p2 :=
begin
rw [←set_like.mem_coe, coe_direction_eq_vsub_set h],
exact ⟨λ ⟨p1, p2, hp1, hp2, hv⟩, ⟨p1, hp1, p2, hp2, hv.symm⟩,
λ ⟨p1, hp1, p2, hp2, hv⟩, ⟨p1, p2, hp1, hp2, hv.symm⟩⟩
end
/-- Adding a vector in the direction to a point in the subspace
produces a point in the subspace. -/
lemma vadd_mem_of_mem_direction {s : affine_subspace k P} {v : V} (hv : v ∈ s.direction) {p : P}
(hp : p ∈ s) : v +ᵥ p ∈ s :=
begin
rw mem_direction_iff_eq_vsub ⟨p, hp⟩ at hv,
rcases hv with ⟨p1, hp1, p2, hp2, hv⟩,
rw hv,
convert s.smul_vsub_vadd_mem 1 hp1 hp2 hp,
rw one_smul
end
/-- Subtracting two points in the subspace produces a vector in the
direction. -/
lemma vsub_mem_direction {s : affine_subspace k P} {p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) :
(p1 -ᵥ p2) ∈ s.direction :=
vsub_mem_vector_span k hp1 hp2
/-- Adding a vector to a point in a subspace produces a point in the
subspace if and only if the vector is in the direction. -/
lemma vadd_mem_iff_mem_direction {s : affine_subspace k P} (v : V) {p : P} (hp : p ∈ s) :
v +ᵥ p ∈ s ↔ v ∈ s.direction :=
⟨λ h, by simpa using vsub_mem_direction h hp, λ h, vadd_mem_of_mem_direction h hp⟩
/-- Given a point in an affine subspace, the set of vectors in its
direction equals the set of vectors subtracting that point on the
right. -/
lemma coe_direction_eq_vsub_set_right {s : affine_subspace k P} {p : P} (hp : p ∈ s) :
(s.direction : set V) = (-ᵥ p) '' s :=
begin
rw coe_direction_eq_vsub_set ⟨p, hp⟩,
refine le_antisymm _ _,
{ rintros v ⟨p1, p2, hp1, hp2, rfl⟩,
exact ⟨p1 -ᵥ p2 +ᵥ p,
vadd_mem_of_mem_direction (vsub_mem_direction hp1 hp2) hp,
(vadd_vsub _ _)⟩ },
{ rintros v ⟨p2, hp2, rfl⟩,
exact ⟨p2, p, hp2, hp, rfl⟩ }
end
/-- Given a point in an affine subspace, the set of vectors in its
direction equals the set of vectors subtracting that point on the
left. -/
lemma coe_direction_eq_vsub_set_left {s : affine_subspace k P} {p : P} (hp : p ∈ s) :
(s.direction : set V) = (-ᵥ) p '' s :=
begin
ext v,
rw [set_like.mem_coe, ←submodule.neg_mem_iff, ←set_like.mem_coe,
coe_direction_eq_vsub_set_right hp, set.mem_image_iff_bex, set.mem_image_iff_bex],
conv_lhs { congr, funext, rw [←neg_vsub_eq_vsub_rev, neg_inj] }
end
/-- Given a point in an affine subspace, a vector is in its direction
if and only if it results from subtracting that point on the right. -/
lemma mem_direction_iff_eq_vsub_right {s : affine_subspace k P} {p : P} (hp : p ∈ s) (v : V) :
v ∈ s.direction ↔ ∃ p2 ∈ s, v = p2 -ᵥ p :=
begin
rw [←set_like.mem_coe, coe_direction_eq_vsub_set_right hp],
exact ⟨λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩, λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩⟩
end
/-- Given a point in an affine subspace, a vector is in its direction
if and only if it results from subtracting that point on the left. -/
lemma mem_direction_iff_eq_vsub_left {s : affine_subspace k P} {p : P} (hp : p ∈ s) (v : V) :
v ∈ s.direction ↔ ∃ p2 ∈ s, v = p -ᵥ p2 :=
begin
rw [←set_like.mem_coe, coe_direction_eq_vsub_set_left hp],
exact ⟨λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩, λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩⟩
end
/-- Given a point in an affine subspace, a result of subtracting that
point on the right is in the direction if and only if the other point
is in the subspace. -/
lemma vsub_right_mem_direction_iff_mem {s : affine_subspace k P} {p : P} (hp : p ∈ s) (p2 : P) :
p2 -ᵥ p ∈ s.direction ↔ p2 ∈ s :=
begin
rw mem_direction_iff_eq_vsub_right hp,
simp
end
/-- Given a point in an affine subspace, a result of subtracting that
point on the left is in the direction if and only if the other point
is in the subspace. -/
lemma vsub_left_mem_direction_iff_mem {s : affine_subspace k P} {p : P} (hp : p ∈ s) (p2 : P) :
p -ᵥ p2 ∈ s.direction ↔ p2 ∈ s :=
begin
rw mem_direction_iff_eq_vsub_left hp,
simp
end
/-- Two affine subspaces are equal if they have the same points. -/
@[ext] lemma coe_injective : function.injective (coe : affine_subspace k P → set P) :=
λ s1 s2 h, begin
cases s1,
cases s2,
congr,
exact h
end
@[simp] lemma ext_iff (s₁ s₂ : affine_subspace k P) :
(s₁ : set P) = s₂ ↔ s₁ = s₂ :=
⟨λ h, coe_injective h, by tidy⟩
/-- Two affine subspaces with the same direction and nonempty
intersection are equal. -/
lemma ext_of_direction_eq {s1 s2 : affine_subspace k P} (hd : s1.direction = s2.direction)
(hn : ((s1 : set P) ∩ s2).nonempty) : s1 = s2 :=
begin
ext p,
have hq1 := set.mem_of_mem_inter_left hn.some_mem,
have hq2 := set.mem_of_mem_inter_right hn.some_mem,
split,
{ intro hp,
rw ←vsub_vadd p hn.some,
refine vadd_mem_of_mem_direction _ hq2,
rw ←hd,
exact vsub_mem_direction hp hq1 },
{ intro hp,
rw ←vsub_vadd p hn.some,
refine vadd_mem_of_mem_direction _ hq1,
rw hd,
exact vsub_mem_direction hp hq2 }
end
instance to_add_torsor (s : affine_subspace k P) [nonempty s] : add_torsor s.direction s :=
{ vadd := λ a b, ⟨(a:V) +ᵥ (b:P), vadd_mem_of_mem_direction a.2 b.2⟩,
zero_vadd := by simp,
add_vadd := λ a b c, by { ext, apply add_vadd },
vsub := λ a b, ⟨(a:P) -ᵥ (b:P), (vsub_left_mem_direction_iff_mem a.2 _).mpr b.2 ⟩,
nonempty := by apply_instance,
vsub_vadd' := λ a b, by { ext, apply add_torsor.vsub_vadd' },
vadd_vsub' := λ a b, by { ext, apply add_torsor.vadd_vsub' } }
@[simp, norm_cast] lemma coe_vsub (s : affine_subspace k P) [nonempty s] (a b : s) :
↑(a -ᵥ b) = (a:P) -ᵥ (b:P) :=
rfl
@[simp, norm_cast] lemma coe_vadd (s : affine_subspace k P) [nonempty s] (a : s.direction) (b : s) :
↑(a +ᵥ b) = (a:V) +ᵥ (b:P) :=
rfl
/-- Two affine subspaces with nonempty intersection are equal if and
only if their directions are equal. -/
lemma eq_iff_direction_eq_of_mem {s₁ s₂ : affine_subspace k P} {p : P} (h₁ : p ∈ s₁)
(h₂ : p ∈ s₂) : s₁ = s₂ ↔ s₁.direction = s₂.direction :=
⟨λ h, h ▸ rfl, λ h, ext_of_direction_eq h ⟨p, h₁, h₂⟩⟩
/-- Construct an affine subspace from a point and a direction. -/
def mk' (p : P) (direction : submodule k V) : affine_subspace k P :=
{ carrier := {q | ∃ v ∈ direction, q = v +ᵥ p},
smul_vsub_vadd_mem := λ c p1 p2 p3 hp1 hp2 hp3, begin
rcases hp1 with ⟨v1, hv1, hp1⟩,
rcases hp2 with ⟨v2, hv2, hp2⟩,
rcases hp3 with ⟨v3, hv3, hp3⟩,
use [c • (v1 - v2) + v3,
direction.add_mem (direction.smul_mem c (direction.sub_mem hv1 hv2)) hv3],
simp [hp1, hp2, hp3, vadd_vadd]
end }
/-- An affine subspace constructed from a point and a direction contains
that point. -/
lemma self_mem_mk' (p : P) (direction : submodule k V) :
p ∈ mk' p direction :=
⟨0, ⟨direction.zero_mem, (zero_vadd _ _).symm⟩⟩
/-- An affine subspace constructed from a point and a direction contains
the result of adding a vector in that direction to that point. -/
lemma vadd_mem_mk' {v : V} (p : P) {direction : submodule k V} (hv : v ∈ direction) :
v +ᵥ p ∈ mk' p direction :=
⟨v, hv, rfl⟩
/-- An affine subspace constructed from a point and a direction is
nonempty. -/
lemma mk'_nonempty (p : P) (direction : submodule k V) : (mk' p direction : set P).nonempty :=
⟨p, self_mem_mk' p direction⟩
/-- The direction of an affine subspace constructed from a point and a
direction. -/
@[simp] lemma direction_mk' (p : P) (direction : submodule k V) :
(mk' p direction).direction = direction :=
begin
ext v,
rw mem_direction_iff_eq_vsub (mk'_nonempty _ _),
split,
{ rintros ⟨p1, ⟨v1, hv1, hp1⟩, p2, ⟨v2, hv2, hp2⟩, hv⟩,
rw [hv, hp1, hp2, vadd_vsub_vadd_cancel_right],
exact direction.sub_mem hv1 hv2 },
{ exact λ hv, ⟨v +ᵥ p, vadd_mem_mk' _ hv, p,
self_mem_mk' _ _, (vadd_vsub _ _).symm⟩ }
end
/-- Constructing an affine subspace from a point in a subspace and
that subspace's direction yields the original subspace. -/
@[simp] lemma mk'_eq {s : affine_subspace k P} {p : P} (hp : p ∈ s) : mk' p s.direction = s :=
ext_of_direction_eq (direction_mk' p s.direction)
⟨p, set.mem_inter (self_mem_mk' _ _) hp⟩
/-- If an affine subspace contains a set of points, it contains the
`span_points` of that set. -/
lemma span_points_subset_coe_of_subset_coe {s : set P} {s1 : affine_subspace k P} (h : s ⊆ s1) :
span_points k s ⊆ s1 :=
begin
rintros p ⟨p1, hp1, v, hv, hp⟩,
rw hp,
have hp1s1 : p1 ∈ (s1 : set P) := set.mem_of_mem_of_subset hp1 h,
refine vadd_mem_of_mem_direction _ hp1s1,
have hs : vector_span k s ≤ s1.direction := vector_span_mono k h,
rw set_like.le_def at hs,
rw ←set_like.mem_coe,
exact set.mem_of_mem_of_subset hv hs
end
end affine_subspace
lemma affine_map.line_map_mem
{k V P : Type*} [ring k] [add_comm_group V] [module k V] [add_torsor V P]
{Q : affine_subspace k P} {p₀ p₁ : P} (c : k) (h₀ : p₀ ∈ Q) (h₁ : p₁ ∈ Q) :
affine_map.line_map p₀ p₁ c ∈ Q :=
begin
rw affine_map.line_map_apply,
exact Q.smul_vsub_vadd_mem c h₁ h₀ h₀,
end
section affine_span
variables (k : Type*) {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V]
[affine_space V P]
include V
/-- The affine span of a set of points is the smallest affine subspace
containing those points. (Actually defined here in terms of spans in
modules.) -/
def affine_span (s : set P) : affine_subspace k P :=
{ carrier := span_points k s,
smul_vsub_vadd_mem := λ c p1 p2 p3 hp1 hp2 hp3,
vadd_mem_span_points_of_mem_span_points_of_mem_vector_span k hp3
((vector_span k s).smul_mem c
(vsub_mem_vector_span_of_mem_span_points_of_mem_span_points k hp1 hp2)) }
/-- The affine span, converted to a set, is `span_points`. -/
@[simp] lemma coe_affine_span (s : set P) :
(affine_span k s : set P) = span_points k s :=
rfl
/-- A set is contained in its affine span. -/
lemma subset_affine_span (s : set P) : s ⊆ affine_span k s :=
subset_span_points k s
/-- The direction of the affine span is the `vector_span`. -/
lemma direction_affine_span (s : set P) : (affine_span k s).direction = vector_span k s :=
begin
apply le_antisymm,
{ refine submodule.span_le.2 _,
rintros v ⟨p1, p3, ⟨p2, hp2, v1, hv1, hp1⟩, ⟨p4, hp4, v2, hv2, hp3⟩, rfl⟩,
rw [hp1, hp3, vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, set_like.mem_coe],
exact (vector_span k s).sub_mem ((vector_span k s).add_mem hv1
(vsub_mem_vector_span k hp2 hp4)) hv2 },
{ exact vector_span_mono k (subset_span_points k s) }
end
/-- A point in a set is in its affine span. -/
lemma mem_affine_span {p : P} {s : set P} (hp : p ∈ s) : p ∈ affine_span k s :=
mem_span_points k p s hp
end affine_span
namespace affine_subspace
variables {k : Type*} {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V]
[S : affine_space V P]
include S
instance : complete_lattice (affine_subspace k P) :=
{ sup := λ s1 s2, affine_span k (s1 ∪ s2),
le_sup_left := λ s1 s2, set.subset.trans (set.subset_union_left s1 s2)
(subset_span_points k _),
le_sup_right := λ s1 s2, set.subset.trans (set.subset_union_right s1 s2)
(subset_span_points k _),
sup_le := λ s1 s2 s3 hs1 hs2, span_points_subset_coe_of_subset_coe (set.union_subset hs1 hs2),
inf := λ s1 s2, mk (s1 ∩ s2)
(λ c p1 p2 p3 hp1 hp2 hp3,
⟨s1.smul_vsub_vadd_mem c hp1.1 hp2.1 hp3.1,
s2.smul_vsub_vadd_mem c hp1.2 hp2.2 hp3.2⟩),
inf_le_left := λ _ _, set.inter_subset_left _ _,
inf_le_right := λ _ _, set.inter_subset_right _ _,
le_inf := λ _ _ _, set.subset_inter,
top := { carrier := set.univ,
smul_vsub_vadd_mem := λ _ _ _ _ _ _ _, set.mem_univ _ },
le_top := λ _ _ _, set.mem_univ _,
bot := { carrier := ∅,
smul_vsub_vadd_mem := λ _ _ _ _, false.elim },
bot_le := λ _ _, false.elim,
Sup := λ s, affine_span k (⋃ s' ∈ s, (s' : set P)),
Inf := λ s, mk (⋂ s' ∈ s, (s' : set P))
(λ c p1 p2 p3 hp1 hp2 hp3, set.mem_Inter₂.2 $ λ s2 hs2, begin
rw set.mem_Inter₂ at *,
exact s2.smul_vsub_vadd_mem c (hp1 s2 hs2) (hp2 s2 hs2) (hp3 s2 hs2)
end),
le_Sup := λ _ _ h, set.subset.trans (set.subset_bUnion_of_mem h) (subset_span_points k _),
Sup_le := λ _ _ h, span_points_subset_coe_of_subset_coe (set.Union₂_subset h),
Inf_le := λ _ _, set.bInter_subset_of_mem,
le_Inf := λ _ _, set.subset_Inter₂,
.. partial_order.lift (coe : affine_subspace k P → set P) coe_injective }
instance : inhabited (affine_subspace k P) := ⟨⊤⟩
/-- The `≤` order on subspaces is the same as that on the corresponding
sets. -/
lemma le_def (s1 s2 : affine_subspace k P) : s1 ≤ s2 ↔ (s1 : set P) ⊆ s2 :=
iff.rfl
/-- One subspace is less than or equal to another if and only if all
its points are in the second subspace. -/
lemma le_def' (s1 s2 : affine_subspace k P) : s1 ≤ s2 ↔ ∀ p ∈ s1, p ∈ s2 :=
iff.rfl
/-- The `<` order on subspaces is the same as that on the corresponding
sets. -/
lemma lt_def (s1 s2 : affine_subspace k P) : s1 < s2 ↔ (s1 : set P) ⊂ s2 :=
iff.rfl
/-- One subspace is not less than or equal to another if and only if
it has a point not in the second subspace. -/
lemma not_le_iff_exists (s1 s2 : affine_subspace k P) : ¬ s1 ≤ s2 ↔ ∃ p ∈ s1, p ∉ s2 :=
set.not_subset
/-- If a subspace is less than another, there is a point only in the
second. -/
lemma exists_of_lt {s1 s2 : affine_subspace k P} (h : s1 < s2) : ∃ p ∈ s2, p ∉ s1 :=
set.exists_of_ssubset h
/-- A subspace is less than another if and only if it is less than or
equal to the second subspace and there is a point only in the
second. -/
lemma lt_iff_le_and_exists (s1 s2 : affine_subspace k P) : s1 < s2 ↔ s1 ≤ s2 ∧ ∃ p ∈ s2, p ∉ s1 :=
by rw [lt_iff_le_not_le, not_le_iff_exists]
/-- If an affine subspace is nonempty and contained in another with
the same direction, they are equal. -/
lemma eq_of_direction_eq_of_nonempty_of_le {s₁ s₂ : affine_subspace k P}
(hd : s₁.direction = s₂.direction) (hn : (s₁ : set P).nonempty) (hle : s₁ ≤ s₂) :
s₁ = s₂ :=
let ⟨p, hp⟩ := hn in ext_of_direction_eq hd ⟨p, hp, hle hp⟩
variables (k V)
/-- The affine span is the `Inf` of subspaces containing the given
points. -/
lemma affine_span_eq_Inf (s : set P) : affine_span k s = Inf {s' | s ⊆ s'} :=
le_antisymm (span_points_subset_coe_of_subset_coe $ set.subset_Inter₂ $ λ _, id)
(Inf_le (subset_span_points k _))
variables (P)
/-- The Galois insertion formed by `affine_span` and coercion back to
a set. -/
protected def gi : galois_insertion (affine_span k) (coe : affine_subspace k P → set P) :=
{ choice := λ s _, affine_span k s,
gc := λ s1 s2, ⟨λ h, set.subset.trans (subset_span_points k s1) h,
span_points_subset_coe_of_subset_coe⟩,
le_l_u := λ _, subset_span_points k _,
choice_eq := λ _ _, rfl }
/-- The span of the empty set is `⊥`. -/
@[simp] lemma span_empty : affine_span k (∅ : set P) = ⊥ :=
(affine_subspace.gi k V P).gc.l_bot
/-- The span of `univ` is `⊤`. -/
@[simp] lemma span_univ : affine_span k (set.univ : set P) = ⊤ :=
eq_top_iff.2 $ subset_span_points k _
variables {k V P}
lemma _root_.affine_span_le {s : set P} {Q : affine_subspace k P} :
affine_span k s ≤ Q ↔ s ⊆ (Q : set P) :=
(affine_subspace.gi k V P).gc _ _
variables (k V) {P}
/-- The affine span of a single point, coerced to a set, contains just
that point. -/
@[simp] lemma coe_affine_span_singleton (p : P) : (affine_span k ({p} : set P) : set P) = {p} :=
begin
ext x,
rw [mem_coe, ←vsub_right_mem_direction_iff_mem (mem_affine_span k (set.mem_singleton p)) _,
direction_affine_span],
simp
end
/-- A point is in the affine span of a single point if and only if
they are equal. -/
@[simp] lemma mem_affine_span_singleton (p1 p2 : P) :
p1 ∈ affine_span k ({p2} : set P) ↔ p1 = p2 :=
by simp [←mem_coe]
/-- The span of a union of sets is the sup of their spans. -/
lemma span_union (s t : set P) : affine_span k (s ∪ t) = affine_span k s ⊔ affine_span k t :=
(affine_subspace.gi k V P).gc.l_sup
/-- The span of a union of an indexed family of sets is the sup of
their spans. -/
lemma span_Union {ι : Type*} (s : ι → set P) :
affine_span k (⋃ i, s i) = ⨆ i, affine_span k (s i) :=
(affine_subspace.gi k V P).gc.l_supr
variables (P)
/-- `⊤`, coerced to a set, is the whole set of points. -/
@[simp] lemma top_coe : ((⊤ : affine_subspace k P) : set P) = set.univ :=
rfl
variables {P}
/-- All points are in `⊤`. -/
lemma mem_top (p : P) : p ∈ (⊤ : affine_subspace k P) :=
set.mem_univ p
variables (P)
/-- The direction of `⊤` is the whole module as a submodule. -/
@[simp] lemma direction_top : (⊤ : affine_subspace k P).direction = ⊤ :=
begin
cases S.nonempty with p,
ext v,
refine ⟨imp_intro submodule.mem_top, λ hv, _⟩,
have hpv : (v +ᵥ p -ᵥ p : V) ∈ (⊤ : affine_subspace k P).direction :=
vsub_mem_direction (mem_top k V _) (mem_top k V _),
rwa vadd_vsub at hpv
end
/-- `⊥`, coerced to a set, is the empty set. -/
@[simp] lemma bot_coe : ((⊥ : affine_subspace k P) : set P) = ∅ :=
rfl
lemma bot_ne_top : (⊥ : affine_subspace k P) ≠ ⊤ :=
begin
intros contra,
rw [← ext_iff, bot_coe, top_coe] at contra,
exact set.empty_ne_univ contra,
end
instance : nontrivial (affine_subspace k P) := ⟨⟨⊥, ⊤, bot_ne_top k V P⟩⟩
lemma nonempty_of_affine_span_eq_top {s : set P} (h : affine_span k s = ⊤) : s.nonempty :=
begin
rw ← set.ne_empty_iff_nonempty,
rintros rfl,
rw affine_subspace.span_empty at h,
exact bot_ne_top k V P h,
end
/-- If the affine span of a set is `⊤`, then the vector span of the same set is the `⊤`. -/
lemma vector_span_eq_top_of_affine_span_eq_top {s : set P} (h : affine_span k s = ⊤) :
vector_span k s = ⊤ :=
by rw [← direction_affine_span, h, direction_top]
/-- For a nonempty set, the affine span is `⊤` iff its vector span is `⊤`. -/
lemma affine_span_eq_top_iff_vector_span_eq_top_of_nonempty {s : set P} (hs : s.nonempty) :
affine_span k s = ⊤ ↔ vector_span k s = ⊤ :=
begin
refine ⟨vector_span_eq_top_of_affine_span_eq_top k V P, _⟩,
intros h,
suffices : nonempty (affine_span k s),
{ obtain ⟨p, hp : p ∈ affine_span k s⟩ := this,
rw [eq_iff_direction_eq_of_mem hp (mem_top k V p), direction_affine_span, h, direction_top] },
obtain ⟨x, hx⟩ := hs,
exact ⟨⟨x, mem_affine_span k hx⟩⟩,
end
/-- For a non-trivial space, the affine span of a set is `⊤` iff its vector span is `⊤`. -/
lemma affine_span_eq_top_iff_vector_span_eq_top_of_nontrivial {s : set P} [nontrivial P] :
affine_span k s = ⊤ ↔ vector_span k s = ⊤ :=
begin
cases s.eq_empty_or_nonempty with hs hs,
{ simp [hs, subsingleton_iff_bot_eq_top, add_torsor.subsingleton_iff V P, not_subsingleton], },
{ rw affine_span_eq_top_iff_vector_span_eq_top_of_nonempty k V P hs, },
end
lemma card_pos_of_affine_span_eq_top {ι : Type*} [fintype ι] {p : ι → P}
(h : affine_span k (range p) = ⊤) :
0 < fintype.card ι :=
begin
obtain ⟨-, ⟨i, -⟩⟩ := nonempty_of_affine_span_eq_top k V P h,
exact fintype.card_pos_iff.mpr ⟨i⟩,
end
variables {P}
/-- No points are in `⊥`. -/
lemma not_mem_bot (p : P) : p ∉ (⊥ : affine_subspace k P) :=
set.not_mem_empty p
variables (P)
/-- The direction of `⊥` is the submodule `⊥`. -/
@[simp] lemma direction_bot : (⊥ : affine_subspace k P).direction = ⊥ :=
by rw [direction_eq_vector_span, bot_coe, vector_span_def, vsub_empty, submodule.span_empty]
variables {k V P}
@[simp] lemma coe_eq_bot_iff (Q : affine_subspace k P) : (Q : set P) = ∅ ↔ Q = ⊥ :=
coe_injective.eq_iff' (bot_coe _ _ _)
@[simp] lemma coe_eq_univ_iff (Q : affine_subspace k P) : (Q : set P) = univ ↔ Q = ⊤ :=
coe_injective.eq_iff' (top_coe _ _ _)
lemma nonempty_iff_ne_bot (Q : affine_subspace k P) : (Q : set P).nonempty ↔ Q ≠ ⊥ :=
by { rw ← ne_empty_iff_nonempty, exact not_congr Q.coe_eq_bot_iff }
lemma eq_bot_or_nonempty (Q : affine_subspace k P) : Q = ⊥ ∨ (Q : set P).nonempty :=
by { rw nonempty_iff_ne_bot, apply eq_or_ne }
lemma subsingleton_of_subsingleton_span_eq_top {s : set P} (h₁ : s.subsingleton)
(h₂ : affine_span k s = ⊤) : subsingleton P :=
begin
obtain ⟨p, hp⟩ := affine_subspace.nonempty_of_affine_span_eq_top k V P h₂,
have : s = {p}, { exact subset.antisymm (λ q hq, h₁ hq hp) (by simp [hp]), },
rw [this, ← affine_subspace.ext_iff, affine_subspace.coe_affine_span_singleton,
affine_subspace.top_coe, eq_comm, ← subsingleton_iff_singleton (mem_univ _)] at h₂,
exact subsingleton_of_univ_subsingleton h₂,
end
lemma eq_univ_of_subsingleton_span_eq_top {s : set P} (h₁ : s.subsingleton)
(h₂ : affine_span k s = ⊤) : s = (univ : set P) :=
begin
obtain ⟨p, hp⟩ := affine_subspace.nonempty_of_affine_span_eq_top k V P h₂,
have : s = {p}, { exact subset.antisymm (λ q hq, h₁ hq hp) (by simp [hp]), },
rw [this, eq_comm, ← subsingleton_iff_singleton (mem_univ p), subsingleton_univ_iff],
exact subsingleton_of_subsingleton_span_eq_top h₁ h₂,
end
/-- A nonempty affine subspace is `⊤` if and only if its direction is
`⊤`. -/
@[simp] lemma direction_eq_top_iff_of_nonempty {s : affine_subspace k P}
(h : (s : set P).nonempty) : s.direction = ⊤ ↔ s = ⊤ :=
begin
split,
{ intro hd,
rw ←direction_top k V P at hd,
refine ext_of_direction_eq hd _,
simp [h] },
{ rintro rfl,
simp }
end
/-- The inf of two affine subspaces, coerced to a set, is the
intersection of the two sets of points. -/
@[simp] lemma inf_coe (s1 s2 : affine_subspace k P) : ((s1 ⊓ s2) : set P) = s1 ∩ s2 :=
rfl
/-- A point is in the inf of two affine subspaces if and only if it is
in both of them. -/
lemma mem_inf_iff (p : P) (s1 s2 : affine_subspace k P) : p ∈ s1 ⊓ s2 ↔ p ∈ s1 ∧ p ∈ s2 :=
iff.rfl
/-- The direction of the inf of two affine subspaces is less than or
equal to the inf of their directions. -/
lemma direction_inf (s1 s2 : affine_subspace k P) :
(s1 ⊓ s2).direction ≤ s1.direction ⊓ s2.direction :=
begin
repeat { rw [direction_eq_vector_span, vector_span_def] },
exact le_inf
(Inf_le_Inf (λ p hp, trans (vsub_self_mono (inter_subset_left _ _)) hp))
(Inf_le_Inf (λ p hp, trans (vsub_self_mono (inter_subset_right _ _)) hp))
end
/-- If two affine subspaces have a point in common, the direction of
their inf equals the inf of their directions. -/
lemma direction_inf_of_mem {s₁ s₂ : affine_subspace k P} {p : P} (h₁ : p ∈ s₁) (h₂ : p ∈ s₂) :
(s₁ ⊓ s₂).direction = s₁.direction ⊓ s₂.direction :=
begin
ext v,
rw [submodule.mem_inf, ←vadd_mem_iff_mem_direction v h₁, ←vadd_mem_iff_mem_direction v h₂,
←vadd_mem_iff_mem_direction v ((mem_inf_iff p s₁ s₂).2 ⟨h₁, h₂⟩), mem_inf_iff]
end
/-- If two affine subspaces have a point in their inf, the direction
of their inf equals the inf of their directions. -/
lemma direction_inf_of_mem_inf {s₁ s₂ : affine_subspace k P} {p : P} (h : p ∈ s₁ ⊓ s₂) :
(s₁ ⊓ s₂).direction = s₁.direction ⊓ s₂.direction :=
direction_inf_of_mem ((mem_inf_iff p s₁ s₂).1 h).1 ((mem_inf_iff p s₁ s₂).1 h).2
/-- If one affine subspace is less than or equal to another, the same
applies to their directions. -/
lemma direction_le {s1 s2 : affine_subspace k P} (h : s1 ≤ s2) : s1.direction ≤ s2.direction :=
begin
repeat { rw [direction_eq_vector_span, vector_span_def] },
exact vector_span_mono k h
end
/-- If one nonempty affine subspace is less than another, the same
applies to their directions -/
lemma direction_lt_of_nonempty {s1 s2 : affine_subspace k P} (h : s1 < s2)
(hn : (s1 : set P).nonempty) : s1.direction < s2.direction :=
begin
cases hn with p hp,
rw lt_iff_le_and_exists at h,
rcases h with ⟨hle, p2, hp2, hp2s1⟩,
rw set_like.lt_iff_le_and_exists,
use [direction_le hle, p2 -ᵥ p, vsub_mem_direction hp2 (hle hp)],
intro hm,
rw vsub_right_mem_direction_iff_mem hp p2 at hm,
exact hp2s1 hm
end
/-- The sup of the directions of two affine subspaces is less than or
equal to the direction of their sup. -/
lemma sup_direction_le (s1 s2 : affine_subspace k P) :
s1.direction ⊔ s2.direction ≤ (s1 ⊔ s2).direction :=
begin
repeat { rw [direction_eq_vector_span, vector_span_def] },
exact sup_le
(Inf_le_Inf (λ p hp, set.subset.trans (vsub_self_mono (le_sup_left : s1 ≤ s1 ⊔ s2)) hp))
(Inf_le_Inf (λ p hp, set.subset.trans (vsub_self_mono (le_sup_right : s2 ≤ s1 ⊔ s2)) hp))
end
/-- The sup of the directions of two nonempty affine subspaces with
empty intersection is less than the direction of their sup. -/
lemma sup_direction_lt_of_nonempty_of_inter_empty {s1 s2 : affine_subspace k P}
(h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty) (he : (s1 ∩ s2 : set P) = ∅) :
s1.direction ⊔ s2.direction < (s1 ⊔ s2).direction :=
begin
cases h1 with p1 hp1,
cases h2 with p2 hp2,
rw set_like.lt_iff_le_and_exists,
use [sup_direction_le s1 s2, p2 -ᵥ p1,
vsub_mem_direction ((le_sup_right : s2 ≤ s1 ⊔ s2) hp2) ((le_sup_left : s1 ≤ s1 ⊔ s2) hp1)],
intro h,
rw submodule.mem_sup at h,
rcases h with ⟨v1, hv1, v2, hv2, hv1v2⟩,
rw [←sub_eq_zero, sub_eq_add_neg, neg_vsub_eq_vsub_rev, add_comm v1, add_assoc,
←vadd_vsub_assoc, ←neg_neg v2, add_comm, ←sub_eq_add_neg, ←vsub_vadd_eq_vsub_sub,
vsub_eq_zero_iff_eq] at hv1v2,
refine set.nonempty.ne_empty _ he,
use [v1 +ᵥ p1, vadd_mem_of_mem_direction hv1 hp1],
rw hv1v2,
exact vadd_mem_of_mem_direction (submodule.neg_mem _ hv2) hp2
end
/-- If the directions of two nonempty affine subspaces span the whole
module, they have nonempty intersection. -/
lemma inter_nonempty_of_nonempty_of_sup_direction_eq_top {s1 s2 : affine_subspace k P}
(h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty)
(hd : s1.direction ⊔ s2.direction = ⊤) : ((s1 : set P) ∩ s2).nonempty :=
begin
by_contradiction h,
rw set.not_nonempty_iff_eq_empty at h,
have hlt := sup_direction_lt_of_nonempty_of_inter_empty h1 h2 h,
rw hd at hlt,
exact not_top_lt hlt
end
/-- If the directions of two nonempty affine subspaces are complements
of each other, they intersect in exactly one point. -/
lemma inter_eq_singleton_of_nonempty_of_is_compl {s1 s2 : affine_subspace k P}
(h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty)
(hd : is_compl s1.direction s2.direction) : ∃ p, (s1 : set P) ∩ s2 = {p} :=
begin
cases inter_nonempty_of_nonempty_of_sup_direction_eq_top h1 h2 hd.sup_eq_top with p hp,
use p,
ext q,
rw set.mem_singleton_iff,
split,
{ rintros ⟨hq1, hq2⟩,
have hqp : q -ᵥ p ∈ s1.direction ⊓ s2.direction :=
⟨vsub_mem_direction hq1 hp.1, vsub_mem_direction hq2 hp.2⟩,
rwa [hd.inf_eq_bot, submodule.mem_bot, vsub_eq_zero_iff_eq] at hqp },
{ exact λ h, h.symm ▸ hp }
end
/-- Coercing a subspace to a set then taking the affine span produces
the original subspace. -/
@[simp] lemma affine_span_coe (s : affine_subspace k P) : affine_span k (s : set P) = s :=
begin
refine le_antisymm _ (subset_span_points _ _),
rintros p ⟨p1, hp1, v, hv, rfl⟩,
exact vadd_mem_of_mem_direction hv hp1
end
end affine_subspace
section affine_space'
variables (k : Type*) {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V]
[affine_space V P]
variables {ι : Type*}
include V
open affine_subspace set
/-- The `vector_span` is the span of the pairwise subtractions with a
given point on the left. -/
lemma vector_span_eq_span_vsub_set_left {s : set P} {p : P} (hp : p ∈ s) :
vector_span k s = submodule.span k ((-ᵥ) p '' s) :=
begin
rw vector_span_def,
refine le_antisymm _ (submodule.span_mono _),
{ rw submodule.span_le,
rintros v ⟨p1, p2, hp1, hp2, hv⟩,
rw ←vsub_sub_vsub_cancel_left p1 p2 p at hv,
rw [←hv, set_like.mem_coe, submodule.mem_span],
exact λ m hm, submodule.sub_mem _ (hm ⟨p2, hp2, rfl⟩) (hm ⟨p1, hp1, rfl⟩) },
{ rintros v ⟨p2, hp2, hv⟩,
exact ⟨p, p2, hp, hp2, hv⟩ }
end
/-- The `vector_span` is the span of the pairwise subtractions with a
given point on the right. -/
lemma vector_span_eq_span_vsub_set_right {s : set P} {p : P} (hp : p ∈ s) :
vector_span k s = submodule.span k ((-ᵥ p) '' s) :=
begin
rw vector_span_def,
refine le_antisymm _ (submodule.span_mono _),
{ rw submodule.span_le,
rintros v ⟨p1, p2, hp1, hp2, hv⟩,
rw ←vsub_sub_vsub_cancel_right p1 p2 p at hv,
rw [←hv, set_like.mem_coe, submodule.mem_span],
exact λ m hm, submodule.sub_mem _ (hm ⟨p1, hp1, rfl⟩) (hm ⟨p2, hp2, rfl⟩) },
{ rintros v ⟨p2, hp2, hv⟩,
exact ⟨p2, p, hp2, hp, hv⟩ }
end
/-- The `vector_span` is the span of the pairwise subtractions with a
given point on the left, excluding the subtraction of that point from
itself. -/
lemma vector_span_eq_span_vsub_set_left_ne {s : set P} {p : P} (hp : p ∈ s) :
vector_span k s = submodule.span k ((-ᵥ) p '' (s \ {p})) :=
begin
conv_lhs { rw [vector_span_eq_span_vsub_set_left k hp, ←set.insert_eq_of_mem hp,
←set.insert_diff_singleton, set.image_insert_eq] },
simp [submodule.span_insert_eq_span]
end
/-- The `vector_span` is the span of the pairwise subtractions with a
given point on the right, excluding the subtraction of that point from
itself. -/
lemma vector_span_eq_span_vsub_set_right_ne {s : set P} {p : P} (hp : p ∈ s) :
vector_span k s = submodule.span k ((-ᵥ p) '' (s \ {p})) :=
begin
conv_lhs { rw [vector_span_eq_span_vsub_set_right k hp, ←set.insert_eq_of_mem hp,
←set.insert_diff_singleton, set.image_insert_eq] },
simp [submodule.span_insert_eq_span]
end
/-- The `vector_span` is the span of the pairwise subtractions with a
given point on the right, excluding the subtraction of that point from
itself. -/
lemma vector_span_eq_span_vsub_finset_right_ne {s : finset P} {p : P} (hp : p ∈ s) :
vector_span k (s : set P) = submodule.span k ((s.erase p).image (-ᵥ p)) :=
by simp [vector_span_eq_span_vsub_set_right_ne _ (finset.mem_coe.mpr hp)]
/-- The `vector_span` of the image of a function is the span of the
pairwise subtractions with a given point on the left, excluding the
subtraction of that point from itself. -/
lemma vector_span_image_eq_span_vsub_set_left_ne (p : ι → P) {s : set ι} {i : ι} (hi : i ∈ s) :
vector_span k (p '' s) = submodule.span k ((-ᵥ) (p i) '' (p '' (s \ {i}))) :=
begin
conv_lhs { rw [vector_span_eq_span_vsub_set_left k (set.mem_image_of_mem p hi),
←set.insert_eq_of_mem hi, ←set.insert_diff_singleton, set.image_insert_eq,
set.image_insert_eq] },
simp [submodule.span_insert_eq_span]
end
/-- The `vector_span` of the image of a function is the span of the
pairwise subtractions with a given point on the right, excluding the
subtraction of that point from itself. -/
lemma vector_span_image_eq_span_vsub_set_right_ne (p : ι → P) {s : set ι} {i : ι} (hi : i ∈ s) :
vector_span k (p '' s) = submodule.span k ((-ᵥ (p i)) '' (p '' (s \ {i}))) :=
begin
conv_lhs { rw [vector_span_eq_span_vsub_set_right k (set.mem_image_of_mem p hi),
←set.insert_eq_of_mem hi, ←set.insert_diff_singleton, set.image_insert_eq,
set.image_insert_eq] },
simp [submodule.span_insert_eq_span]
end
/-- The `vector_span` of an indexed family is the span of the pairwise
subtractions with a given point on the left. -/
lemma vector_span_range_eq_span_range_vsub_left (p : ι → P) (i0 : ι) :
vector_span k (set.range p) = submodule.span k (set.range (λ (i : ι), p i0 -ᵥ p i)) :=
by rw [vector_span_eq_span_vsub_set_left k (set.mem_range_self i0), ←set.range_comp]
/-- The `vector_span` of an indexed family is the span of the pairwise
subtractions with a given point on the right. -/
lemma vector_span_range_eq_span_range_vsub_right (p : ι → P) (i0 : ι) :
vector_span k (set.range p) = submodule.span k (set.range (λ (i : ι), p i -ᵥ p i0)) :=
by rw [vector_span_eq_span_vsub_set_right k (set.mem_range_self i0), ←set.range_comp]
/-- The `vector_span` of an indexed family is the span of the pairwise
subtractions with a given point on the left, excluding the subtraction
of that point from itself. -/
lemma vector_span_range_eq_span_range_vsub_left_ne (p : ι → P) (i₀ : ι) :
vector_span k (set.range p) = submodule.span k (set.range (λ (i : {x // x ≠ i₀}), p i₀ -ᵥ p i)) :=
begin
rw [←set.image_univ, vector_span_image_eq_span_vsub_set_left_ne k _ (set.mem_univ i₀)],
congr' with v,
simp only [set.mem_range, set.mem_image, set.mem_diff, set.mem_singleton_iff, subtype.exists,
subtype.coe_mk],
split,
{ rintros ⟨x, ⟨i₁, ⟨⟨hi₁u, hi₁⟩, rfl⟩⟩, hv⟩,
exact ⟨i₁, hi₁, hv⟩ },
{ exact λ ⟨i₁, hi₁, hv⟩, ⟨p i₁, ⟨i₁, ⟨set.mem_univ _, hi₁⟩, rfl⟩, hv⟩ }
end
/-- The `vector_span` of an indexed family is the span of the pairwise
subtractions with a given point on the right, excluding the subtraction
of that point from itself. -/
lemma vector_span_range_eq_span_range_vsub_right_ne (p : ι → P) (i₀ : ι) :
vector_span k (set.range p) = submodule.span k (set.range (λ (i : {x // x ≠ i₀}), p i -ᵥ p i₀)) :=
begin
rw [←set.image_univ, vector_span_image_eq_span_vsub_set_right_ne k _ (set.mem_univ i₀)],
congr' with v,
simp only [set.mem_range, set.mem_image, set.mem_diff, set.mem_singleton_iff, subtype.exists,
subtype.coe_mk],
split,
{ rintros ⟨x, ⟨i₁, ⟨⟨hi₁u, hi₁⟩, rfl⟩⟩, hv⟩,
exact ⟨i₁, hi₁, hv⟩ },
{ exact λ ⟨i₁, hi₁, hv⟩, ⟨p i₁, ⟨i₁, ⟨set.mem_univ _, hi₁⟩, rfl⟩, hv⟩ }
end
/-- The affine span of a set is nonempty if and only if that set
is. -/
lemma affine_span_nonempty (s : set P) :
(affine_span k s : set P).nonempty ↔ s.nonempty :=
span_points_nonempty k s
/-- The affine span of a nonempty set is nonempty. -/
instance {s : set P} [nonempty s] : nonempty (affine_span k s) :=
((affine_span_nonempty k s).mpr (nonempty_subtype.mp ‹_›)).to_subtype
variables {k}
/-- Suppose a set of vectors spans `V`. Then a point `p`, together
with those vectors added to `p`, spans `P`. -/
lemma affine_span_singleton_union_vadd_eq_top_of_span_eq_top {s : set V} (p : P)
(h : submodule.span k (set.range (coe : s → V)) = ⊤) :
affine_span k ({p} ∪ (λ v, v +ᵥ p) '' s) = ⊤ :=
begin
convert ext_of_direction_eq _
⟨p,
mem_affine_span k (set.mem_union_left _ (set.mem_singleton _)),
mem_top k V p⟩,
rw [direction_affine_span, direction_top,
vector_span_eq_span_vsub_set_right k
((set.mem_union_left _ (set.mem_singleton _)) : p ∈ _), eq_top_iff, ←h],
apply submodule.span_mono,
rintros v ⟨v', rfl⟩,
use (v' : V) +ᵥ p,
simp
end
variables (k)
/-- `affine_span` is monotone. -/
@[mono]
lemma affine_span_mono {s₁ s₂ : set P} (h : s₁ ⊆ s₂) : affine_span k s₁ ≤ affine_span k s₂ :=
span_points_subset_coe_of_subset_coe (set.subset.trans h (subset_affine_span k _))
/-- Taking the affine span of a set, adding a point and taking the
span again produces the same results as adding the point to the set
and taking the span. -/
lemma affine_span_insert_affine_span (p : P) (ps : set P) :
affine_span k (insert p (affine_span k ps : set P)) = affine_span k (insert p ps) :=
by rw [set.insert_eq, set.insert_eq, span_union, span_union, affine_span_coe]
/-- If a point is in the affine span of a set, adding it to that set
does not change the affine span. -/
lemma affine_span_insert_eq_affine_span {p : P} {ps : set P} (h : p ∈ affine_span k ps) :
affine_span k (insert p ps) = affine_span k ps :=
begin
rw ←mem_coe at h,
rw [←affine_span_insert_affine_span, set.insert_eq_of_mem h, affine_span_coe]
end
end affine_space'
namespace affine_subspace
variables {k : Type*} {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V]
[affine_space V P]
include V
/-- The direction of the sup of two nonempty affine subspaces is the
sup of the two directions and of any one difference between points in
the two subspaces. -/
lemma direction_sup {s1 s2 : affine_subspace k P} {p1 p2 : P} (hp1 : p1 ∈ s1) (hp2 : p2 ∈ s2) :
(s1 ⊔ s2).direction = s1.direction ⊔ s2.direction ⊔ k ∙ (p2 -ᵥ p1) :=
begin
refine le_antisymm _ _,
{ change (affine_span k ((s1 : set P) ∪ s2)).direction ≤ _,
rw ←mem_coe at hp1,
rw [direction_affine_span, vector_span_eq_span_vsub_set_right k (set.mem_union_left _ hp1),
submodule.span_le],
rintros v ⟨p3, hp3, rfl⟩,
cases hp3,
{ rw [sup_assoc, sup_comm, set_like.mem_coe, submodule.mem_sup],
use [0, submodule.zero_mem _, p3 -ᵥ p1, vsub_mem_direction hp3 hp1],
rw zero_add },
{ rw [sup_assoc, set_like.mem_coe, submodule.mem_sup],
use [0, submodule.zero_mem _, p3 -ᵥ p1],
rw [and_comm, zero_add],
use rfl,
rw [←vsub_add_vsub_cancel p3 p2 p1, submodule.mem_sup],
use [p3 -ᵥ p2, vsub_mem_direction hp3 hp2, p2 -ᵥ p1,
submodule.mem_span_singleton_self _] } },
{ refine sup_le (sup_direction_le _ _) _,
rw [direction_eq_vector_span, vector_span_def],
exact Inf_le_Inf (λ p hp, set.subset.trans
(set.singleton_subset_iff.2
(vsub_mem_vsub (mem_span_points k p2 _ (set.mem_union_right _ hp2))
(mem_span_points k p1 _ (set.mem_union_left _ hp1))))
hp) }
end
/-- The direction of the span of the result of adding a point to a
nonempty affine subspace is the sup of the direction of that subspace
and of any one difference between that point and a point in the
subspace. -/
lemma direction_affine_span_insert {s : affine_subspace k P} {p1 p2 : P} (hp1 : p1 ∈ s) :
(affine_span k (insert p2 (s : set P))).direction = submodule.span k {p2 -ᵥ p1} ⊔ s.direction :=
begin
rw [sup_comm, ←set.union_singleton, ←coe_affine_span_singleton k V p2],
change (s ⊔ affine_span k {p2}).direction = _,
rw [direction_sup hp1 (mem_affine_span k (set.mem_singleton _)), direction_affine_span],
simp
end
/-- Given a point `p1` in an affine subspace `s`, and a point `p2`, a
point `p` is in the span of `s` with `p2` added if and only if it is a
multiple of `p2 -ᵥ p1` added to a point in `s`. -/
lemma mem_affine_span_insert_iff {s : affine_subspace k P} {p1 : P} (hp1 : p1 ∈ s) (p2 p : P) :
p ∈ affine_span k (insert p2 (s : set P)) ↔
∃ (r : k) (p0 : P) (hp0 : p0 ∈ s), p = r • (p2 -ᵥ p1 : V) +ᵥ p0 :=
begin
rw ←mem_coe at hp1,
rw [←vsub_right_mem_direction_iff_mem (mem_affine_span k (set.mem_insert_of_mem _ hp1)),
direction_affine_span_insert hp1, submodule.mem_sup],
split,
{ rintros ⟨v1, hv1, v2, hv2, hp⟩,
rw submodule.mem_span_singleton at hv1,
rcases hv1 with ⟨r, rfl⟩,
use [r, v2 +ᵥ p1, vadd_mem_of_mem_direction hv2 hp1],
symmetry' at hp,
rw [←sub_eq_zero, ←vsub_vadd_eq_vsub_sub, vsub_eq_zero_iff_eq] at hp,
rw [hp, vadd_vadd] },
{ rintros ⟨r, p3, hp3, rfl⟩,
use [r • (p2 -ᵥ p1), submodule.mem_span_singleton.2 ⟨r, rfl⟩, p3 -ᵥ p1,
vsub_mem_direction hp3 hp1],
rw [vadd_vsub_assoc, add_comm] }
end
end affine_subspace
section map_comap
variables {k V₁ P₁ V₂ P₂ V₃ P₃ : Type*} [ring k]
variables [add_comm_group V₁] [module k V₁] [add_torsor V₁ P₁]
variables [add_comm_group V₂] [module k V₂] [add_torsor V₂ P₂]
variables [add_comm_group V₃] [module k V₃] [add_torsor V₃ P₃]
include V₁ V₂
section
variables (f : P₁ →ᵃ[k] P₂)
@[simp] lemma affine_map.vector_span_image_eq_submodule_map {s : set P₁} :
submodule.map f.linear (vector_span k s) = vector_span k (f '' s) :=
by simp [f.image_vsub_image, vector_span_def]
namespace affine_subspace
/-- The image of an affine subspace under an affine map as an affine subspace. -/
def map (s : affine_subspace k P₁) : affine_subspace k P₂ :=
{ carrier := f '' s,
smul_vsub_vadd_mem :=
begin
rintros t - - - ⟨p₁, h₁, rfl⟩ ⟨p₂, h₂, rfl⟩ ⟨p₃, h₃, rfl⟩,
use t • (p₁ -ᵥ p₂) +ᵥ p₃,
suffices : t • (p₁ -ᵥ p₂) +ᵥ p₃ ∈ s, { simp [this], },
exact s.smul_vsub_vadd_mem t h₁ h₂ h₃,
end }
@[simp] lemma coe_map (s : affine_subspace k P₁) : (s.map f : set P₂) = f '' s := rfl
@[simp] lemma mem_map {f : P₁ →ᵃ[k] P₂} {x : P₂} {s : affine_subspace k P₁} :
x ∈ s.map f ↔ ∃ y ∈ s, f y = x := mem_image_iff_bex
@[simp] lemma map_bot : (⊥ : affine_subspace k P₁).map f = ⊥ :=
coe_injective $ image_empty f
omit V₂
@[simp] lemma map_id (s : affine_subspace k P₁) : s.map (affine_map.id k P₁) = s :=
coe_injective $ image_id _
include V₂ V₃
lemma map_map (s : affine_subspace k P₁) (f : P₁ →ᵃ[k] P₂) (g : P₂ →ᵃ[k] P₃) :
(s.map f).map g = s.map (g.comp f) :=
coe_injective $ image_image _ _ _
omit V₃
@[simp] lemma map_direction (s : affine_subspace k P₁) :
(s.map f).direction = s.direction.map f.linear :=
by simp [direction_eq_vector_span]
lemma map_span (s : set P₁) :
(affine_span k s).map f = affine_span k (f '' s) :=
begin
rcases s.eq_empty_or_nonempty with rfl | ⟨p, hp⟩, { simp, },
apply ext_of_direction_eq,
{ simp [direction_affine_span], },
{ exact ⟨f p, mem_image_of_mem f (subset_affine_span k _ hp),
subset_affine_span k _ (mem_image_of_mem f hp)⟩, },
end
end affine_subspace
namespace affine_map
@[simp] lemma map_top_of_surjective (hf : function.surjective f) : affine_subspace.map f ⊤ = ⊤ :=
begin
rw ← affine_subspace.ext_iff,
exact image_univ_of_surjective hf,
end
lemma span_eq_top_of_surjective {s : set P₁}
(hf : function.surjective f) (h : affine_span k s = ⊤) :
affine_span k (f '' s) = ⊤ :=
by rw [← affine_subspace.map_span, h, map_top_of_surjective f hf]
end affine_map
namespace affine_equiv
lemma span_eq_top_iff {s : set P₁} (e : P₁ ≃ᵃ[k] P₂) :
affine_span k s = ⊤ ↔ affine_span k (e '' s) = ⊤ :=
begin
refine ⟨(e : P₁ →ᵃ[k] P₂).span_eq_top_of_surjective e.surjective, _⟩,
intros h,
have : s = e.symm '' (e '' s), { simp [← image_comp], },
rw this,
exact (e.symm : P₂ →ᵃ[k] P₁).span_eq_top_of_surjective e.symm.surjective h,
end
end affine_equiv
end
namespace affine_subspace
/-- The preimage of an affine subspace under an affine map as an affine subspace. -/
def comap (f : P₁ →ᵃ[k] P₂) (s : affine_subspace k P₂) : affine_subspace k P₁ :=
{ carrier := f ⁻¹' s,
smul_vsub_vadd_mem := λ t p₁ p₂ p₃ (hp₁ : f p₁ ∈ s) (hp₂ : f p₂ ∈ s) (hp₃ : f p₃ ∈ s),
show f _ ∈ s, begin
rw [affine_map.map_vadd, linear_map.map_smul, affine_map.linear_map_vsub],
apply s.smul_vsub_vadd_mem _ hp₁ hp₂ hp₃,
end }
@[simp] lemma coe_comap (f : P₁ →ᵃ[k] P₂) (s : affine_subspace k P₂) :
(s.comap f : set P₁) = f ⁻¹' ↑s := rfl
@[simp] lemma mem_comap {f : P₁ →ᵃ[k] P₂} {x : P₁} {s : affine_subspace k P₂} :
x ∈ s.comap f ↔ f x ∈ s := iff.rfl
lemma comap_mono {f : P₁ →ᵃ[k] P₂} {s t : affine_subspace k P₂} : s ≤ t → s.comap f ≤ t.comap f :=
preimage_mono
@[simp] lemma comap_top {f : P₁ →ᵃ[k] P₂} : (⊤ : affine_subspace k P₂).comap f = ⊤ :=
by { rw ← ext_iff, exact preimage_univ, }
omit V₂
@[simp] lemma comap_id (s : affine_subspace k P₁) : s.comap (affine_map.id k P₁) = s :=
coe_injective rfl
include V₂ V₃
lemma comap_comap (s : affine_subspace k P₃) (f : P₁ →ᵃ[k] P₂) (g : P₂ →ᵃ[k] P₃) :
(s.comap g).comap f = s.comap (g.comp f) :=
coe_injective rfl
omit V₃
-- lemmas about map and comap derived from the galois connection
lemma map_le_iff_le_comap {f : P₁ →ᵃ[k] P₂} {s : affine_subspace k P₁} {t : affine_subspace k P₂} :
s.map f ≤ t ↔ s ≤ t.comap f :=
image_subset_iff
lemma gc_map_comap (f : P₁ →ᵃ[k] P₂) : galois_connection (map f) (comap f) :=
λ _ _, map_le_iff_le_comap
lemma map_comap_le (f : P₁ →ᵃ[k] P₂) (s : affine_subspace k P₂) : (s.comap f).map f ≤ s :=
(gc_map_comap f).l_u_le _
lemma le_comap_map (f : P₁ →ᵃ[k] P₂) (s : affine_subspace k P₁) : s ≤ (s.map f).comap f :=
(gc_map_comap f).le_u_l _
lemma map_sup (s t : affine_subspace k P₁) (f : P₁ →ᵃ[k] P₂) : (s ⊔ t).map f = s.map f ⊔ t.map f :=
(gc_map_comap f).l_sup
lemma map_supr {ι : Sort*} (f : P₁ →ᵃ[k] P₂) (s : ι → affine_subspace k P₁) :
(supr s).map f = ⨆ i, (s i).map f :=
(gc_map_comap f).l_supr
lemma comap_inf (s t : affine_subspace k P₂) (f : P₁ →ᵃ[k] P₂) :
(s ⊓ t).comap f = s.comap f ⊓ t.comap f :=
(gc_map_comap f).u_inf
lemma comap_supr {ι : Sort*} (f : P₁ →ᵃ[k] P₂) (s : ι → affine_subspace k P₂) :
(infi s).comap f = ⨅ i, (s i).comap f :=
(gc_map_comap f).u_infi
end affine_subspace
end map_comap
|
92981df9a65f600e92931e03347c232632ce3e1f | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/coe_issue.lean | 83b856258d9995f388451b7fa130728b9f02d2c5 | [
"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 | 60 | lean | import data.int
open int algebra
example : has_mul int := _
|
ac95da180d236241240ab8064acad84f01291e72 | b147e1312077cdcfea8e6756207b3fa538982e12 | /data/polynomial.lean | dee4884de9293163c8288b881596961b4c7322c0 | [
"Apache-2.0"
] | permissive | SzJS/mathlib | 07836ee708ca27cd18347e1e11ce7dd5afb3e926 | 23a5591fca0d43ee5d49d89f6f0ee07a24a6ca29 | refs/heads/master | 1,584,980,332,064 | 1,532,063,841,000 | 1,532,063,841,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 39,922 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes Hölzl, Jens Wagemaker
Theory of univariate polynomials, represented as `ℕ →₀ α`, where α is a commutative semiring.
-/
import data.finsupp algebra.euclidean_domain
/-- `polynomial α` is the type of univariate polynomials over `α`.
Polynomials should be seen as (semi-)rings with the additional the constructor `X`. `C` is the
embedding from `α`. -/
def polynomial (α : Type*) [comm_semiring α] := ℕ →₀ α
open finsupp finset lattice
namespace polynomial
universe u
variables {α : Type u} {a b : α} {m n : ℕ}
variables [decidable_eq α]
section comm_semiring
variables [comm_semiring α] {p q : polynomial α}
instance : has_coe_to_fun (polynomial α) := finsupp.has_coe_to_fun
instance : has_zero (polynomial α) := finsupp.has_zero
instance : has_one (polynomial α) := finsupp.has_one
instance : has_add (polynomial α) := finsupp.has_add
instance : has_mul (polynomial α) := finsupp.has_mul
instance : comm_semiring (polynomial α) := finsupp.to_comm_semiring
instance : decidable_eq (polynomial α) := finsupp.decidable_eq
local attribute [instance] finsupp.to_comm_semiring
@[simp] lemma support_zero : (0 : polynomial α).support = ∅ := rfl
/-- `C a` is the constant polynomial `a`. -/
def C (a : α) : polynomial α := single 0 a
/-- `X` is the polynomial variable (aka indeterminant). -/
def X : polynomial α := single 1 1
/-- `degree p` is the degree of the polynomial `p`, i.e. the largest `X`-exponent in `p`.
`degree p = some n` when `p ≠ 0` and `n` is the highest power of `X` that appears in `p`, otherwise
`degree 0 = ⊥`. -/
def degree (p : polynomial α) : with_bot ℕ := p.support.sup some
def degree_lt_wf : well_founded (λp q : polynomial α, degree p < degree q) :=
inv_image.wf degree (with_bot.well_founded_lt nat.lt_wf)
/-- `nat_degree p` forces `degree p` to ℕ, by fixing the zero polnomial to the 0 degree. -/
def nat_degree (p : polynomial α) : ℕ := (degree p).get_or_else 0
lemma single_eq_C_mul_X : ∀{n}, single n a = C a * X^n
| 0 := by simp; refl
| (n+1) :=
calc single (n + 1) a = single n a * X : by rw [X, single_mul_single, mul_one]
... = (C a * X^n) * X : by rw [single_eq_C_mul_X]
... = C a * X^(n+1) : by simp [pow_add, mul_assoc]
@[elab_as_eliminator] protected lemma induction_on {M : polynomial α → Prop} (p : polynomial α)
(h_C : ∀a, M (C a))
(h_add : ∀p q, M p → M q → M (p + q))
(h_monomial : ∀(n : ℕ) (a : α), M (C a * X^n) → M (C a * X^(n+1))) :
M p :=
have ∀{n:ℕ} {a}, M (C a * X^n),
begin
assume n a,
induction n with n ih,
{ simp [h_C] },
{ exact h_monomial _ _ ih }
end,
finsupp.induction p
(suffices M (C 0), by simpa [C],
h_C 0)
(assume n a p _ _ hp, suffices M (C a * X^n + p), by rwa [single_eq_C_mul_X],
h_add _ _ this hp)
@[simp] lemma zero_apply (n : ℕ) : (0 : polynomial α) n = 0 := rfl
@[simp] lemma one_apply_zero (n : ℕ) : (1 : polynomial α) 0 = 1 := rfl
@[simp] lemma add_apply (p q : polynomial α) (n : ℕ) : (p + q) n = p n + q n :=
finsupp.add_apply
lemma C_apply : (C a : ℕ → α) n = ite (0 = n) a 0 := rfl
@[simp] lemma C_apply_zero : (C a : ℕ → α) 0 = a := rfl
@[simp] lemma X_apply_one : (X : polynomial α) 1 = 1 := rfl
@[simp] lemma C_0 : C (0 : α) = 0 := by simp [C]; refl
@[simp] lemma C_1 : C (1 : α) = 1 := rfl
@[simp] lemma C_mul_C : C a * C b = C (a * b) :=
by simp [C, single_mul_single]
@[simp] lemma C_mul_apply (p : polynomial α) : (C a * p) n = a * p n :=
begin
conv in (a * _) { rw [← @sum_single _ _ _ _ _ p, sum_apply] },
rw [mul_def, C, sum_single_index],
{ simp [single_apply, finsupp.mul_sum],
apply sum_congr rfl,
assume i hi, by_cases i = n; simp [h] },
simp
end
@[simp] lemma X_pow_apply (n i : ℕ) : (X ^ n : polynomial α) i = (if n = i then 1 else 0) :=
suffices (single n 1 : polynomial α) i = (if n = i then 1 else 0),
by rw [single_eq_C_mul_X] at this; simpa,
single_apply
section eval
variable {x : α}
/-- `eval x p` is the evaluation of the polynomial `p` at `x` -/
def eval (x : α) (p : polynomial α) : α :=
p.sum (λ e a, a * x ^ e)
@[simp] lemma eval_C : (C a).eval x = a :=
by simp [C, eval, sum_single_index]
@[simp] lemma eval_X : X.eval x = x :=
by simp [X, eval, sum_single_index]
@[simp] lemma eval_zero : (0 : polynomial α).eval x = 0 :=
finsupp.sum_zero_index
@[simp] lemma eval_add : (p + q).eval x = p.eval x + q.eval x :=
finsupp.sum_add_index (by simp) (by simp [add_mul])
@[simp] lemma eval_one : (1 : polynomial α).eval x = 1 :=
by rw [← C_1, eval_C]
@[simp] lemma eval_mul : (p * q).eval x = p.eval x * q.eval x :=
begin
dunfold eval,
rw [mul_def, finsupp.sum_mul _ p],
simp [finsupp.mul_sum _ q, sum_sum_index, sum_single_index, add_mul, pow_add],
exact sum_congr rfl (assume i hi, sum_congr rfl $ assume j hj, by ac_refl)
end
/-- `is_root p x` implies `x` is a root of `p`. The evaluation of `p` at `x` is zero -/
def is_root (p : polynomial α) (a : α) : Prop := p.eval a = 0
instance : decidable (is_root p a) := by unfold is_root; apply_instance
@[simp] lemma is_root.def : is_root p a ↔ p.eval a = 0 := iff.rfl
lemma root_mul_left_of_is_root (p : polynomial α) {q : polynomial α} :
is_root q a → is_root (p * q) a :=
by simp [is_root.def, eval_mul] {contextual := tt}
lemma root_mul_right_of_is_root {p : polynomial α} (q : polynomial α) :
is_root p a → is_root (p * q) a :=
by simp [is_root.def, eval_mul] {contextual := tt}
end eval
/-- `leading_coeff p` gives the coefficient of the highest power of `X` in `p`-/
def leading_coeff (p : polynomial α) : α := p (nat_degree p)
/-- a polynomial is `monic` if its leading coefficient is 1 -/
def monic (p : polynomial α) := leading_coeff p = (1 : α)
lemma monic.def : monic p ↔ leading_coeff p = 1 := iff.rfl
instance monic.decidable : decidable (monic p) :=
by unfold monic; apply_instance
@[simp] lemma degree_zero : degree (0 : polynomial α) = ⊥ := rfl
@[simp] lemma degree_C (ha : a ≠ 0) : degree (C a) = (0 : with_bot ℕ) :=
show sup (ite (a = 0) ∅ {0}) some = 0,
by rw [if_neg ha]; refl
lemma degree_C_le : degree (C a) ≤ (0 : with_bot ℕ) :=
by by_cases h : a = 0; simp [h]; exact le_refl _
lemma degree_one_le : degree (1 : polynomial α) ≤ (0 : with_bot ℕ) :=
by rw [← C_1]; exact degree_C_le
lemma degree_eq_bot : degree p = ⊥ ↔ p = 0 :=
⟨λ h, by rw [degree, ← max_eq_sup_with_bot] at h;
exact support_eq_empty.1 (max_eq_none.1 h),
λ h, h.symm ▸ rfl⟩
lemma degree_eq_nat_degree (hp : p ≠ 0) : degree p = (nat_degree p : with_bot ℕ) :=
let ⟨n, hn⟩ :=
classical.not_forall.1 (mt option.eq_none_iff_forall_not_mem.2 (mt degree_eq_bot.1 hp)) in
have hn : degree p = some n := not_not.1 hn,
by rw [nat_degree, hn]; refl
lemma nat_degree_eq_of_degree_eq (h : degree p = degree q) : nat_degree p = nat_degree q :=
by unfold nat_degree; rw h
@[simp] lemma nat_degree_C (a : α) : nat_degree (C a) = 0 :=
begin
by_cases ha : a = 0,
{ have : C a = 0, { simp [ha] },
rw [nat_degree, degree_eq_bot.2 this],
refl },
{ rw [nat_degree, degree_C ha], refl }
end
@[simp] lemma degree_monomial (n : ℕ) (ha : a ≠ 0) : degree (C a * X ^ n) = n :=
by rw [← single_eq_C_mul_X, degree, support_single_ne_zero ha]; refl
lemma degree_monomial_le (n : ℕ) (a : α) : degree (C a * X ^ n) ≤ n :=
if h : a = 0 then by simp [h] else le_of_eq (degree_monomial n h)
lemma le_degree_of_ne_zero (h : p n ≠ 0) : (n : with_bot ℕ) ≤ degree p :=
show @has_le.le (with_bot ℕ) _ (some n : with_bot ℕ) (p.support.sup some : with_bot ℕ),
from finset.le_sup ((finsupp.mem_support_iff _ _).2 h)
lemma eq_zero_of_degree_lt (h : degree p < n) : p n = 0 :=
not_not.1 (mt le_degree_of_ne_zero (not_le_of_gt h))
lemma ne_zero_of_degree_gt {n : with_bot ℕ} (h : n < degree p) : p ≠ 0 :=
mt degree_eq_bot.2 (ne.symm (ne_of_lt (lt_of_le_of_lt bot_le h)))
lemma eq_C_of_degree_le_zero (h : degree p ≤ 0) : p = C (p 0) :=
begin
ext n,
cases n,
{ refl },
{ have : degree p < ↑(nat.succ n) := lt_of_le_of_lt h (with_bot.some_lt_some.2 (nat.succ_pos _)),
rw [C_apply, if_neg (nat.succ_ne_zero _).symm, eq_zero_of_degree_lt this] }
end
lemma degree_add_le (p q : polynomial α) : degree (p + q) ≤ max (degree p) (degree q) :=
calc degree (p + q) = ((p + q).support).sup some : rfl
... ≤ (p.support ∪ q.support).sup some : sup_mono support_add
... = p.support.sup some ⊔ q.support.sup some : sup_union
... = _ : with_bot.sup_eq_max _ _
@[simp] lemma leading_coeff_zero : leading_coeff (0 : polynomial α) = 0 := rfl
@[simp] lemma leading_coeff_eq_zero : leading_coeff p = 0 ↔ p = 0 :=
⟨λ h, by_contradiction $ λ hp, mt (mem_support_iff _ _).1
(not_not.2 h) (mem_of_max (degree_eq_nat_degree hp)),
by simp {contextual := tt}⟩
lemma degree_add_eq_of_degree_lt (h : degree p < degree q) : degree (p + q) = degree q :=
le_antisymm (max_eq_right_of_lt h ▸ degree_add_le _ _) $
begin
have hq0 : q ≠ 0, { rintro rfl, exact not_lt_bot h },
rw degree_eq_nat_degree hq0 at *,
refine le_degree_of_ne_zero _,
rw [add_apply, eq_zero_of_degree_lt h, zero_add],
exact mt leading_coeff_eq_zero.1 hq0
end
lemma degree_add_eq_of_leading_coeff_add_ne_zero (h : leading_coeff p + leading_coeff q ≠ 0) :
degree (p + q) = max p.degree q.degree :=
le_antisymm (degree_add_le _ _) $
match lt_trichotomy (degree p) (degree q) with
| or.inl hlt :=
by rw [degree_add_eq_of_degree_lt hlt, max_eq_right_of_lt hlt]; exact le_refl _
| or.inr (or.inl heq) :=
have hq : q ≠ 0 := assume hq,
have hp : p = 0, by simpa [hq, degree_eq_bot] using heq,
by simpa [hp, hq] using h,
le_of_not_gt $
assume hlt : max (degree p) (degree q) > degree (p + q),
h $ show leading_coeff p + leading_coeff q = 0,
begin
rw [heq, max_self, degree_eq_nat_degree hq] at hlt,
rw [leading_coeff, leading_coeff, nat_degree_eq_of_degree_eq heq, ← add_apply],
exact eq_zero_of_degree_lt hlt,
end
| or.inr (or.inr hlt) :=
by rw [add_comm, degree_add_eq_of_degree_lt hlt, max_eq_left_of_lt hlt]; exact le_refl _
end
lemma degree_erase_le (p : polynomial α) (n : ℕ) : degree (p.erase n) ≤ degree p :=
sup_mono (erase_subset _ _)
lemma degree_erase_lt (hp : p ≠ 0) : degree (p.erase (nat_degree p)) < degree p :=
lt_of_le_of_ne (degree_erase_le _ _) $
(degree_eq_nat_degree hp).symm ▸ λ h, not_mem_erase _ _ (mem_of_max h)
lemma degree_sum_le {β : Type*} [decidable_eq β] (s : finset β) (f : β → polynomial α) :
degree (s.sum f) ≤ s.sup (degree ∘ f) :=
finset.induction_on s (by simp [finsupp.support_zero]) $
assume a s has ih,
calc degree (sum (insert a s) f) ≤ max (degree (f a)) (degree (s.sum f)) :
by rw sum_insert has; exact degree_add_le _ _
... ≤ _ : by rw [sup_insert, with_bot.sup_eq_max]; exact max_le_max (le_refl _) ih
lemma degree_mul_le (p q : polynomial α) : degree (p * q) ≤ degree p + degree q :=
calc degree (p * q) ≤ (p.support).sup (λi, degree (sum q (λj a, C (p i * a) * X ^ (i + j)))) :
by simp [single_eq_C_mul_X.symm]; exact degree_sum_le _ _
... ≤ p.support.sup (λi, q.support.sup (λj, degree (C (p i * q j) * X ^ (i + j)))) :
finset.sup_mono_fun (assume i hi, degree_sum_le _ _)
... ≤ degree p + degree q :
begin
refine finset.sup_le (λ a ha, finset.sup_le (λ b hb, _)),
by_cases hpq : p a * q b = 0,
{ simp [hpq] },
{ rw [degree_monomial _ hpq, with_bot.coe_add],
rw mem_support_iff at ha hb,
exact add_le_add' (le_degree_of_ne_zero ha) (le_degree_of_ne_zero hb) }
end
lemma degree_pow_le (p : polynomial α) : ∀ n, degree (p ^ n) ≤ add_monoid.smul n (degree p)
| 0 := by rw [pow_zero, add_monoid.zero_smul]; exact degree_one_le
| (n+1) := calc degree (p ^ (n + 1)) ≤ degree p + degree (p ^ n) :
by rw pow_succ; exact degree_mul_le _ _
... ≤ _ : by rw succ_smul; exact add_le_add' (le_refl _) (degree_pow_le _)
@[simp] lemma leading_coeff_monomial (a : α) (n : ℕ) : leading_coeff (C a * X ^ n) = a :=
begin
by_cases ha : a = 0,
{ simp [ha] },
{ rw [leading_coeff, nat_degree, degree_monomial _ ha, ← single_eq_C_mul_X],
exact finsupp.single_eq_same }
end
@[simp] lemma leading_coeff_C (a : α) : leading_coeff (C a) = a :=
suffices leading_coeff (C a * X^0) = a, by simpa,
leading_coeff_monomial a 0
@[simp] lemma leading_coeff_X : leading_coeff (X : polynomial α) = 1 :=
suffices leading_coeff (C (1:α) * X^1) = 1, by simpa,
leading_coeff_monomial 1 1
@[simp] lemma leading_coeff_one : leading_coeff (1 : polynomial α) = 1 :=
suffices leading_coeff (C (1:α) * X^0) = 1, by simpa,
leading_coeff_monomial 1 0
@[simp] lemma monic_one : monic (1 : polynomial α) := leading_coeff_C _
lemma leading_coeff_add_of_degree_lt (h : degree p < degree q) :
leading_coeff (p + q) = leading_coeff q :=
have hq0 : q ≠ 0 := ne_zero_of_degree_gt h,
have hpq0 : p + q ≠ 0 := ne_zero_of_degree_gt
(show degree p < degree (p + q), by rwa degree_add_eq_of_degree_lt h),
have h : nat_degree (p + q) = nat_degree q := option.some_inj.1 $
show (nat_degree (p + q) : with_bot ℕ) = nat_degree q,
by rw [← degree_eq_nat_degree hq0, ← degree_eq_nat_degree hpq0];
exact degree_add_eq_of_degree_lt h,
begin
unfold leading_coeff,
rw [h, add_apply, eq_zero_of_degree_lt, zero_add],
rwa ← degree_eq_nat_degree hq0
end
lemma leading_coeff_add_of_degree_eq (h : degree p = degree q)
(hlc : leading_coeff p + leading_coeff q ≠ 0) :
leading_coeff (p + q) = leading_coeff p + leading_coeff q :=
if hp0 : p = 0 then by simp [hp0]
else
have hpq0 : p + q ≠ 0 := λ hpq0,
by rw [leading_coeff, leading_coeff, nat_degree, nat_degree, h,
← add_apply, hpq0, zero_apply] at hlc;
exact hlc rfl,
have hpq : nat_degree (p + q) = nat_degree p := option.some_inj.1
$ show (nat_degree (p + q) : with_bot ℕ) = nat_degree p,
by rw [← degree_eq_nat_degree hp0, ← degree_eq_nat_degree hpq0,
degree_add_eq_of_leading_coeff_add_ne_zero hlc, h, max_self],
by rw [leading_coeff, add_apply, hpq, leading_coeff, nat_degree_eq_of_degree_eq h];
refl
@[simp] lemma mul_apply_degree_add_degree (p q : polynomial α) :
(p * q) (nat_degree p + nat_degree q) = leading_coeff p * leading_coeff q :=
begin
by_cases hpl : leading_coeff p = 0,
{ rw [hpl, zero_mul, leading_coeff_eq_zero.1 hpl, zero_mul, zero_apply] },
by_cases hql : leading_coeff q = 0,
{ rw [hql, mul_zero, leading_coeff_eq_zero.1 hql, mul_zero, zero_apply] },
calc p.sum (λ a b, sum q (λ a₂ b₂, single (a + a₂) (p a * b₂))) (nat_degree p + nat_degree q) =
p.sum (λ a b, sum q (λ a₂ b₂, C (p a * b₂) * X^(a + a₂))) (nat_degree p + nat_degree q) :
begin
apply congr_fun _ _,
congr, ext i a,
congr, ext j b,
apply single_eq_C_mul_X
end
... = sum (finset.singleton (nat_degree p))
(λ a, sum q (λ a₂ b₂, C (p a * b₂) * X^(a + a₂)) (nat_degree p + nat_degree q)) :
begin
rw [sum_apply, finsupp.sum],
refine eq.symm (sum_subset (λ n hn, (mem_support_iff _ _).2
((mem_singleton.1 hn).symm ▸ hpl)) (λ n hnp hn, _)),
rw [← @sum_const_zero _ _ q.support, finsupp.sum_apply, finsupp.sum],
refine finset.sum_congr rfl (λ m hm, _),
have : n + m ≠ nat_degree p + nat_degree q := (ne_of_lt $ add_lt_add_of_lt_of_le
(lt_of_le_of_ne
(le_of_not_gt (λ h,
have degree p < n :=
by rw degree_eq_nat_degree (mt leading_coeff_eq_zero.2 hpl);
exact with_bot.some_lt_some.2 h,
mt (mem_support_iff _ _).1 (not_not.2 (eq_zero_of_degree_lt this)) hnp))
(mt mem_singleton.2 hn))
(le_of_not_gt $ λ h,
have degree q < m :=
by rw degree_eq_nat_degree (mt leading_coeff_eq_zero.2 hql);
exact with_bot.some_lt_some.2 h,
mt eq_zero_of_degree_lt ((mem_support_iff _ _).1 hm) this)),
simp [this]
end
... = (finset.singleton (nat_degree q)).sum
(λ a, (C (p (nat_degree p) * q a) * X^(nat_degree p + a)) (nat_degree p + nat_degree q)) :
begin
rw [sum_singleton, sum_apply, finsupp.sum],
refine eq.symm (sum_subset (λ n hn, (mem_support_iff _ _).2
((mem_singleton.1 hn).symm ▸ hql)) (λ n hnq hn, _)),
have : nat_degree p + n ≠ nat_degree p + nat_degree q :=
mt add_left_cancel (mt mem_singleton.2 hn),
simp [this]
end
... = leading_coeff p * leading_coeff q :
by simp [leading_coeff]
end
lemma degree_mul_eq' (h : leading_coeff p * leading_coeff q ≠ 0) :
degree (p * q) = degree p + degree q :=
have hp : p ≠ 0 := by refine mt _ h; simp {contextual := tt},
have hq : q ≠ 0 := by refine mt _ h; by simp {contextual := tt},
le_antisymm (degree_mul_le _ _)
begin
rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq],
refine le_degree_of_ne_zero _,
rwa mul_apply_degree_add_degree
end
lemma nat_degree_mul_eq' (h : leading_coeff p * leading_coeff q ≠ 0) :
nat_degree (p * q) = nat_degree p + nat_degree q :=
have hp : p ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, by simpa [h₁] using h),
have hq : q ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, by simpa [h₁] using h),
have hpq : p * q ≠ 0 := λ hpq, by rw [← mul_apply_degree_add_degree, hpq, zero_apply] at h;
exact h rfl,
option.some_inj.1 (show (nat_degree (p * q) : with_bot ℕ) = nat_degree p + nat_degree q,
by rw [← degree_eq_nat_degree hpq, degree_mul_eq' h, degree_eq_nat_degree hp, degree_eq_nat_degree hq])
lemma leading_coeff_mul' (h : leading_coeff p * leading_coeff q ≠ 0) :
leading_coeff (p * q) = leading_coeff p * leading_coeff q :=
begin
unfold leading_coeff,
rw [nat_degree_mul_eq' h, mul_apply_degree_add_degree],
refl
end
lemma leading_coeff_pow' : leading_coeff p ^ n ≠ 0 →
leading_coeff (p ^ n) = leading_coeff p ^ n :=
nat.rec_on n (by simp) $
λ n ih h,
have h₁ : leading_coeff p ^ n ≠ 0 :=
λ h₁, by simpa [h₁, pow_succ] using h,
have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 :=
by rwa [pow_succ, ← ih h₁] at h,
by rw [pow_succ, pow_succ, leading_coeff_mul' h₂, ih h₁]
lemma degree_pow_eq' : ∀ {n}, leading_coeff p ^ n ≠ 0 →
degree (p ^ n) = add_monoid.smul n (degree p)
| 0 := λ h, by rw [pow_zero, ← C_1] at *;
rw [degree_C h, add_monoid.zero_smul]
| (n+1) := λ h,
have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁,
by simpa [h₁, pow_succ] using h,
have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 :=
by rwa [pow_succ, ← leading_coeff_pow' h₁] at h,
by rw [pow_succ, degree_mul_eq' h₂, succ_smul, degree_pow_eq' h₁]
end comm_semiring
section comm_ring
variables [comm_ring α] {p q : polynomial α}
instance : comm_ring (polynomial α) := finsupp.to_comm_ring
instance : has_scalar α (polynomial α) := finsupp.to_has_scalar
instance : module α (polynomial α) := finsupp.to_module
instance {x : α} : is_ring_hom (eval x) := ⟨λ x y, eval_add, λ x y, eval_mul, eval_C⟩
@[simp] lemma degree_neg (p : polynomial α) : degree (-p) = degree p :=
by unfold degree; rw support_neg
@[simp] lemma neg_apply (p : polynomial α) (n : ℕ) : (-p) n = -p n := neg_apply
@[simp] lemma eval_neg (p : polynomial α) (x : α) : (-p).eval x = -p.eval x :=
is_ring_hom.map_neg _
@[simp] lemma eval_sub (p q : polynomial α) (x : α) : (p - q).eval x = p.eval x - q.eval x :=
is_ring_hom.map_sub _
lemma degree_sub_lt (hd : degree p = degree q)
(hp0 : p ≠ 0) (hlc : leading_coeff p = leading_coeff q) :
degree (p - q) < degree p :=
have hp : single (nat_degree p) (leading_coeff p) + p.erase (nat_degree p) = p :=
finsupp.single_add_erase,
have hq : single (nat_degree q) (leading_coeff q) + q.erase (nat_degree q) = q :=
finsupp.single_add_erase,
have hd' : nat_degree p = nat_degree q := by unfold nat_degree; rw hd,
have hq0 : q ≠ 0 := mt degree_eq_bot.2 (hd ▸ mt degree_eq_bot.1 hp0),
calc degree (p - q) = degree (erase (nat_degree q) p + -erase (nat_degree q) q) :
by conv {to_lhs, rw [← hp, ← hq, hlc, hd', add_sub_add_left_eq_sub, sub_eq_add_neg]}
... ≤ max (degree (erase (nat_degree q) p)) (degree (erase (nat_degree q) q))
: degree_neg (erase (nat_degree q) q) ▸ degree_add_le _ _
... < degree p : max_lt_iff.2 ⟨hd' ▸ degree_erase_lt hp0, hd.symm ▸ degree_erase_lt hq0⟩
instance : has_well_founded (polynomial α) := ⟨_, degree_lt_wf⟩
lemma ne_zero_of_ne_zero_of_monic (hp : p ≠ 0) (hq : monic q) : q ≠ 0
| h := begin
rw [h, monic.def, leading_coeff_zero] at hq,
rw [← mul_one p, ← C_1, ← hq, C_0, mul_zero] at hp,
exact hp rfl
end
lemma div_wf_lemma (h : degree q ≤ degree p ∧ p ≠ 0) (hq : monic q) :
degree (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) < degree p :=
have hp : leading_coeff p ≠ 0 := mt leading_coeff_eq_zero.1 h.2,
have hpq : leading_coeff (C (leading_coeff p) * X ^ (nat_degree p - nat_degree q)) *
leading_coeff q ≠ 0,
by rwa [leading_coeff_monomial, monic.def.1 hq, mul_one],
if h0 : p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q = 0
then h0.symm ▸ (lt_of_not_ge $ mt le_bot_iff.1 (mt degree_eq_bot.1 h.2))
else
have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic h.2 hq,
have hlt : nat_degree q ≤ nat_degree p := with_bot.coe_le_coe.1
(by rw [← degree_eq_nat_degree h.2, ← degree_eq_nat_degree hq0];
exact h.1),
degree_sub_lt
(by rw [degree_mul_eq' hpq, degree_monomial _ hp, degree_eq_nat_degree h.2,
degree_eq_nat_degree hq0, ← with_bot.coe_add, nat.sub_add_cancel hlt])
h.2
(by rw [leading_coeff_mul' hpq, leading_coeff_monomial, monic.def.1 hq, mul_one])
def div_mod_by_monic_aux : Π (p : polynomial α) {q : polynomial α},
monic q → polynomial α × polynomial α
| p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then
let z := C (leading_coeff p) * X^(nat_degree p - nat_degree q) in
have wf : _ := div_wf_lemma h hq,
let dm := div_mod_by_monic_aux (p - z * q) hq in
⟨z + dm.1, dm.2⟩
else ⟨0, p⟩
using_well_founded {dec_tac := tactic.assumption}
/-- `div_by_monic` gives the quotient of `p` by a monic polynomial `q`. -/
def div_by_monic (p q : polynomial α) : polynomial α :=
if hq : monic q then (div_mod_by_monic_aux p hq).1 else 0
/-- `mod_by_monic` gives the remainder of `p` by a monic polynomial `q`. -/
def mod_by_monic (p q : polynomial α) : polynomial α :=
if hq : monic q then (div_mod_by_monic_aux p hq).2 else p
infixl ` /ₘ ` : 70 := div_by_monic
infixl ` %ₘ ` : 70 := mod_by_monic
lemma degree_mod_by_monic_lt : ∀ (p : polynomial α) {q : polynomial α} (hq : monic q)
(hq0 : q ≠ 0), degree (p %ₘ q) < degree q
| p := λ q hq hq0,
if h : degree q ≤ degree p ∧ p ≠ 0 then
have wf : _ := div_wf_lemma ⟨h.1, h.2⟩ hq,
have degree ((p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) %ₘ q) < degree q :=
degree_mod_by_monic_lt (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q)
hq hq0,
begin
unfold mod_by_monic at this ⊢,
unfold div_mod_by_monic_aux,
rw dif_pos hq at this ⊢,
rw if_pos h,
exact this
end
else
or.cases_on (not_and_distrib.1 h) begin
unfold mod_by_monic div_mod_by_monic_aux,
rw [dif_pos hq, if_neg h],
exact lt_of_not_ge,
end
begin
assume hp,
unfold mod_by_monic div_mod_by_monic_aux,
rw [dif_pos hq, if_neg h, not_not.1 hp],
exact lt_of_le_of_ne bot_le
(ne.symm (mt degree_eq_bot.1 hq0)),
end
using_well_founded {dec_tac := tactic.assumption}
lemma mod_by_monic_eq_sub_mul_div : ∀ (p : polynomial α) {q : polynomial α} (hq : monic q),
p %ₘ q = p - q * (p /ₘ q)
| p := λ q hq,
if h : degree q ≤ degree p ∧ p ≠ 0 then
have wf : _ := div_wf_lemma h hq,
have ih : _ := mod_by_monic_eq_sub_mul_div
(p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq,
begin
unfold mod_by_monic div_by_monic div_mod_by_monic_aux,
rw [dif_pos hq, if_pos h],
rw [mod_by_monic, dif_pos hq] at ih,
refine ih.trans _,
simp [mul_add, add_mul, mul_comm, hq, h, div_by_monic]
end
else
begin
unfold mod_by_monic div_by_monic div_mod_by_monic_aux,
rw [dif_pos hq, if_neg h, dif_pos hq, if_neg h],
simp
end
using_well_founded {dec_tac := tactic.assumption}
lemma subsingleton_of_monic_zero (h : monic (0 : polynomial α)) :
(∀ p q : polynomial α, p = q) ∧ (∀ a b : α, a = b) :=
by rw [monic.def, leading_coeff_zero] at h;
exact ⟨λ p q, by rw [← mul_one p, ← mul_one q, ← C_1, ← h, C_0, mul_zero, mul_zero],
λ a b, by rw [← mul_one a, ← mul_one b, ← h, mul_zero, mul_zero]⟩
lemma mod_by_monic_add_div (p : polynomial α) {q : polynomial α} (hq : monic q) :
p %ₘ q + q * (p /ₘ q) = p := eq_sub_iff_add_eq.1 (mod_by_monic_eq_sub_mul_div p hq)
@[simp] lemma zero_mod_by_monic (p : polynomial α) : 0 %ₘ p = 0 :=
begin
unfold mod_by_monic div_mod_by_monic_aux,
split_ifs;
simp * at *
end
@[simp] lemma zero_div_by_monic (p : polynomial α) : 0 /ₘ p = 0 :=
begin
unfold div_by_monic div_mod_by_monic_aux,
split_ifs;
simp * at *
end
@[simp] lemma mod_by_monic_zero (p : polynomial α) : p %ₘ 0 = p :=
if h : monic (0 : polynomial α) then (subsingleton_of_monic_zero h).1 _ _ else
begin
unfold mod_by_monic div_mod_by_monic_aux,
split_ifs;
simp * at *
end
@[simp] lemma div_by_monic_zero (p : polynomial α) : p /ₘ 0 = 0 :=
if h : monic (0 : polynomial α) then (subsingleton_of_monic_zero h).1 _ _ else
begin
unfold div_by_monic div_mod_by_monic_aux,
split_ifs;
simp * at *
end
lemma div_by_monic_eq_of_not_monic (p : polynomial α) (hq : ¬monic q) : p /ₘ q = 0 := dif_neg hq
lemma mod_by_monic_eq_of_not_monic (p : polynomial α) (hq : ¬monic q) : p %ₘ q = p := dif_neg hq
lemma mod_by_monic_eq_self_iff (hq : monic q) (hq0 : q ≠ 0) : p %ₘ q = p ↔ degree p < degree q :=
⟨λ h, h ▸ degree_mod_by_monic_lt _ hq hq0,
λ h, have ¬ degree q ≤ degree p := not_le_of_gt h,
by unfold mod_by_monic div_mod_by_monic_aux; simp *⟩
lemma div_by_monic_eq_zero_iff (hq : monic q) (hq0 : q ≠ 0) : p /ₘ q = 0 ↔ degree p < degree q :=
⟨λ h, by have := mod_by_monic_add_div p hq;
rwa [h, mul_zero, add_zero, mod_by_monic_eq_self_iff hq hq0] at this,
λ h, have ¬ degree q ≤ degree p := not_le_of_gt h,
by unfold div_by_monic div_mod_by_monic_aux; simp *⟩
lemma degree_add_div_by_monic (hq : monic q) (h : degree q ≤ degree p) :
degree q + degree (p /ₘ q) = degree p :=
if hq0 : q = 0 then
have ∀ (p : polynomial α), p = 0,
from λ p, (@subsingleton_of_monic_zero α _ _ (hq0 ▸ hq)).1 _ _,
by rw [this (p /ₘ q), this p, this q]; refl
else
have hdiv0 : p /ₘ q ≠ 0 := by rwa [(≠), div_by_monic_eq_zero_iff hq hq0, not_lt],
have hlc : leading_coeff q * leading_coeff (p /ₘ q) ≠ 0 :=
by rwa [monic.def.1 hq, one_mul, (≠), leading_coeff_eq_zero],
have hmod : degree (p %ₘ q) < degree (q * (p /ₘ q)) :=
calc degree (p %ₘ q) < degree q : degree_mod_by_monic_lt _ hq hq0
... ≤ _ : by rw [degree_mul_eq' hlc, degree_eq_nat_degree hq0,
degree_eq_nat_degree hdiv0, ← with_bot.coe_add, with_bot.coe_le_coe];
exact nat.le_add_right _ _,
calc degree q + degree (p /ₘ q) = degree (q * (p /ₘ q)) : eq.symm (degree_mul_eq' hlc)
... = degree (p %ₘ q + q * (p /ₘ q)) : (degree_add_eq_of_degree_lt hmod).symm
... = _ : congr_arg _ (mod_by_monic_add_div _ hq)
lemma degree_div_by_monic_le (p q : polynomial α) : degree (p /ₘ q) ≤ degree p :=
if hp0 : p = 0 then by simp [hp0]
else if hq : monic q then
have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic hp0 hq,
if h : degree q ≤ degree p
then by rw [← degree_add_div_by_monic hq h, degree_eq_nat_degree hq0,
degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq hq0).1 (not_lt.2 h))];
exact with_bot.coe_le_coe.2 (nat.le_add_left _ _)
else
by unfold div_by_monic div_mod_by_monic_aux;
simp [dif_pos hq, h]
else (div_by_monic_eq_of_not_monic p hq).symm ▸ bot_le
lemma degree_div_by_monic_lt (p : polynomial α) {q : polynomial α} (hq : monic q)
(hp0 : p ≠ 0) (h0q : 0 < degree q) : degree (p /ₘ q) < degree p :=
have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic hp0 hq,
if hpq : degree p < degree q
then begin
rw [(div_by_monic_eq_zero_iff hq hq0).2 hpq, degree_eq_nat_degree hp0],
exact with_bot.bot_lt_some _
end
else begin
rw [← degree_add_div_by_monic hq (not_lt.1 hpq), degree_eq_nat_degree hq0,
degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq hq0).1 hpq)],
exact with_bot.coe_lt_coe.2 (nat.lt_add_of_pos_left
(with_bot.coe_lt_coe.1 $ (degree_eq_nat_degree hq0) ▸ h0q))
end
lemma dvd_iff_mod_by_monic_eq_zero (hq : monic q) : p %ₘ q = 0 ↔ q ∣ p :=
⟨λ h, by rw [← mod_by_monic_add_div p hq, h, zero_add];
exact dvd_mul_right _ _,
λ h, if hq0 : q = 0 then by rw hq0 at hq;
exact (subsingleton_of_monic_zero hq).1 _ _
else
let ⟨r, hr⟩ := exists_eq_mul_right_of_dvd h in
by_contradiction (λ hpq0,
have hmod : p %ₘ q = q * (r - p /ₘ q) :=
by rw [mod_by_monic_eq_sub_mul_div _ hq, mul_sub, ← hr],
have degree (q * (r - p /ₘ q)) < degree q :=
hmod ▸ degree_mod_by_monic_lt _ hq hq0,
have hrpq0 : leading_coeff (r - p /ₘ q) ≠ 0 :=
λ h, hpq0 $ leading_coeff_eq_zero.1
(by rw [hmod, leading_coeff_eq_zero.1 h, mul_zero, leading_coeff_zero]),
have hlc : leading_coeff q * leading_coeff (r - p /ₘ q) ≠ 0 :=
by rwa [monic.def.1 hq, one_mul],
by rw [degree_mul_eq' hlc, degree_eq_nat_degree hq0,
degree_eq_nat_degree (mt leading_coeff_eq_zero.2 hrpq0)] at this;
exact not_lt_of_ge (nat.le_add_right _ _) (with_bot.some_lt_some.1 this))⟩
end comm_ring
section nonzero_comm_ring
variables [nonzero_comm_ring α] {p q : polynomial α}
instance : nonzero_comm_ring (polynomial α) :=
{ zero_ne_one := λ (h : (0 : polynomial α) = 1),
@zero_ne_one α _ $
calc (0 : α) = eval 0 0 : eval_zero.symm
... = eval 0 1 : congr_arg _ h
... = 1 : eval_C,
..polynomial.comm_ring }
@[simp] lemma degree_one : degree (1 : polynomial α) = (0 : with_bot ℕ) :=
degree_C (show (1 : α) ≠ 0, from zero_ne_one.symm)
@[simp] lemma degree_X : degree (X : polynomial α) = 1 :=
begin
unfold X degree single finsupp.support,
rw if_neg (zero_ne_one).symm,
refl
end
@[simp] lemma degree_X_sub_C (a : α) : degree (X - C a) = 1 :=
begin
rw [sub_eq_add_neg, add_comm, ← @degree_X α],
by_cases ha : a = 0,
{ simp [ha] },
exact degree_add_eq_of_degree_lt (by rw [degree_X, degree_neg, degree_C ha]; exact dec_trivial)
end
@[simp] lemma not_monic_zero : ¬monic (0 : polynomial α) :=
by simp [monic, zero_ne_one]
lemma ne_zero_of_monic (h : monic p) : p ≠ 0 :=
λ h₁, @not_monic_zero α _ _ (h₁ ▸ h)
lemma monic_X_sub_C (a : α) : monic (X - C a) :=
have degree (-C a) < degree (X : polynomial α) :=
if ha : a = 0 then by simp [ha]; exact dec_trivial else by simp [degree_C ha]; exact dec_trivial,
by unfold monic;
rw [sub_eq_add_neg, add_comm, leading_coeff_add_of_degree_lt this, leading_coeff_X]
lemma root_X_sub_C : is_root (X - C a) b ↔ a = b :=
by rw [is_root.def, eval_sub, eval_X, eval_C, sub_eq_zero_iff_eq, eq_comm]
@[simp] lemma mod_by_monic_X_sub_C_eq_C_eval (p : polynomial α) (a : α) : p %ₘ (X - C a) = C (p.eval a) :=
have h : (p %ₘ (X - C a)).eval a = p.eval a :=
by rw [mod_by_monic_eq_sub_mul_div _ (monic_X_sub_C a), eval_sub, eval_mul,
eval_sub, eval_X, eval_C, sub_self, zero_mul, sub_zero],
have degree (p %ₘ (X - C a)) < 1 :=
degree_X_sub_C a ▸ degree_mod_by_monic_lt p (monic_X_sub_C a) ((degree_X_sub_C a).symm ▸
ne_zero_of_monic (monic_X_sub_C _)),
have degree (p %ₘ (X - C a)) ≤ 0 :=
begin
cases (degree (p %ₘ (X - C a))),
{ exact bot_le },
{ exact with_bot.some_le_some.2 (nat.le_of_lt_succ (with_bot.some_lt_some.1 this)) }
end,
begin
rw [eq_C_of_degree_le_zero this, eval_C] at h,
rw [eq_C_of_degree_le_zero this, h]
end
lemma mul_div_by_monic_eq_iff_is_root : (X - C a) * (p /ₘ (X - C a)) = p ↔ is_root p a :=
⟨λ h, by rw [← h, is_root.def, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul],
λ h : p.eval a = 0,
by conv {to_rhs, rw ← mod_by_monic_add_div p (monic_X_sub_C a)};
rw [mod_by_monic_X_sub_C_eq_C_eval, h, C_0, zero_add]⟩
end nonzero_comm_ring
section integral_domain
variables [integral_domain α] {p q : polynomial α}
@[simp] lemma degree_mul_eq : degree (p * q) = degree p + degree q :=
if hp0 : p = 0 then by simp [hp0]
else if hq0 : q = 0 then by simp [hq0]
else degree_mul_eq' $ mul_ne_zero (mt leading_coeff_eq_zero.1 hp0)
(mt leading_coeff_eq_zero.1 hq0)
@[simp] lemma degree_pow_eq (p : polynomial α) (n : ℕ) :
degree (p ^ n) = add_monoid.smul n (degree p) :=
by induction n; simp [*, pow_succ, succ_smul]
@[simp] lemma leading_coeff_mul (p q : polynomial α) : leading_coeff (p * q) =
leading_coeff p * leading_coeff q :=
begin
by_cases hp : p = 0,
{ simp [hp] },
{ by_cases hq : q = 0,
{ simp [hq] },
{ rw [leading_coeff_mul'],
exact mul_ne_zero (mt leading_coeff_eq_zero.1 hp) (mt leading_coeff_eq_zero.1 hq) } }
end
@[simp] lemma leading_coeff_pow (p : polynomial α) (n : ℕ) :
leading_coeff (p ^ n) = leading_coeff p ^ n :=
by induction n; simp [*, pow_succ]
instance : integral_domain (polynomial α) :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, begin
have : leading_coeff 0 = leading_coeff a * leading_coeff b := h ▸ leading_coeff_mul a b,
rw [leading_coeff_zero, eq_comm] at this,
rw [← leading_coeff_eq_zero, ← leading_coeff_eq_zero],
exact eq_zero_or_eq_zero_of_mul_eq_zero this
end,
..polynomial.nonzero_comm_ring }
lemma root_or_root_of_root_mul (h : is_root (p * q) a) : is_root p a ∨ is_root q a :=
by rw [is_root, eval_mul] at h;
exact eq_zero_or_eq_zero_of_mul_eq_zero h
lemma degree_pos_of_root (hp : p ≠ 0) (h : is_root p a) : 0 < degree p :=
lt_of_not_ge $ λ hlt, begin
have := eq_C_of_degree_le_zero hlt,
rw [is_root, this, eval_C] at h,
exact hp (ext (λ n, show p n = 0, from
nat.cases_on n h (λ _, eq_zero_of_degree_lt (lt_of_le_of_lt hlt
(with_bot.coe_lt_coe.2 (nat.succ_pos _)))))),
end
lemma exists_finset_roots : ∀ {p : polynomial α} (hp : p ≠ 0),
∃ s : finset α, (s.card : with_bot ℕ) ≤ degree p ∧ ∀ x, x ∈ s ↔ is_root p x
| p := λ hp, by haveI := classical.prop_decidable (∃ x, is_root p x); exact
if h : ∃ x, is_root p x
then
let ⟨x, hx⟩ := h in
have hpd : 0 < degree p := degree_pos_of_root hp hx,
have hd0 : p /ₘ (X - C x) ≠ 0 :=
λ h, by have := mul_div_by_monic_eq_iff_is_root.2 hx;
simp * at *,
have wf : degree (p /ₘ _) < degree p :=
degree_div_by_monic_lt _ (monic_X_sub_C x) hp
((degree_X_sub_C x).symm ▸ dec_trivial),
let ⟨t, htd, htr⟩ := @exists_finset_roots (p /ₘ (X - C x)) hd0 in
have hdeg : degree (X - C x) ≤ degree p := begin
rw [degree_X_sub_C, degree_eq_nat_degree hp],
rw degree_eq_nat_degree hp at hpd,
exact with_bot.coe_le_coe.2 (with_bot.coe_lt_coe.1 hpd)
end,
have hdiv0 : p /ₘ (X - C x) ≠ 0 := mt (div_by_monic_eq_zero_iff (monic_X_sub_C x)
(ne_zero_of_monic (monic_X_sub_C x))).1 $ not_lt.2 hdeg,
⟨insert x t, calc (card (insert x t) : with_bot ℕ) ≤ card t + 1 :
with_bot.coe_le_coe.2 $ finset.card_insert_le _ _
... ≤ degree p :
by rw [← degree_add_div_by_monic (monic_X_sub_C x) hdeg,
degree_X_sub_C, add_comm];
exact add_le_add' (le_refl (1 : with_bot ℕ)) htd,
begin
assume y,
rw [mem_insert, htr, eq_comm, ← root_X_sub_C],
conv {to_rhs, rw ← mul_div_by_monic_eq_iff_is_root.2 hx},
exact ⟨λ h, or.cases_on h (root_mul_right_of_is_root _) (root_mul_left_of_is_root _),
root_or_root_of_root_mul⟩
end⟩
else
⟨∅, (degree_eq_nat_degree hp).symm ▸ with_bot.coe_le_coe.2 (nat.zero_le _),
by clear exists_finset_roots; finish⟩
using_well_founded {dec_tac := tactic.assumption}
/-- `roots p` noncomputably gives a finset containing all the roots of `p` -/
noncomputable def roots (p : polynomial α) : finset α :=
if h : p = 0 then ∅ else classical.some (exists_finset_roots h)
lemma card_roots (hp0 : p ≠ 0) : ((roots p).card : with_bot ℕ) ≤ degree p :=
begin
unfold roots,
rw dif_neg hp0,
exact (classical.some_spec (exists_finset_roots hp0)).1
end
@[simp] lemma mem_roots (hp : p ≠ 0) : a ∈ p.roots ↔ is_root p a :=
by unfold roots; rw dif_neg hp; exact (classical.some_spec (exists_finset_roots hp)).2 _
end integral_domain
section field
variables [field α] {p q : polynomial α}
instance : vector_space α (polynomial α) :=
{ ..finsupp.to_module }
lemma monic_mul_leading_coeff_inv (h : p ≠ 0) :
monic (p * C (leading_coeff p)⁻¹) :=
by rw [monic, leading_coeff_mul, leading_coeff_C,
mul_inv_cancel (show leading_coeff p ≠ 0, from mt leading_coeff_eq_zero.1 h)]
lemma degree_mul_leading_coeff_inv (h : p ≠ 0) :
degree (p * C (leading_coeff p)⁻¹) = degree p :=
have h₁ : (leading_coeff p)⁻¹ ≠ 0 :=
inv_ne_zero (mt leading_coeff_eq_zero.1 h),
by rw [degree_mul_eq, degree_C h₁, add_zero]
def div (p q : polynomial α) :=
C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹))
def mod (p q : polynomial α) :=
p %ₘ (q * C (leading_coeff q)⁻¹)
private lemma quotient_mul_add_remainder_eq_aux (p q : polynomial α) :
q * div p q + mod p q = p :=
if h : q = 0 then by simp [h, mod_by_monic, div, mod]
else begin
conv {to_rhs, rw ← mod_by_monic_add_div p (monic_mul_leading_coeff_inv h)},
rw [div, mod, add_comm, mul_assoc]
end
private lemma val_remainder_lt_aux (p : polynomial α) (hq : q ≠ 0) :
degree (mod p q) < degree q :=
degree_mul_leading_coeff_inv hq ▸
degree_mod_by_monic_lt p (monic_mul_leading_coeff_inv hq)
(mul_ne_zero hq (mt leading_coeff_eq_zero.2 (by rw leading_coeff_C;
exact inv_ne_zero (mt leading_coeff_eq_zero.1 hq))))
instance : has_div (polynomial α) := ⟨div⟩
instance : has_mod (polynomial α) := ⟨mod⟩
lemma mod_by_monic_eq_mod (p : polynomial α) (hq : monic q) : p %ₘ q = p % q :=
show p %ₘ q = p %ₘ (q * C (leading_coeff q)⁻¹), by simp [monic.def.1 hq]
lemma div_by_monic_eq_div (p : polynomial α) (hq : monic q) : p /ₘ q = p / q :=
show p /ₘ q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)),
by simp [monic.def.1 hq]
lemma mod_X_sub_C_eq_C_eval (p : polynomial α) (a : α) : p % (X - C a) = C (p.eval a) :=
mod_by_monic_eq_mod p (monic_X_sub_C a) ▸ mod_by_monic_X_sub_C_eq_C_eval _ _
lemma mul_div_eq_iff_is_root : (X - C a) * (p / (X - C a)) = p ↔ is_root p a :=
div_by_monic_eq_div p (monic_X_sub_C a) ▸ mul_div_by_monic_eq_iff_is_root
/-
instance : euclidean_domain (polynomial α) :=
{ quotient := div_aux,
remainder := mod_aux,
quotient_mul_add_remainder_eq := quotient_mul_add_remainder_eq_aux,
valuation := euclid_val_poly,
val_remainder_lt := λ p q hq, val_remainder_lt_aux _ hq,
val_le_mul_left := λ p q hq,
if hp : p = 0 then begin
unfold euclid_val_poly,
rw [if_pos hp],
exact nat.zero_le _
end
else begin
unfold euclid_val_poly,
rw [if_neg hp, if_neg (mul_ne_zero hp hq), degree_mul_eq hp hq],
exact nat.succ_le_succ (nat.le_add_right _ _),
end }
lemma degree_add_div (p : polynomial α) {q : polynomial α} (hq0 : q ≠ 0) :
degree q + degree (p / q) = degree p := sorry
-/
end field
end polynomial
|
8703f03679cc68640c0eee3c8515ab057f85b71b | 6fb1523f14e3297f9ad9b10eb132e6170b011888 | /src/2021/sets/sheet7.lean | b6c1c6092448a94970fa1f847d38413464cd70b9 | [] | no_license | jfmc/M40001_lean | 392ef2ca3984f0d56b2f9bb22eafc45416e694ba | 4502e3eb1af550c345cfda3aef7ffa89474fac24 | refs/heads/master | 1,693,810,669,330 | 1,634,755,889,000 | 1,634,755,889,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,713 | lean | /-
Copyright (c) 2021 Kevin Buzzard. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author : Kevin Buzzard
-/
import tactic -- imports all the Lean tactics
/-!
# Sets in Lean, sheet 7 : the sets API
It might have occurred to you that if you had a prove
things like commutativity of `∩` every time you needed it,
then things would get boring quite quickly.
Fortunately, the writers of Lean's mathematics library
already proved these things and *gave the proofs names*.
On the previous sheet you showed that you could do these
things yourself, so on this sheet I'll tell you the names
of the Lean versions of the proofs, and show you how to use them.
Here are some examples of proof names in Lean.
`set.union_comm A B : A ∪ B = B ∪ A`
`set.inter_comm A B : A ∩ B = B ∩ A`
-- note `A ∪ B ∪ C` means `(A ∪ B) ∪ C`
`set.union_assoc A B C : A ∪ B ∪ C = A ∪ (B ∪ C)`
-- similar comment for `∩`
`set.inter_assoc A B C : A ∩ B ∩ C = A ∩ (B ∩ C)`
(A technical point: note that `∪` and `∩` are "left associative",
in contrast to `→` which is right associative: `P → Q → R` means `P → (Q → R)`).
These lemmas are all in the `set` namespace (i.e. their full names
all begin with `set.`). It's annoying having to type `set.` all the time
so we `open set` which means you can skip it and just write things
like `union_comm A B`.
Note that `union_comm A B` is the *proof* that `A ∪ B = B ∪ A`.
In the language of type theory, `union_comm A B` is a
"term of type `A ∪ B = B ∪ A`". Let's just compare this with what we
were seeing in the logic sheet:
```
P : Prop -- P is a proposition
hP : P -- hP is a proof of P
```
Similarly here we have
```
A ∪ B = B ∪ A : Prop -- this is the *statement*
union_comm A B : A ∪ B = B ∪ A -- this is the *proof*
```
## New tactics you will need
* `rw` ("rewrite")
### The `rw` tactic
If `h : A = B` or `h : P ↔ Q` is a proof of either an equality, or a
logical equivalence, then `rw h,` changes all occurrences of the left
hand side of `h` in the goal, into the right hand side. So `rw` is
a "substitute in" command.
After the substitution has occurred, Lean tries `refl` just to see if it works.
For example if `A`, `B`, `C` are sets, and our context is
```
h : A = B
⊢ A ∩ C = B ∩ C
```
then `rw h` changes the goal into `B ∩ C = B ∩ C` and then solves
the goal automatically, because `refl` works.
`rw` is a smart tactic. If the goal is
```
⊢ (A ∪ B) ∩ C = D
```
and you want to change it to `⊢ (B ∪ A) ∩ C = D` then you don't
have to write `rw union_comm A B`, you can write `rw union_comm`
and Lean will figure out what you meant.
-/
open set
variables
(X : Type) -- Everything will be a subset of `X`
(A B C D E : set X) -- A,B,C,D,E are subsets of `X`
(x y z : X) -- x,y,z are elements of `X` or, more precisely, terms of type `X`
-- You can solve this one with `exact union_comm A B` or `rw union_comm`
example : A ∪ B = B ∪ A :=
begin
sorry
end
example : (A ∪ B) ∩ C = C ∩ (B ∪ A) :=
begin
sorry
end
/-
Note that `rw union_comm A` will change `A ∪ ?` to
`? ∪ A` for some set `?`. You can even do `rw union_comm _ B` if you
want to change `? ∪ B` to `B ∪ ?`
-/
example : A ∪ B ∪ C = C ∪ B ∪ A :=
begin
sorry
end
example : x ∈ A ∩ B ∩ C ↔ x ∈ B ∩ C ∩ A :=
begin
sorry
end
example : ((A ∪ B) ∪ C) ∪ D = A ∪ (B ∪ (C ∪ D)) :=
begin
sorry
end
example : A ∪ B = C ∩ D → B ∪ A ∪ E = E ∪ (C ∩ D) :=
begin
sorry
end
/-
Here are some distributivity results.
`set.union_distrib_left A B C : A ∪ (B ∩ C) = (A ∪ B) ∩ (A ∪ C)`
`set.union_distrib_right A B C : (A ∩ B) ∪ C = (A ∪ C) ∩ (B ∪ C)`
`set.inter_distrib_left A B C : A ∩ (B ∪ C) = (A ∩ B) ∪ (A ∩ C)`
`set.inter_distrib_right A B C : (A ∪ B) ∩ C = (A ∩ C) ∪ (B ∩ C)`
Which ones will you use to do the following? Note that because of the `open set`
line much earlier, you don't have to write the `set.` part of the name.
-/
example : (A ∪ B) ∩ (C ∪ D) = (A ∩ C) ∪ (B ∩ C) ∪ (A ∩ D) ∪ (B ∩ D) :=
begin
sorry
end
/-
## Top tips
How the heck are we supposed to remember all the names of these lemmas
in Lean's maths library??
Method 1) There is a logic to the naming system! You will slowly
get used to the logic.
Method 2) Until then, just use the `library_search` tactic
to look up proofs.
If you run the below code
```
example : A ∩ B = B ∩ A :=
begin
library_search
end
```
you'll see some output on the right hand side of the screen containing
the name of the lemma which proves this example.
-/
|
4a0bf8242789bda0a1c114756ba9dd073dcf3bec | 6ae186a0c6ab366b39397ec9250541c9d5aeb023 | /src/category_theory/grothendieck_category.lean | 4824f8bd935fd2f73a8a3c18fdbab7a774332382 | [] | no_license | ThanhPhamPhuong/lean-category-theory | 0d5c4fe1137866b4fe29ec2753d99aa0d0667881 | 968a29fe7c0b20e10d8a27e120aca8ddc184e1ea | refs/heads/master | 1,587,206,682,489 | 1,544,045,056,000 | 1,544,045,056,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 404 | lean | import category_theory.types
namespace category_theory
universes u v
variables {C : Type u} [𝒞 : category.{u v} C]
include 𝒞
def grothendieck_category (F : C ⥤ Type u) : category (Σ c : C, F.obj c) :=
{ hom := λ p q, { f : p.1 ⟶ q.1 // (F.map f) p.2 = q.2 },
id := λ p, ⟨ 𝟙 p.1, by obviously ⟩,
comp := λ p q r f g, ⟨ f.val ≫ g.val, by obviously ⟩ }
end category_theory |
7e5e4d274142487f40483cea5c78a146e0c29d10 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /src/Init/Lean/MetavarContext.lean | e4005dbcb48710eeb131251fa1c0c79b4f63dfb0 | [
"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 | 47,800 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Control.Reader
import Init.Data.Nat
import Init.Data.Option
import Init.Lean.Util.MonadCache
import Init.Lean.LocalContext
namespace Lean
/-
The metavariable context stores metavariable declarations and their
assignments. It is used in the elaborator, tactic framework, unifier
(aka `isDefEq`), and type class resolution (TC). First, we list all
the requirements imposed by these modules.
- We may invoke TC while executing `isDefEq`. We need this feature to
be able to solve unification problems such as:
```
f ?a (ringHasAdd ?s) ?x ?y =?= f Int intHasAdd n m
```
where `(?a : Type) (?s : Ring ?a) (?x ?y : ?a)`
During `isDefEq` (i.e., unification), it will need to solve the constrain
```
ringHasAdd ?s =?= intHasAdd
```
We say `ringHasAdd ?s` is stuck because it cannot be reduced until we
synthesize the term `?s : Ring ?a` using TC. This can be done since we
have assigned `?a := Int` when solving `?a =?= Int`.
- TC uses `isDefEq`, and `isDefEq` may create TC problems as shown
aaa. Thus, we may have nested TC problems.
- `isDefEq` extends the local context when going inside binders. Thus,
the local context for nested TC may be an extension of the local
context for outer TC.
- TC should not assign metavariables created by the elaborator, simp,
tactic framework, and outer TC problems. Reason: TC commits to the
first solution it finds. Consider the TC problem `HasCoe Nat ?x`,
where `?x` is a metavariable created by the caller. There are many
solutions to this problem (e.g., `?x := Int`, `?x := Real`, ...),
and it doesn’t make sense to commit to the first one since TC does
not know the the constraints the caller may impose on `?x` after the
TC problem is solved.
Remark: we claim it is not feasible to make the whole system backtrackable,
and allow the caller to backtrack back to TC and ask it for another solution
if the first one found did not work. We claim it would be too inefficient.
- TC metavariables should not leak outside of TC. Reason: we want to
get rid of them after we synthesize the instance.
- `simp` invokes `isDefEq` for matching the left-hand-side of
equations to terms in our goal. Thus, it may invoke TC indirectly.
- In Lean3, we didn’t have to create a fresh pattern for trying to
match the left-hand-side of equations when executing `simp`. We had a
mechanism called tmp metavariables. It avoided this overhead, but it
created many problems since `simp` may indirectly call TC which may
recursively call TC. Moreover, we want to allow TC to invoke
tactics. Thus, when `simp` invokes `isDefEq`, it may indirectly invoke
a tactic and `simp` itself. The Lean3 approach assumed that
metavariables were short-lived, this is not true in Lean4, and to some
extent was also not true in Lean3 since `simp`, in principle, could
trigger an arbitrary number of nested TC problems.
- Here are some possible call stack traces we could have in Lean3 (and Lean4).
```
Elaborator (-> TC -> isDefEq)+
Elaborator -> isDefEq (-> TC -> isDefEq)*
Elaborator -> simp -> isDefEq (-> TC -> isDefEq)*
```
In Lean4, TC may also invoke tactics.
- In Lean3 and Lean4, TC metavariables are not really short-lived. We
solve an arbitrary number of unification problems, and we may have
nested TC invocations.
- TC metavariables do not share the same local context even in the
same invocation. In the C++ and Lean implementations we use a trick to
ensure they do:
https://github.com/leanprover/lean/blob/92826917a252a6092cffaf5fc5f1acb1f8cef379/src/library/type_context.cpp#L3583-L3594
- Metavariables may be natural, synthetic or syntheticOpaque.
a) Natural metavariables may be assigned by unification (i.e., `isDefEq`).
b) Synthetic metavariables may still be assigned by unification,
but whenever possible `isDefEq` will avoid the assignment. For example,
if we have the unification constaint `?m =?= ?n`, where `?m` is synthetic,
but `?n` is not, `isDefEq` solves it by using the assignment `?n := ?m`.
We use synthetic metavariables for type class resolution.
Any module that creates synthetic metavariables, must also check
whether they have been assigned by `isDefEq`, and then still synthesize
them, and check whether the sythesized result is compatible with the one
assigned by `isDefEq`.
c) SyntheticOpaque metavariables are never assigned by `isDefEq`.
That is, the constraint `?n =?= Nat.succ Nat.zero` always fail
if `?n` is a syntheticOpaque metavariable. This kind of metavariable
is created by tactics such as `intro`. Reason: in the tactic framework,
subgoals as represented as metavariables, and a subgoal `?n` is considered
as solved whenever the metavariable is assigned.
This distinction was not precise in Lean3 and produced
counterintuitive behavior. For example, the following hack was added
in Lean3 to work around one of these issues:
https://github.com/leanprover/lean/blob/92826917a252a6092cffaf5fc5f1acb1f8cef379/src/library/type_context.cpp#L2751
- When creating lambda/forall expressions, we need to convert/abstract
free variables and convert them to bound variables. Now, suppose we a
trying to create a lambda/forall expression by abstracting free
variables `xs` and a term `t[?m]` which contains a metavariable `?m`,
and the local context of `?m` contains `xs`. The term
```
fun xs => t[?m]
```
will be ill-formed if we later assign a term `s` to `?m`, and
`s` contains free variables in `xs`. We address this issue by changing
the free variable abstraction procedure. We consider two cases: `?m`
is natural, `?m` is synthetic. Assume the type of `?m` is
`A[xs]`. Then, in both cases we create an auxiliary metavariable `?n` with
type `forall xs => A[xs]`, and local context := local context of `?m` - `xs`.
In both cases, we produce the term `fun xs => t[?n xs]`
1- If `?m` is natural or synthetic, then we assign `?m := ?n xs`, and we produce
the term `fun xs => t[?n xs]`
2- If `?m` is syntheticOpaque, then we mark `?n` as a syntheticOpaque variable.
However, `?n` is managed by the metavariable context itself.
We say we have a "delayed assignment" `?n xs := ?m`.
That is, after a term `s` is assigned to `?m`, and `s`
does not contain metavariables, we replace any occurrence
`?n ts` with `s[xs := ts]`.
Gruesome details:
- When we create the type `forall xs => A` for `?n`, we may
encounter the same issue if `A` contains metavariables. So, the
process above is recursive. We claim it terminates because we keep
creating new metavariables with smaller local contexts.
- Suppose, we have `t[?m]` and we want to create a let-expression by
abstracting a let-decl free variable `x`, and the local context of
`?m` contatins `x`. Similarly to the previous case
```
let x : T := v; t[?m]
```
will be ill-formed if we later assign a term `s` to `?m`, and
`s` contains free variable `x`. Again, assume the type of `?m` is `A[x]`.
1- If `?m` is natural or synthetic, then we create `?n : (let x : T := v; A[x])` with
and local context := local context of `?m` - `x`, we assign `?m := ?n`,
and produce the term `let x : T := v; t[?n]`. That is, we are just making
sure `?n` must never be assigned to a term containing `x`.
2- If `?m` is syntheticOpaque, we create a fresh syntheticOpaque `?n`
with type `?n : T -> (let x : T := v; A[x])` and local context := local context of `?m` - `x`,
create the delayed assignment `?n #[x] := ?m`, and produce the term `let x : T := v; t[?n x]`.
Now suppose we assign `s` to `?m`. We do not assign the term `fun (x : T) => s` to `?n`, since
`fun (x : T) => s` may not even be type correct. Instead, we just replace applications `?n r`
with `s[x/r]`. The term `r` may not necessarily be a bound variable. For example, a tactic
may have reduced `let x : T := v; t[?n x]` into `t[?n v]`.
We are essentially using the pair "delayed assignment + application" to implement a delayed
substitution.
- We use TC for implementing coercions. Both Joe Hendrix and Reid Barton
reported a nasty limitation. In Lean3, TC will not be used if there are
metavariables in the TC problem. For example, the elaborator will not try
to synthesize `HasCoe Nat ?x`. This is good, but this constraint is too
strict for problems such as `HasCoe (Vector Bool ?n) (BV ?n)`. The coercion
exists independently of `?n`. Thus, during TC, we want `isDefEq` to throw
an exception instead of return `false` whenever it tries to assign
a metavariable owned by its caller. The idea is to sign to the caller that
it cannot solve the TC problem at this point, and more information is needed.
That is, the caller must make progress an assign its metavariables before
trying to invoke TC again.
In Lean4, we are using a simpler design for the `MetavarContext`.
- No distinction betwen temporary and regular metavariables.
- Metavariables have a `depth` Nat field.
- MetavarContext also has a `depth` field.
- We bump the `MetavarContext` depth when we create a nested problem.
Example: Elaborator (depth = 0) -> Simplifier matcher (depth = 1) -> TC (level = 2) -> TC (level = 3) -> ...
- When `MetavarContext` is at depth N, `isDefEq` does not assign variables from `depth < N`.
- Metavariables from depth N+1 must be fully assigned before we return to level N.
- New design even allows us to invoke tactics from TC.
* Main concern
We don't have tmp metavariables anymore in Lean4. Thus, before trying to match
the left-hand-side of an equation in `simp`. We first must bump the level of the `MetavarContext`,
create fresh metavariables, then create a new pattern by replacing the free variable on the left-hand-side with
these metavariables. We are hoping to minimize this overhead by
- Using better indexing data structures in `simp`. They should reduce the number of time `simp` must invoke `isDefEq`.
- Implementing `isDefEqApprox` which ignores metavariables and returns only `false` or `undef`.
It is a quick filter that allows us to fail quickly and avoid the creation of new fresh metavariables,
and a new pattern.
- Adding built-in support for arithmetic, Logical connectives, etc. Thus, we avoid a bunch of lemmas in the simp set.
- Adding support for AC-rewriting. In Lean3, users use AC lemmas as
rewriting rules for "sorting" terms. This is inefficient, requires
a quadratic number of rewrite steps, and does not preserve the
structure of the goal.
The temporary metavariables were also used in the "app builder" module used in Lean3. The app builder uses
`isDefEq`. So, it could, in principle, invoke an arbitrary number of nested TC problems. However, in Lean3,
all app builder uses are controlled. That is, it is mainly used to synthesize implicit arguments using
very simple unification and/or non-nested TC. So, if the "app builder" becomes a bottleneck without tmp metavars,
we may solve the issue by implementing `isDefEqCheap` that never invokes TC and uses tmp metavars.
-/
structure LocalInstance :=
(className : Name)
(fvar : Expr)
abbrev LocalInstances := Array LocalInstance
def LocalInstance.beq (i₁ i₂ : LocalInstance) : Bool :=
i₁.fvar == i₂.fvar
instance LocalInstance.hasBeq : HasBeq LocalInstance := ⟨LocalInstance.beq⟩
/-- Remove local instance with the given `fvarId`. Do nothing if `localInsts` does not contain any free variable with id `fvarId`. -/
def LocalInstances.erase (localInsts : LocalInstances) (fvarId : FVarId) : LocalInstances :=
match localInsts.findIdx? (fun inst => inst.fvar.fvarId! == fvarId) with
| some idx => localInsts.eraseIdx idx
| _ => localInsts
inductive MetavarKind
| natural
| synthetic
| syntheticOpaque
def MetavarKind.isSyntheticOpaque : MetavarKind → Bool
| MetavarKind.syntheticOpaque => true
| _ => false
structure MetavarDecl :=
(userName : Name := Name.anonymous)
(lctx : LocalContext)
(type : Expr)
(depth : Nat)
(localInstances : LocalInstances)
(kind : MetavarKind)
@[export lean_mk_metavar_decl]
def mkMetavarDeclEx (userName : Name) (lctx : LocalContext) (type : Expr) (depth : Nat) (localInstances : LocalInstances) (kind : MetavarKind) : MetavarDecl :=
{ userName := userName, lctx := lctx, type := type, depth := depth, localInstances := localInstances, kind := kind }
namespace MetavarDecl
instance : Inhabited MetavarDecl := ⟨{ lctx := arbitrary _, type := arbitrary _, depth := 0, localInstances := #[], kind := MetavarKind.natural }⟩
end MetavarDecl
/--
A delayed assignment for a metavariable `?m`. It represents an assignment of the form
`?m := (fun fvars => val)`. The local context `lctx` provides the declarations for `fvars`.
Note that `fvars` may not be defined in the local context for `?m`.
- TODO: after we delete the old frontend, we can remove the field `lctx`.
This field is only used in old C++ implementation. -/
structure DelayedMetavarAssignment :=
(lctx : LocalContext)
(fvars : Array Expr)
(val : Expr)
structure MetavarContext :=
(depth : Nat := 0)
(lDepth : PersistentHashMap MVarId Nat := {})
(decls : PersistentHashMap MVarId MetavarDecl := {})
(lAssignment : PersistentHashMap MVarId Level := {})
(eAssignment : PersistentHashMap MVarId Expr := {})
(dAssignment : PersistentHashMap MVarId DelayedMetavarAssignment := {})
namespace MetavarContext
instance : Inhabited MetavarContext := ⟨{}⟩
@[export lean_mk_metavar_ctx]
def mkMetavarContext : Unit → MetavarContext :=
fun _ => {}
/- Low level API for adding/declaring metavariable declarations.
It is used to implement actions in the monads `MetaM`, `ElabM` and `TacticM`.
It should not be used directly since the argument `(mvarId : MVarId)` is assumed to be "unique". -/
@[export lean_metavar_ctx_mk_decl]
def addExprMVarDecl (mctx : MetavarContext)
(mvarId : MVarId)
(userName : Name)
(lctx : LocalContext)
(localInstances : LocalInstances)
(type : Expr) (kind : MetavarKind := MetavarKind.natural) : MetavarContext :=
{ decls := mctx.decls.insert mvarId {
userName := userName,
lctx := lctx,
localInstances := localInstances,
type := type,
depth := mctx.depth,
kind := kind },
.. mctx }
/- Low level API for adding/declaring universe level metavariable declarations.
It is used to implement actions in the monads `MetaM`, `ElabM` and `TacticM`.
It should not be used directly since the argument `(mvarId : MVarId)` is assumed to be "unique". -/
def addLevelMVarDecl (mctx : MetavarContext) (mvarId : MVarId) : MetavarContext :=
{ lDepth := mctx.lDepth.insert mvarId mctx.depth,
.. mctx }
@[export lean_metavar_ctx_find_decl]
def findDecl? (mctx : MetavarContext) (mvarId : MVarId) : Option MetavarDecl :=
mctx.decls.find? mvarId
def getDecl (mctx : MetavarContext) (mvarId : MVarId) : MetavarDecl :=
match mctx.decls.find? mvarId with
| some decl => decl
| none => panic! "unknown metavariable"
def setMVarKind (mctx : MetavarContext) (mvarId : MVarId) (kind : MetavarKind) : MetavarContext :=
let decl := mctx.getDecl mvarId;
{ decls := mctx.decls.insert mvarId { kind := kind, .. decl }, .. mctx }
def setMVarUserName (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) : MetavarContext :=
let decl := mctx.getDecl mvarId;
{ decls := mctx.decls.insert mvarId { userName := userName, .. decl }, .. mctx }
def findLevelDepth? (mctx : MetavarContext) (mvarId : MVarId) : Option Nat :=
mctx.lDepth.find? mvarId
def getLevelDepth (mctx : MetavarContext) (mvarId : MVarId) : Nat :=
match mctx.findLevelDepth? mvarId with
| some d => d
| none => panic! "unknown metavariable"
def isAnonymousMVar (mctx : MetavarContext) (mvarId : MVarId) : Bool :=
match mctx.findDecl? mvarId with
| none => false
| some mvarDecl => mvarDecl.userName.isAnonymous
def renameMVar (mctx : MetavarContext) (mvarId : MVarId) (newUserName : Name) : MetavarContext :=
match mctx.findDecl? mvarId with
| none => panic! "unknown metavariable"
| some mvarDecl => { decls := mctx.decls.insert mvarId { userName := newUserName, .. mvarDecl }, .. mctx }
@[export lean_metavar_ctx_assign_level]
def assignLevel (m : MetavarContext) (mvarId : MVarId) (val : Level) : MetavarContext :=
{ lAssignment := m.lAssignment.insert mvarId val, .. m }
@[export lean_metavar_ctx_assign_expr]
def assignExprCore (m : MetavarContext) (mvarId : MVarId) (val : Expr) : MetavarContext :=
{ eAssignment := m.eAssignment.insert mvarId val, .. m }
def assignExpr (m : MetavarContext) (mvarId : MVarId) (val : Expr) : MetavarContext :=
{ eAssignment := m.eAssignment.insert mvarId val, .. m }
@[export lean_metavar_ctx_assign_delayed]
def assignDelayed (m : MetavarContext) (mvarId : MVarId) (lctx : LocalContext) (fvars : Array Expr) (val : Expr) : MetavarContext :=
{ dAssignment := m.dAssignment.insert mvarId { lctx := lctx, fvars := fvars, val := val }, .. m }
@[export lean_metavar_ctx_get_level_assignment]
def getLevelAssignment? (m : MetavarContext) (mvarId : MVarId) : Option Level :=
m.lAssignment.find? mvarId
@[export lean_metavar_ctx_get_expr_assignment]
def getExprAssignment? (m : MetavarContext) (mvarId : MVarId) : Option Expr :=
m.eAssignment.find? mvarId
@[export lean_metavar_ctx_get_delayed_assignment]
def getDelayedAssignment? (m : MetavarContext) (mvarId : MVarId) : Option DelayedMetavarAssignment :=
m.dAssignment.find? mvarId
@[export lean_metavar_ctx_is_level_assigned]
def isLevelAssigned (m : MetavarContext) (mvarId : MVarId) : Bool :=
m.lAssignment.contains mvarId
@[export lean_metavar_ctx_is_expr_assigned]
def isExprAssigned (m : MetavarContext) (mvarId : MVarId) : Bool :=
m.eAssignment.contains mvarId
@[export lean_metavar_ctx_is_delayed_assigned]
def isDelayedAssigned (m : MetavarContext) (mvarId : MVarId) : Bool :=
m.dAssignment.contains mvarId
@[export lean_metavar_ctx_erase_delayed]
def eraseDelayed (m : MetavarContext) (mvarId : MVarId) : MetavarContext :=
{ dAssignment := m.dAssignment.erase mvarId, .. m }
def isLevelAssignable (mctx : MetavarContext) (mvarId : MVarId) : Bool :=
match mctx.lDepth.find? mvarId with
| some d => d == mctx.depth
| _ => panic! "unknown universe metavariable"
def isExprAssignable (mctx : MetavarContext) (mvarId : MVarId) : Bool :=
let decl := mctx.getDecl mvarId;
decl.depth == mctx.depth
def incDepth (mctx : MetavarContext) : MetavarContext :=
{ depth := mctx.depth + 1, .. mctx }
/-- Return true iff the given level contains an assigned metavariable. -/
def hasAssignedLevelMVar (mctx : MetavarContext) : Level → Bool
| Level.succ lvl _ => lvl.hasMVar && hasAssignedLevelMVar lvl
| Level.max lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignedLevelMVar lvl₁) || (lvl₂.hasMVar && hasAssignedLevelMVar lvl₂)
| Level.imax lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignedLevelMVar lvl₁) || (lvl₂.hasMVar && hasAssignedLevelMVar lvl₂)
| Level.mvar mvarId _ => mctx.isLevelAssigned mvarId
| Level.zero _ => false
| Level.param _ _ => false
/-- Return `true` iff expression contains assigned (level/expr) metavariables or delayed assigned mvars -/
def hasAssignedMVar (mctx : MetavarContext) : Expr → Bool
| Expr.const _ lvls _ => lvls.any (hasAssignedLevelMVar mctx)
| Expr.sort lvl _ => hasAssignedLevelMVar mctx lvl
| Expr.app f a _ => (f.hasMVar && hasAssignedMVar f) || (a.hasMVar && hasAssignedMVar a)
| Expr.letE _ t v b _ => (t.hasMVar && hasAssignedMVar t) || (v.hasMVar && hasAssignedMVar v) || (b.hasMVar && hasAssignedMVar b)
| Expr.forallE _ d b _ => (d.hasMVar && hasAssignedMVar d) || (b.hasMVar && hasAssignedMVar b)
| Expr.lam _ d b _ => (d.hasMVar && hasAssignedMVar d) || (b.hasMVar && hasAssignedMVar b)
| Expr.fvar _ _ => false
| Expr.bvar _ _ => false
| Expr.lit _ _ => false
| Expr.mdata _ e _ => e.hasMVar && hasAssignedMVar e
| Expr.proj _ _ e _ => e.hasMVar && hasAssignedMVar e
| Expr.mvar mvarId _ => mctx.isExprAssigned mvarId || mctx.isDelayedAssigned mvarId
| Expr.localE _ _ _ _ => unreachable!
/-- Return true iff the given level contains a metavariable that can be assigned. -/
def hasAssignableLevelMVar (mctx : MetavarContext) : Level → Bool
| Level.succ lvl _ => lvl.hasMVar && hasAssignableLevelMVar lvl
| Level.max lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignableLevelMVar lvl₁) || (lvl₂.hasMVar && hasAssignableLevelMVar lvl₂)
| Level.imax lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignableLevelMVar lvl₁) || (lvl₂.hasMVar && hasAssignableLevelMVar lvl₂)
| Level.mvar mvarId _ => mctx.isLevelAssignable mvarId
| Level.zero _ => false
| Level.param _ _ => false
/-- Return `true` iff expression contains a metavariable that can be assigned. -/
def hasAssignableMVar (mctx : MetavarContext) : Expr → Bool
| Expr.const _ lvls _ => lvls.any (hasAssignableLevelMVar mctx)
| Expr.sort lvl _ => hasAssignableLevelMVar mctx lvl
| Expr.app f a _ => (f.hasMVar && hasAssignableMVar f) || (a.hasMVar && hasAssignableMVar a)
| Expr.letE _ t v b _ => (t.hasMVar && hasAssignableMVar t) || (v.hasMVar && hasAssignableMVar v) || (b.hasMVar && hasAssignableMVar b)
| Expr.forallE _ d b _ => (d.hasMVar && hasAssignableMVar d) || (b.hasMVar && hasAssignableMVar b)
| Expr.lam _ d b _ => (d.hasMVar && hasAssignableMVar d) || (b.hasMVar && hasAssignableMVar b)
| Expr.fvar _ _ => false
| Expr.bvar _ _ => false
| Expr.lit _ _ => false
| Expr.mdata _ e _ => e.hasMVar && hasAssignableMVar e
| Expr.proj _ _ e _ => e.hasMVar && hasAssignableMVar e
| Expr.mvar mvarId _ => mctx.isExprAssignable mvarId
| Expr.localE _ _ _ _ => unreachable!
partial def instantiateLevelMVars : Level → StateM MetavarContext Level
| lvl@(Level.succ lvl₁ _) => do lvl₁ ← instantiateLevelMVars lvl₁; pure (Level.updateSucc! lvl lvl₁)
| lvl@(Level.max lvl₁ lvl₂ _) => do lvl₁ ← instantiateLevelMVars lvl₁; lvl₂ ← instantiateLevelMVars lvl₂; pure (Level.updateMax! lvl lvl₁ lvl₂)
| lvl@(Level.imax lvl₁ lvl₂ _) => do lvl₁ ← instantiateLevelMVars lvl₁; lvl₂ ← instantiateLevelMVars lvl₂; pure (Level.updateIMax! lvl lvl₁ lvl₂)
| lvl@(Level.mvar mvarId _) => do
mctx ← get;
match getLevelAssignment? mctx mvarId with
| some newLvl =>
if !newLvl.hasMVar then pure newLvl
else do
newLvl' ← instantiateLevelMVars newLvl;
modify $ fun mctx => mctx.assignLevel mvarId newLvl';
pure newLvl'
| none => pure lvl
| lvl => pure lvl
namespace InstantiateExprMVars
private abbrev M := StateM (WithHashMapCache Expr Expr MetavarContext)
@[inline] def instantiateLevelMVars (lvl : Level) : M Level :=
WithHashMapCache.fromState $ MetavarContext.instantiateLevelMVars lvl
@[inline] private def visit (f : Expr → M Expr) (e : Expr) : M Expr :=
if !e.hasMVar then pure e else checkCache e f
@[inline] private def getMCtx : M MetavarContext := do
s ← get; pure s.state
@[inline] private def modifyCtx (f : MetavarContext → MetavarContext) : M Unit :=
modify $ fun s => { state := f s.state, .. s }
/-- instantiateExprMVars main function -/
partial def main : Expr → M Expr
| e@(Expr.proj _ _ s _) => do s ← visit main s; pure (e.updateProj! s)
| e@(Expr.forallE _ d b _) => do d ← visit main d; b ← visit main b; pure (e.updateForallE! d b)
| e@(Expr.lam _ d b _) => do d ← visit main d; b ← visit main b; pure (e.updateLambdaE! d b)
| e@(Expr.letE _ t v b _) => do t ← visit main t; v ← visit main v; b ← visit main b; pure (e.updateLet! t v b)
| e@(Expr.const _ lvls _) => do lvls ← lvls.mapM instantiateLevelMVars; pure (e.updateConst! lvls)
| e@(Expr.sort lvl _) => do lvl ← instantiateLevelMVars lvl; pure (e.updateSort! lvl)
| e@(Expr.mdata _ b _) => do b ← visit main b; pure (e.updateMData! b)
| e@(Expr.app _ _ _) => e.withApp $ fun f args => do
let instArgs (f : Expr) : M Expr := do {
args ← args.mapM (visit main);
pure (mkAppN f args)
};
let instApp : M Expr := do {
let wasMVar := f.isMVar;
f ← visit main f;
if wasMVar && f.isLambda then
/- Some of the arguments in args are irrelevant after we beta reduce. -/
visit main (f.betaRev args.reverse)
else
instArgs f
};
match f with
| Expr.mvar mvarId _ => do
mctx ← getMCtx;
match mctx.getDelayedAssignment? mvarId with
| none => instApp
| some { fvars := fvars, val := val, .. } =>
/-
Apply "delayed substitution" (i.e., delayed assignment + application).
That is, `f` is some metavariable `?m`, that is delayed assigned to `val`.
If after instantiating `val`, we obtain `newVal`, and `newVal` does not contain
metavariables, we replace the free variables `fvars` in `newVal` with the first
`fvars.size` elements of `args`. -/
if fvars.size > args.size then
/- We don't have sufficient arguments for instantiating the free variables `fvars`.
This can only happy if a tactic or elaboration function is not implemented correctly.
We decided to not use `panic!` here and report it as an error in the frontend
when we are checking for unassigned metavariables in an elaborated term. -/
instArgs f
else do
newVal ← visit main val;
if newVal.hasExprMVar then
instArgs f
else do
args ← args.mapM (visit main);
/-
Example: suppose we have
`?m t1 t2 t3`
That is, `f := ?m` and `args := #[t1, t2, t3]`
Morever, `?m` is delayed assigned
`?m #[x, y] := f x y`
where, `fvars := #[x, y]` and `newVal := f x y`.
After abstracting `newVal`, we have `f (Expr.bvar 0) (Expr.bvar 1)`.
After `instantiaterRevRange 0 2 args`, we have `f t1 t2`.
After `mkAppRange 2 3`, we have `f t1 t2 t3` -/
let newVal := newVal.abstract fvars;
let result := newVal.instantiateRevRange 0 fvars.size args;
let result := mkAppRange result fvars.size args.size args;
pure $ result
| _ => instApp
| e@(Expr.mvar mvarId _) => checkCache e $ fun e => do
mctx ← getMCtx;
match mctx.getExprAssignment? mvarId with
| some newE => do
newE' ← visit main newE;
modifyCtx $ fun mctx => mctx.assignExpr mvarId newE';
pure newE'
| none => pure e
| e => pure e
end InstantiateExprMVars
def instantiateMVars (mctx : MetavarContext) (e : Expr) : Expr × MetavarContext :=
if !e.hasMVar then (e, mctx)
else (WithHashMapCache.toState $ InstantiateExprMVars.main e).run mctx
def instantiateLCtxMVars (mctx : MetavarContext) (lctx : LocalContext) : LocalContext × MetavarContext :=
lctx.foldl
(fun (result : LocalContext × MetavarContext) ldecl =>
let (lctx, mctx) := result;
match ldecl with
| LocalDecl.cdecl _ fvarId userName type bi =>
let (type, mctx) := mctx.instantiateMVars type;
(lctx.mkLocalDecl fvarId userName type bi, mctx)
| LocalDecl.ldecl _ fvarId userName type value =>
let (type, mctx) := mctx.instantiateMVars type;
let (value, mctx) := mctx.instantiateMVars value;
(lctx.mkLetDecl fvarId userName type value, mctx))
({}, mctx)
def instantiateMVarDeclMVars (mctx : MetavarContext) (mvarId : MVarId) : MetavarContext :=
let mvarDecl := mctx.getDecl mvarId;
let (lctx, mctx) := mctx.instantiateLCtxMVars mvarDecl.lctx;
let (type, mctx) := mctx.instantiateMVars mvarDecl.type;
{ decls := mctx.decls.insert mvarId { lctx := lctx, type := type, .. mvarDecl }, .. mctx }
namespace DependsOn
private abbrev M := StateM ExprSet
private def visit? (e : Expr) : M Bool :=
if !e.hasMVar && !e.hasFVar then
pure false
else do
s ← get;
if s.contains e then
pure false
else do
modify $ fun s => s.insert e;
pure true
@[inline] private def visit (main : Expr → M Bool) (e : Expr) : M Bool :=
condM (visit? e) (main e) (pure false)
@[specialize] private partial def dep (mctx : MetavarContext) (p : FVarId → Bool) : Expr → M Bool
| e@(Expr.proj _ _ s _) => visit dep s
| e@(Expr.forallE _ d b _) => visit dep d <||> visit dep b
| e@(Expr.lam _ d b _) => visit dep d <||> visit dep b
| e@(Expr.letE _ t v b _) => visit dep t <||> visit dep v <||> visit dep b
| e@(Expr.mdata _ b _) => visit dep b
| e@(Expr.app f a _) => visit dep a <||> if f.isApp then dep f else visit dep f
| e@(Expr.mvar mvarId _) =>
match mctx.getExprAssignment? mvarId with
| some a => visit dep a
| none =>
let lctx := (mctx.getDecl mvarId).lctx;
pure $ lctx.any $ fun decl => p decl.fvarId
| e@(Expr.fvar fvarId _) => pure $ p fvarId
| e => pure false
@[inline] partial def main (mctx : MetavarContext) (p : FVarId → Bool) (e : Expr) : M Bool :=
if !e.hasFVar && !e.hasMVar then pure false else dep mctx p e
end DependsOn
/--
Return `true` iff `e` depends on a free variable `x` s.t. `p x` is `true`.
For each metavariable `?m` occurring in `x`
1- If `?m := t`, then we visit `t` looking for `x`
2- If `?m` is unassigned, then we consider the worst case and check whether `x` is in the local context of `?m`.
This case is a "may dependency". That is, we may assign a term `t` to `?m` s.t. `t` contains `x`. -/
@[inline] def findExprDependsOn (mctx : MetavarContext) (e : Expr) (p : FVarId → Bool) : Bool :=
(DependsOn.main mctx p e).run' {}
/--
Similar to `findExprDependsOn`, but checks the expressions in the given local declaration
depends on a free variable `x` s.t. `p x` is `true`. -/
@[inline] def findLocalDeclDependsOn (mctx : MetavarContext) (localDecl : LocalDecl) (p : FVarId → Bool) : Bool :=
match localDecl with
| LocalDecl.cdecl _ _ _ type _ => findExprDependsOn mctx type p
| LocalDecl.ldecl _ _ _ type value => (DependsOn.main mctx p type <||> DependsOn.main mctx p value).run' {}
def exprDependsOn (mctx : MetavarContext) (e : Expr) (fvarId : FVarId) : Bool :=
findExprDependsOn mctx e $ fun fvarId' => fvarId == fvarId'
def localDeclDependsOn (mctx : MetavarContext) (localDecl : LocalDecl) (fvarId : FVarId) : Bool :=
findLocalDeclDependsOn mctx localDecl $ fun fvarId' => fvarId == fvarId'
namespace MkBinding
inductive Exception
| revertFailure (mctx : MetavarContext) (lctx : LocalContext) (toRevert : Array Expr) (decl : LocalDecl)
def Exception.toString : Exception → String
| Exception.revertFailure _ lctx toRevert decl =>
"failed to revert "
++ toString (toRevert.map (fun x => "'" ++ toString (lctx.getFVar! x).userName ++ "'"))
++ ", '" ++ toString decl.userName ++ "' depends on them, and it is an auxiliary declaration created by the elaborator"
++ " (possible solution: use tactic 'clear' to remove '" ++ toString decl.userName ++ "' from local context)"
instance Exception.hasToString : HasToString Exception := ⟨Exception.toString⟩
/--
`MkBinding` and `elimMVarDepsAux` are mutually recursive, but `cache` is only used at `elimMVarDepsAux`.
We use a single state object for convenience.
We have a `NameGenerator` because we need to generate fresh auxiliary metavariables. -/
structure State :=
(mctx : MetavarContext)
(ngen : NameGenerator)
(cache : HashMap Expr Expr := {}) --
abbrev MCore := EStateM Exception State
abbrev M := ReaderT Bool (EStateM Exception State)
def preserveOrder : M Bool := read
instance : MonadHashMapCacheAdapter Expr Expr M :=
{ getCache := do s ← get; pure s.cache,
modifyCache := fun f => modify $ fun s => { cache := f s.cache, .. s } }
/-- Return the local declaration of the free variable `x` in `xs` with the smallest index -/
private def getLocalDeclWithSmallestIdx (lctx : LocalContext) (xs : Array Expr) : LocalDecl :=
let d : LocalDecl := lctx.getFVar! $ xs.get! 0;
xs.foldlFrom
(fun d x =>
let decl := lctx.getFVar! x;
if decl.index < d.index then decl else d)
d 1
/-- Given `toRevert` an array of free variables s.t. `lctx` contains their declarations,
return a new array of free variables that contains `toRevert` and all free variables
in `lctx` that may depend on `toRevert`.
Remark: the result is sorted by `LocalDecl` indices. -/
private def collectDeps (mctx : MetavarContext) (lctx : LocalContext) (toRevert : Array Expr) (preserveOrder : Bool) : Except Exception (Array Expr) :=
if toRevert.size == 0 then pure toRevert
else do
when preserveOrder $ do {
-- Make sure none of `toRevert` is an AuxDecl
-- Make sure toRevert[j] does not depend on toRevert[i] for j > i
toRevert.size.forM $ fun i => do
let fvar := toRevert.get! i;
let decl := lctx.getFVar! fvar;
when decl.binderInfo.isAuxDecl $
throw (Exception.revertFailure mctx lctx toRevert decl);
i.forM $ fun j =>
let prevFVar := toRevert.get! j;
let prevDecl := lctx.getFVar! prevFVar;
when (localDeclDependsOn mctx prevDecl fvar.fvarId!) $
throw (Exception.revertFailure mctx lctx toRevert prevDecl)
};
let newToRevert := if preserveOrder then toRevert else Array.mkEmpty toRevert.size;
let firstDeclToVisit := getLocalDeclWithSmallestIdx lctx toRevert;
let initSize := newToRevert.size;
lctx.foldlFromM
(fun (newToRevert : Array Expr) decl =>
if initSize.any $ fun i => decl.fvarId == (newToRevert.get! i).fvarId! then pure newToRevert
else if toRevert.any (fun x => decl.fvarId == x.fvarId!) then
pure (newToRevert.push decl.toExpr)
else if findLocalDeclDependsOn mctx decl (fun fvarId => newToRevert.any $ fun x => x.fvarId! == fvarId) then
if decl.binderInfo.isAuxDecl then
throw (Exception.revertFailure mctx lctx toRevert decl)
else
pure (newToRevert.push decl.toExpr)
else
pure newToRevert)
newToRevert
firstDeclToVisit
/-- Create a new `LocalContext` by removing the free variables in `toRevert` from `lctx`.
We use this function when we create auxiliary metavariables at `elimMVarDepsAux`. -/
private def reduceLocalContext (lctx : LocalContext) (toRevert : Array Expr) : LocalContext :=
toRevert.foldr
(fun x lctx => lctx.erase x.fvarId!)
lctx
@[inline] private def visit (f : Expr → M Expr) (e : Expr) : M Expr :=
if !e.hasMVar then pure e else checkCache e f
@[inline] private def getMCtx : M MetavarContext := do
s ← get; pure s.mctx
/-- Return free variables in `xs` that are in the local context `lctx` -/
private def getInScope (lctx : LocalContext) (xs : Array Expr) : Array Expr :=
xs.foldl
(fun scope x =>
if lctx.contains x.fvarId! then
scope.push x
else
scope)
#[]
/-- Execute `x` with an empty cache, and then restore the original cache. -/
@[inline] private def withFreshCache {α} (x : M α) : M α := do
cache ← modifyGet $ fun s => (s.cache, { cache := {}, .. s });
a ← x;
modify $ fun s => { cache := cache, .. s };
pure a
@[inline] private def abstractRangeAux (elimMVarDeps : Expr → M Expr) (xs : Array Expr) (i : Nat) (e : Expr) : M Expr := do
e ← elimMVarDeps e;
pure (e.abstractRange i xs)
private def mkAuxMVarType (elimMVarDeps : Expr → M Expr) (lctx : LocalContext) (xs : Array Expr) (kind : MetavarKind) (e : Expr) : M Expr := do
e ← abstractRangeAux elimMVarDeps xs xs.size e;
xs.size.foldRevM
(fun i e =>
let x := xs.get! i;
match lctx.getFVar! x with
| LocalDecl.cdecl _ _ n type bi => do
type ← abstractRangeAux elimMVarDeps xs i type;
pure $ Lean.mkForall n bi type e
| LocalDecl.ldecl _ _ n type value => do
type ← abstractRangeAux elimMVarDeps xs i type;
value ← abstractRangeAux elimMVarDeps xs i value;
let e := mkLet n type value e;
match kind with
| MetavarKind.syntheticOpaque =>
-- See "Gruesome details" section in the beginning of the file
let e := e.liftLooseBVars 0 1;
pure $ mkForall n BinderInfo.default type e
| _ => pure e)
e
/--
Create an application `mvar ys` where `ys` are the free variables.
See "Gruesome details" in the beginning of the file for understanding
how let-decl free variables are handled. -/
private def mkMVarApp (lctx : LocalContext) (mvar : Expr) (xs : Array Expr) (kind : MetavarKind) : Expr :=
xs.foldl
(fun e x =>
match kind with
| MetavarKind.syntheticOpaque => mkApp e x
| _ => if (lctx.getFVar! x).isLet then e else mkApp e x)
mvar
private def mkAuxMVar (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (kind : MetavarKind) : M MVarId := do
s ← get;
let mvarId := s.ngen.curr;
modify $ fun s => { mctx := s.mctx.addExprMVarDecl mvarId Name.anonymous lctx localInsts type kind, ngen := s.ngen.next, .. s };
pure mvarId
/-- Return true iff some `e` in `es` depends on `fvarId` -/
private def anyDependsOn (mctx : MetavarContext) (es : Array Expr) (fvarId : FVarId) : Bool :=
es.any $ fun e => exprDependsOn mctx e fvarId
private partial def elimMVarDepsApp (elimMVarDepsAux : Expr → M Expr) (xs : Array Expr) : Expr → Array Expr → M Expr
| f, args =>
match f with
| Expr.mvar mvarId _ => do
let processDefault (newF : Expr) : M Expr := do {
if newF.isLambda then do
args ← args.mapM (visit elimMVarDepsAux);
elimMVarDepsAux $ newF.betaRev args.reverse
else if newF == f then do
args ← args.mapM (visit elimMVarDepsAux);
pure $ mkAppN newF args
else
elimMVarDepsApp newF args
};
mctx ← getMCtx;
match mctx.getExprAssignment? mvarId with
| some val => processDefault val
| _ =>
let mvarDecl := mctx.getDecl mvarId;
let mvarLCtx := mvarDecl.lctx;
let toRevert := getInScope mvarLCtx xs;
if toRevert.size == 0 then
processDefault f
else
let newMVarKind := if !mctx.isExprAssignable mvarId then MetavarKind.syntheticOpaque else mvarDecl.kind;
/- If `mvarId` is the lhs of a delayed assignment `?m #[x_1, ... x_n] := val`,
then `nestedFVars` is `#[x_1, ..., x_n]`.
In this case, we produce a new `syntheticOpaque` metavariable `?n` and a delayed assignment
```
?n #[y_1, ..., y_m, x_1, ... x_n] := ?m x_1 ... x_n
```
where `#[y_1, ..., y_m]` is `toRevert` after `collectDeps`.
Remark: `newMVarKind != MetavarKind.syntheticOpaque ==> nestedFVars == #[]`
-/
let continue (nestedFVars : Array Expr) : M Expr := do {
args ← args.mapM (visit elimMVarDepsAux);
preserve ← preserveOrder;
match collectDeps mctx mvarLCtx toRevert preserve with
| Except.error ex => throw ex
| Except.ok toRevert => do
let newMVarLCtx := reduceLocalContext mvarLCtx toRevert;
let newLocalInsts := mvarDecl.localInstances.filter $ fun inst => toRevert.all $ fun x => inst.fvar != x;
newMVarType ← mkAuxMVarType elimMVarDepsAux mvarLCtx toRevert newMVarKind mvarDecl.type;
newMVarId ← mkAuxMVar newMVarLCtx newLocalInsts newMVarType newMVarKind;
let newMVar := mkMVar newMVarId;
let result := mkMVarApp mvarLCtx newMVar toRevert newMVarKind;
match newMVarKind with
| MetavarKind.syntheticOpaque =>
modify $ fun s => { mctx := assignDelayed s.mctx newMVarId mvarLCtx (toRevert ++ nestedFVars) (mkAppN f nestedFVars), .. s }
| _ =>
modify $ fun s => { mctx := assignExpr s.mctx mvarId result, .. s };
pure (mkAppN result args)
};
if !mvarDecl.kind.isSyntheticOpaque then
continue #[]
else match mctx.getDelayedAssignment? mvarId with
| none => continue #[]
| some { fvars := fvars, .. } => continue fvars
| _ => do
f ← visit elimMVarDepsAux f;
args ← args.mapM (visit elimMVarDepsAux);
pure (mkAppN f args)
private partial def elimMVarDepsAux (xs : Array Expr) : Expr → M Expr
| e@(Expr.proj _ _ s _) => do s ← visit elimMVarDepsAux s; pure (e.updateProj! s)
| e@(Expr.forallE _ d b _) => do d ← visit elimMVarDepsAux d; b ← visit elimMVarDepsAux b; pure (e.updateForallE! d b)
| e@(Expr.lam _ d b _) => do d ← visit elimMVarDepsAux d; b ← visit elimMVarDepsAux b; pure (e.updateLambdaE! d b)
| e@(Expr.letE _ t v b _) => do t ← visit elimMVarDepsAux t; v ← visit elimMVarDepsAux v; b ← visit elimMVarDepsAux b; pure (e.updateLet! t v b)
| e@(Expr.mdata _ b _) => do b ← visit elimMVarDepsAux b; pure (e.updateMData! b)
| e@(Expr.app _ _ _) => e.withApp $ fun f args => elimMVarDepsApp elimMVarDepsAux xs f args
| e@(Expr.mvar mvarId _) => elimMVarDepsApp elimMVarDepsAux xs e #[]
| e => pure e
partial def elimMVarDeps (xs : Array Expr) (e : Expr) : M Expr :=
if !e.hasMVar then
pure e
else
withFreshCache $ elimMVarDepsAux xs e
/--
Similar to `Expr.abstractRange`, but handles metavariables correctly.
It uses `elimMVarDeps` to ensure `e` and the type of the free variables `xs` do not
contain a metavariable `?m` s.t. local context of `?m` contains a free variable in `xs`.
`elimMVarDeps` is defined later in this file. -/
@[inline] private def abstractRange (xs : Array Expr) (i : Nat) (e : Expr) : M Expr := do
e ← elimMVarDeps xs e;
pure (e.abstractRange i xs)
/--
Similar to `LocalContext.mkBinding`, but handles metavariables correctly.
If `usedOnly == false` then `forall` and `lambda` are created only for used variables. -/
@[specialize] def mkBinding (isLambda : Bool) (lctx : LocalContext) (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) : M (Expr × Nat) := do
e ← abstractRange xs xs.size e;
xs.size.foldRevM
(fun i (p : Expr × Nat) =>
let (e, num) := p;
let x := xs.get! i;
match lctx.getFVar! x with
| LocalDecl.cdecl _ _ n type bi =>
if !usedOnly || e.hasLooseBVar 0 then do
type ← abstractRange xs i type;
if isLambda then
pure (Lean.mkLambda n bi type e, num + 1)
else
pure (Lean.mkForall n bi type e, num + 1)
else
pure (e.lowerLooseBVars 1 1, num)
| LocalDecl.ldecl _ _ n type value => do
if e.hasLooseBVar 0 then do
type ← abstractRange xs i type;
value ← abstractRange xs i value;
pure (mkLet n type value e, num + 1)
else
pure (e.lowerLooseBVars 1 1, num))
(e, 0)
end MkBinding
abbrev MkBindingM := ReaderT LocalContext MkBinding.MCore
def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool) : MkBindingM Expr :=
fun _ => MkBinding.elimMVarDeps xs e preserveOrder
def mkBinding (isLambda : Bool) (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) : MkBindingM (Expr × Nat) :=
fun lctx => MkBinding.mkBinding isLambda lctx xs e usedOnly false
@[inline] def mkLambda (xs : Array Expr) (e : Expr) : MkBindingM Expr := do
(e, _) ← mkBinding true xs e;
pure e
@[inline] def mkForall (xs : Array Expr) (e : Expr) : MkBindingM Expr := do
(e, _) ← mkBinding false xs e;
pure e
@[inline] def mkForallUsedOnly (xs : Array Expr) (e : Expr) : MkBindingM (Expr × Nat) := do
mkBinding false xs e true
/--
`isWellFormed mctx lctx e` return true if
- All locals in `e` are declared in `lctx`
- All metavariables `?m` in `e` have a local context which is a subprefix of `lctx` or are assigned, and the assignment is well-formed. -/
partial def isWellFormed (mctx : MetavarContext) (lctx : LocalContext) : Expr → Bool
| Expr.mdata _ e _ => isWellFormed e
| Expr.proj _ _ e _ => isWellFormed e
| e@(Expr.app f a _) => (e.hasExprMVar || e.hasFVar) && isWellFormed f && isWellFormed a
| e@(Expr.lam _ d b _) => (e.hasExprMVar || e.hasFVar) && isWellFormed d && isWellFormed b
| e@(Expr.forallE _ d b _) => (e.hasExprMVar || e.hasFVar) && isWellFormed d && isWellFormed b
| e@(Expr.letE _ t v b _) => (e.hasExprMVar || e.hasFVar) && isWellFormed t && isWellFormed v && isWellFormed b
| Expr.const _ _ _ => true
| Expr.bvar _ _ => true
| Expr.sort _ _ => true
| Expr.lit _ _ => true
| Expr.mvar mvarId _ =>
let mvarDecl := mctx.getDecl mvarId;
if mvarDecl.lctx.isSubPrefixOf lctx then true
else match mctx.getExprAssignment? mvarId with
| none => false
| some v => isWellFormed v
| Expr.fvar fvarId _ => lctx.contains fvarId
| Expr.localE _ _ _ _ => unreachable!
namespace LevelMVarToParam
structure Context :=
(paramNamePrefix : Name)
(alreadyUsedPred : Name → Bool)
structure State :=
(mctx : MetavarContext)
(paramNames : Array Name := #[])
(nextParamIdx : Nat)
abbrev M := ReaderT Context $ StateM State
partial def mkParamName : Unit → M Name
| _ => do
ctx ← read;
s ← get;
let newParamName := ctx.paramNamePrefix.appendIndexAfter s.nextParamIdx;
if ctx.alreadyUsedPred newParamName then do
modify $ fun s => { nextParamIdx := s.nextParamIdx + 1, .. s};
mkParamName ()
else do
modify $ fun s => { nextParamIdx := s.nextParamIdx + 1, paramNames := s.paramNames.push newParamName, .. s};
pure newParamName
partial def visitLevel : Level → M Level
| u@(Level.succ v _) => do v ← visitLevel v; pure (u.updateSucc v rfl)
| u@(Level.max v₁ v₂ _) => do v₁ ← visitLevel v₁; v₂ ← visitLevel v₂; pure (u.updateMax v₁ v₂ rfl)
| u@(Level.imax v₁ v₂ _) => do v₁ ← visitLevel v₁; v₂ ← visitLevel v₂; pure (u.updateIMax v₁ v₂ rfl)
| u@(Level.zero _) => pure u
| u@(Level.param _ _) => pure u
| u@(Level.mvar mvarId _) => do
s ← get;
match s.mctx.getLevelAssignment? mvarId with
| some v => visitLevel v
| none => do
p ← mkParamName ();
let p := mkLevelParam p;
modify $ fun s => { mctx := s.mctx.assignLevel mvarId p, .. s };
pure p
@[inline] private def visit (f : Expr → M Expr) (e : Expr) : M Expr :=
if e.hasLevelMVar then f e else pure e
partial def main : Expr → M Expr
| e@(Expr.proj _ _ s _) => do s ← visit main s; pure (e.updateProj! s)
| e@(Expr.forallE _ d b _) => do d ← visit main d; b ← visit main b; pure (e.updateForallE! d b)
| e@(Expr.lam _ d b _) => do d ← visit main d; b ← visit main b; pure (e.updateLambdaE! d b)
| e@(Expr.letE _ t v b _) => do t ← visit main t; v ← visit main v; b ← visit main b; pure (e.updateLet! t v b)
| e@(Expr.app f a _) => do f ← visit main f; a ← visit main a; pure (e.updateApp! f a)
| e@(Expr.mdata _ b _) => do b ← visit main b; pure (e.updateMData! b)
| e@(Expr.const _ us _) => do us ← us.mapM visitLevel; pure (e.updateConst! us)
| e@(Expr.sort u _) => do u ← visitLevel u; pure (e.updateSort! u)
| e => pure e
end LevelMVarToParam
structure UnivMVarParamResult :=
(mctx : MetavarContext)
(newParamNames : Array Name)
(nextParamIdx : Nat)
(expr : Expr)
def levelMVarToParam (mctx : MetavarContext) (alreadyUsedPred : Name → Bool) (e : Expr) (paramNamePrefix : Name := `u) (nextParamIdx : Nat := 1)
: UnivMVarParamResult :=
let (e, s) := LevelMVarToParam.main e { paramNamePrefix := paramNamePrefix, alreadyUsedPred := alreadyUsedPred } { mctx := mctx, nextParamIdx := nextParamIdx };
{ mctx := mctx,
newParamNames := s.paramNames,
nextParamIdx := s.nextParamIdx,
expr := e }
end MetavarContext
end Lean
|
cf780858af0f733c1f766b5326aca4ca42621a9d | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Init/Notation.lean | 26704441335601122c8a7a18718c34cbb9d97fcf | [
"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 | 21,866 | 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, Mario Carneiro
Notation for operators defined at Prelude.lean
-/
prelude
import Init.Prelude
import Init.Coe
set_option linter.missingDocs true -- keep it documented
namespace Lean
/--
Auxiliary type used to represent syntax categories. We mainly use auxiliary
definitions with this type to attach doc strings to syntax categories.
-/
structure Parser.Category
namespace Parser.Category
/-- `command` is the syntax category for things that appear at the top level
of a lean file. For example, `def foo := 1` is a `command`, as is
`namespace Foo` and `end Foo`. Commands generally have an effect on the state of
adding something to the environment (like a new definition), as well as
commands like `variable` which modify future commands within a scope. -/
def command : Category := {}
/-- `term` is the builtin syntax category for terms. A term denotes an expression
in lean's type theory, for example `2 + 2` is a term. The difference between
`Term` and `Expr` is that the former is a kind of syntax, while the latter is
the result of elaboration. For example `by simp` is also a `Term`, but it elaborates
to different `Expr`s depending on the context. -/
def term : Category := {}
/-- `tactic` is the builtin syntax category for tactics. These appear after
`by` in proofs, and they are programs that take in the proof context
(the hypotheses in scope plus the type of the term to synthesize) and construct
a term of the expected type. For example, `simp` is a tactic, used in:
```
example : 2 + 2 = 4 := by simp
```
-/
def tactic : Category := {}
/-- `doElem` is a builtin syntax category for elements that can appear in the `do` notation.
For example, `let x ← e` is a `doElem`, and a `do` block consists of a list of `doElem`s. -/
def doElem : Category := {}
/-- `level` is a builtin syntax category for universe levels.
This is the `u` in `Sort u`: it can contain `max` and `imax`, addition with
constants, and variables. -/
def level : Category := {}
/-- `attr` is a builtin syntax category for attributes.
Declarations can be annotated with attributes using the `@[...]` notation. -/
def attr : Category := {}
/-- `stx` is a builtin syntax category for syntax. This is the abbreviated
parser notation used inside `syntax` and `macro` declarations. -/
def stx : Category := {}
/-- `prio` is a builtin syntax category for priorities.
Priorities are used in many different attributes.
Higher numbers denote higher priority, and for example typeclass search will
try high priority instances before low priority.
In addition to literals like `37`, you can also use `low`, `mid`, `high`, as well as
add and subtract priorities. -/
def prio : Category := {}
/-- `prec` is a builtin syntax category for precedences. A precedence is a value
that expresses how tightly a piece of syntax binds: for example `1 + 2 * 3` is
parsed as `1 + (2 * 3)` because `*` has a higher pr0ecedence than `+`.
Higher numbers denote higher precedence.
In addition to literals like `37`, there are some special named priorities:
* `arg` for the precedence of function arguments
* `max` for the highest precedence used in term parsers (not actually the maximum possible value)
* `lead` for the precedence of terms not supposed to be used as arguments
and you can also add and subtract precedences. -/
def prec : Category := {}
end Parser.Category
namespace Parser.Syntax
/-! DSL for specifying parser precedences and priorities -/
/-- Addition of precedences. This is normally used only for offseting, e.g. `max + 1`. -/
syntax:65 (name := addPrec) prec " + " prec:66 : prec
/-- Subtraction of precedences. This is normally used only for offseting, e.g. `max - 1`. -/
syntax:65 (name := subPrec) prec " - " prec:66 : prec
/-- Addition of priorities. This is normally used only for offseting, e.g. `default + 1`. -/
syntax:65 (name := addPrio) prio " + " prio:66 : prio
/-- Subtraction of priorities. This is normally used only for offseting, e.g. `default - 1`. -/
syntax:65 (name := subPrio) prio " - " prio:66 : prio
end Parser.Syntax
instance : CoeOut (TSyntax ks) Syntax where
coe stx := stx.raw
instance : Coe SyntaxNodeKind SyntaxNodeKinds where
coe k := List.cons k List.nil
end Lean
/--
Maximum precedence used in term parsers, in particular for terms in
function position (`ident`, `paren`, ...)
-/
macro "max" : prec => `(prec| 1024)
/-- Precedence used for application arguments (`do`, `by`, ...). -/
macro "arg" : prec => `(prec| 1023)
/-- Precedence used for terms not supposed to be used as arguments (`let`, `have`, ...). -/
macro "lead" : prec => `(prec| 1022)
/-- Parentheses are used for grouping precedence expressions. -/
macro "(" p:prec ")" : prec => return p
/-- Minimum precedence used in term parsers. -/
macro "min" : prec => `(prec| 10)
/-- `(min+1)` (we can only write `min+1` after `Meta.lean`) -/
macro "min1" : prec => `(prec| 11)
/--
`max:prec` as a term. It is equivalent to `eval_prec max` for `eval_prec` defined at `Meta.lean`.
We use `max_prec` to workaround bootstrapping issues.
-/
macro "max_prec" : term => `(1024)
/-- The default priority `default = 1000`, which is used when no priority is set. -/
macro "default" : prio => `(prio| 1000)
/-- The standardized "low" priority `low = 100`, for things that should be lower than default priority. -/
macro "low" : prio => `(prio| 100)
/--
The standardized "medium" priority `mid = 500`. This is lower than `default`, and higher than `low`.
-/
macro "mid" : prio => `(prio| 500)
/-- The standardized "high" priority `high = 10000`, for things that should be higher than default priority. -/
macro "high" : prio => `(prio| 10000)
/-- Parentheses are used for grouping priority expressions. -/
macro "(" p:prio ")" : prio => return p
/-
Note regarding priorities. We want `low < mid < default` because we have the following default instances:
```
@[default_instance low] instance (n : Nat) : OfNat Nat n where ...
@[default_instance mid] instance : Neg Int where ...
@[default_instance default] instance [Add α] : HAdd α α α where ...
@[default_instance default] instance [Sub α] : HSub α α α where ...
...
```
Monomorphic default instances must always "win" to preserve the Lean 3 monomorphic "look&feel".
The `Neg Int` instance must have precedence over the `OfNat Nat n` one, otherwise we fail to elaborate `#check -42`
See issue #1813 for an example that failed when `mid = default`.
-/
-- Basic notation for defining parsers
-- NOTE: precedence must be at least `arg` to be used in `macro` without parentheses
/--
`p+` is shorthand for `many1(p)`. It uses parser `p` 1 or more times, and produces a
`nullNode` containing the array of parsed results. This parser has arity 1.
If `p` has arity more than 1, it is auto-grouped in the items generated by the parser.
-/
syntax:arg stx:max "+" : stx
/--
`p*` is shorthand for `many(p)`. It uses parser `p` 0 or more times, and produces a
`nullNode` containing the array of parsed results. This parser has arity 1.
If `p` has arity more than 1, it is auto-grouped in the items generated by the parser.
-/
syntax:arg stx:max "*" : stx
/--
`(p)?` is shorthand for `optional(p)`. It uses parser `p` 0 or 1 times, and produces a
`nullNode` containing the array of parsed results. This parser has arity 1.
`p` is allowed to have arity n > 1 (in which case the node will have either 0 or n children),
but if it has arity 0 then the result will be ambiguous.
Because `?` is an identifier character, `ident?` will not work as intended.
You have to write either `ident ?` or `(ident)?` for it to parse as the `?` combinator
applied to the `ident` parser.
-/
syntax:arg stx:max "?" : stx
/--
`p1 <|> p2` is shorthand for `orelse(p1, p2)`, and parses either `p1` or `p2`.
It does not backtrack, meaning that if `p1` consumes at least one token then
`p2` will not be tried. Therefore, the parsers should all differ in their first
token. The `atomic(p)` parser combinator can be used to locally backtrack a parser.
(For full backtracking, consider using extensible syntax classes instead.)
On success, if the inner parser does not generate exactly one node, it will be
automatically wrapped in a `group` node, so the result will always be arity 1.
The `<|>` combinator does not generate a node of its own, and in particular
does not tag the inner parsers to distinguish them, which can present a problem
when reconstructing the parse. A well formed `<|>` parser should use disjoint
node kinds for `p1` and `p2`.
-/
syntax:2 stx:2 " <|> " stx:1 : stx
macro_rules
| `(stx| $p +) => `(stx| many1($p))
| `(stx| $p *) => `(stx| many($p))
| `(stx| $p ?) => `(stx| optional($p))
| `(stx| $p₁ <|> $p₂) => `(stx| orelse($p₁, $p₂))
/--
`p,*` is shorthand for `sepBy(p, ",")`. It parses 0 or more occurrences of
`p` separated by `,`, that is: `empty | p | p,p | p,p,p | ...`.
It produces a `nullNode` containing a `SepArray` with the interleaved parser
results. It has arity 1, and auto-groups its component parser if needed.
-/
macro:arg x:stx:max ",*" : stx => `(stx| sepBy($x, ",", ", "))
/--
`p,+` is shorthand for `sepBy(p, ",")`. It parses 1 or more occurrences of
`p` separated by `,`, that is: `p | p,p | p,p,p | ...`.
It produces a `nullNode` containing a `SepArray` with the interleaved parser
results. It has arity 1, and auto-groups its component parser if needed.
-/
macro:arg x:stx:max ",+" : stx => `(stx| sepBy1($x, ",", ", "))
/--
`p,*,?` is shorthand for `sepBy(p, ",", allowTrailingSep)`.
It parses 0 or more occurrences of `p` separated by `,`, possibly including
a trailing `,`, that is: `empty | p | p, | p,p | p,p, | p,p,p | ...`.
It produces a `nullNode` containing a `SepArray` with the interleaved parser
results. It has arity 1, and auto-groups its component parser if needed.
-/
macro:arg x:stx:max ",*,?" : stx => `(stx| sepBy($x, ",", ", ", allowTrailingSep))
/--
`p,+,?` is shorthand for `sepBy1(p, ",", allowTrailingSep)`.
It parses 1 or more occurrences of `p` separated by `,`, possibly including
a trailing `,`, that is: `p | p, | p,p | p,p, | p,p,p | ...`.
It produces a `nullNode` containing a `SepArray` with the interleaved parser
results. It has arity 1, and auto-groups its component parser if needed.
-/
macro:arg x:stx:max ",+,?" : stx => `(stx| sepBy1($x, ",", ", ", allowTrailingSep))
/--
`!p` parses the negation of `p`. That is, it fails if `p` succeeds, and
otherwise parses nothing. It has arity 0.
-/
macro:arg "!" x:stx:max : stx => `(stx| notFollowedBy($x))
/--
The `nat_lit n` macro constructs "raw numeric literals". This corresponds to the
`Expr.lit (.natVal n)` constructor in the `Expr` data type.
Normally, when you write a numeral like `#check 37`, the parser turns this into
an application of `OfNat.ofNat` to the raw literal `37` to cast it into the
target type, even if this type is `Nat` (so the cast is the identity function).
But sometimes it is necessary to talk about the raw numeral directly,
especially when proving properties about the `ofNat` function itself.
-/
syntax (name := rawNatLit) "nat_lit " num : term
@[inherit_doc] infixr:90 " ∘ " => Function.comp
@[inherit_doc] infixr:35 " × " => Prod
@[inherit_doc] infixl:55 " ||| " => HOr.hOr
@[inherit_doc] infixl:58 " ^^^ " => HXor.hXor
@[inherit_doc] infixl:60 " &&& " => HAnd.hAnd
@[inherit_doc] infixl:65 " + " => HAdd.hAdd
@[inherit_doc] infixl:65 " - " => HSub.hSub
@[inherit_doc] infixl:70 " * " => HMul.hMul
@[inherit_doc] infixl:70 " / " => HDiv.hDiv
@[inherit_doc] infixl:70 " % " => HMod.hMod
@[inherit_doc] infixl:75 " <<< " => HShiftLeft.hShiftLeft
@[inherit_doc] infixl:75 " >>> " => HShiftRight.hShiftRight
@[inherit_doc] infixr:80 " ^ " => HPow.hPow
@[inherit_doc] infixl:65 " ++ " => HAppend.hAppend
@[inherit_doc] prefix:75 "-" => Neg.neg
@[inherit_doc] prefix:100 "~~~" => Complement.complement
/-!
Remark: the infix commands above ensure a delaborator is generated for each relations.
We redefine the macros below to be able to use the auxiliary `binop%` elaboration helper for binary operators.
It addresses issue #382. -/
macro_rules | `($x ||| $y) => `(binop% HOr.hOr $x $y)
macro_rules | `($x ^^^ $y) => `(binop% HXor.hXor $x $y)
macro_rules | `($x &&& $y) => `(binop% HAnd.hAnd $x $y)
macro_rules | `($x + $y) => `(binop% HAdd.hAdd $x $y)
macro_rules | `($x - $y) => `(binop% HSub.hSub $x $y)
macro_rules | `($x * $y) => `(binop% HMul.hMul $x $y)
macro_rules | `($x / $y) => `(binop% HDiv.hDiv $x $y)
macro_rules | `($x % $y) => `(binop% HMod.hMod $x $y)
macro_rules | `($x ^ $y) => `(binop% HPow.hPow $x $y)
macro_rules | `($x ++ $y) => `(binop% HAppend.hAppend $x $y)
macro_rules | `(- $x) => `(unop% Neg.neg $x)
-- declare ASCII alternatives first so that the latter Unicode unexpander wins
@[inherit_doc] infix:50 " <= " => LE.le
@[inherit_doc] infix:50 " ≤ " => LE.le
@[inherit_doc] infix:50 " < " => LT.lt
@[inherit_doc] infix:50 " >= " => GE.ge
@[inherit_doc] infix:50 " ≥ " => GE.ge
@[inherit_doc] infix:50 " > " => GT.gt
@[inherit_doc] infix:50 " = " => Eq
@[inherit_doc] infix:50 " == " => BEq.beq
/-!
Remark: the infix commands above ensure a delaborator is generated for each relations.
We redefine the macros below to be able to use the auxiliary `binrel%` elaboration helper for binary relations.
It has better support for applying coercions. For example, suppose we have `binrel% Eq n i` where `n : Nat` and
`i : Int`. The default elaborator fails because we don't have a coercion from `Int` to `Nat`, but
`binrel%` succeeds because it also tries a coercion from `Nat` to `Int` even when the nat occurs before the int. -/
macro_rules | `($x <= $y) => `(binrel% LE.le $x $y)
macro_rules | `($x ≤ $y) => `(binrel% LE.le $x $y)
macro_rules | `($x < $y) => `(binrel% LT.lt $x $y)
macro_rules | `($x > $y) => `(binrel% GT.gt $x $y)
macro_rules | `($x >= $y) => `(binrel% GE.ge $x $y)
macro_rules | `($x ≥ $y) => `(binrel% GE.ge $x $y)
macro_rules | `($x = $y) => `(binrel% Eq $x $y)
macro_rules | `($x == $y) => `(binrel_no_prop% BEq.beq $x $y)
@[inherit_doc] infixr:35 " /\\ " => And
@[inherit_doc] infixr:35 " ∧ " => And
@[inherit_doc] infixr:30 " \\/ " => Or
@[inherit_doc] infixr:30 " ∨ " => Or
@[inherit_doc] notation:max "¬" p:40 => Not p
@[inherit_doc] infixl:35 " && " => and
@[inherit_doc] infixl:30 " || " => or
@[inherit_doc] notation:max "!" b:40 => not b
@[inherit_doc] infix:50 " ∈ " => Membership.mem
/-- `a ∉ b` is negated elementhood. It is notation for `¬ (a ∈ b)`. -/
notation:50 a:50 " ∉ " b:50 => ¬ (a ∈ b)
@[inherit_doc] infixr:67 " :: " => List.cons
@[inherit_doc HOrElse.hOrElse] syntax:20 term:21 " <|> " term:20 : term
@[inherit_doc HAndThen.hAndThen] syntax:60 term:61 " >> " term:60 : term
@[inherit_doc] infixl:55 " >>= " => Bind.bind
@[inherit_doc] notation:60 a:60 " <*> " b:61 => Seq.seq a fun _ : Unit => b
@[inherit_doc] notation:60 a:60 " <* " b:61 => SeqLeft.seqLeft a fun _ : Unit => b
@[inherit_doc] notation:60 a:60 " *> " b:61 => SeqRight.seqRight a fun _ : Unit => b
@[inherit_doc] infixr:100 " <$> " => Functor.map
macro_rules | `($x <|> $y) => `(binop_lazy% HOrElse.hOrElse $x $y)
macro_rules | `($x >> $y) => `(binop_lazy% HAndThen.hAndThen $x $y)
namespace Lean
/--
`binderIdent` matches an `ident` or a `_`. It is used for identifiers in binding
position, where `_` means that the value should be left unnamed and inaccessible.
-/
syntax binderIdent := ident <|> hole
namespace Parser.Tactic
/--
A case tag argument has the form `tag x₁ ... xₙ`; it refers to tag `tag` and renames
the last `n` hypotheses to `x₁ ... xₙ`.
-/
syntax caseArg := binderIdent (ppSpace binderIdent)*
end Parser.Tactic
end Lean
@[inherit_doc dite] syntax (name := termDepIfThenElse)
ppRealGroup(ppRealFill(ppIndent("if " Lean.binderIdent " : " term " then") ppSpace term)
ppDedent(ppSpace) ppRealFill("else " term)) : term
macro_rules
| `(if $h:ident : $c then $t else $e) => do
let mvar ← Lean.withRef c `(?m)
`(let_mvar% ?m := $c; wait_if_type_mvar% ?m; dite $mvar (fun $h:ident => $t) (fun $h:ident => $e))
| `(if _%$h : $c then $t else $e) => do
let mvar ← Lean.withRef c `(?m)
`(let_mvar% ?m := $c; wait_if_type_mvar% ?m; dite $mvar (fun _%$h => $t) (fun _%$h => $e))
@[inherit_doc ite] syntax (name := termIfThenElse)
ppRealGroup(ppRealFill(ppIndent("if " term " then") ppSpace term)
ppDedent(ppSpace) ppRealFill("else " term)) : term
macro_rules
| `(if $c then $t else $e) => do
let mvar ← Lean.withRef c `(?m)
`(let_mvar% ?m := $c; wait_if_type_mvar% ?m; ite $mvar $t $e)
/--
`if let pat := d then t else e` is a shorthand syntax for:
```
match d with
| pat => t
| _ => e
```
It matches `d` against the pattern `pat` and the bindings are available in `t`.
If the pattern does not match, it returns `e` instead.
-/
syntax (name := termIfLet)
ppRealGroup(ppRealFill(ppIndent("if " "let " term " := " term " then") ppSpace term)
ppDedent(ppSpace) ppRealFill("else " term)) : term
macro_rules
| `(if let $pat := $d then $t else $e) =>
`(match $d:term with | $pat => $t | _ => $e)
@[inherit_doc cond] syntax (name := boolIfThenElse)
ppRealGroup(ppRealFill(ppIndent("bif " term " then") ppSpace term)
ppDedent(ppSpace) ppRealFill("else " term)) : term
macro_rules
| `(bif $c then $t else $e) => `(cond $c $t $e)
/--
Haskell-like pipe operator `<|`. `f <| x` means the same as the same as `f x`,
except that it parses `x` with lower precedence, which means that `f <| g <| x`
is interpreted as `f (g x)` rather than `(f g) x`.
-/
syntax:min term " <| " term:min : term
macro_rules
| `($f $args* <| $a) => `($f $args* $a)
| `($f <| $a) => `($f $a)
/--
Haskell-like pipe operator `|>`. `x |> f` means the same as the same as `f x`,
and it chains such that `x |> f |> g` is interpreted as `g (f x)`.
-/
syntax:min term " |> " term:min1 : term
macro_rules
| `($a |> $f $args*) => `($f $args* $a)
| `($a |> $f) => `($f $a)
/--
Alternative syntax for `<|`. `f $ x` means the same as the same as `f x`,
except that it parses `x` with lower precedence, which means that `f $ g $ x`
is interpreted as `f (g x)` rather than `(f g) x`.
-/
-- Note that we have a whitespace after `$` to avoid an ambiguity with antiquotations.
syntax:min term atomic(" $" ws) term:min : term
macro_rules
| `($f $args* $ $a) => `($f $args* $a)
| `($f $ $a) => `($f $a)
@[inherit_doc Subtype] syntax "{ " withoutPosition(ident (" : " term)? " // " term) " }" : term
macro_rules
| `({ $x : $type // $p }) => ``(Subtype (fun ($x:ident : $type) => $p))
| `({ $x // $p }) => ``(Subtype (fun ($x:ident : _) => $p))
/--
`without_expected_type t` instructs Lean to elaborate `t` without an expected type.
Recall that terms such as `match ... with ...` and `⟨...⟩` will postpone elaboration until
expected type is known. So, `without_expected_type` is not effective in this case.
-/
macro "without_expected_type " x:term : term => `(let aux := $x; aux)
/--
The syntax `[a, b, c]` is shorthand for `a :: b :: c :: []`, or
`List.cons a (List.cons b (List.cons c List.nil))`. It allows conveniently constructing
list literals.
For lists of length at least 64, an alternative desugaring strategy is used
which uses let bindings as intermediates as in
`let left := [d, e, f]; a :: b :: c :: left` to avoid creating very deep expressions.
Note that this changes the order of evaluation, although it should not be observable
unless you use side effecting operations like `dbg_trace`.
-/
syntax "[" withoutPosition(term,*) "]" : term
/--
Auxiliary syntax for implementing `[$elem,*]` list literal syntax.
The syntax `%[a,b,c|tail]` constructs a value equivalent to `a::b::c::tail`.
It uses binary partitioning to construct a tree of intermediate let bindings as in
`let left := [d, e, f]; a :: b :: c :: left` to avoid creating very deep expressions.
-/
syntax "%[" withoutPosition(term,* " | " term) "]" : term
namespace Lean
macro_rules
| `([ $elems,* ]) => do
-- NOTE: we do not have `TSepArray.getElems` yet at this point
let rec expandListLit (i : Nat) (skip : Bool) (result : TSyntax `term) : MacroM Syntax := do
match i, skip with
| 0, _ => pure result
| i+1, true => expandListLit i false result
| i+1, false => expandListLit i true (← ``(List.cons $(⟨elems.elemsAndSeps.get! i⟩) $result))
if elems.elemsAndSeps.size < 64 then
expandListLit elems.elemsAndSeps.size false (← ``(List.nil))
else
`(%[ $elems,* | List.nil ])
/--
Category for carrying raw syntax trees between macros; any content is printed as is by the pretty printer.
The only accepted parser for this category is an antiquotation.
-/
declare_syntax_cat rawStx
instance : Coe Syntax (TSyntax `rawStx) where
coe stx := ⟨stx⟩
/-- `with_annotate_term stx e` annotates the lexical range of `stx : Syntax` with term info for `e`. -/
scoped syntax (name := withAnnotateTerm) "with_annotate_term " rawStx ppSpace term : term
/--
The attribute `@[deprecated]` on a declaration indicates that the declaration
is discouraged for use in new code, and/or should be migrated away from in
existing code. It may be removed in a future version of the library.
`@[deprecated myBetterDef]` means that `myBetterDef` is the suggested replacement.
-/
syntax (name := deprecated) "deprecated" (ppSpace ident)? : attr
/--
When `parent_dir` contains the current Lean file, `include_str "path" / "to" / "file"` becomes
a string literal with the contents of the file at `"parent_dir" / "path" / "to" / "file"`. If this
file cannot be read, elaboration fails.
-/
syntax (name := includeStr) "include_str " term : term
|
cf192047a4d3fea72bacc0903e026dfa027b4602 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /archive/100-theorems-list/83_friendship_graphs.lean | c7ecbf6eae4fbf2cc666de710b7e527cfeff9ac1 | [
"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 | 13,912 | lean | /-
Copyright (c) 2020 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Aaron Anderson, Jalex Stark, Kyle Miller.
-/
import combinatorics.adj_matrix
import linear_algebra.char_poly.coeff
import data.int.modeq
import data.zmod.basic
import tactic.interval_cases
/-!
# The Friendship Theorem
## Definitions and Statement
- A `friendship` graph is one in which any two distinct vertices have exactly one neighbor in common
- A `politician`, at least in the context of this problem, is a vertex in a graph which is adjacent
to every other vertex.
- The friendship theorem (Erdős, Rényi, Sós 1966) states that every finite friendship graph has a
politician.
## Proof outline
The proof revolves around the theory of adjacency matrices, although some steps could equivalently
be phrased in terms of counting walks.
- Assume `G` is a finite friendship graph.
- First we show that any two nonadjacent vertices have the same degree
- Assume for contradiction that `G` does not have a politician.
- Conclude from the last two points that `G` is `d`-regular for some `d : ℕ`.
- Show that `G` has `d ^ 2 - d + 1` vertices.
- By casework, show that if `d = 0, 1, 2`, then `G` has a politician.
- If `3 ≤ d`, let `p` be a prime factor of `d - 1`.
- If `A` is the adjacency matrix of `G` with entries in `ℤ/pℤ`, we show that `A ^ p` has trace `1`.
- This gives a contradiction, as `A` has trace `0`, and thus `A ^ p` has trace `0`.
## References
- [P. Erdős, A. Rényi, V. Sós, *On A Problem of Graph Theory*][erdosrenyisos]
- [C. Huneke, *The Friendship Theorem*][huneke2002]
-/
open_locale classical big_operators
noncomputable theory
open finset simple_graph matrix
universes u v
variables {V : Type u} {R : Type v} [semiring R]
section friendship_def
variables (G : simple_graph V)
/--
This is the set of all vertices mutually adjacent to a pair of vertices.
-/
def common_friends [fintype V] (v w : V) : finset V := G.neighbor_finset v ∩ G.neighbor_finset w
/--
This property of a graph is the hypothesis of the friendship theorem:
every pair of nonadjacent vertices has exactly one common friend,
a vertex to which both are adjacent.
-/
def friendship [fintype V] : Prop := ∀ ⦃v w : V⦄, v ≠ w → (common_friends G v w).card = 1
/--
A politician is a vertex that is adjacent to all other vertices.
-/
def exists_politician : Prop := ∃ (v : V), ∀ (w : V), v ≠ w → G.adj v w
lemma mem_common_friends [fintype V] {v w : V} {a : V} :
a ∈ common_friends G v w ↔ G.adj v a ∧ G.adj w a :=
by simp [common_friends]
end friendship_def
variables [fintype V] [inhabited V] {G : simple_graph V} {d : ℕ} (hG : friendship G)
include hG
namespace friendship
variables (R)
/-- One characterization of a friendship graph is that there is exactly one walk of length 2
between distinct vertices. These walks are counted in off-diagonal entries of the square of
the adjacency matrix, so for a friendship graph, those entries are all 1. -/
theorem adj_matrix_sq_of_ne {v w : V} (hvw : v ≠ w) :
((G.adj_matrix R) ^ 2) v w = 1 :=
begin
rw [pow_two, ← nat.cast_one, ← hG hvw],
simp [common_friends, neighbor_finset_eq_filter, finset.filter_filter, finset.filter_inter],
end
/-- This calculation amounts to counting the number of length 3 walks between nonadjacent vertices.
We use it to show that nonadjacent vertices have equal degrees. -/
lemma adj_matrix_pow_three_of_not_adj {v w : V} (non_adj : ¬ G.adj v w) :
((G.adj_matrix R) ^ 3) v w = degree G v :=
begin
rw [pow_succ, mul_eq_mul, adj_matrix_mul_apply, degree, card_eq_sum_ones, sum_nat_cast],
apply sum_congr rfl,
intros x hx,
rw [adj_matrix_sq_of_ne _ hG, nat.cast_one],
rintro ⟨rfl⟩,
rw mem_neighbor_finset at hx,
apply non_adj hx,
end
variable {R}
/-- As `v` and `w` not being adjacent implies
`degree G v = ((G.adj_matrix R) ^ 3) v w` and `degree G w = ((G.adj_matrix R) ^ 3) v w`,
the degrees are equal if `((G.adj_matrix R) ^ 3) v w = ((G.adj_matrix R) ^ 3) w v`
This is true as the adjacency matrix is symmetric. -/
lemma degree_eq_of_not_adj {v w : V} (hvw : ¬ G.adj v w) :
degree G v = degree G w :=
begin
rw [← nat.cast_id (G.degree v), ← nat.cast_id (G.degree w),
← adj_matrix_pow_three_of_not_adj ℕ hG hvw,
← adj_matrix_pow_three_of_not_adj ℕ hG (λ h, hvw (G.sym h))],
conv_lhs {rw ← transpose_adj_matrix},
simp only [pow_succ, pow_two, mul_eq_mul, ← transpose_mul, transpose_apply],
simp only [← mul_eq_mul, mul_assoc],
end
/-- If `G` is a friendship graph without a politician (a vertex adjacent to all others), then
it is regular. We have shown that nonadjacent vertices of a friendship graph have the same degree,
and if there isn't a politician, we can show this for adjacent vertices by finding a vertex
neither is adjacent to, and then using transitivity. -/
theorem is_regular_of_not_exists_politician (hG' : ¬exists_politician G) :
∃ (d : ℕ), G.is_regular_of_degree d :=
begin
have v := arbitrary V,
use G.degree v,
intro x,
by_cases hvx : G.adj v x, swap, { exact eq.symm (degree_eq_of_not_adj hG hvx), },
dunfold exists_politician at hG',
push_neg at hG',
rcases hG' v with ⟨w, hvw', hvw⟩,
rcases hG' x with ⟨y, hxy', hxy⟩,
by_cases hxw : G.adj x w,
swap, { rw degree_eq_of_not_adj hG hvw, apply degree_eq_of_not_adj hG hxw },
rw degree_eq_of_not_adj hG hxy,
by_cases hvy : G.adj v y,
swap, { apply eq.symm (degree_eq_of_not_adj hG hvy) },
rw degree_eq_of_not_adj hG hvw,
apply degree_eq_of_not_adj hG,
intro hcontra,
rcases finset.card_eq_one.mp (hG hvw') with ⟨a, h⟩,
have hx : x ∈ common_friends G v w := (mem_common_friends G).mpr ⟨hvx, G.sym hxw⟩,
have hy : y ∈ common_friends G v w := (mem_common_friends G).mpr ⟨hvy, G.sym hcontra⟩,
rw [h, mem_singleton] at hx hy,
apply hxy',
rw [hy, hx],
end
/-- Let `A` be the adjacency matrix of a graph `G`.
If `G` is a friendship graph, then all of the off-diagonal entries of `A^2` are 1.
If `G` is `d`-regular, then all of the diagonal entries of `A^2` are `d`.
Putting these together determines `A^2` exactly for a `d`-regular friendship graph. -/
theorem adj_matrix_sq_of_regular (hd : G.is_regular_of_degree d) :
((G.adj_matrix R) ^ 2) = λ v w, if v = w then d else 1 :=
begin
ext v w, by_cases h : v = w,
{ rw [h, pow_two, mul_eq_mul, adj_matrix_mul_self_apply_self, hd], simp, },
{ rw [adj_matrix_sq_of_ne R hG h, if_neg h], },
end
/-- Let `A` be the adjacency matrix of a `d`-regular friendship graph, and let `v` be a vector
all of whose components are `1`. Then `v` is an eigenvector of `A ^ 2`, and we can compute
the eigenvalue to be `d * d`, or as `d + (fintype.card V - 1)`, so those quantities must be equal.
This essentially means that the graph has `d ^ 2 - d + 1` vertices. -/
lemma card_of_regular (hd : G.is_regular_of_degree d) :
d + (fintype.card V - 1) = d * d :=
begin
let v := arbitrary V,
transitivity ((G.adj_matrix ℕ) ^ 2).mul_vec (λ _, 1) v,
{ rw [adj_matrix_sq_of_regular hG hd, mul_vec, dot_product, ← insert_erase (mem_univ v)],
simp only [sum_insert, mul_one, if_true, nat.cast_id, eq_self_iff_true,
mem_erase, not_true, ne.def, not_false_iff, add_right_inj, false_and],
rw [finset.sum_const_nat, card_erase_of_mem (mem_univ v), mul_one], refl,
intros x hx, simp [(ne_of_mem_erase hx).symm], },
{ rw [pow_two, mul_eq_mul, ← mul_vec_mul_vec],
simp [adj_matrix_mul_vec_const_apply_of_regular hd, neighbor_finset,
card_neighbor_set_eq_degree, hd v], }
end
/-- The size of a `d`-regular friendship graph is `1 mod (d-1)`, and thus `1 mod p` for a
factor `p ∣ d-1`. -/
lemma card_mod_p_of_regular {p : ℕ} (dmod : (d : zmod p) = 1) (hd : G.is_regular_of_degree d) :
(fintype.card V : zmod p) = 1 :=
begin
have hpos : 0 < (fintype.card V),
{ rw fintype.card_pos_iff, apply_instance, },
rw [← nat.succ_pred_eq_of_pos hpos, nat.succ_eq_add_one, nat.pred_eq_sub_one],
simp only [add_left_eq_self, nat.cast_add, nat.cast_one],
have h := congr_arg (λ n, (↑n : zmod p)) (card_of_regular hG hd),
revert h, simp [dmod],
end
lemma adj_matrix_sq_mod_p_of_regular {p : ℕ} (dmod : (d : zmod p) = 1)
(hd : G.is_regular_of_degree d) :
(G.adj_matrix (zmod p)) ^ 2 = λ _ _, 1 :=
by simp [adj_matrix_sq_of_regular hG hd, dmod]
lemma adj_matrix_sq_mul_const_one_of_regular (hd : G.is_regular_of_degree d) :
(G.adj_matrix R) * (λ _ _, 1) = λ _ _, d :=
by { ext x, simp [← hd x, degree] }
lemma adj_matrix_mul_const_one_mod_p_of_regular {p : ℕ} (dmod : (d : zmod p) = 1)
(hd : G.is_regular_of_degree d) :
(G.adj_matrix (zmod p)) * (λ _ _, 1) = λ _ _, 1 :=
by rw [adj_matrix_sq_mul_const_one_of_regular hG hd, dmod]
/-- Modulo a factor of `d-1`, the square and all higher powers of the adjacency matrix
of a `d`-regular friendship graph reduce to the matrix whose entries are all 1. -/
lemma adj_matrix_pow_mod_p_of_regular {p : ℕ} (dmod : (d : zmod p) = 1) (hd : G.is_regular_of_degree d)
{k : ℕ} (hk : 2 ≤ k) :
(G.adj_matrix (zmod p)) ^ k = λ _ _, 1 :=
begin
iterate 2 {cases k with k, { exfalso, linarith, }, },
induction k with k hind,
apply adj_matrix_sq_mod_p_of_regular hG dmod hd,
rw pow_succ,
have h2 : 2 ≤ k.succ.succ := by omega,
rw hind h2,
apply adj_matrix_mul_const_one_mod_p_of_regular hG dmod hd,
end
/-- This is the main proof. Assuming that `3 ≤ d`, we take `p` to be a prime factor of `d-1`.
Then the `p`th power of the adjacency matrix of a `d`-regular friendship graph must have trace 1
mod `p`, but we can also show that the trace must be the `p`th power of the trace of the original
adjacency matrix, which is 0, a contradiction.
-/
lemma false_of_three_le_degree
(hd : G.is_regular_of_degree d) (h : 3 ≤ d) : false :=
begin
-- get a prime factor of d - 1
let p : ℕ := (d - 1).min_fac,
have p_dvd_d_pred := (zmod.nat_coe_zmod_eq_zero_iff_dvd _ _).mpr (d - 1).min_fac_dvd,
have dpos : 0 < d := by linarith,
have d_cast : ↑(d - 1) = (d : ℤ) - 1 := by norm_cast,
haveI : fact p.prime := nat.min_fac_prime (by linarith),
have hp2 : 2 ≤ p, { apply nat.prime.two_le, assumption },
have dmod : (d : zmod p) = 1,
{ rw [← nat.succ_pred_eq_of_pos dpos, nat.succ_eq_add_one, nat.pred_eq_sub_one],
simp only [add_left_eq_self, nat.cast_add, nat.cast_one], apply p_dvd_d_pred, },
have Vmod := card_mod_p_of_regular hG dmod hd,
-- now we reduce to a trace calculation
have := zmod.trace_pow_card (G.adj_matrix (zmod p)),
contrapose! this, clear this,
-- the trace is 0 mod p when computed one way
rw [trace_adj_matrix, zero_pow],
-- but the trace is 1 mod p when computed the other way
rw adj_matrix_pow_mod_p_of_regular hG dmod hd hp2,
swap, { apply nat.prime.pos, assumption, },
{ dunfold fintype.card at Vmod,
simp only [matrix.trace, diag_apply, mul_one, nsmul_eq_mul, linear_map.coe_mk, sum_const],
rw [Vmod, ← nat.cast_one, zmod.nat_coe_zmod_eq_zero_iff_dvd, nat.dvd_one, nat.min_fac_eq_one_iff],
linarith, },
end
/-- If `d ≤ 1`, a `d`-regular friendship graph has at most one vertex, which is
trivially a politician. -/
lemma exists_politician_of_degree_le_one (hd : G.is_regular_of_degree d) (hd1 : d ≤ 1) :
exists_politician G :=
begin
have sq : d * d = d := by { interval_cases d; norm_num },
have h := card_of_regular hG hd,
rw sq at h,
have : fintype.card V ≤ 1,
{ cases fintype.card V with n,
{ exact zero_le _, },
{ have : n = 0,
{ rw [nat.succ_sub_succ_eq_sub, nat.sub_zero] at h,
linarith },
subst n, } },
use arbitrary V, intros w h,
exfalso, apply h,
apply fintype.card_le_one_iff.mp this,
end
/-- If `d = 2`, a `d`-regular friendship graph has 3 vertices, so it must be complete graph,
and all the vertices are politicians. -/
lemma neighbor_finset_eq_of_degree_eq_two (hd : G.is_regular_of_degree 2) (v : V) :
G.neighbor_finset v = finset.univ.erase v :=
begin
apply finset.eq_of_subset_of_card_le,
{ rw finset.subset_iff,
intro x,
rw [mem_neighbor_finset, finset.mem_erase],
exact λ h, ⟨ne.symm (G.ne_of_adj h), finset.mem_univ _⟩ },
convert_to 2 ≤ _,
convert_to _ = fintype.card V - 1,
{ have hfr:= card_of_regular hG hd,
linarith },
{ exact finset.card_erase_of_mem (finset.mem_univ _), },
{ dsimp [is_regular_of_degree, degree] at hd,
rw hd, }
end
lemma exists_politician_of_degree_eq_two (hd : G.is_regular_of_degree 2) :
exists_politician G :=
begin
have v := arbitrary V,
use v, intros w hvw,
rw [← mem_neighbor_finset, neighbor_finset_eq_of_degree_eq_two hG hd v, finset.mem_erase],
exact ⟨ne.symm hvw, finset.mem_univ _⟩,
end
lemma exists_politician_of_degree_le_two (hd : G.is_regular_of_degree d) (h : d ≤ 2) :
exists_politician G :=
begin
interval_cases d,
iterate 2 { apply exists_politician_of_degree_le_one hG hd, norm_num },
{ exact exists_politician_of_degree_eq_two hG hd },
end
end friendship
/-- We wish to show that a friendship graph has a politician (a vertex adjacent to all others).
We proceed by contradiction, and assume the graph has no politician.
We have already proven that a friendship graph with no politician is `d`-regular for some `d`,
and now we do casework on `d`.
If the degree is at most 2, we observe by casework that it has a politician anyway.
If the degree is at least 3, the graph cannot exist. -/
theorem friendship_theorem : exists_politician G :=
begin
by_contradiction npG,
rcases hG.is_regular_of_not_exists_politician npG with ⟨d, dreg⟩,
have h : d ≤ 2 ∨ 3 ≤ d := by omega,
cases h with dle2 dge3,
{ refine npG (hG.exists_politician_of_degree_le_two dreg dle2) },
{ exact hG.false_of_three_le_degree dreg dge3 },
end
|
c5c6a74ee21e6ae0712473681e311f384e7301a4 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/gcd_monoid/finset.lean | ddd10ea5a762b78cb5bceb569f19b8c52d9a923e | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 8,512 | 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.fold
import algebra.gcd_monoid.multiset
/-!
# GCD and LCM operations on finsets
## Main definitions
- `finset.gcd` - the greatest common denominator of a `finset` of elements of a `gcd_monoid`
- `finset.lcm` - the least common multiple of a `finset` of elements of a `gcd_monoid`
## Implementation notes
Many of the proofs use the lemmas `gcd.def` and `lcm.def`, which relate `finset.gcd`
and `finset.lcm` to `multiset.gcd` and `multiset.lcm`.
TODO: simplify with a tactic and `data.finset.lattice`
## Tags
finset, gcd
-/
variables {α β γ : Type*}
namespace finset
open multiset
variables [cancel_comm_monoid_with_zero α] [normalized_gcd_monoid α]
/-! ### lcm -/
section lcm
/-- Least common multiple of a finite set -/
def lcm (s : finset β) (f : β → α) : α := s.fold gcd_monoid.lcm 1 f
variables {s s₁ s₂ : finset β} {f : β → α}
lemma lcm_def : s.lcm f = (s.1.map f).lcm := rfl
@[simp] lemma lcm_empty : (∅ : finset β).lcm f = 1 :=
fold_empty
@[simp] lemma lcm_dvd_iff {a : α} : s.lcm f ∣ a ↔ (∀b ∈ s, f b ∣ a) :=
begin
apply iff.trans multiset.lcm_dvd,
simp only [multiset.mem_map, and_imp, exists_imp_distrib],
exact ⟨λ k b hb, k _ _ hb rfl, λ k a' b hb h, h ▸ k _ hb⟩,
end
lemma lcm_dvd {a : α} : (∀b ∈ s, f b ∣ a) → s.lcm f ∣ a :=
lcm_dvd_iff.2
lemma dvd_lcm {b : β} (hb : b ∈ s) : f b ∣ s.lcm f :=
lcm_dvd_iff.1 dvd_rfl _ hb
@[simp] lemma lcm_insert [decidable_eq β] {b : β} :
(insert b s : finset β).lcm f = gcd_monoid.lcm (f b) (s.lcm f) :=
begin
by_cases h : b ∈ s,
{ rw [insert_eq_of_mem h,
(lcm_eq_right_iff (f b) (s.lcm f) (multiset.normalize_lcm (s.1.map f))).2 (dvd_lcm h)] },
apply fold_insert h,
end
@[simp] lemma lcm_singleton {b : β} : ({b} : finset β).lcm f = normalize (f b) :=
multiset.lcm_singleton
@[simp] lemma normalize_lcm : normalize (s.lcm f) = s.lcm f := by simp [lcm_def]
lemma lcm_union [decidable_eq β] : (s₁ ∪ s₂).lcm f = gcd_monoid.lcm (s₁.lcm f) (s₂.lcm f) :=
finset.induction_on s₁ (by rw [empty_union, lcm_empty, lcm_one_left, normalize_lcm]) $ λ a s has ih,
by rw [insert_union, lcm_insert, lcm_insert, ih, lcm_assoc]
theorem lcm_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a ∈ s₂, f a = g a) :
s₁.lcm f = s₂.lcm g :=
by { subst hs, exact finset.fold_congr hfg }
lemma lcm_mono_fun {g : β → α} (h : ∀ b ∈ s, f b ∣ g b) : s.lcm f ∣ s.lcm g :=
lcm_dvd (λ b hb, (h b hb).trans (dvd_lcm hb))
lemma lcm_mono (h : s₁ ⊆ s₂) : s₁.lcm f ∣ s₂.lcm f :=
lcm_dvd $ assume b hb, dvd_lcm (h hb)
lemma lcm_image [decidable_eq β] {g : γ → β} (s : finset γ) : (s.image g).lcm f = s.lcm (f ∘ g) :=
by { classical, induction s using finset.induction with c s hc ih; simp [*] }
lemma lcm_eq_lcm_image [decidable_eq α] : s.lcm f = (s.image f).lcm id := eq.symm $ lcm_image _
theorem lcm_eq_zero_iff [nontrivial α] : s.lcm f = 0 ↔ 0 ∈ f '' s :=
by simp only [multiset.mem_map, lcm_def, multiset.lcm_eq_zero_iff, set.mem_image, mem_coe,
← finset.mem_def]
end lcm
/-! ### gcd -/
section gcd
/-- Greatest common divisor of a finite set -/
def gcd (s : finset β) (f : β → α) : α := s.fold gcd_monoid.gcd 0 f
variables {s s₁ s₂ : finset β} {f : β → α}
lemma gcd_def : s.gcd f = (s.1.map f).gcd := rfl
@[simp] lemma gcd_empty : (∅ : finset β).gcd f = 0 :=
fold_empty
lemma dvd_gcd_iff {a : α} : a ∣ s.gcd f ↔ ∀b ∈ s, a ∣ f b :=
begin
apply iff.trans multiset.dvd_gcd,
simp only [multiset.mem_map, and_imp, exists_imp_distrib],
exact ⟨λ k b hb, k _ _ hb rfl, λ k a' b hb h, h ▸ k _ hb⟩,
end
lemma gcd_dvd {b : β} (hb : b ∈ s) : s.gcd f ∣ f b :=
dvd_gcd_iff.1 dvd_rfl _ hb
lemma dvd_gcd {a : α} : (∀b ∈ s, a ∣ f b) → a ∣ s.gcd f :=
dvd_gcd_iff.2
@[simp] lemma gcd_insert [decidable_eq β] {b : β} :
(insert b s : finset β).gcd f = gcd_monoid.gcd (f b) (s.gcd f) :=
begin
by_cases h : b ∈ s,
{ rw [insert_eq_of_mem h,
(gcd_eq_right_iff (f b) (s.gcd f) (multiset.normalize_gcd (s.1.map f))).2 (gcd_dvd h)] ,},
apply fold_insert h,
end
@[simp] lemma gcd_singleton {b : β} : ({b} : finset β).gcd f = normalize (f b) :=
multiset.gcd_singleton
@[simp] lemma normalize_gcd : normalize (s.gcd f) = s.gcd f := by simp [gcd_def]
lemma gcd_union [decidable_eq β] : (s₁ ∪ s₂).gcd f = gcd_monoid.gcd (s₁.gcd f) (s₂.gcd f) :=
finset.induction_on s₁ (by rw [empty_union, gcd_empty, gcd_zero_left, normalize_gcd]) $
λ a s has ih, by rw [insert_union, gcd_insert, gcd_insert, ih, gcd_assoc]
theorem gcd_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a ∈ s₂, f a = g a) :
s₁.gcd f = s₂.gcd g :=
by { subst hs, exact finset.fold_congr hfg }
lemma gcd_mono_fun {g : β → α} (h : ∀ b ∈ s, f b ∣ g b) : s.gcd f ∣ s.gcd g :=
dvd_gcd (λ b hb, (gcd_dvd hb).trans (h b hb))
lemma gcd_mono (h : s₁ ⊆ s₂) : s₂.gcd f ∣ s₁.gcd f :=
dvd_gcd $ assume b hb, gcd_dvd (h hb)
lemma gcd_image [decidable_eq β] {g : γ → β} (s : finset γ) : (s.image g).gcd f = s.gcd (f ∘ g) :=
by { classical, induction s using finset.induction with c s hc ih; simp [*] }
lemma gcd_eq_gcd_image [decidable_eq α] : s.gcd f = (s.image f).gcd id := eq.symm $ gcd_image _
theorem gcd_eq_zero_iff : s.gcd f = 0 ↔ ∀ (x : β), x ∈ s → f x = 0 :=
begin
rw [gcd_def, multiset.gcd_eq_zero_iff],
split; intro h,
{ intros b bs,
apply h (f b),
simp only [multiset.mem_map, mem_def.1 bs],
use b,
simp [mem_def.1 bs] },
{ intros a as,
rw multiset.mem_map at as,
rcases as with ⟨b, ⟨bs, rfl⟩⟩,
apply h b (mem_def.1 bs) }
end
lemma gcd_eq_gcd_filter_ne_zero [decidable_pred (λ (x : β), f x = 0)] :
s.gcd f = (s.filter (λ x, f x ≠ 0)).gcd f :=
begin
classical,
transitivity ((s.filter (λ x, f x = 0)) ∪ (s.filter (λ x, f x ≠ 0))).gcd f,
{ rw filter_union_filter_neg_eq },
rw gcd_union,
transitivity gcd_monoid.gcd (0 : α) _,
{ refine congr (congr rfl _) rfl,
apply s.induction_on, { simp },
intros a s has h,
rw filter_insert,
split_ifs with h1; simp [h, h1], },
simp [gcd_zero_left, normalize_gcd],
end
lemma gcd_mul_left {a : α} : s.gcd (λ x, a * f x) = normalize a * s.gcd f :=
begin
classical,
apply s.induction_on,
{ simp },
intros b t hbt h,
rw [gcd_insert, gcd_insert, h, ← gcd_mul_left],
apply ((normalize_associated a).mul_right _).gcd_eq_right
end
lemma gcd_mul_right {a : α} : s.gcd (λ x, f x * a) = s.gcd f * normalize a :=
begin
classical,
apply s.induction_on,
{ simp },
intros b t hbt h,
rw [gcd_insert, gcd_insert, h, ← gcd_mul_right],
apply ((normalize_associated a).mul_left _).gcd_eq_right
end
lemma extract_gcd' (f g : β → α) (hs : ∃ x, x ∈ s ∧ f x ≠ 0)
(hg : ∀ b ∈ s, f b = s.gcd f * g b) : s.gcd g = 1 :=
((@mul_right_eq_self₀ _ _ (s.gcd f) _).1 $
by conv_lhs { rw [← normalize_gcd, ← gcd_mul_left, ← gcd_congr rfl hg] }).resolve_right $
by {contrapose! hs, exact gcd_eq_zero_iff.1 hs}
lemma extract_gcd (f : β → α) (hs : s.nonempty) :
∃ g : β → α, (∀ b ∈ s, f b = s.gcd f * g b) ∧ s.gcd g = 1 :=
begin
classical,
by_cases h : ∀ x ∈ s, f x = (0 : α),
{ refine ⟨λ b, 1, λ b hb, by rw [h b hb, gcd_eq_zero_iff.2 h, mul_one], _⟩,
rw [gcd_eq_gcd_image, image_const hs, gcd_singleton, id, normalize_one] },
{ choose g' hg using @gcd_dvd _ _ _ _ s f,
have := λ b hb, _, push_neg at h,
refine ⟨λ b, if hb : b ∈ s then g' hb else 0, this, extract_gcd' f _ h this⟩,
rw [dif_pos hb, hg hb] },
end
end gcd
end finset
namespace finset
section is_domain
variables [comm_ring α] [is_domain α] [normalized_gcd_monoid α]
lemma gcd_eq_of_dvd_sub {s : finset β} {f g : β → α} {a : α}
(h : ∀ x : β, x ∈ s → a ∣ f x - g x) :
gcd_monoid.gcd a (s.gcd f) = gcd_monoid.gcd a (s.gcd g) :=
begin
classical,
revert h,
apply s.induction_on,
{ simp },
intros b s bs hi h,
rw [gcd_insert, gcd_insert, gcd_comm (f b), ← gcd_assoc, hi (λ x hx, h _ (mem_insert_of_mem hx)),
gcd_comm a, gcd_assoc, gcd_comm a (gcd_monoid.gcd _ _),
gcd_comm (g b), gcd_assoc _ _ a, gcd_comm _ a],
exact congr_arg _ (gcd_eq_of_dvd_sub_right (h _ (mem_insert_self _ _)))
end
end is_domain
end finset
|
fb45cc6b05c5cbdf53bbbfd394971451839332da | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/init/control/lawful_auto.lean | 1c4d299d8f1b956d66924124997b900f4a3acde5 | [] | 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,216 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.control.monad
import Mathlib.Lean3Lib.init.meta.interactive
import Mathlib.Lean3Lib.init.control.state
import Mathlib.Lean3Lib.init.control.except
import Mathlib.Lean3Lib.init.control.reader
import Mathlib.Lean3Lib.init.control.option
universes u v l u_1
namespace Mathlib
class is_lawful_functor (f : Type u → Type v) [Functor f] where
map_const_eq :
autoParam (∀ {α β : Type u}, Functor.mapConst = Functor.map ∘ function.const β)
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.control_laws_tac")
(Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "control_laws_tac") [])
id_map : ∀ {α : Type u} (x : f α), id <$> x = x
comp_map : ∀ {α β γ : Type u} (g : α → β) (h : β → γ) (x : f α), (h ∘ g) <$> x = h <$> g <$> x
-- `functor` is indeed a categorical functor
-- `comp_map` does not make a good simp lemma
class is_lawful_applicative (f : Type u → Type v) [Applicative f] extends is_lawful_functor f where
seq_left_eq :
autoParam (∀ {α β : Type u} (a : f α) (b : f β), a <* b = function.const β <$> a <*> b)
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.control_laws_tac")
(Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "control_laws_tac") [])
seq_right_eq :
autoParam (∀ {α β : Type u} (a : f α) (b : f β), a *> b = function.const α id <$> a <*> b)
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.control_laws_tac")
(Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "control_laws_tac") [])
pure_seq_eq_map : ∀ {α β : Type u} (g : α → β) (x : f α), pure g <*> x = g <$> x
map_pure : ∀ {α β : Type u} (g : α → β) (x : α), g <$> pure x = pure (g x)
seq_pure : ∀ {α β : Type u} (g : f (α → β)) (x : α), g <*> pure x = (fun (g : α → β) => g x) <$> g
seq_assoc :
∀ {α β γ : Type u} (x : f α) (g : f (α → β)) (h : f (β → γ)),
h <*> (g <*> x) = function.comp <$> h <*> g <*> x
-- applicative laws
-- default functor law
-- applicative "law" derivable from other laws
@[simp] theorem pure_id_seq {α : Type u} {f : Type u → Type v} [Applicative f]
[is_lawful_applicative f] (x : f α) : pure id <*> x = x :=
sorry
class is_lawful_monad (m : Type u → Type v) [Monad m] extends is_lawful_applicative m where
bind_pure_comp_eq_map :
autoParam (∀ {α β : Type u} (f : α → β) (x : m α), x >>= pure ∘ f = f <$> x)
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.control_laws_tac")
(Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "control_laws_tac") [])
bind_map_eq_seq :
autoParam
(∀ {α β : Type u} (f : m (α → β)) (x : m α),
(do
let _x ← f
_x <$> x) =
f <*> x)
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.control_laws_tac")
(Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "control_laws_tac") [])
pure_bind : ∀ {α β : Type u} (x : α) (f : α → m β), pure x >>= f = f x
bind_assoc :
∀ {α β γ : Type u} (x : m α) (f : α → m β) (g : β → m γ),
x >>= f >>= g = x >>= fun (x : α) => f x >>= g
-- monad laws
-- monad "law" derivable from other laws
@[simp] theorem bind_pure {α : Type u} {m : Type u → Type v} [Monad m] [is_lawful_monad m]
(x : m α) : x >>= pure = x :=
sorry
theorem bind_ext_congr {α : Type u} {β : Type u} {m : Type u → Type v} [Bind m] {x : m α}
{f : α → m β} {g : α → m β} : (∀ (a : α), f a = g a) → x >>= f = x >>= g :=
sorry
theorem map_ext_congr {α : Type u} {β : Type u} {m : Type u → Type v} [Functor m] {x : m α}
{f : α → β} {g : α → β} : (∀ (a : α), f a = g a) → f <$> x = g <$> x :=
sorry
-- instances of previously defined monads
namespace id
@[simp] theorem map_eq {α : Type} {β : Type} (x : id α) (f : α → β) : f <$> x = f x := rfl
@[simp] theorem bind_eq {α : Type} {β : Type} (x : id α) (f : α → id β) : x >>= f = f x := rfl
end id
@[simp] theorem id.pure_eq {α : Type} (a : α) : pure a = a := rfl
protected instance id.is_lawful_monad : is_lawful_monad id :=
is_lawful_monad.mk (fun (α β : Type u_1) (x : α) (f : α → id β) => Eq.refl (pure x >>= f))
fun (α β γ : Type u_1) (x : id α) (f : α → id β) (g : β → id γ) => Eq.refl (x >>= f >>= g)
namespace state_t
theorem ext {σ : Type u} {m : Type u → Type v} {α : Type u} {x : state_t σ m α} {x' : state_t σ m α}
(h : ∀ (st : σ), run x st = run x' st) : x = x' :=
sorry
@[simp] theorem run_pure {σ : Type u} {m : Type u → Type v} {α : Type u} (st : σ) [Monad m]
(a : α) : run (pure a) st = pure (a, st) :=
rfl
@[simp] theorem run_bind {σ : Type u} {m : Type u → Type v} {α : Type u} {β : Type u}
(x : state_t σ m α) (st : σ) [Monad m] (f : α → state_t σ m β) :
run (x >>= f) st =
do
let p ← run x st
run (f (prod.fst p)) (prod.snd p) :=
sorry
@[simp] theorem run_map {σ : Type u} {m : Type u → Type v} {α : Type u} {β : Type u}
(x : state_t σ m α) (st : σ) [Monad m] (f : α → β) [is_lawful_monad m] :
run (f <$> x) st = (fun (p : α × σ) => (f (prod.fst p), prod.snd p)) <$> run x st :=
sorry
@[simp] theorem run_monad_lift {σ : Type u} {m : Type u → Type v} {α : Type u} (st : σ) [Monad m]
{n : Type u → Type u_1} [has_monad_lift_t n m] (x : n α) :
run (monad_lift x) st =
do
let a ← monad_lift x
pure (a, st) :=
rfl
@[simp] theorem run_monad_map {σ : Type u} {m : Type u → Type v} {α : Type u} (x : state_t σ m α)
(st : σ) [Monad m] {m' : Type u → Type v} {n : Type u → Type u_1} {n' : Type u → Type u_1}
[Monad m'] [monad_functor_t n n' m m'] (f : {α : Type u} → n α → n' α) :
run (monad_map f x) st = monad_map f (run x st) :=
rfl
@[simp] theorem run_adapt {σ : Type u} {m : Type u → Type v} {α : Type u} [Monad m] {σ' : Type u}
{σ'' : Type u} (st : σ) (split : σ → σ' × σ'') (join : σ' → σ'' → σ) (x : state_t σ' m α) :
run (state_t.adapt split join x) st =
(fun (_a : σ' × σ'') =>
prod.cases_on _a
fun (fst : σ') (snd : σ'') =>
idRhs (m (α × σ))
(do
let _p ← run x fst
(fun (_a : α × σ') =>
prod.cases_on _a
fun (fst : α) (snd_1 : σ') =>
idRhs (m (α × σ)) (pure (fst, join snd_1 snd)))
_p))
(split st) :=
sorry
@[simp] theorem run_get {σ : Type u} {m : Type u → Type v} (st : σ) [Monad m] :
run state_t.get st = pure (st, st) :=
rfl
@[simp] theorem run_put {σ : Type u} {m : Type u → Type v} (st : σ) [Monad m] (st' : σ) :
run (state_t.put st') st = pure (PUnit.unit, st') :=
rfl
end state_t
protected instance state_t.is_lawful_monad (m : Type u → Type v) [Monad m] [is_lawful_monad m]
(σ : Type u) : is_lawful_monad (state_t σ m) :=
sorry
namespace except_t
theorem ext {α : Type u} {ε : Type u} {m : Type u → Type v} {x : except_t ε m α}
{x' : except_t ε m α} (h : run x = run x') : x = x' :=
sorry
@[simp] theorem run_pure {α : Type u} {ε : Type u} {m : Type u → Type v} [Monad m] (a : α) :
run (pure a) = pure (except.ok a) :=
rfl
@[simp] theorem run_bind {α : Type u} {β : Type u} {ε : Type u} {m : Type u → Type v}
(x : except_t ε m α) [Monad m] (f : α → except_t ε m β) :
run (x >>= f) = run x >>= except_t.bind_cont f :=
rfl
@[simp] theorem run_map {α : Type u} {β : Type u} {ε : Type u} {m : Type u → Type v}
(x : except_t ε m α) [Monad m] (f : α → β) [is_lawful_monad m] :
run (f <$> x) = except.map f <$> run x :=
sorry
@[simp] theorem run_monad_lift {α : Type u} {ε : Type u} {m : Type u → Type v} [Monad m]
{n : Type u → Type u_1} [has_monad_lift_t n m] (x : n α) :
run (monad_lift x) = except.ok <$> monad_lift x :=
rfl
@[simp] theorem run_monad_map {α : Type u} {ε : Type u} {m : Type u → Type v} (x : except_t ε m α)
[Monad m] {m' : Type u → Type v} {n : Type u → Type u_1} {n' : Type u → Type u_1} [Monad m']
[monad_functor_t n n' m m'] (f : {α : Type u} → n α → n' α) :
run (monad_map f x) = monad_map f (run x) :=
rfl
end except_t
protected instance except_t.is_lawful_monad (m : Type u → Type v) [Monad m] [is_lawful_monad m]
(ε : Type u) : is_lawful_monad (except_t ε m) :=
sorry
namespace reader_t
theorem ext {ρ : Type u} {m : Type u → Type v} {α : Type u} {x : reader_t ρ m α}
{x' : reader_t ρ m α} (h : ∀ (r : ρ), run x r = run x' r) : x = x' :=
sorry
@[simp] theorem run_pure {ρ : Type u} {m : Type u → Type v} {α : Type u} (r : ρ) [Monad m] (a : α) :
run (pure a) r = pure a :=
rfl
@[simp] theorem run_bind {ρ : Type u} {m : Type u → Type v} {α : Type u} {β : Type u}
(x : reader_t ρ m α) (r : ρ) [Monad m] (f : α → reader_t ρ m β) :
run (x >>= f) r =
do
let a ← run x r
run (f a) r :=
rfl
@[simp] theorem run_map {ρ : Type u} {m : Type u → Type v} {α : Type u} {β : Type u}
(x : reader_t ρ m α) (r : ρ) [Monad m] (f : α → β) [is_lawful_monad m] :
run (f <$> x) r = f <$> run x r :=
eq.mpr
(id
(Eq._oldrec (Eq.refl (run (f <$> x) r = f <$> run x r))
(Eq.symm (bind_pure_comp_eq_map f (run x r)))))
(Eq.refl (run (f <$> x) r))
@[simp] theorem run_monad_lift {ρ : Type u} {m : Type u → Type v} {α : Type u} (r : ρ) [Monad m]
{n : Type u → Type u_1} [has_monad_lift_t n m] (x : n α) :
run (monad_lift x) r = monad_lift x :=
rfl
@[simp] theorem run_monad_map {ρ : Type u} {m : Type u → Type v} {α : Type u} (x : reader_t ρ m α)
(r : ρ) [Monad m] {m' : Type u → Type v} {n : Type u → Type u_1} {n' : Type u → Type u_1}
[Monad m'] [monad_functor_t n n' m m'] (f : {α : Type u} → n α → n' α) :
run (monad_map f x) r = monad_map f (run x r) :=
rfl
@[simp] theorem run_read {ρ : Type u} {m : Type u → Type v} (r : ρ) [Monad m] :
run reader_t.read r = pure r :=
rfl
end reader_t
protected instance reader_t.is_lawful_monad (ρ : Type u) (m : Type u → Type v) [Monad m]
[is_lawful_monad m] : is_lawful_monad (reader_t ρ m) :=
sorry
namespace option_t
theorem ext {α : Type u} {m : Type u → Type v} {x : option_t m α} {x' : option_t m α}
(h : run x = run x') : x = x' :=
sorry
@[simp] theorem run_pure {α : Type u} {m : Type u → Type v} [Monad m] (a : α) :
run (pure a) = pure (some a) :=
rfl
@[simp] theorem run_bind {α : Type u} {β : Type u} {m : Type u → Type v} (x : option_t m α)
[Monad m] (f : α → option_t m β) : run (x >>= f) = run x >>= option_t.bind_cont f :=
rfl
@[simp] theorem run_map {α : Type u} {β : Type u} {m : Type u → Type v} (x : option_t m α) [Monad m]
(f : α → β) [is_lawful_monad m] : run (f <$> x) = option.map f <$> run x :=
sorry
@[simp] theorem run_monad_lift {α : Type u} {m : Type u → Type v} [Monad m] {n : Type u → Type u_1}
[has_monad_lift_t n m] (x : n α) : run (monad_lift x) = some <$> monad_lift x :=
rfl
@[simp] theorem run_monad_map {α : Type u} {m : Type u → Type v} (x : option_t m α) [Monad m]
{m' : Type u → Type v} {n : Type u → Type u_1} {n' : Type u → Type u_1} [Monad m']
[monad_functor_t n n' m m'] (f : {α : Type u} → n α → n' α) :
run (monad_map f x) = monad_map f (run x) :=
rfl
end option_t
protected instance option_t.is_lawful_monad (m : Type u → Type v) [Monad m] [is_lawful_monad m] :
is_lawful_monad (option_t m) :=
sorry
end Mathlib |
1146a67aed97b3f58184d649addb060c5b13dfb4 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/tactic/auto_cases.lean | 04801a9ca70a8db10601871f199bb5921d2502f6 | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 2,281 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Keeley Hoek, Scott Morrison
-/
import tactic.hint
namespace tactic
namespace auto_cases
/-- Structure representing a tactic which can be used by `tactic.auto_cases`. -/
meta structure auto_cases_tac :=
(name : string)
{α : Type}
(tac : expr → tactic α)
/-- The `auto_cases_tac` for `tactic.cases`. -/
meta def tac_cases : auto_cases_tac := ⟨"cases", cases⟩
/-- The `auto_cases_tac` for `tactic.induction`. -/
meta def tac_induction : auto_cases_tac := ⟨"induction", induction⟩
/-- Find an `auto_cases_tac` which matches the given `type : expr`. -/
meta def find_tac : expr → option auto_cases_tac
| `(empty) := tac_cases
| `(pempty) := tac_cases
| `(false) := tac_cases
| `(unit) := tac_cases
| `(punit) := tac_cases
| `(ulift _) := tac_cases
| `(plift _) := tac_cases
| `(prod _ _) := tac_cases
| `(and _ _) := tac_cases
| `(sigma _) := tac_cases
| `(psigma _) := tac_cases
| `(subtype _) := tac_cases
| `(Exists _) := tac_cases
| `(fin 0) := tac_cases
| `(sum _ _) := tac_cases -- This is perhaps dangerous!
| `(or _ _) := tac_cases -- This is perhaps dangerous!
| `(iff _ _) := tac_cases -- This is perhaps dangerous!
/- `cases` can be dangerous on `eq` and `quot`, producing mysterious errors during type checking.
instead we attempt `induction`. -/
| `(eq _ _) := tac_induction
| `(quot _) := tac_induction
| _ := none
end auto_cases
/-- Applies `cases` or `induction` on the local_hypothesis `hyp : expr`. -/
meta def auto_cases_at (hyp : expr) : tactic string :=
do t ← infer_type hyp >>= whnf,
match auto_cases.find_tac t with
| some atac := do
atac.tac hyp,
pp ← pp hyp,
return sformat!"{atac.name} {pp}"
| none := fail "hypothesis type unsupported"
end
/-- Applies `cases` or `induction` on certain hypotheses. -/
@[hint_tactic]
meta def auto_cases : tactic string :=
do l ← local_context,
results ← successes $ l.reverse.map auto_cases_at,
when (results.empty) $
fail "`auto_cases` did not find any hypotheses to apply `cases` or `induction` to",
return (string.intercalate ", " results)
end tactic
|
18e7579da21b50b7f554d13574447f5e5a2816c7 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/compiler/closure_bug4.lean | 3bd1dff6dbbdb5f21c812dd29d5edc6314381b30 | [
"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 | 529 | lean |
def f (x : Nat) : Nat × (Nat → String) :=
let x1 := x + 1
let x2 := x + 2
let x3 := x + 3
let x4 := x + 4
let x5 := x + 5
let x6 := x + 6
let x7 := x + 7
let x8 := x + 8
let x9 := x + 9
let x10 := x + 10
let x11 := x + 11
let x12 := x + 12
let x13 := x + 13
let x14 := x + 14
let x15 := x + 15
let x16 := x + 16
let x17 := x + 17
(x, fun y => toString [x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15])
def main (xs : List String) : IO Unit :=
IO.println ((f (xs.headD "0").toNat!).2 (xs.headD "0").toNat!)
|
7b7ff51b4939480d018a473247a5e9c3b6e773b3 | 271e26e338b0c14544a889c31c30b39c989f2e0f | /src/Init/Lean/Meta/Message.lean | 48888166ee7f107067b495c4b45a3a59b7035a6a | [
"Apache-2.0"
] | permissive | dgorokho/lean4 | 805f99b0b60c545b64ac34ab8237a8504f89d7d4 | e949a052bad59b1c7b54a82d24d516a656487d8a | refs/heads/master | 1,607,061,363,851 | 1,578,006,086,000 | 1,578,006,086,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,148 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Lean.Meta.Basic
namespace Lean
def indentExpr (msg : MessageData) : MessageData :=
MessageData.nest 2 (Format.line ++ msg)
namespace Meta
namespace Exception
private def run? {α} (ctx : ExceptionContext) (x : MetaM α) : Option α :=
match x { lctx := ctx.lctx } { env := ctx.env, mctx := ctx.mctx, ngen := { namePrefix := `_meta_exception } } with
| EStateM.Result.ok a _ => some a
| EStateM.Result.error _ _ => none
private def inferType? (ctx : ExceptionContext) (e : Expr) : Option Expr :=
run? ctx (inferType e)
private def inferDomain? (ctx : ExceptionContext) (f : Expr) : Option Expr :=
run? ctx $ do
fType ← inferType f;
fType ← whnf fType;
match fType with
| Expr.forallE _ d _ _ => pure d
| _ => throw $ Exception.other "unexpected"
private def whnf? (ctx : ExceptionContext) (e : Expr) : Option Expr :=
run? ctx (whnf e)
def mkAppTypeMismatchMessage (f a : Expr) (ctx : ExceptionContext) : MessageData :=
mkCtx ctx $
let e := mkApp f a;
match inferType? ctx a, inferDomain? ctx f with
| some aType, some expectedType =>
"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
| _, _ =>
"application type mismatch" ++ indentExpr e
def mkLetTypeMismatchMessage (fvarId : FVarId) (ctx : ExceptionContext) : MessageData :=
mkCtx ctx $
match ctx.lctx.find? fvarId with
| some (LocalDecl.ldecl _ n t v b) =>
match inferType? ctx v with
| some vType =>
"invalid let declaration, term" ++ indentExpr v
++ Format.line ++ "has type " ++ indentExpr vType
++ Format.line ++ "but is expected to have type" ++ indentExpr t
| none => "type mismatch at let declaration for " ++ n
| _ => unreachable!
/--
Convert to `MessageData` that is supposed to be displayed in user-friendly error messages. -/
def toMessageData : Exception → MessageData
| unknownConst c ctx => mkCtx ctx $ "unknown constant " ++ c
| unknownFVar fvarId ctx => mkCtx ctx $ "unknown free variable " ++ fvarId
| unknownExprMVar mvarId ctx => mkCtx ctx $ "unknown metavariable " ++ mvarId
| unknownLevelMVar mvarId ctx => mkCtx ctx $ "unknown universe level metavariable " ++ mvarId
| unexpectedBVar bvarIdx => "unexpected bound variable " ++ mkBVar bvarIdx
| functionExpected f a ctx => mkCtx ctx $ "function expected " ++ mkApp f a
| typeExpected t ctx => mkCtx ctx $ "type expected " ++ t
| incorrectNumOfLevels c lvls ctx => mkCtx ctx $ "incorrect number of universe levels " ++ mkConst c lvls
| invalidProjection s i e ctx => mkCtx ctx $ "invalid projection" ++ indentExpr (mkProj s i e)
| revertFailure xs decl ctx => mkCtx ctx $ "revert failure"
| readOnlyMVar mvarId ctx => mkCtx ctx $ "tried to update read only metavariable " ++ mkMVar mvarId
| isLevelDefEqStuck u v ctx => mkCtx ctx $ "stuck at " ++ u ++ " =?= " ++ v
| isExprDefEqStuck t s ctx => mkCtx ctx $ "stuck at " ++ t ++ " =?= " ++ s
| letTypeMismatch fvarId ctx => mkLetTypeMismatchMessage fvarId ctx
| appTypeMismatch f a ctx => mkAppTypeMismatchMessage f a ctx
| notInstance i ctx => mkCtx ctx $ "not a type class instance " ++ i
| appBuilder op msg args ctx => mkCtx ctx $ "application builder failure " ++ op ++ " " ++ args ++ " " ++ msg
| synthInstance inst ctx => mkCtx ctx $ "failed to synthesize" ++ indentExpr inst
| bug _ _ => "internal bug" -- TODO improve
| other s => s
end Exception
end Meta
namespace KernelException
private def mkCtx (env : Environment) (lctx : LocalContext) (opts : Options) (msg : MessageData) : MessageData :=
MessageData.withContext { env := env, mctx := {}, lctx := lctx, opts := opts } msg
def toMessageData (e : KernelException) (opts : Options) : MessageData :=
match e with
| unknownConstant env constName => mkCtx env {} opts $ "(kernel) unknown constant " ++ constName
| alreadyDeclared env constName => mkCtx env {} opts $ "(kernel) constant has already been declared " ++ constName
| declTypeMismatch env decl givenType =>
let process (n : Name) (expectedType : Expr) : MessageData :=
"(kernel) declaration type mismatch " ++ n
++ Format.line ++ "has type" ++ indentExpr givenType
++ Format.line ++ "but it is expected to have type" ++ indentExpr expectedType;
match decl with
| Declaration.defnDecl { name := n, type := type, .. } => process n type
| Declaration.thmDecl { name := n, type := type, .. } => process n type
| _ => "(kernel) declaration type mismatch" -- TODO fix type checker, type mismatch for mutual decls does not have enough information
| declHasMVars env constName _ => mkCtx env {} opts $ "(kernel) declaration has metavariables " ++ constName
| declHasFVars env constName _ => mkCtx env {} opts $ "(kernel) declaration has free variables " ++ constName
| funExpected env lctx e => mkCtx env lctx opts $ "(kernel) function expected" ++ indentExpr e
| typeExpected env lctx e => mkCtx env lctx opts $ "(kernel) type expected" ++ indentExpr e
| letTypeMismatch env lctx n _ _ => mkCtx env lctx opts $ "(kernel) let-declaration type mismatch " ++ n
| exprTypeMismatch env lctx e _ => mkCtx env lctx opts $ "(kernel) type mismatch at " ++ indentExpr e
| appTypeMismatch env lctx e _ _ =>
match e with
| Expr.app f a _ => "(kernel) " ++ Meta.Exception.mkAppTypeMismatchMessage f a { env := env, lctx := lctx, mctx := {}, opts := opts }
| _ => "(kernel) application type mismatch at" ++ indentExpr e
| invalidProj env lctx e => mkCtx env lctx opts $ "(kernel) invalid projection" ++ indentExpr e
| other msg => "(kernel) " ++ msg
end KernelException
end Lean
|
fac2f91394af00de45c5e5a80b6339d07ba835c6 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/category_theory/abelian/opposite.lean | 3dd2cf2967c26c2d0bd0131ccfa09d40bb7d368a | [
"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 | 4,087 | lean | /-
Copyright (c) 2021 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.abelian.basic
import category_theory.preadditive.opposite
import category_theory.limits.opposites
import category_theory.limits.constructions.limits_of_products_and_equalizers
/-!
# The opposite of an abelian category is abelian.
-/
noncomputable theory
namespace category_theory
open category_theory.limits
variables (C : Type*) [category C] [abelian C]
local attribute [instance]
finite_limits_from_equalizers_and_finite_products
finite_colimits_from_coequalizers_and_finite_coproducts
has_finite_limits_opposite has_finite_colimits_opposite has_finite_products_opposite
instance : abelian Cᵒᵖ :=
{ normal_mono_of_mono := λ X Y f m, by exactI
normal_mono_of_normal_epi_unop _ (normal_epi_of_epi f.unop),
normal_epi_of_epi := λ X Y f m, by exactI
normal_epi_of_normal_mono_unop _ (normal_mono_of_mono f.unop), }
section
variables {C} {X Y : C} (f : X ⟶ Y) {A B : Cᵒᵖ} (g : A ⟶ B)
-- TODO: Generalize (this will work whenever f has a cokernel)
-- (The abelian case is probably sufficient for most applications.)
/-- The kernel of `f.op` is the opposite of `cokernel f`. -/
@[simps]
def kernel_op_unop : (kernel f.op).unop ≅ cokernel f :=
{ hom := (kernel.lift f.op (cokernel.π f).op $ by simp [← op_comp]).unop,
inv := cokernel.desc f (kernel.ι f.op).unop $
by { rw [← f.unop_op, ← unop_comp, f.unop_op], simp },
hom_inv_id' := begin
rw [← unop_id, ← (cokernel.desc f _ _).unop_op, ← unop_comp],
congr' 1,
dsimp,
ext,
simp [← op_comp],
end,
inv_hom_id' := begin
dsimp,
ext,
simp [← unop_comp],
end }
-- TODO: Generalize (this will work whenever f has a kernel)
-- (The abelian case is probably sufficient for most applications.)
/-- The cokernel of `f.op` is the opposite of `kernel f`. -/
@[simps]
def cokernel_op_unop : (cokernel f.op).unop ≅ kernel f :=
{ hom := kernel.lift f (cokernel.π f.op).unop $
by { rw [← f.unop_op, ← unop_comp, f.unop_op], simp },
inv := (cokernel.desc f.op (kernel.ι f).op $ by simp [← op_comp]).unop,
hom_inv_id' := begin
rw [← unop_id, ← (kernel.lift f _ _).unop_op, ← unop_comp],
congr' 1,
dsimp,
ext,
simp [← op_comp],
end,
inv_hom_id' := begin
dsimp,
ext,
simp [← unop_comp],
end }
/-- The kernel of `g.unop` is the opposite of `cokernel g`. -/
@[simps]
def kernel_unop_op : opposite.op (kernel g.unop) ≅ cokernel g :=
(cokernel_op_unop g.unop).op
/-- The cokernel of `g.unop` is the opposite of `kernel g`. -/
@[simps]
def cokernel_unop_op : opposite.op (cokernel g.unop) ≅ kernel g :=
(kernel_op_unop g.unop).op
lemma cokernel.π_op : (cokernel.π f.op).unop =
(cokernel_op_unop f).hom ≫ kernel.ι f ≫ eq_to_hom (opposite.unop_op _).symm :=
by simp [cokernel_op_unop]
lemma kernel.ι_op : (kernel.ι f.op).unop =
eq_to_hom (opposite.unop_op _) ≫ cokernel.π f ≫ (kernel_op_unop f).inv :=
by simp [kernel_op_unop]
/-- The kernel of `f.op` is the opposite of `cokernel f`. -/
@[simps]
def kernel_op_op : kernel f.op ≅ opposite.op (cokernel f) :=
(kernel_op_unop f).op.symm
/-- The cokernel of `f.op` is the opposite of `kernel f`. -/
@[simps]
def cokernel_op_op : cokernel f.op ≅ opposite.op (kernel f) :=
(cokernel_op_unop f).op.symm
/-- The kernel of `g.unop` is the opposite of `cokernel g`. -/
@[simps]
def kernel_unop_unop : kernel g.unop ≅ (cokernel g).unop :=
(kernel_unop_op g).unop.symm
lemma kernel.ι_unop : (kernel.ι g.unop).op =
eq_to_hom (opposite.op_unop _) ≫ cokernel.π g ≫ (kernel_unop_op g).inv :=
by simp
lemma cokernel.π_unop : (cokernel.π g.unop).op =
(cokernel_unop_op g).hom ≫ kernel.ι g ≫ eq_to_hom (opposite.op_unop _).symm :=
by simp
/-- The cokernel of `g.unop` is the opposite of `kernel g`. -/
@[simps]
def cokernel_unop_unop : cokernel g.unop ≅ (kernel g).unop :=
(cokernel_unop_op g).unop.symm
end
end category_theory
|
1f07105ce1e7fa6c88a11db6d4c2041ec0c5d9c7 | 6dc0c8ce7a76229dd81e73ed4474f15f88a9e294 | /src/Leanpkg.lean | 9f9eb9e8c8d0b87874b0ec128192e2c4904fa6ba | [
"Apache-2.0"
] | permissive | williamdemeo/lean4 | 72161c58fe65c3ad955d6a3050bb7d37c04c0d54 | 6d00fcf1d6d873e195f9220c668ef9c58e9c4a35 | refs/heads/master | 1,678,305,356,877 | 1,614,708,995,000 | 1,614,708,995,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,528 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner, Sebastian Ullrich
-/
import Leanpkg.Resolve
import Leanpkg.Git
namespace Leanpkg
def readManifest : IO Manifest := do
let m ← Manifest.fromFile leanpkgTomlFn
if m.leanVersion ≠ leanVersionString then
IO.eprintln $ "\nWARNING: Lean version mismatch: installed version is " ++ leanVersionString
++ ", but package requires " ++ m.leanVersion ++ "\n"
return m
def writeManifest (manifest : Lean.Syntax) (fn : String) : IO Unit := do
IO.FS.writeFile fn manifest.reprint.get!
def lockFileName := ".leanpkg-lock"
partial def withLockFile (x : IO α) : IO α := do
acquire
try
x
finally
IO.removeFile lockFileName
where
acquire (firstTime := true) :=
try
-- TODO: lock file should ideally contain PID
if !System.Platform.isWindows then
discard <| IO.Prim.Handle.mk lockFileName "wx"
else
-- `x` mode doesn't seem to work on Windows even though it's listed at
-- https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/fopen-wfopen?view=msvc-160
-- ...? Let's use the slightly racy approach then.
if ← IO.fileExists lockFileName then
throw <| IO.Error.alreadyExists 0 ""
discard <| IO.Prim.Handle.mk lockFileName "w"
catch
| IO.Error.alreadyExists _ _ => do
if firstTime then
IO.eprintln s!"Waiting for prior leanpkg invocation to finish... (remove '{lockFileName}' if stuck)"
IO.sleep (ms := 300)
acquire (firstTime := false)
| e => throw e
structure Configuration :=
leanPath : String
leanSrcPath : String
def configure : IO Configuration := do
let d ← readManifest
IO.eprintln $ "configuring " ++ d.name ++ " " ++ d.version
let assg ← solveDeps d
let paths ← constructPath assg
for path in paths do
unless path == "./." do
-- build recursively
-- TODO: share build of common dependencies
execCmd {
cmd := (← IO.appPath)
cwd := path
args := #["build"]
}
let sep := System.FilePath.searchPathSeparator.toString
return {
leanPath := sep.intercalate <| paths.map (· ++ "/build")
leanSrcPath := sep.intercalate paths
}
def execMake (makeArgs leanArgs : List String) (leanPath : String) : IO Unit := withLockFile do
let manifest ← readManifest
let leanArgs := (match manifest.timeout with | some t => ["-T", toString t] | none => []) ++ leanArgs
let mut spawnArgs := {
cmd := "sh"
cwd := manifest.effectivePath
args := #["-c", s!"\"{← IO.appDir}/leanmake\" LEAN_OPTS=\"{" ".intercalate leanArgs}\" LEAN_PATH=\"{leanPath}\" {" ".intercalate makeArgs} >&2"]
}
execCmd spawnArgs
def buildImports (imports : List String) (leanArgs : List String) : IO Unit := do
unless (← IO.fileExists leanpkgTomlFn) do
return
let manifest ← readManifest
let cfg ← configure
let imports := imports.map (·.toName)
-- TODO: shoddy check
let localImports := imports.filter fun i => i.getRoot.toString.toLower == manifest.name.toLower
if localImports != [] then
let oleans := localImports.map fun i => s!"\"build{Lean.modPathToFilePath i}.olean\""
execMake oleans leanArgs cfg.leanPath
IO.println cfg.leanPath
IO.println cfg.leanSrcPath
def build (makeArgs leanArgs : List String) : IO Unit := do
execMake makeArgs leanArgs (← configure).leanPath
def initGitignoreContents :=
"/build
"
def initPkg (n : String) (fromNew : Bool) : IO Unit := do
IO.FS.writeFile leanpkgTomlFn s!"[package]
name = \"{n}\"
version = \"0.1\"
"
IO.FS.writeFile s!"{n.capitalize}.lean" "def main : IO Unit :=
IO.println \"Hello, world!\"
"
let h ← IO.FS.Handle.mk ".gitignore" IO.FS.Mode.append (bin := false)
h.putStr initGitignoreContents
let gitEx ← IO.isDir ".git"
unless gitEx do
(do
execCmd {cmd := "git", args := #["init", "-q"]}
unless upstreamGitBranch = "master" do
execCmd {cmd := "git", args := #["checkout", "-B", upstreamGitBranch]}
) <|> IO.eprintln "WARNING: failed to initialize git repository"
def init (n : String) := initPkg n false
def usage :=
"Lean package manager, version " ++ uiLeanVersionString ++ "
Usage: leanpkg <command>
init <name> create a Lean package in the current directory
configure download and build dependencies
build [<args>] configure and build *.olean files
See `leanpkg help <command>` for more information on a specific command."
def main : (cmd : String) → (leanpkgArgs leanArgs : List String) → IO Unit
| "init", [Name], [] => init Name
| "configure", [], [] => discard <| configure
| "print-paths", leanpkgArgs, leanArgs => buildImports leanpkgArgs leanArgs
| "build", makeArgs, leanArgs => build makeArgs leanArgs
| "help", ["configure"], [] => IO.println "Download dependencies
Usage:
leanpkg configure
This command sets up the `build/deps` directory.
For each (transitive) git dependency, the specified commit is checked out
into a sub-directory of `build/deps`. If there are dependencies on multiple
versions of the same package, the version materialized is undefined. No copy
is made of local dependencies."
| "help", ["build"], [] => IO.println "download dependencies and build *.olean files
Usage:
leanpkg build [<leanmake-args>] [-- <lean-args>]
This command invokes `leanpkg configure` followed by `leanmake <leanmake-args> LEAN_OPTS=<lean-args>`.
If defined, the `package.timeout` configuration value is passed to Lean via its `-T` parameter.
If no <lean-args> are given, only .olean files will be produced in `build/`. If `lib` or `bin`
is passed instead, the extracted C code is compiled with `c++` and a static library in `build/lib`
or an executable in `build/bin`, respectively, is created. `leanpkg build bin` requires a declaration
of name `main` in the root namespace, which must return `IO Unit` or `IO UInt32` (the exit code) and
may accept the program's command line arguments as a `List String` parameter.
NOTE: building and linking dependent libraries currently has to be done manually, e.g.
```
$ (cd a; leanpkg build lib)
$ (cd b; leanpkg build bin LINK_OPTS=../a/build/lib/libA.a)
```"
| "help", ["init"], [] => IO.println "Create a new Lean package in the current directory
Usage:
leanpkg init <name>
This command creates a new Lean package with the given name in the current
directory."
| "help", _, [] => IO.println usage
| _, _, _ => throw <| IO.userError usage
private def splitCmdlineArgsCore : List String → List String × List String
| [] => ([], [])
| (arg::args) => if arg == "--"
then ([], args)
else
let (outerArgs, innerArgs) := splitCmdlineArgsCore args
(arg::outerArgs, innerArgs)
def splitCmdlineArgs : List String → IO (String × List String × List String)
| [] => throw <| IO.userError usage
| [cmd] => return (cmd, [], [])
| (cmd::rest) =>
let (outerArgs, innerArgs) := splitCmdlineArgsCore rest
return (cmd, outerArgs, innerArgs)
end Leanpkg
def main (args : List String) : IO Unit := do
Lean.initSearchPath none -- HACK
let (cmd, outerArgs, innerArgs) ← Leanpkg.splitCmdlineArgs args
Leanpkg.main cmd outerArgs innerArgs
|
46a2b23f4e4d2e164b7bba3ec0c3de3af62c40f9 | a46270e2f76a375564f3b3e9c1bf7b635edc1f2c | /4.6.2.lean | 8adb425bf9a1b2bdd4a460eb4a54439efa267f71 | [
"CC0-1.0"
] | permissive | wudcscheme/lean-exercise | 88ea2506714eac343de2a294d1132ee8ee6d3a20 | 5b23b9be3d361fff5e981d5be3a0a1175504b9f6 | refs/heads/master | 1,678,958,930,293 | 1,583,197,205,000 | 1,583,197,205,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 988 | lean | variables (α : Type) (p q : α → Prop)
variable r : Prop
example : α → ((∀ x : α, r) ↔ r) :=
assume y: α,
⟨
assume h: ∀ x: α, r,
h y,
λ hr: r, λ _, hr
⟩
example : (∀ x, p x ∨ r) ↔ (∀ x, p x) ∨ r := ⟨
assume h: (∀ x, p x ∨ r),
show (∀ x, p x) ∨ r, from classical.by_contradiction (
assume hc: ¬ ((∀ x, p x) ∨ r),
classical.by_cases (
assume hr: r,
hc $ or.inr hr
) (
assume hnr: ¬ r,
have hpx: ∀ x, p x, from
λ x, or.elim (h x) (
λ px: p x, px
) (
λ hr: r,
absurd hr hnr
),
hc $ or.inl hpx
)
),
assume h: (∀ x, p x) ∨ r,
or.elim h (
λ hpx, λ x, or.inl $ hpx x
) (
λ hr, λ x, or.inr hr
)
⟩
example : (∀ x, r → p x) ↔ (r → ∀ x, p x) := ⟨
assume h: ∀ x, r → p x,
λ hr, λ x, h x hr,
assume h: r → ∀ x, p x,
λ x, λ hr, h hr x
⟩ |
a1a0a933e7e12da56959680b753b25cc72589f31 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/analysis/complex/cauchy_integral.lean | ff508770890a52b808dd16c7176604f71795f210 | [
"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 | 35,148 | lean | /-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import measure_theory.measure.complex_lebesgue
import measure_theory.integral.divergence_theorem
import measure_theory.integral.circle_integral
import analysis.calculus.dslope
import analysis.analytic.basic
import analysis.complex.re_im_topology
import data.real.cardinality
/-!
# Cauchy integral formula
In this file we prove Cauchy theorem and Cauchy integral formula for integrals over circles. Most
results are formulated for a function `f : ℂ → E` that takes values in a complex Banach space with
second countable topology.
## Main statements
In the following theorems, if the name ends with `off_countable`, then the actual theorem assumes
differentiability at all but countably many points of the set mentioned below.
* `complex.integral_boundary_rect_of_has_fderiv_within_at_real_off_countable`: If a function
`f : ℂ → E` is continuous on a closed rectangle and *real* differentiable on its interior, then
its integral over the boundary of this rectangle is equal to the integral of
`I • f' (x + y * I) 1 - f' (x + y * I) I` over the rectangle, where `f' z w : E` is the derivative
of `f` at `z` in the direction `w` and `I = complex.I` is the imaginary unit.
* `complex.integral_boundary_rect_eq_zero_of_differentiable_on_off_countable`: If a function
`f : ℂ → E` is continuous on a closed rectangle and is *complex* differentiable on its interior,
then its integral over the boundary of this rectangle is equal to zero.
* `complex.circle_integral_sub_center_inv_smul_eq_of_differentiable_on_annulus_off_countable`: If a
function `f : ℂ → E` is continuous on a closed annulus `{z | r ≤ |z - c| ≤ R}` and is complex
differentiable on its interior `{z | r < |z - c| < R}`, then the integrals of `(z - c)⁻¹ • f z`
over the outer boundary and over the inner boundary are equal.
* `complex.circle_integral_sub_center_inv_smul_of_differentiable_on_off_countable_of_tendsto`,
`complex.circle_integral_sub_center_inv_smul_of_differentiable_on_off_countable`:
If a function `f : ℂ → E` is continuous on a punctured closed disc `{z | |z - c| ≤ R ∧ z ≠ c}`, is
complex differentiable on the corresponding punctured open disc, and tends to `y` as `z → c`,
`z ≠ c`, then the integral of `(z - c)⁻¹ • f z` over the circle `|z - c| = R` is equal to
`2πiy`. In particular, if `f` is continuous on the whole closed disc and is complex differentiable
on the corresponding open disc, then this integral is equal to `2πif(c)`.
* `complex.circle_integral_sub_inv_smul_of_differentiable_on_off_countable`,
`complex.two_pi_I_inv_smul_circle_integral_sub_inv_smul_of_differentiable_on_off_countable`
**Cauchy integral formula**: if `f : ℂ → E` is continuous on a closed disc of radius `R` and is
complex differentiable on the corresponding open disc, then for any `w` in the corresponding open
disc the integral of `(z - w)⁻¹ • f z` over the boundary of the disc is equal to `2πif(w)`.
Two versions of the lemma put the multiplier `2πi` at the different sides of the equality.
* `complex.has_fpower_series_on_ball_of_differentiable_off_countable`: If `f : ℂ → E` is continuous
on a closed disc of positive radius and is complex differentiable on the corresponding open disc,
then it is analytic on the corresponding open disc, and the coefficients of the power series are
given by Cauchy integral formulas.
* `differentiable_on.has_fpower_series_on_ball`: If `f : ℂ → E` is complex differentiable on a
closed disc of positive radius, then it is analytic on the corresponding open disc, and the
coefficients of the power series are given by Cauchy integral formulas.
* `differentiable_on.analytic_at`, `differentiable.analytic_at`: If `f : ℂ → E` is differentiable
on a neighborhood of a point, then it is analytic at this point. In particular, if `f : ℂ → E`
is differentiable on the whole `ℂ`, then it is analytic at every point `z : ℂ`.
## Implementation details
The proof of the Cauchy integral formula in this file is based on a very general version of the
divergence theorem, see `measure_theory.integral_divergence_of_has_fderiv_within_at_off_countable`
(a version for functions defined on `fin (n + 1) → ℝ`),
`measure_theory.integral_divergence_prod_Icc_of_has_fderiv_within_at_off_countable_of_le`, and
`measure_theory.integral2_divergence_prod_of_has_fderiv_within_at_off_countable` (versions for
functions defined on `ℝ × ℝ`).
Usually, the divergence theorem is formulated for a $C^1$ smooth function. The theorems formulated
above deal with a function that is
* continuous on a closed box/rectangle;
* differentiable at all but countably many points of its interior;
* have divergence integrable over the closed box/rectangle.
First, we reformulate the theorem for a *real*-differentiable map `ℂ → E`, and relate the integral
of `f` over the boundary of a rectangle in `ℂ` to the integral of the derivative
$\frac{\partial f}{\partial \bar z}$ over the interior of this box. In particular, for a *complex*
differentiable function, the latter derivative is zero, hence the integral over the boundary of a
rectangle is zero. Thus we get Cauchy theorem for a rectangle in `ℂ`.
Next, we apply the this theorem to the function $F(z)=f(c+e^{z})$ on the rectangle
$[\ln r, \ln R]\times [0, 2\pi]$ to prove that
$$
\oint_{|z-c|=r}\frac{f(z)\,dz}{z-c}=\oint_{|z-c|=R}\frac{f(z)\,dz}{z-c}
$$
provided that `f` is continuous on the closed annulus `r ≤ |z - c| ≤ R` and is complex
differentiable on its interior `r < |z - c| < R` (possibly, at all but countably many points).
Here and below, we write $\frac{f(z)}{z-c}$ in the documentation while the actual lemmas use
`(z - c)⁻¹ • f z` because `f z` belongs to some Banach space over `ℂ` and `f z / (z - c)` is
undefined.
Taking the limit of this equality as `r` tends to `𝓝[>] 0`, we prove
$$
\oint_{|z-c|=R}\frac{f(z)\,dz}{z-c}=2\pi if(c)
$$
provided that `f` is continuous on the closed disc `|z - c| ≤ R` and is differentiable at all but
countably many points of its interior. This is the Cauchy integral formula for the center of a
circle. In particular, if we apply this function to `F z = (z - c) • f z`, then we get
$$
\oint_{|z-c|=R} f(z)\,dz=0.
$$
In order to deduce the Cauchy integral formula for any point `w`, `|w - c| < R`, we consider the
slope function `g : ℂ → E` given by `g z = (z - w)⁻¹ • (f z - f w)` if `z ≠ w` and `g w = f' w`.
This function satisfies assumptions of the previous theorem, so we have
$$
\oint_{|z-c|=R} \frac{f(z)\,dz}{z-w}=\oint_{|z-c|=R} \frac{f(w)\,dz}{z-w}=
\left(\oint_{|z-c|=R} \frac{dz}{z-w}\right)f(w).
$$
The latter integral was computed in `circle_integral.integral_sub_inv_of_mem_ball` and is equal to
`2 * π * complex.I`.
There is one more step in the actual proof. Since we allow `f` to be non-differentiable on a
countable set `s`, we cannot immediately claim that `g` is continuous at `w` if `w ∈ s`. So, we use
the proof outlined in the previous paragraph for `w ∉ s` (see
`complex.circle_integral_sub_inv_smul_of_differentiable_on_off_countable_aux`), then use continuity
of both sides of the formula and density of `sᶜ` to prove the formula for all points of the open
ball, see `complex.circle_integral_sub_inv_smul_of_differentiable_on_off_countable`.
Finally, we use the properties of the Cauchy integrals established elsewhere (see
`has_fpower_series_on_cauchy_integral`) and Cauchy integral formula to prove that the original
function is analytic on the open ball.
## Tags
Cauchy theorem, Cauchy integral formula
-/
open topological_space set measure_theory interval_integral metric filter function
open_locale interval real nnreal ennreal topological_space big_operators
noncomputable theory
universes u
variables {E : Type u} [normed_group E] [normed_space ℂ E] [measurable_space E] [borel_space E]
[second_countable_topology E] [complete_space E]
namespace complex
/-- Suppose that a function `f : ℂ → E` is continuous on a closed rectangle with opposite corners at
`z w : ℂ`, is *real* differentiable at all but countably many points of the corresponding open
rectangle, and $\frac{\partial f}{\partial \bar z}$ is integrable on this rectangle. Then the
integral of `f` over the boundary of the rectangle is equal to the integral of
$2i\frac{\partial f}{\partial \bar z}=i\frac{\partial f}{\partial x}-\frac{\partial f}{\partial y}$
over the rectangle. -/
lemma integral_boundary_rect_of_has_fderiv_at_real_off_countable (f : ℂ → E)
(f' : ℂ → ℂ →L[ℝ] E) (z w : ℂ) (s : set ℂ) (hs : countable s)
(Hc : continuous_on f (re ⁻¹' [z.re, w.re] ∩ im ⁻¹' [z.im, w.im]))
(Hd : ∀ x ∈ (re ⁻¹' (Ioo (min z.re w.re) (max z.re w.re)) ∩
im ⁻¹' (Ioo (min z.im w.im) (max z.im w.im))) \ s, has_fderiv_at f (f' x) x)
(Hi : integrable_on (λ z, I • f' z 1 - f' z I) (re ⁻¹' [z.re, w.re] ∩ im ⁻¹' [z.im, w.im])) :
(∫ x : ℝ in z.re..w.re, f (x + z.im * I)) - (∫ x : ℝ in z.re..w.re, f (x + w.im * I)) +
(I • ∫ y : ℝ in z.im..w.im, f (re w + y * I)) - I • ∫ y : ℝ in z.im..w.im, f (re z + y * I) =
∫ x : ℝ in z.re..w.re, ∫ y : ℝ in z.im..w.im, I • f' (x + y * I) 1 - f' (x + y * I) I :=
begin
set e : (ℝ × ℝ) ≃L[ℝ] ℂ := equiv_real_prodₗ.symm,
have he : ∀ x y : ℝ, ↑x + ↑y * I = e (x, y), from λ x y, (mk_eq_add_mul_I x y).symm,
have he₁ : e (1, 0) = 1 := rfl, have he₂ : e (0, 1) = I := rfl,
simp only [he] at *,
set F : (ℝ × ℝ) → E := f ∘ e,
set F' : (ℝ × ℝ) → (ℝ × ℝ) →L[ℝ] E := λ p, (f' (e p)).comp (e : (ℝ × ℝ) →L[ℝ] ℂ),
have hF' : ∀ p : ℝ × ℝ, (-(I • F' p)) (1, 0) + F' p (0, 1) = -(I • f' (e p) 1 - f' (e p) I),
{ rintro ⟨x, y⟩, simp [F', he₁, he₂, ← sub_eq_neg_add], },
set R : set (ℝ × ℝ) := [z.re, w.re] ×ˢ [w.im, z.im],
set t : set (ℝ × ℝ) := e ⁻¹' s,
rw [interval_swap z.im] at Hc Hi, rw [min_comm z.im, max_comm z.im] at Hd,
have hR : e ⁻¹' (re ⁻¹' [z.re, w.re] ∩ im ⁻¹' [w.im, z.im]) = R := rfl,
have htc : continuous_on F R, from Hc.comp e.continuous_on hR.ge,
have htd : ∀ p ∈ Ioo (min z.re w.re) (max z.re w.re) ×ˢ Ioo (min w.im z.im) (max w.im z.im) \ t,
has_fderiv_at F (F' p) p := λ p hp, (Hd (e p) hp).comp p e.has_fderiv_at,
simp_rw [← interval_integral.integral_smul, interval_integral.integral_symm w.im z.im,
← interval_integral.integral_neg, ← hF'],
refine (integral2_divergence_prod_of_has_fderiv_within_at_off_countable
(λ p, -(I • F p)) F (λ p, - (I • F' p)) F' z.re w.im w.re z.im t (hs.preimage e.injective)
(continuous_on_const.smul htc).neg htc (λ p hp, ((htd p hp).const_smul I).neg) htd _).symm,
rw [← volume_preserving_equiv_real_prod.symm.integrable_on_comp_preimage
(measurable_equiv.measurable_embedding _)] at Hi,
simpa only [hF'] using Hi.neg
end
/-- Suppose that a function `f : ℂ → E` is continuous on a closed rectangle with opposite corners at
`z w : ℂ`, is *real* differentiable on the corresponding open rectangle, and
$\frac{\partial f}{\partial \bar z}$ is integrable on this rectangle. Then the integral of `f` over
the boundary of the rectangle is equal to the integral of
$2i\frac{\partial f}{\partial \bar z}=i\frac{\partial f}{\partial x}-\frac{\partial f}{\partial y}$
over the rectangle. -/
lemma integral_boundary_rect_of_continuous_on_of_has_fderiv_at_real (f : ℂ → E)
(f' : ℂ → ℂ →L[ℝ] E) (z w : ℂ)
(Hc : continuous_on f (re ⁻¹' [z.re, w.re] ∩ im ⁻¹' [z.im, w.im]))
(Hd : ∀ x ∈ (re ⁻¹' (Ioo (min z.re w.re) (max z.re w.re)) ∩
im ⁻¹' (Ioo (min z.im w.im) (max z.im w.im))), has_fderiv_at f (f' x) x)
(Hi : integrable_on (λ z, I • f' z 1 - f' z I) (re ⁻¹' [z.re, w.re] ∩ im ⁻¹' [z.im, w.im])) :
(∫ x : ℝ in z.re..w.re, f (x + z.im * I)) - (∫ x : ℝ in z.re..w.re, f (x + w.im * I)) +
(I • ∫ y : ℝ in z.im..w.im, f (re w + y * I)) - I • ∫ y : ℝ in z.im..w.im, f (re z + y * I) =
∫ x : ℝ in z.re..w.re, ∫ y : ℝ in z.im..w.im, I • f' (x + y * I) 1 - f' (x + y * I) I :=
integral_boundary_rect_of_has_fderiv_at_real_off_countable f f' z w ∅ countable_empty Hc
(λ x hx, Hd x hx.1) Hi
/-- Suppose that a function `f : ℂ → E` is *real* differentiable on a closed rectangle with opposite
corners at `z w : ℂ` and $\frac{\partial f}{\partial \bar z}$ is integrable on this rectangle. Then
the integral of `f` over the boundary of the rectangle is equal to the integral of
$2i\frac{\partial f}{\partial \bar z}=i\frac{\partial f}{\partial x}-\frac{\partial f}{\partial y}$
over the rectangle. -/
lemma integral_boundary_rect_of_differentiable_on_real (f : ℂ → E) (z w : ℂ)
(Hd : differentiable_on ℝ f (re ⁻¹' [z.re, w.re] ∩ im ⁻¹' [z.im, w.im]))
(Hi : integrable_on (λ z, I • fderiv ℝ f z 1 - fderiv ℝ f z I)
(re ⁻¹' [z.re, w.re] ∩ im ⁻¹' [z.im, w.im])) :
(∫ x : ℝ in z.re..w.re, f (x + z.im * I)) - (∫ x : ℝ in z.re..w.re, f (x + w.im * I)) +
(I • ∫ y : ℝ in z.im..w.im, f (re w + y * I)) - I • ∫ y : ℝ in z.im..w.im, f (re z + y * I) =
∫ x : ℝ in z.re..w.re, ∫ y : ℝ in z.im..w.im,
I • fderiv ℝ f (x + y * I) 1 - fderiv ℝ f (x + y * I) I :=
integral_boundary_rect_of_has_fderiv_at_real_off_countable f (fderiv ℝ f) z w ∅ countable_empty
Hd.continuous_on
(λ x hx, Hd.has_fderiv_at $ by simpa only [← mem_interior_iff_mem_nhds,
interior_preimage_re_inter_preimage_im, interval, interior_Icc] using hx.1) Hi
/-- **Cauchy theorem**: the integral of a complex differentiable function over the boundary of a
rectangle equals zero. More precisely, if `f` is continuous on a closed rectangle and is complex
differentiable at all but countably many points of the corresponding open rectangle, then its
integral over the boundary of the rectangle equals zero. -/
lemma integral_boundary_rect_eq_zero_of_differentiable_on_off_countable (f : ℂ → E)
(z w : ℂ) (s : set ℂ) (hs : countable s)
(Hc : continuous_on f (re ⁻¹' [z.re, w.re] ∩ im ⁻¹' [z.im, w.im]))
(Hd : ∀ x ∈ (re ⁻¹' (Ioo (min z.re w.re) (max z.re w.re)) ∩
im ⁻¹' (Ioo (min z.im w.im) (max z.im w.im))) \ s, differentiable_at ℂ f x) :
(∫ x : ℝ in z.re..w.re, f (x + z.im * I)) - (∫ x : ℝ in z.re..w.re, f (x + w.im * I)) +
(I • ∫ y : ℝ in z.im..w.im, f (re w + y * I)) -
I • ∫ y : ℝ in z.im..w.im, f (re z + y * I) = 0 :=
by refine (integral_boundary_rect_of_has_fderiv_at_real_off_countable f
(λ z, (fderiv ℂ f z).restrict_scalars ℝ) z w s hs Hc
(λ x hx, (Hd x hx).has_fderiv_at.restrict_scalars ℝ) _).trans _;
simp [← continuous_linear_map.map_smul]
/-- **Cauchy theorem**: the integral of a complex differentiable function over the boundary of a
rectangle equals zero. More precisely, if `f` is continuous on a closed rectangle and is complex
differentiable on the corresponding open rectangle, then its integral over the boundary of the
rectangle equals zero. -/
lemma integral_boundary_rect_eq_zero_of_continuous_on_of_differentiable_on (f : ℂ → E) (z w : ℂ)
(Hc : continuous_on f (re ⁻¹' [z.re, w.re] ∩ im ⁻¹' [z.im, w.im]))
(Hd : differentiable_on ℂ f (re ⁻¹' (Ioo (min z.re w.re) (max z.re w.re)) ∩
im ⁻¹' (Ioo (min z.im w.im) (max z.im w.im)))) :
(∫ x : ℝ in z.re..w.re, f (x + z.im * I)) - (∫ x : ℝ in z.re..w.re, f (x + w.im * I)) +
(I • ∫ y : ℝ in z.im..w.im, f (re w + y * I)) -
I • ∫ y : ℝ in z.im..w.im, f (re z + y * I) = 0 :=
integral_boundary_rect_eq_zero_of_differentiable_on_off_countable f z w ∅ countable_empty
Hc $ λ x hx, Hd.differentiable_at $ (is_open_Ioo.re_prod_im is_open_Ioo).mem_nhds hx.1
/-- **Cauchy theorem**: the integral of a complex differentiable function over the boundary of a
rectangle equals zero. More precisely, if `f` is complex differentiable on a closed rectangle, then
its integral over the boundary of the rectangle equals zero. -/
lemma integral_boundary_rect_eq_zero_of_differentiable_on (f : ℂ → E) (z w : ℂ)
(H : differentiable_on ℂ f (re ⁻¹' [z.re, w.re] ∩ im ⁻¹' [z.im, w.im])) :
(∫ x : ℝ in z.re..w.re, f (x + z.im * I)) - (∫ x : ℝ in z.re..w.re, f (x + w.im * I)) +
(I • ∫ y : ℝ in z.im..w.im, f (re w + y * I)) -
I • ∫ y : ℝ in z.im..w.im, f (re z + y * I) = 0 :=
integral_boundary_rect_eq_zero_of_continuous_on_of_differentiable_on f z w H.continuous_on $
H.mono $
inter_subset_inter (preimage_mono Ioo_subset_Icc_self) (preimage_mono Ioo_subset_Icc_self)
/-- If `f : ℂ → E` is continuous the closed annulus `r ≤ ∥z - c∥ ≤ R`, `0 < r ≤ R`, and is complex
differentiable at all but countably many points of its interior, then the integrals of
`f z / (z - c)` (formally, `(z - c)⁻¹ • f z`) over the circles `∥z - c∥ = r` and `∥z - c∥ = R` are
equal to each other. -/
lemma circle_integral_sub_center_inv_smul_eq_of_differentiable_on_annulus_off_countable
{c : ℂ} {r R : ℝ} (h0 : 0 < r) (hle : r ≤ R) {f : ℂ → E} {s : set ℂ} (hs : countable s)
(hc : continuous_on f (closed_ball c R \ ball c r))
(hd : ∀ z ∈ ball c R \ closed_ball c r \ s, differentiable_at ℂ f z) :
∮ z in C(c, R), (z - c)⁻¹ • f z = ∮ z in C(c, r), (z - c)⁻¹ • f z :=
begin
/- We apply the previous lemma to `λ z, f (c + exp z)` on the rectangle
`[log r, log R] × [0, 2 * π]`. -/
set A := closed_ball c R \ ball c r,
obtain ⟨a, rfl⟩ : ∃ a, real.exp a = r, from ⟨real.log r, real.exp_log h0⟩,
obtain ⟨b, rfl⟩ : ∃ b, real.exp b = R, from ⟨real.log R, real.exp_log (h0.trans_le hle)⟩,
rw [real.exp_le_exp] at hle,
-- Unfold definition of `circle_integral` and cancel some terms.
suffices : ∫ θ in 0..2 * π, I • f (circle_map c (real.exp b) θ) =
∫ θ in 0..2 * π, I • f (circle_map c (real.exp a) θ),
by simpa only [circle_integral, add_sub_cancel', of_real_exp, ← exp_add, smul_smul,
← div_eq_mul_inv, mul_div_cancel_left _ (circle_map_ne_center (real.exp_pos _).ne'),
circle_map_sub_center, deriv_circle_map],
set R := re ⁻¹' [a, b] ∩ im ⁻¹' [0, 2 * π],
set g : ℂ → ℂ := (+) c ∘ exp,
have hdg : differentiable ℂ g := differentiable_exp.const_add _,
replace hs : countable (g ⁻¹' s) := (hs.preimage (add_right_injective c)).preimage_cexp,
have h_maps : maps_to g R A,
{ rintro z ⟨h, -⟩, simpa [dist_eq, g, abs_exp, hle] using h.symm },
replace hc : continuous_on (f ∘ g) R, from hc.comp hdg.continuous.continuous_on h_maps,
replace hd : ∀ z ∈ re ⁻¹' (Ioo (min a b) (max a b)) ∩
im ⁻¹' (Ioo (min 0 (2 * π)) (max 0 (2 * π))) \ g ⁻¹' s, differentiable_at ℂ (f ∘ g) z,
{ refine λ z hz, (hd (g z) ⟨_, hz.2⟩).comp z (hdg _),
simpa [g, dist_eq, abs_exp, hle, and.comm] using hz.1.1 },
simpa [g, circle_map, exp_periodic _, sub_eq_zero, ← exp_add]
using integral_boundary_rect_eq_zero_of_differentiable_on_off_countable _ ⟨a, 0⟩ ⟨b, 2 * π⟩
_ hs hc hd
end
/-- **Cauchy integral formula** for the value at the center of a disc. If `f` is continuous on a
punctured closed disc of radius `R`, is differentiable at all but countably many points of the
interior of this disc, and has a limit `y` at the center of the disc, then the integral
$\oint_{∥z-c∥=R} \frac{f(z)}{z-c}\,dz$ is equal to $2πiy`. -/
lemma circle_integral_sub_center_inv_smul_of_differentiable_on_off_countable_of_tendsto
{c : ℂ} {R : ℝ} (h0 : 0 < R) {f : ℂ → E} {y : E} {s : set ℂ} (hs : countable s)
(hc : continuous_on f (closed_ball c R \ {c}))
(hd : ∀ z ∈ ball c R \ {c} \ s, differentiable_at ℂ f z)
(hy : tendsto f (𝓝[{c}ᶜ] c) (𝓝 y)) :
∮ z in C(c, R), (z - c)⁻¹ • f z = (2 * π * I : ℂ) • y :=
begin
rw [← sub_eq_zero, ← norm_le_zero_iff],
refine le_of_forall_le_of_dense (λ ε ε0, _),
obtain ⟨δ, δ0, hδ⟩ :
∃ δ > (0 : ℝ), ∀ z ∈ closed_ball c δ \ {c}, dist (f z) y < ε / (2 * π),
from ((nhds_within_has_basis nhds_basis_closed_ball _).tendsto_iff nhds_basis_ball).1 hy _
(div_pos ε0 real.two_pi_pos),
obtain ⟨r, hr0, hrδ, hrR⟩ : ∃ r, 0 < r ∧ r ≤ δ ∧ r ≤ R :=
⟨min δ R, lt_min δ0 h0, min_le_left _ _, min_le_right _ _⟩,
have hsub : closed_ball c R \ ball c r ⊆ closed_ball c R \ {c},
from diff_subset_diff_right (singleton_subset_iff.2 $ mem_ball_self hr0),
have hsub' : ball c R \ closed_ball c r ⊆ ball c R \ {c},
from diff_subset_diff_right (singleton_subset_iff.2 $ mem_closed_ball_self hr0.le),
have hzne : ∀ z ∈ sphere c r, z ≠ c,
from λ z hz, ne_of_mem_of_not_mem hz (λ h, hr0.ne' $ dist_self c ▸ eq.symm h),
/- The integral `∮ z in C(c, r), f z / (z - c)` does not depend on `0 < r ≤ R` and tends to
`2πIy` as `r → 0`. -/
calc ∥(∮ z in C(c, R), (z - c)⁻¹ • f z) - (2 * ↑π * I) • y∥
= ∥(∮ z in C(c, r), (z - c)⁻¹ • f z) - ∮ z in C(c, r), (z - c)⁻¹ • y∥ :
begin
congr' 2,
{ exact circle_integral_sub_center_inv_smul_eq_of_differentiable_on_annulus_off_countable
hr0 hrR hs (hc.mono hsub) (λ z hz, hd z ⟨hsub' hz.1, hz.2⟩) },
{ simp [hr0.ne'] }
end
... = ∥∮ z in C(c, r), (z - c)⁻¹ • (f z - y)∥ :
begin
simp only [smul_sub],
have hc' : continuous_on (λ z, (z - c)⁻¹) (sphere c r),
from (continuous_on_id.sub continuous_on_const).inv₀ (λ z hz, sub_ne_zero.2 $ hzne _ hz),
rw circle_integral.integral_sub; refine (hc'.smul _).circle_integrable hr0.le,
{ exact hc.mono (subset_inter (sphere_subset_closed_ball.trans $
closed_ball_subset_closed_ball hrR) hzne) },
{ exact continuous_on_const }
end
... ≤ 2 * π * r * (r⁻¹ * (ε / (2 * π))) :
begin
refine circle_integral.norm_integral_le_of_norm_le_const hr0.le (λ z hz, _),
specialize hzne z hz,
rw [mem_sphere, dist_eq_norm] at hz,
rw [norm_smul, normed_field.norm_inv, hz, ← dist_eq_norm],
refine mul_le_mul_of_nonneg_left (hδ _ ⟨_, hzne⟩).le (inv_nonneg.2 hr0.le),
rwa [mem_closed_ball_iff_norm, hz]
end
... = ε : by { field_simp [hr0.ne', real.two_pi_pos.ne'], ac_refl }
end
/-- **Cauchy integral formula** for the value at the center of a disc. If `f : ℂ → E` is continuous
on a closed disc of radius `R` and is complex differentiable at all but countably many points of its
interior, then the integral $\oint_{|z-c|=R} \frac{f(z)}{z-c}\,dz$ is equal to $2πiy`. -/
lemma circle_integral_sub_center_inv_smul_of_differentiable_on_off_countable {R : ℝ} (h0 : 0 < R)
{f : ℂ → E} {c : ℂ} {s : set ℂ} (hs : countable s)
(hc : continuous_on f (closed_ball c R)) (hd : ∀ z ∈ ball c R \ s, differentiable_at ℂ f z) :
∮ z in C(c, R), (z - c)⁻¹ • f z = (2 * π * I : ℂ) • f c :=
circle_integral_sub_center_inv_smul_of_differentiable_on_off_countable_of_tendsto h0 hs
(hc.mono $ diff_subset _ _) (λ z hz, hd z ⟨hz.1.1, hz.2⟩)
(hc.continuous_at $ closed_ball_mem_nhds _ h0).continuous_within_at
/-- **Cauchy theorem**: if `f : ℂ → E` is continuous on a closed ball `{z | ∥z - c∥ ≤ R}` and is
complex differentiable at all but countably many points of its interior, then the integral
$\oint_{|z-c|=R}f(z)\,dz$ equals zero. -/
lemma circle_integral_eq_zero_of_differentiable_on_off_countable {R : ℝ} (h0 : 0 ≤ R) {f : ℂ → E}
{c : ℂ} {s : set ℂ} (hs : countable s) (hc : continuous_on f (closed_ball c R))
(hd : ∀ z ∈ ball c R \ s, differentiable_at ℂ f z) :
∮ z in C(c, R), f z = 0 :=
begin
rcases h0.eq_or_lt with rfl|h0, { apply circle_integral.integral_radius_zero },
calc ∮ z in C(c, R), f z = ∮ z in C(c, R), (z - c)⁻¹ • (z - c) • f z :
begin
refine circle_integral.integral_congr h0.le (λ z hz, (inv_smul_smul₀ (λ h₀, _) _).symm),
rw [mem_sphere, dist_eq, h₀, abs_zero] at hz,
exact h0.ne hz
end
... = (2 * ↑π * I : ℂ) • (c - c) • f c :
circle_integral_sub_center_inv_smul_of_differentiable_on_off_countable h0 hs
((continuous_on_id.sub continuous_on_const).smul hc)
(λ z hz, (differentiable_at_id.sub_const _).smul (hd z hz))
... = 0 : by rw [sub_self, zero_smul, smul_zero]
end
/-- An auxiliary lemma for
`complex.circle_integral_sub_inv_smul_of_differentiable_on_off_countable`. This lemma assumes
`w ∉ s` while the main lemma drops this assumption. -/
lemma circle_integral_sub_inv_smul_of_differentiable_on_off_countable_aux {R : ℝ} {c w : ℂ}
{f : ℂ → E} {s : set ℂ} (hs : countable s) (hw : w ∈ ball c R \ s)
(hc : continuous_on f (closed_ball c R)) (hd : ∀ x ∈ ball c R \ s, differentiable_at ℂ f x) :
∮ z in C(c, R), (z - w)⁻¹ • f z = (2 * π * I : ℂ) • f w :=
begin
have hR : 0 < R := dist_nonneg.trans_lt hw.1,
set F : ℂ → E := dslope f w,
have hws : countable (insert w s) := hs.insert _,
have hnhds : closed_ball c R ∈ 𝓝 w, from closed_ball_mem_nhds_of_mem hw.1,
have hcF : continuous_on F (closed_ball c R),
from (continuous_on_dslope $ closed_ball_mem_nhds_of_mem hw.1).2 ⟨hc, hd _ hw⟩,
have hdF : ∀ z ∈ ball (c : ℂ) R \ (insert w s), differentiable_at ℂ F z,
from λ z hz, (differentiable_at_dslope_of_ne
(ne_of_mem_of_not_mem (mem_insert _ _) hz.2).symm).2
(hd _ (diff_subset_diff_right (subset_insert _ _) hz)),
have HI := circle_integral_eq_zero_of_differentiable_on_off_countable hR.le hws hcF hdF,
have hne : ∀ z ∈ sphere c R, z ≠ w, from λ z hz, ne_of_mem_of_not_mem hz (ne_of_lt hw.1),
have hFeq : eq_on F (λ z, (z - w)⁻¹ • f z - (z - w)⁻¹ • f w) (sphere c R),
{ intros z hz,
calc F z = (z - w)⁻¹ • (f z - f w) : update_noteq (hne z hz) _ _
... = (z - w)⁻¹ • f z - (z - w)⁻¹ • f w : smul_sub _ _ _ },
have hc' : continuous_on (λ z, (z - w)⁻¹) (sphere c R),
from (continuous_on_id.sub continuous_on_const).inv₀ (λ z hz, sub_ne_zero.2 $ hne z hz),
rw [← circle_integral.integral_sub_inv_of_mem_ball hw.1, ← circle_integral.integral_smul_const,
← sub_eq_zero, ← circle_integral.integral_sub, ← circle_integral.integral_congr hR.le hFeq, HI],
exacts [(hc'.smul (hc.mono sphere_subset_closed_ball)).circle_integrable hR.le,
(hc'.smul continuous_on_const).circle_integrable hR.le]
end
/-- **Cauchy integral formula**: if `f : ℂ → E` is continuous on a closed disc of radius `R` and is
complex differentiable at all but countably many points of its interior, then for any `w` in this
interior we have $\frac{1}{2πi}\oint_{|z-c|=R}(z-w)^{-1}f(z)\,dz=f(w)$.
-/
lemma two_pi_I_inv_smul_circle_integral_sub_inv_smul_of_differentiable_on_off_countable
{R : ℝ} {c w : ℂ} {f : ℂ → E} {s : set ℂ} (hs : countable s) (hw : w ∈ ball c R)
(hc : continuous_on f (closed_ball c R)) (hd : ∀ x ∈ ball c R \ s, differentiable_at ℂ f x) :
(2 * π * I : ℂ)⁻¹ • ∮ z in C(c, R), (z - w)⁻¹ • f z = f w :=
begin
have hR : 0 < R := dist_nonneg.trans_lt hw,
suffices : w ∈ closure (ball c R \ s),
{ lift R to ℝ≥0 using hR.le,
have A : continuous_at (λ w, (2 * π * I : ℂ)⁻¹ • ∮ z in C(c, R), (z - w)⁻¹ • f z) w,
{ have := has_fpower_series_on_cauchy_integral
((hc.mono sphere_subset_closed_ball).circle_integrable R.coe_nonneg) hR,
refine this.continuous_on.continuous_at (emetric.is_open_ball.mem_nhds _),
rwa metric.emetric_ball_nnreal },
have B : continuous_at f w, from hc.continuous_at (closed_ball_mem_nhds_of_mem hw),
refine tendsto_nhds_unique_of_frequently_eq A B ((mem_closure_iff_frequently.1 this).mono _),
intros z hz,
rw [circle_integral_sub_inv_smul_of_differentiable_on_off_countable_aux hs hz hc hd,
inv_smul_smul₀],
simp [real.pi_ne_zero, I_ne_zero] },
refine mem_closure_iff_nhds.2 (λ t ht, _),
-- TODO: generalize to any vector space over `ℝ`
set g : ℝ → ℂ := λ x, w + x,
have : tendsto g (𝓝 0) (𝓝 w),
from (continuous_const.add continuous_of_real).tendsto' 0 w (add_zero _),
rcases mem_nhds_iff_exists_Ioo_subset.1 (this $ inter_mem ht $ is_open_ball.mem_nhds hw)
with ⟨l, u, hlu₀, hlu_sub⟩,
obtain ⟨x, hx⟩ : (Ioo l u \ g ⁻¹' s).nonempty,
{ refine nonempty_diff.2 (λ hsub, _),
have : countable (Ioo l u),
from (hs.preimage ((add_right_injective w).comp of_real_injective)).mono hsub,
rw [← cardinal.mk_set_le_omega, cardinal.mk_Ioo_real (hlu₀.1.trans hlu₀.2)] at this,
exact this.not_lt cardinal.omega_lt_continuum },
exact ⟨g x, (hlu_sub hx.1).1, (hlu_sub hx.1).2, hx.2⟩
end
/-- **Cauchy integral formula**: if `f : ℂ → E` is continuous on a closed disc of radius `R` and is
complex differentiable at all but countably many points of its interior, then for any `w` in this
interior we have $\oint_{|z-c|=R}(z-w)^{-1}f(z)\,dz=2πif(w)$.
-/
lemma circle_integral_sub_inv_smul_of_differentiable_on_off_countable
{R : ℝ} {c w : ℂ} {f : ℂ → E} {s : set ℂ} (hs : countable s) (hw : w ∈ ball c R)
(hc : continuous_on f (closed_ball c R)) (hd : ∀ x ∈ ball c R \ s, differentiable_at ℂ f x) :
∮ z in C(c, R), (z - w)⁻¹ • f z = (2 * π * I : ℂ) • f w :=
by { rw [← two_pi_I_inv_smul_circle_integral_sub_inv_smul_of_differentiable_on_off_countable
hs hw hc hd, smul_inv_smul₀], simp [real.pi_ne_zero, I_ne_zero] }
/-- **Cauchy integral formula**: if `f : ℂ → E` is continuous on a closed disc of radius `R` and is
complex differentiable on its interior, then for any `w` in this interior we have
$\oint_{|z-c|=R}(z-w)^{-1}f(z)\,dz=2πif(w)$.
-/
lemma circle_integral_sub_inv_smul_of_continuous_on_of_differentiable_on
{R : ℝ} {c w : ℂ} {f : ℂ → E} (hw : w ∈ ball c R)
(hc : continuous_on f (closed_ball c R)) (hd : differentiable_on ℂ f (ball c R)) :
∮ z in C(c, R), (z - w)⁻¹ • f z = (2 * π * I : ℂ) • f w :=
circle_integral_sub_inv_smul_of_differentiable_on_off_countable countable_empty hw hc $ λ z hz,
hd.differentiable_at (is_open_ball.mem_nhds hz.1)
/-- **Cauchy integral formula**: if `f : ℂ → E` is complex differentiable on a closed disc of radius
`R`, then for any `w` in its interior we have $\oint_{|z-c|=R}(z-w)^{-1}f(z)\,dz=2πif(w)$. -/
lemma circle_integral_sub_inv_smul_of_differentiable_on
{R : ℝ} {c w : ℂ} {f : ℂ → E} (hw : w ∈ ball c R) (hd : differentiable_on ℂ f (closed_ball c R)) :
∮ z in C(c, R), (z - w)⁻¹ • f z = (2 * π * I : ℂ) • f w :=
circle_integral_sub_inv_smul_of_continuous_on_of_differentiable_on hw hd.continuous_on $
hd.mono $ ball_subset_closed_ball
/-- **Cauchy integral formula**: if `f : ℂ → ℂ` is continuous on a closed disc of radius `R` and is
complex differentiable at all but countably many points of its interior, then for any `w` in this
interior we have $\oint_{|z-c|=R}\frac{f(z)}{z-w}dz=2\pi i\,f(w)$.
-/
lemma circle_integral_div_sub_of_differentiable_on_off_countable {R : ℝ} {c w : ℂ} {s : set ℂ}
(hs : countable s) (hw : w ∈ ball c R) {f : ℂ → ℂ} (hc : continuous_on f (closed_ball c R))
(hd : ∀ z ∈ ball c R \ s, differentiable_at ℂ f z) :
∮ z in C(c, R), f z / (z - w) = 2 * π * I * f w :=
by simpa only [smul_eq_mul, div_eq_inv_mul]
using circle_integral_sub_inv_smul_of_differentiable_on_off_countable hs hw hc hd
/-- If `f : ℂ → E` is continuous on a closed ball of positive radius and is differentiable at all
but countably many points of the corresponding open ball, then it is analytic on the open ball with
coefficients of the power series given by Cauchy integral formulas. -/
lemma has_fpower_series_on_ball_of_differentiable_off_countable {R : ℝ≥0} {c : ℂ} {f : ℂ → E}
{s : set ℂ} (hs : countable s) (hc : continuous_on f (closed_ball c R))
(hd : ∀ z ∈ ball c R \ s, differentiable_at ℂ f z) (hR : 0 < R) :
has_fpower_series_on_ball f (cauchy_power_series f c R) c R :=
{ r_le := le_radius_cauchy_power_series _ _ _,
r_pos := ennreal.coe_pos.2 hR,
has_sum := λ w hw,
begin
have hw' : c + w ∈ ball c R,
by simpa only [add_mem_ball_iff_norm, ← coe_nnnorm, mem_emetric_ball_zero_iff,
nnreal.coe_lt_coe, ennreal.coe_lt_coe] using hw,
rw ← two_pi_I_inv_smul_circle_integral_sub_inv_smul_of_differentiable_on_off_countable hs
hw' hc hd,
exact (has_fpower_series_on_cauchy_integral
((hc.mono sphere_subset_closed_ball).circle_integrable R.2) hR).has_sum hw
end }
/-- If `f : ℂ → E` is continuous on a closed ball of positive radius and is complex differentiable
on its interior, then it is analytic on the open ball with coefficients of the power series given by
Cauchy integral formulas. -/
lemma has_fpower_series_on_ball_of_continuous_on_of_differentiable_on {R : ℝ≥0} {c : ℂ} {f : ℂ → E}
(hc : continuous_on f (closed_ball c R)) (hd : differentiable_on ℂ f (ball c R)) (hR : 0 < R) :
has_fpower_series_on_ball f (cauchy_power_series f c R) c R :=
has_fpower_series_on_ball_of_differentiable_off_countable countable_empty hc
(λ z hz, hd.differentiable_at $ is_open_ball.mem_nhds hz.1) hR
/-- If `f : ℂ → E` is complex differentiable on a closed disc of positive radius, then it is
analytic on the corresponding open disc, and the coefficients of the power series are given by
Cauchy integral formulas. See also
`complex.has_fpower_series_on_ball_of_differentiable_off_countable` for a version of this lemma with
weaker assumptions. -/
protected lemma _root_.differentiable_on.has_fpower_series_on_ball {R : ℝ≥0} {c : ℂ} {f : ℂ → E}
(hd : differentiable_on ℂ f (closed_ball c R)) (hR : 0 < R) :
has_fpower_series_on_ball f (cauchy_power_series f c R) c R :=
has_fpower_series_on_ball_of_continuous_on_of_differentiable_on hd.continuous_on
(hd.mono ball_subset_closed_ball) hR
/-- If `f : ℂ → E` is complex differentiable on some set `s`, then it is analytic at any point `z`
such that `s ∈ 𝓝 z` (equivalently, `z ∈ interior s`). -/
protected lemma _root_.differentiable_on.analytic_at {s : set ℂ} {f : ℂ → E} {z : ℂ}
(hd : differentiable_on ℂ f s) (hz : s ∈ 𝓝 z) : analytic_at ℂ f z :=
begin
rcases nhds_basis_closed_ball.mem_iff.1 hz with ⟨R, hR0, hRs⟩,
lift R to ℝ≥0 using hR0.le,
exact ((hd.mono hRs).has_fpower_series_on_ball hR0).analytic_at
end
/-- A complex differentiable function `f : ℂ → E` is analytic at every point. -/
protected lemma _root_.differentiable.analytic_at {f : ℂ → E} (hf : differentiable ℂ f) (z : ℂ) :
analytic_at ℂ f z :=
hf.differentiable_on.analytic_at univ_mem
end complex
|
4a2543069520a1c8b52908c47d94512a33cc36c0 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/category_theory/limits/filtered_colimit_commutes_finite_limit.lean | 4bded6371f99de116f0dd4f4d1c20a9db3ef8caf | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 13,442 | 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 category_theory.limits.colimit_limit
import category_theory.limits.shapes.finite_limits
/-!
# Filtered colimits commute with finite limits.
We show that for a functor `F : J × K ⥤ Type v`, when `J` is finite and `K` is filtered,
the universal morphism `colimit_limit_to_limit_colimit F` comparing the
colimit (over `K`) of the limits (over `J`) with the limit of the colimits is an isomorphism.
(In fact, to prove that it is injective only requires that `J` has finitely many objects.)
## References
* Borceux, Handbook of categorical algebra 1, Theorem 2.13.4
* [Stacks: Filtered colimits](https://stacks.math.columbia.edu/tag/002W)
-/
universes v u
open category_theory
open category_theory.category
open category_theory.limits.types
open category_theory.limits.types.filtered_colimit
namespace category_theory.limits
variables {J K : Type v} [small_category J] [small_category K]
variables (F : J × K ⥤ Type v)
open category_theory.prod
variables [is_filtered K]
section
/-!
Injectivity doesn't need that we have finitely many morphisms in `J`,
only that there are finitely many objects.
-/
variables [fintype J]
/--
This follows this proof from
* Borceux, Handbook of categorical algebra 1, Theorem 2.13.4
-/
lemma colimit_limit_to_limit_colimit_injective :
function.injective (colimit_limit_to_limit_colimit F) :=
begin
classical,
-- Suppose we have two terms `x y` in the colimit (over `K`) of the limits (over `J`),
-- and that these have the same image under `colimit_limit_to_limit_colimit F`.
intros x y h,
-- These elements of the colimit have representatives somewhere:
obtain ⟨kx, x, rfl⟩ := jointly_surjective' x,
obtain ⟨ky, y, rfl⟩ := jointly_surjective' y,
dsimp at x y,
-- Since the images of `x` and `y` are equal in a limit, they are equal componentwise
-- (indexed by `j : J`),
replace h := λ j, congr_arg (limit.π ((curry.obj F) ⋙ colim) j) h,
-- and they are equations in a filtered colimit,
-- so for each `j` we have some place `k j` to the right of both `kx` and `ky`
simp [colimit_eq_iff] at h,
let k := λ j, (h j).some,
let f : Π j, kx ⟶ k j := λ j, (h j).some_spec.some,
let g : Π j, ky ⟶ k j := λ j, (h j).some_spec.some_spec.some,
-- where the images of the components of the representatives become equal:
have w : Π j,
F.map ((𝟙 j, f j) : (j, kx) ⟶ (j, k j)) (limit.π ((curry.obj (swap K J ⋙ F)).obj kx) j x) =
F.map ((𝟙 j, g j) : (j, ky) ⟶ (j, k j)) (limit.π ((curry.obj (swap K J ⋙ F)).obj ky) j y) :=
λ j, (h j).some_spec.some_spec.some_spec,
-- We now use that `K` is filtered, picking some point to the right of all these
-- morphisms `f j` and `g j`.
let O : finset K := (finset.univ).image k ∪ {kx, ky},
have kxO : kx ∈ O := finset.mem_union.mpr (or.inr (by simp)),
have kyO : ky ∈ O := finset.mem_union.mpr (or.inr (by simp)),
have kjO : ∀ j, k j ∈ O := λ j, finset.mem_union.mpr (or.inl (by simp)),
let H : finset (Σ' (X Y : K) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) :=
(finset.univ).image (λ j : J, ⟨kx, k j, kxO,
finset.mem_union.mpr (or.inl (by simp)),
f j⟩) ∪
(finset.univ).image (λ j : J, ⟨ky, k j, kyO,
finset.mem_union.mpr (or.inl (by simp)),
g j⟩),
obtain ⟨S, T, W⟩ := is_filtered.sup_exists O H,
have fH :
∀ j, (⟨kx, k j, kxO, kjO j, f j⟩ : (Σ' (X Y : K) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y)) ∈ H :=
λ j, (finset.mem_union.mpr (or.inl
begin
simp only [true_and, finset.mem_univ, eq_self_iff_true, exists_prop_of_true,
finset.mem_image, heq_iff_eq],
refine ⟨j, rfl, _⟩,
simp only [heq_iff_eq],
exact ⟨rfl, rfl, rfl⟩,
end)),
have gH :
∀ j, (⟨ky, k j, kyO, kjO j, g j⟩ : (Σ' (X Y : K) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y)) ∈ H :=
λ j, (finset.mem_union.mpr (or.inr
begin
simp only [true_and, finset.mem_univ, eq_self_iff_true, exists_prop_of_true,
finset.mem_image, heq_iff_eq],
refine ⟨j, rfl, _⟩,
simp only [heq_iff_eq],
exact ⟨rfl, rfl, rfl⟩,
end)),
-- Our goal is now an equation between equivalence classes of representatives of a colimit,
-- and so it suffices to show those representative become equal somewhere, in particular at `S`.
apply colimit_sound' (T kxO) (T kyO),
-- We can check if two elements of a limit (in `Type`) are equal by comparing them componentwise.
ext,
-- Now it's just a calculation using `W` and `w`.
simp only [functor.comp_map, limit.map_π_apply, curry.obj_map_app, swap_map],
rw ←W _ _ (fH j),
rw ←W _ _ (gH j),
simp [w],
end
end
variables [fin_category J]
/--
This follows this proof from
* Borceux, Handbook of categorical algebra 1, Theorem 2.13.4
although with different names.
-/
lemma colimit_limit_to_limit_colimit_surjective :
function.surjective (colimit_limit_to_limit_colimit F) :=
begin
classical,
-- We begin with some element `x` in the limit (over J) over the colimits (over K),
intro x,
-- This consists of some coherent family of elements in the various colimits,
-- and so our first task is to pick representatives of these elements.
have z := λ j, jointly_surjective' (limit.π (curry.obj F ⋙ limits.colim) j x),
-- `k : J ⟶ K` records where the representative of the element in the `j`-th element of `x` lives
let k : J → K := λ j, (z j).some,
-- `y j : F.obj (j, k j)` is the representative
let y : Π j, F.obj (j, k j) := λ j, (z j).some_spec.some,
-- and we record that these representatives, when mapped back into the relevant colimits,
-- are actually the components of `x`.
have e : ∀ j,
colimit.ι ((curry.obj F).obj j) (k j) (y j) =
limit.π (curry.obj F ⋙ limits.colim) j x := λ j, (z j).some_spec.some_spec,
clear_value k y, -- A little tidying up of things we no longer need.
clear z,
-- As a first step, we use that `K` is filtered to pick some point `k' : K` above all the `k j`
let k' : K := is_filtered.sup (finset.univ.image k) ∅,
-- and name the morphisms as `g j : k j ⟶ k'`.
have g : Π j, k j ⟶ k' := λ j, is_filtered.to_sup (finset.univ.image k) ∅ (by simp),
clear_value k',
-- Recalling that the components of `x`, which are indexed by `j : J`, are "coherent",
-- in other words preserved by morphisms in the `J` direction,
-- we see that for any morphism `f : j ⟶ j'` in `J`,
-- the images of `y j` and `y j'`, when mapped to `F.obj (j', k')` respectively by
-- `(f, g j)` and `(𝟙 j', g j')`, both represent the same element in the colimit.
have w : ∀ {j j' : J} (f : j ⟶ j'),
colimit.ι ((curry.obj F).obj j') k' (F.map ((𝟙 j', g j') : (j', k j') ⟶ (j', k')) (y j')) =
colimit.ι ((curry.obj F).obj j') k' (F.map ((f, g j) : (j, k j) ⟶ (j', k')) (y j)),
{ intros j j' f,
have t : (f, g j) = (((f, 𝟙 (k j)) : (j, k j) ⟶ (j', k j)) ≫ (𝟙 j', g j) : (j, k j) ⟶ (j', k')),
{ simp only [id_comp, comp_id, prod_comp], },
erw [colimit.w_apply, t, functor_to_types.map_comp_apply, colimit.w_apply, e,
←limit.w_apply f, ←e],
simp, },
-- Because `K` is filtered, we can restate this as saying that
-- for each such `f`, there is some place to the right of `k'`
-- where these images of `y j` and `y j'` become equal.
simp_rw colimit_eq_iff at w,
-- We take a moment to restate `w` more conveniently.
let kf : Π {j j'} (f : j ⟶ j'), K := λ _ _ f, (w f).some,
let gf : Π {j j'} (f : j ⟶ j'), k' ⟶ kf f := λ _ _ f, (w f).some_spec.some,
let hf : Π {j j'} (f : j ⟶ j'), k' ⟶ kf f := λ _ _ f, (w f).some_spec.some_spec.some,
have wf : Π {j j'} (f : j ⟶ j'),
F.map ((𝟙 j', g j' ≫ gf f) : (j', k j') ⟶ (j', kf f)) (y j') =
F.map ((f, g j ≫ hf f) : (j, k j) ⟶ (j', kf f)) (y j) := λ j j' f,
begin
have q :
((curry.obj F).obj j').map (gf f) (F.map _ (y j')) =
((curry.obj F).obj j').map (hf f) (F.map _ (y j)) :=
(w f).some_spec.some_spec.some_spec,
dsimp at q,
simp_rw ←functor_to_types.map_comp_apply at q,
convert q; simp only [comp_id],
end,
clear_value kf gf hf, -- and clean up some things that are no longer needed.
clear w,
-- We're now ready to use the fact that `K` is filtered a second time,
-- picking some place to the right of all of
-- the morphisms `gf f : k' ⟶ kh f` and `hf f : k' ⟶ kf f`.
-- At this point we're relying on there being only finitely morphisms in `J`.
let O := finset.univ.bUnion (λ j, finset.univ.bUnion (λ j', finset.univ.image (@kf j j'))) ∪ {k'},
have kfO : ∀ {j j'} (f : j ⟶ j'), kf f ∈ O := λ j j' f, finset.mem_union.mpr (or.inl (
begin
rw [finset.mem_bUnion],
refine ⟨j, finset.mem_univ j, _⟩,
rw [finset.mem_bUnion],
refine ⟨j', finset.mem_univ j', _⟩,
rw [finset.mem_image],
refine ⟨f, finset.mem_univ _, _⟩,
refl,
end)),
have k'O : k' ∈ O := finset.mem_union.mpr (or.inr (finset.mem_singleton.mpr rfl)),
let H : finset (Σ' (X Y : K) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) :=
finset.univ.bUnion (λ j : J, finset.univ.bUnion (λ j' : J, finset.univ.bUnion (λ f : j ⟶ j',
{⟨k', kf f, k'O, kfO f, gf f⟩, ⟨k', kf f, k'O, kfO f, hf f⟩}))),
obtain ⟨k'', i', s'⟩ := is_filtered.sup_exists O H,
-- We then restate this slightly more conveniently, as a family of morphism `i f : kf f ⟶ k''`,
-- satisfying `gf f ≫ i f = hf f' ≫ i f'`.
let i : Π {j j'} (f : j ⟶ j'), kf f ⟶ k'' := λ j j' f, i' (kfO f),
have s : ∀ {j₁ j₂ j₃ j₄} (f : j₁ ⟶ j₂) (f' : j₃ ⟶ j₄), gf f ≫ i f = hf f' ≫ i f' :=
begin
intros,
rw [s', s'],
swap 2,
exact k'O,
swap 2,
{ rw [finset.mem_bUnion],
refine ⟨j₁, finset.mem_univ _, _⟩,
rw [finset.mem_bUnion],
refine ⟨j₂, finset.mem_univ _, _⟩,
rw [finset.mem_bUnion],
refine ⟨f, finset.mem_univ _, _⟩,
simp only [true_or, eq_self_iff_true, and_self, finset.mem_insert, heq_iff_eq], },
{ rw [finset.mem_bUnion],
refine ⟨j₃, finset.mem_univ _, _⟩,
rw [finset.mem_bUnion],
refine ⟨j₄, finset.mem_univ _, _⟩,
rw [finset.mem_bUnion],
refine ⟨f', finset.mem_univ _, _⟩,
simp only [eq_self_iff_true, or_true, and_self, finset.mem_insert, finset.mem_singleton,
heq_iff_eq], }
end,
clear_value i,
clear s' i' H kfO k'O O,
-- We're finally ready to construct the pre-image, and verify it really maps to `x`.
fsplit,
{ -- We construct the pre-image (which, recall is meant to be a point
-- in the colimit (over `K`) of the limits (over `J`)) via a representative at `k''`.
apply colimit.ι (curry.obj (swap K J ⋙ F) ⋙ limits.lim) k'' _,
dsimp,
-- This representative is meant to be an element of a limit,
-- so we need to construct a family of elements in `F.obj (j, k'')` for varying `j`,
-- then show that are coherent with respect to morphisms in the `j` direction.
ext, swap,
{ -- We construct the elements as the images of the `y j`.
exact λ j, F.map (⟨𝟙 j, g j ≫ gf (𝟙 j) ≫ i (𝟙 j)⟩ : (j, k j) ⟶ (j, k'')) (y j), },
{ -- After which it's just a calculation, using `s` and `wf`, to see they are coherent.
dsimp,
simp only [←functor_to_types.map_comp_apply, prod_comp, id_comp, comp_id],
calc F.map ((f, g j ≫ gf (𝟙 j) ≫ i (𝟙 j)) : (j, k j) ⟶ (j', k'')) (y j)
= F.map ((f, g j ≫ hf f ≫ i f) : (j, k j) ⟶ (j', k'')) (y j)
: by rw s (𝟙 j) f
... = F.map ((𝟙 j', i f) : (j', kf f) ⟶ (j', k''))
(F.map ((f, g j ≫ hf f) : (j, k j) ⟶ (j', kf f)) (y j))
: by rw [←functor_to_types.map_comp_apply, prod_comp, comp_id, assoc]
... = F.map ((𝟙 j', i f) : (j', kf f) ⟶ (j', k''))
(F.map ((𝟙 j', g j' ≫ gf f) : (j', k j') ⟶ (j', kf f)) (y j'))
: by rw ←wf f
... = F.map ((𝟙 j', g j' ≫ gf f ≫ i f) : (j', k j') ⟶ (j', k'')) (y j')
: by rw [←functor_to_types.map_comp_apply, prod_comp, id_comp, assoc]
... = F.map ((𝟙 j', g j' ≫ gf (𝟙 j') ≫ i (𝟙 j')) : (j', k j') ⟶ (j', k'')) (y j')
: by rw [s f (𝟙 j'), ←s (𝟙 j') (𝟙 j')], }, },
-- Finally we check that this maps to `x`.
{ -- We can do this componentwise:
apply limit_ext,
intro j,
-- and as each component is an equation in a colimit, we can verify it by
-- pointing out the morphism which carries one representative to the other:
simp only [←e, colimit_eq_iff, curry.obj_obj_map, limit.π_mk,
bifunctor.map_id_comp, id.def, types_comp_apply,
limits.ι_colimit_limit_to_limit_colimit_π_apply],
refine ⟨k'', 𝟙 k'', g j ≫ gf (𝟙 j) ≫ i (𝟙 j), _⟩,
simp only [bifunctor.map_id_comp, types_comp_apply, bifunctor.map_id, types_id_apply], },
end
instance colimit_limit_to_limit_colimit_is_iso :
is_iso (colimit_limit_to_limit_colimit F) :=
(is_iso_iff_bijective _).mpr
⟨colimit_limit_to_limit_colimit_injective F, colimit_limit_to_limit_colimit_surjective F⟩
end category_theory.limits
|
b1afe9c205123156381883779cd3afa42f539e7e | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/char_p/invertible.lean | 4b265c9f7f510cd5fdd1d1a79a2159e979092a51 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 2,285 | 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 algebra.invertible
import algebra.char_p.basic
/-!
# Invertibility of elements given a characteristic
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file includes some instances of `invertible` for specific numbers in
characteristic zero. Some more cases are given as a `def`, to be included only
when needed. To construct instances for concrete numbers,
`invertible_of_nonzero` is a useful definition.
-/
variables {K : Type*}
section field
variables [field K]
/-- A natural number `t` is invertible in a field `K` if the charactistic of `K` does not divide
`t`. -/
def invertible_of_ring_char_not_dvd
{t : ℕ} (not_dvd : ¬(ring_char K ∣ t)) : invertible (t : K) :=
invertible_of_nonzero (λ h, not_dvd ((ring_char.spec K t).mp h))
lemma not_ring_char_dvd_of_invertible {t : ℕ} [invertible (t : K)] :
¬(ring_char K ∣ t) :=
begin
rw [← ring_char.spec, ← ne.def],
exact nonzero_of_invertible (t : K)
end
/-- A natural number `t` is invertible in a field `K` of charactistic `p` if `p` does not divide
`t`. -/
def invertible_of_char_p_not_dvd {p : ℕ} [char_p K p]
{t : ℕ} (not_dvd : ¬(p ∣ t)) : invertible (t : K) :=
invertible_of_nonzero (λ h, not_dvd ((char_p.cast_eq_zero_iff K p t).mp h))
-- warning: this could potentially loop with `ne_zero.invertible` - if there is weird type-class
-- loops, watch out for that.
instance invertible_of_pos [char_zero K] (n : ℕ) [ne_zero n] : invertible (n : K) :=
invertible_of_nonzero $ ne_zero.out
end field
section division_ring
variables [division_ring K] [char_zero K]
instance invertible_succ (n : ℕ) : invertible (n.succ : K) :=
invertible_of_nonzero (nat.cast_ne_zero.mpr (nat.succ_ne_zero _))
/-!
A few `invertible n` instances for small numerals `n`. Feel free to add your own
number when you need its inverse.
-/
instance invertible_two : invertible (2 : K) :=
invertible_of_nonzero (by exact_mod_cast (dec_trivial : 2 ≠ 0))
instance invertible_three : invertible (3 : K) :=
invertible_of_nonzero (by exact_mod_cast (dec_trivial : 3 ≠ 0))
end division_ring
|
20cc90134c6915d162f32b55835054438bd32284 | 7571914d3f4d9677288f35ab1a53a2ad70a62bd7 | /library/init/meta/simp_tactic.lean | c01e7453532a7be095cefca2d996a5aadcdabfa0 | [
"Apache-2.0"
] | permissive | picrin/lean-1 | a395fed5287995f09a15a190bb24609919a0727f | b50597228b42a7eaa01bf8cb7a4fb1a98e7a8aab | refs/heads/master | 1,610,757,735,162 | 1,502,008,413,000 | 1,502,008,413,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 21,931 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.meta.tactic init.meta.attribute init.meta.constructor_tactic
import init.meta.relation_tactics init.meta.occurrences
import init.data.option.instances
open tactic
def simp.default_max_steps := 10000000
meta constant simp_lemmas : Type
meta constant simp_lemmas.mk : simp_lemmas
meta constant simp_lemmas.join : simp_lemmas → simp_lemmas → simp_lemmas
meta constant simp_lemmas.erase : simp_lemmas → list name → simp_lemmas
meta constant simp_lemmas.mk_default : tactic simp_lemmas
meta constant simp_lemmas.add : simp_lemmas → expr → tactic simp_lemmas
meta constant simp_lemmas.add_simp : simp_lemmas → name → tactic simp_lemmas
meta constant simp_lemmas.add_congr : simp_lemmas → name → tactic simp_lemmas
meta def simp_lemmas.append (s : simp_lemmas) (hs : list expr) : tactic simp_lemmas :=
hs.mfoldl simp_lemmas.add s
/-- `simp_lemmas.rewrite_core s e prove R` apply a simplification lemma from 's'
- 'e' is the expression to be "simplified"
- 'prove' is used to discharge proof obligations.
- 'r' is the equivalence relation being used (e.g., 'eq', 'iff')
Result (new_e, pr) is the new expression 'new_e' and a proof (pr : e R new_e) -/
meta constant simp_lemmas.rewrite (s : simp_lemmas) (e : expr)
(prove : tactic unit := failed) (r : name := `eq) (md := reducible)
: tactic (expr × expr)
/-- `simp_lemmas.drewrite s e` tries to rewrite 'e' using only refl lemmas in 's' -/
meta constant simp_lemmas.drewrite (s : simp_lemmas) (e : expr) (md := reducible) : tactic expr
meta constant is_valid_simp_lemma_cnst : name → tactic bool
meta constant is_valid_simp_lemma : expr → tactic bool
meta constant simp_lemmas.pp : simp_lemmas → tactic format
namespace tactic
meta def revert_and_transform (transform : expr → tactic expr) (h : expr) : tactic unit :=
do num_reverted : ℕ ← revert h,
t ← target,
match t with
| expr.pi n bi d b :=
do h_simp ← transform d,
unsafe_change $ expr.pi n bi h_simp b
| expr.elet n g e f :=
do h_simp ← transform g,
unsafe_change $ expr.elet n h_simp e f
| _ := fail "reverting hypothesis created neither a pi nor an elet expr (unreachable?)"
end,
intron num_reverted
/-- `get_eqn_lemmas_for deps d` returns the automatically generated equational lemmas for definition d.
If deps is tt, then lemmas for automatically generated auxiliary declarations used to define d are also included. -/
meta constant get_eqn_lemmas_for : bool → name → tactic (list name)
structure dsimp_config :=
(md := reducible)
(max_steps : nat := simp.default_max_steps)
(canonize_instances : bool := tt)
(single_pass : bool := ff)
(fail_if_unchanged := tt)
(eta := tt)
(zeta : bool := tt)
(beta : bool := tt)
(proj : bool := tt) -- reduce projections
(iota : bool := tt)
(unfold_reducible := ff) -- if tt, reducible definitions will be unfolded (delta-reduced)
(memoize := tt)
end tactic
/-- (Definitional) Simplify the given expression using *only* reflexivity equality lemmas from the given set of lemmas.
The resulting expression is definitionally equal to the input.
The list `u` contains defintions to be delta-reduced, and projections to be reduced.-/
meta constant simp_lemmas.dsimplify (s : simp_lemmas) (u : list name := []) (e : expr) (cfg : tactic.dsimp_config := {}) : tactic expr
namespace tactic
/- Remark: the configuration parameters `cfg.md` and `cfg.eta` are ignored by this tactic. -/
meta constant dsimplify_core
/- The user state type. -/
{α : Type}
/- Initial user data -/
(a : α)
/- (pre a e) is invoked before visiting the children of subterm 'e',
if it succeeds the result (new_a, new_e, flag) where
- 'new_a' is the new value for the user data
- 'new_e' is a new expression that must be definitionally equal to 'e',
- 'flag' if tt 'new_e' children should be visited, and 'post' invoked. -/
(pre : α → expr → tactic (α × expr × bool))
/- (post a e) is invoked after visiting the children of subterm 'e',
The output is similar to (pre a e), but the 'flag' indicates whether
the new expression should be revisited or not. -/
(post : α → expr → tactic (α × expr × bool))
(e : expr)
(cfg : dsimp_config := {})
: tactic (α × expr)
meta def dsimplify
(pre : expr → tactic (expr × bool))
(post : expr → tactic (expr × bool))
: expr → tactic expr :=
λ e, do (a, new_e) ← dsimplify_core ()
(λ u e, do r ← pre e, return (u, r))
(λ u e, do r ← post e, return (u, r)) e,
return new_e
meta def get_simp_lemmas_or_default : option simp_lemmas → tactic simp_lemmas
| none := simp_lemmas.mk_default
| (some s) := return s
meta def dsimp_target (s : option simp_lemmas := none) (u : list name := []) (cfg : dsimp_config := {}) : tactic unit :=
do s ← get_simp_lemmas_or_default s, t ← target, s.dsimplify u t cfg >>= unsafe_change
meta def dsimp_hyp (h : expr) (s : option simp_lemmas := none) (u : list name := []) (cfg : dsimp_config := {}) : tactic unit :=
do s ← get_simp_lemmas_or_default s, revert_and_transform (λ e, s.dsimplify u e cfg) h
/- Remark: we use transparency.instances by default to make sure that we
can unfold projections of type classes. Example:
(@has_add.add nat nat.has_add a b)
-/
/-- Tries to unfold `e` if it is a constant or a constant application.
Remark: this is not a recursive procedure. -/
meta constant dunfold_head (e : expr) (md := transparency.instances) : tactic expr
structure dunfold_config extends dsimp_config :=
(md := transparency.instances)
/- Remark: in principle, dunfold can be implemented on top of dsimp. We don't do it for
performance reasons. -/
meta constant dunfold (cs : list name) (e : expr) (cfg : dunfold_config := {}) : tactic expr
meta def dunfold_target (cs : list name) (cfg : dunfold_config := {}) : tactic unit :=
do t ← target, dunfold cs t cfg >>= unsafe_change
meta def dunfold_hyp (cs : list name) (h : expr) (cfg : dunfold_config := {}) : tactic unit :=
revert_and_transform (λ e, dunfold cs e cfg) h
structure delta_config :=
(max_steps := simp.default_max_steps)
(visit_instances := tt)
private meta def is_delta_target (e : expr) (cs : list name) : bool :=
cs.any (λ c,
if e.is_app_of c then tt /- Exact match -/
else let f := e.get_app_fn in
/- f is an auxiliary constant generated when compiling c -/
f.is_constant && f.const_name.is_internal && (f.const_name.get_prefix = c))
/-- Delta reduce the given constant names -/
meta def delta (cs : list name) (e : expr) (cfg : delta_config := {}) : tactic expr :=
let unfold (u : unit) (e : expr) : tactic (unit × expr × bool) := do
guard (is_delta_target e cs),
(expr.const f_name f_lvls) ← return e.get_app_fn,
env ← get_env,
decl ← env.get f_name,
new_f ← decl.instantiate_value_univ_params f_lvls,
new_e ← head_beta (expr.mk_app new_f e.get_app_args),
return (u, new_e, tt)
in do (c, new_e) ← dsimplify_core () (λ c e, failed) unfold e {max_steps := cfg.max_steps, canonize_instances := cfg.visit_instances},
return new_e
meta def delta_target (cs : list name) (cfg : delta_config := {}) : tactic unit :=
do t ← target, delta cs t cfg >>= unsafe_change
meta def delta_hyp (cs : list name) (h : expr) (cfg : delta_config := {}) :tactic unit :=
revert_and_transform (λ e, delta cs e cfg) h
structure unfold_proj_config extends dsimp_config :=
(md := transparency.instances)
/-- If `e` is a projection application, try to unfold it, otherwise fail. -/
meta constant unfold_proj (e : expr) (md := transparency.instances) : tactic expr
meta def unfold_projs (e : expr) (cfg : unfold_proj_config := {}) : tactic expr :=
let unfold (changed : bool) (e : expr) : tactic (bool × expr × bool) := do
new_e ← unfold_proj e cfg.md,
return (tt, new_e, tt)
in do (tt, new_e) ← dsimplify_core ff (λ c e, failed) unfold e cfg.to_dsimp_config | fail "no projections to unfold",
return new_e
meta def unfold_projs_target (cfg : unfold_proj_config := {}) : tactic unit :=
do t ← target, unfold_projs t cfg >>= unsafe_change
meta def unfold_projs_hyp (h : expr) (cfg : unfold_proj_config := {}) : tactic unit :=
revert_and_transform (λ e, unfold_projs e cfg) h
structure simp_config :=
(max_steps : nat := simp.default_max_steps)
(contextual : bool := ff)
(lift_eq : bool := tt)
(canonize_instances : bool := tt)
(canonize_proofs : bool := ff)
(use_axioms : bool := tt)
(zeta : bool := tt)
(beta : bool := tt)
(eta : bool := tt)
(proj : bool := tt) -- reduce projections
(iota : bool := tt)
(single_pass : bool := ff)
(fail_if_unchanged := tt)
(memoize := tt)
/--
`simplify s e cfg r prove` simplify `e` using `s` using bottom-up traversal.
`discharger` is a tactic for dischaging new subgoals created by the simplifier.
If it fails, the simplifier tries to discharge the subgoal by simplifying it to `true`.
The parameter `to_unfold` specifies definitions that should be delta-reduced,
and projection applications that should be unfolded.
-/
meta constant simplify (s : simp_lemmas) (to_unfold : list name := []) (e : expr) (cfg : simp_config := {}) (r : name := `eq)
(discharger : tactic unit := failed) : tactic (expr × expr)
meta def simp_target (s : simp_lemmas) (to_unfold : list name := []) (cfg : simp_config := {}) (discharger : tactic unit := failed) : tactic unit :=
do t ← target,
(new_t, pr) ← simplify s to_unfold t cfg `eq discharger,
replace_target new_t pr
meta def simp_hyp (s : simp_lemmas) (to_unfold : list name := []) (h : expr) (cfg : simp_config := {}) (discharger : tactic unit := failed) : tactic expr :=
do when (expr.is_local_constant h = ff) (fail "tactic simp_at failed, the given expression is not a hypothesis"),
htype ← infer_type h,
(h_new_type, pr) ← simplify s to_unfold htype cfg `eq discharger,
replace_hyp h h_new_type pr
meta constant ext_simplify_core
/- The user state type. -/
{α : Type}
/- Initial user data -/
(a : α)
(c : simp_config)
/- Congruence and simplification lemmas.
Remark: the simplification lemmas at not applied automatically like in the simplify tactic.
the caller must use them at pre/post. -/
(s : simp_lemmas)
/- Tactic for dischaging hypothesis in conditional rewriting rules.
The argument 'α' is the current user state. -/
(discharger : α → tactic α)
/- (pre a S r s p e) is invoked before visiting the children of subterm 'e',
'r' is the simplification relation being used, 's' is the updated set of lemmas if 'contextual' is tt,
'p' is the "parent" expression (if there is one).
if it succeeds the result is (new_a, new_e, new_pr, flag) where
- 'new_a' is the new value for the user data
- 'new_e' is a new expression s.t. 'e r new_e'
- 'new_pr' is a proof for 'e r new_e', If it is none, the proof is assumed to be by reflexivity
- 'flag' if tt 'new_e' children should be visited, and 'post' invoked. -/
(pre : α → simp_lemmas → name → option expr → expr → tactic (α × expr × option expr × bool))
/- (post a r s p e) is invoked after visiting the children of subterm 'e',
The output is similar to (pre a r s p e), but the 'flag' indicates whether
the new expression should be revisited or not. -/
(post : α → simp_lemmas → name → option expr → expr → tactic (α × expr × option expr × bool))
/- simplification relation -/
(r : name) :
expr → tactic (α × expr × expr)
private meta def is_equation : expr → bool
| (expr.pi n bi d b) := is_equation b
| e := match (expr.is_eq e) with (some a) := tt | none := ff end
private meta def collect_simps : list expr → tactic (list expr)
| [] := return []
| (h :: hs) := do
result ← collect_simps hs,
htype ← infer_type h >>= whnf,
if is_equation htype
then return (h :: result)
else do
pr ← is_prop htype,
return $ if pr then (h :: result) else result
meta def collect_ctx_simps : tactic (list expr) :=
local_context >>= collect_simps
section simp_intros
meta def intro1_aux : bool → list name → tactic expr
| ff _ := intro1
| tt (n::ns) := intro n
| _ _ := failed
structure simp_intros_config extends simp_config :=
(use_hyps := ff)
meta def simp_intros_aux (cfg : simp_config) (use_hyps : bool) (to_unfold : list name) : simp_lemmas → bool → list name → tactic simp_lemmas
| S tt [] := try (simp_target S to_unfold cfg) >> return S
| S use_ns ns := do
t ← target,
if t.is_napp_of `not 1 then
intro1_aux use_ns ns >> simp_intros_aux S use_ns ns.tail
else if t.is_arrow then
do {
d ← return t.binding_domain,
(new_d, h_d_eq_new_d) ← simplify S to_unfold d cfg,
h_d ← intro1_aux use_ns ns,
h_new_d ← mk_eq_mp h_d_eq_new_d h_d,
assertv_core h_d.local_pp_name new_d h_new_d,
clear h_d,
h_new ← intro1,
new_S ← if use_hyps then mcond (is_prop new_d) (S.add h_new) (return S)
else return S,
simp_intros_aux new_S use_ns ns.tail
}
<|>
-- failed to simplify... we just introduce and continue
(intro1_aux use_ns ns >> simp_intros_aux S use_ns ns.tail)
else if t.is_pi || t.is_let then
intro1_aux use_ns ns >> simp_intros_aux S use_ns ns.tail
else do
new_t ← whnf t reducible,
if new_t.is_pi then unsafe_change new_t >> simp_intros_aux S use_ns ns
else
try (simp_target S to_unfold cfg) >>
mcond (expr.is_pi <$> target)
(simp_intros_aux S use_ns ns)
(if use_ns ∧ ¬ns.empty then failed else return S)
meta def simp_intros (s : simp_lemmas) (to_unfold : list name := []) (ids : list name := []) (cfg : simp_intros_config := {}) : tactic unit :=
step $ simp_intros_aux cfg.to_simp_config cfg.use_hyps to_unfold s (bnot ids.empty) ids
end simp_intros
meta def mk_eq_simp_ext (simp_ext : expr → tactic (expr × expr)) : tactic unit :=
do (lhs, rhs) ← target >>= match_eq,
(new_rhs, heq) ← simp_ext lhs,
unify rhs new_rhs,
exact heq
/- Simp attribute support -/
meta def to_simp_lemmas : simp_lemmas → list name → tactic simp_lemmas
| S [] := return S
| S (n::ns) := do S' ← S.add_simp n, to_simp_lemmas S' ns
meta def mk_simp_attr (attr_name : name) : command :=
do let t := `(caching_user_attribute simp_lemmas),
let v := `({name := attr_name,
descr := "simplifier attribute",
mk_cache := λ ns, do {tactic.to_simp_lemmas simp_lemmas.mk ns},
dependencies := [`reducibility] } : caching_user_attribute simp_lemmas),
add_decl (declaration.defn attr_name [] t v reducibility_hints.abbrev ff),
attribute.register attr_name
meta def get_user_simp_lemmas (attr_name : name) : tactic simp_lemmas :=
if attr_name = `default then simp_lemmas.mk_default
else do
cnst ← return (expr.const attr_name []),
attr ← eval_expr (caching_user_attribute simp_lemmas) cnst,
caching_user_attribute.get_cache attr
meta def join_user_simp_lemmas_core : simp_lemmas → list name → tactic simp_lemmas
| S [] := return S
| S (attr_name::R) := do S' ← get_user_simp_lemmas attr_name, join_user_simp_lemmas_core (S.join S') R
meta def join_user_simp_lemmas (no_dflt : bool) (attrs : list name) : tactic simp_lemmas :=
if no_dflt then
join_user_simp_lemmas_core simp_lemmas.mk attrs
else do
s ← simp_lemmas.mk_default,
join_user_simp_lemmas_core s attrs
/-- Normalize numerical expression, returns a pair (n, pr) where n is the resultant numeral,
and pr is a proof that the input argument is equal to n. -/
meta constant norm_num : expr → tactic (expr × expr)
meta def simplify_top_down {α} (a : α) (pre : α → expr → tactic (α × expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (α × expr × expr) :=
ext_simplify_core a cfg simp_lemmas.mk (λ _, failed)
(λ a _ _ _ e, do (new_a, new_e, pr) ← pre a e, guard (¬ new_e =ₐ e), return (new_a, new_e, some pr, tt))
(λ _ _ _ _ _, failed)
`eq e
meta def simp_top_down (pre : expr → tactic (expr × expr)) (cfg : simp_config := {}) : tactic unit :=
do t ← target,
(_, new_target, pr) ← simplify_top_down () (λ _ e, do (new_e, pr) ← pre e, return ((), new_e, pr)) t cfg,
replace_target new_target pr
meta def simplify_bottom_up {α} (a : α) (post : α → expr → tactic (α × expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (α × expr × expr) :=
ext_simplify_core a cfg simp_lemmas.mk (λ _, failed)
(λ _ _ _ _ _, failed)
(λ a _ _ _ e, do (new_a, new_e, pr) ← post a e, guard (¬ new_e =ₐ e), return (new_a, new_e, some pr, tt))
`eq e
meta def simp_bottom_up (post : expr → tactic (expr × expr)) (cfg : simp_config := {}) : tactic unit :=
do t ← target,
(_, new_target, pr) ← simplify_bottom_up () (λ _ e, do (new_e, pr) ← post e, return ((), new_e, pr)) t cfg,
replace_target new_target pr
private meta def remove_deps (s : name_set) (h : expr) : name_set :=
if s.empty then s
else h.fold s (λ e o s, if e.is_local_constant then s.erase e.local_uniq_name else s)
/- Return the list of hypothesis that are propositions and do not have
forward dependencies. -/
meta def non_dep_prop_hyps : tactic (list expr) :=
do
ctx ← local_context,
s ← ctx.mfoldl (λ s h, do
h_type ← infer_type h,
let s := remove_deps s h_type,
h_val ← head_zeta h,
let s := if h_val =ₐ h then s else remove_deps s h_val,
mcond (is_prop h_type)
(return $ s.insert h.local_uniq_name)
(return s)) mk_name_set,
t ← target,
let s := remove_deps s t,
return $ ctx.filter (λ h, s.contains h.local_uniq_name)
section simp_all
meta structure simp_all_entry :=
(h : expr) -- hypothesis
(new_type : expr) -- new type
(pr : option expr) -- proof that type of h is equal to new_type
(s : simp_lemmas) -- simplification lemmas for simplifying new_type
private meta def update_simp_lemmas (es : list simp_all_entry) (h : expr) : tactic (list simp_all_entry) :=
es.mmap $ λ e, do new_s ← e.s.add h, return {e with s := new_s}
/- Helper tactic for `init`.
Remark: the following tactic is quadratic on the length of list expr (the list of non dependent propositions).
We can make it more efficient as soon as we have an efficient simp_lemmas.erase. -/
private meta def init_aux : list expr → simp_lemmas → list simp_all_entry → tactic (simp_lemmas × list simp_all_entry)
| [] s r := return (s, r)
| (h::hs) s r := do
new_r ← update_simp_lemmas r h,
new_s ← s.add h,
h_type ← infer_type h,
init_aux hs new_s (⟨h, h_type, none, s⟩::new_r)
private meta def init (s : simp_lemmas) (hs : list expr) : tactic (simp_lemmas × list simp_all_entry) :=
init_aux hs s []
private meta def add_new_hyps (es : list simp_all_entry) : tactic unit :=
es.mmap' $ λ e,
match e.pr with
| none := return ()
| some pr :=
assert e.h.local_pp_name e.new_type >>
mk_eq_mp pr e.h >>= exact
end
private meta def clear_old_hyps (es : list simp_all_entry) : tactic unit :=
es.mmap' $ λ e, when (e.pr ≠ none) (try (clear e.h))
private meta def join_pr : option expr → expr → tactic expr
| none pr₂ := return pr₂
| (some pr₁) pr₂ := mk_eq_trans pr₁ pr₂
private meta def loop (cfg : simp_config) (discharger : tactic unit) (to_unfold : list name)
: list simp_all_entry → list simp_all_entry → simp_lemmas → bool → tactic unit
| [] r s m :=
if m then loop r [] s ff
else do
add_new_hyps r,
target_changed ← (simp_target s to_unfold cfg discharger >> return tt) <|> return ff,
guard (cfg.fail_if_unchanged = ff ∨ target_changed ∨ r.any (λ e, e.pr ≠ none)) <|> fail "simp_all tactic failed to simplify",
clear_old_hyps r
| (e::es) r s m := do
let ⟨h, h_type, h_pr, s'⟩ := e,
(new_h_type, new_pr) ← simplify s' to_unfold h_type {cfg with fail_if_unchanged := ff} `eq discharger,
if h_type =ₐ new_h_type then loop es (e::r) s m
else do
new_pr ← join_pr h_pr new_pr,
new_fact_pr ← mk_eq_mp new_pr h,
if new_h_type = `(false) then do
tgt ← target,
to_expr ``(@false.rec %%tgt %%new_fact_pr) >>= exact
else do
h0_type ← infer_type h,
let new_fact_pr := mk_id_locked_proof new_h_type new_fact_pr,
new_es ← update_simp_lemmas es new_fact_pr,
new_r ← update_simp_lemmas r new_fact_pr,
let new_r := {e with new_type := new_h_type, pr := new_pr} :: new_r,
new_s ← s.add new_fact_pr,
loop new_es new_r new_s tt
meta def simp_all (s : simp_lemmas) (to_unfold : list name) (cfg : simp_config := {}) (discharger : tactic unit := failed) : tactic unit :=
do hs ← non_dep_prop_hyps,
(s, es) ← init s hs,
loop cfg discharger to_unfold es [] s ff
end simp_all
/- debugging support for algebraic normalizer -/
meta constant trace_algebra_info : expr → tactic unit
end tactic
export tactic (mk_simp_attr)
|
884f71af63696603ace9ec39ed51960f773b9a37 | 5d166a16ae129621cb54ca9dde86c275d7d2b483 | /tests/lean/set_attr1.lean | b5848f773e549755cdbe8e17f4cfd1c2e1899b1f | [
"Apache-2.0"
] | permissive | jcarlson23/lean | b00098763291397e0ac76b37a2dd96bc013bd247 | 8de88701247f54d325edd46c0eed57aeacb64baf | refs/heads/master | 1,611,571,813,719 | 1,497,020,963,000 | 1,497,021,515,000 | 93,882,536 | 1 | 0 | null | 1,497,029,896,000 | 1,497,029,896,000 | null | UTF-8 | Lean | false | false | 389 | lean | open tactic
constant f : nat → nat
constant foo : ∀ n, f n = n + 1
constant addz : ∀ n, n + 0 = n
definition ex1 (n : nat) : f n + 0 = n + 1 :=
by do
set_basic_attribute `simp `foo ff,
set_basic_attribute `simp `addz ff,
simp
definition ex2 (n : nat) : f n + 0 = n + 1 :=
by do
unset_attribute `simp `foo,
simp -- should fail since we remove [simp] attribute from `foo`
|
bda1c056cd4138d13a209c1431791bdb6a08c652 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /stage0/src/Init/Lean/Elab/BuiltinNotation.lean | 7508912b033211d826451aa798ee8d90acea6c75 | [
"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 | 11,994 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Lean.Elab.Term
import Init.Lean.Elab.Quotation
import Init.Lean.Elab.SyntheticMVars
namespace Lean
namespace Elab
namespace Term
@[builtinMacro Lean.Parser.Term.dollar] def expandDollar : Macro :=
fun stx => match_syntax stx with
| `($f $args* $ $a) => let args := args.push a; `($f $args*)
| `($f $ $a) => `($f $a)
| _ => Macro.throwUnsupported
@[builtinMacro Lean.Parser.Term.dollarProj] def expandDollarProj : Macro :=
fun stx => match_syntax stx with
| `($term $.$field) => `($(term).$field)
| _ => Macro.throwUnsupported
@[builtinMacro Lean.Parser.Term.if] def expandIf : Macro :=
fun stx => match_syntax stx with
| `(if $h : $cond then $t else $e) => `(dite $cond (fun $h:ident => $t) (fun $h:ident => $e))
| `(if $cond then $t else $e) => `(ite $cond $t $e)
| _ => Macro.throwUnsupported
@[builtinMacro Lean.Parser.Term.subtype] def expandSubtype : Macro :=
fun stx => match_syntax stx with
| `({ $x : $type // $p }) => `(Subtype (fun ($x:ident : $type) => $p))
| `({ $x // $p }) => `(Subtype (fun ($x:ident : _) => $p))
| _ => Macro.throwUnsupported
@[builtinTermElab anonymousCtor] def elabAnonymousCtor : TermElab :=
fun stx expectedType? => match_syntax stx with
| `(⟨$args*⟩) => do
let ref := stx;
tryPostponeIfNoneOrMVar expectedType?;
match expectedType? with
| some expectedType => do
expectedType ← instantiateMVars ref expectedType;
let expectedType := expectedType.consumeMData;
match expectedType.getAppFn with
| Expr.const constName _ _ => do
env ← getEnv;
match env.find? constName with
| some (ConstantInfo.inductInfo val) =>
match val.ctors with
| [ctor] => do
stx ← `($(mkCTermIdFrom ref ctor) $(args.getSepElems)*);
withMacroExpansion ref stx $ elabTerm stx expectedType?
| _ => throwError ref ("invalid constructor ⟨...⟩, '" ++ constName ++ "' must have only one constructor")
| _ => throwError ref ("invalid constructor ⟨...⟩, '" ++ constName ++ "' is not an inductive type")
| _ => throwError ref ("invalid constructor ⟨...⟩, expected type is not an inductive type " ++ indentExpr expectedType)
| none => throwError ref "invalid constructor ⟨...⟩, expected type must be known"
| _ => throwUnsupportedSyntax
@[builtinMacro Lean.Parser.Term.show] def expandShow : Macro :=
fun stx => match_syntax stx with
| `(show $type from $val) => let thisId := mkIdentFrom stx `this; `(let! $thisId : $type := $val; $thisId)
| _ => Macro.throwUnsupported
@[builtinMacro Lean.Parser.Term.have] def expandHave : Macro :=
fun stx => match_syntax stx with
| `(have $type from $val; $body) => let thisId := mkIdentFrom stx `this; `(let! $thisId : $type := $val; $body)
| `(have $type := $val; $body) => let thisId := mkIdentFrom stx `this; `(let! $thisId : $type := $val; $body)
| `(have $x : $type from $val; $body) => `(let! $x:ident : $type := $val; $body)
| `(have $x : $type := $val; $body) => `(let! $x:ident : $type := $val; $body)
| _ => Macro.throwUnsupported
@[builtinMacro Lean.Parser.Term.where] def expandWhere : Macro :=
fun stx => match_syntax stx with
| `($body where $decls:letDecl*) => do
let decls := decls.getEvenElems;
decls.foldrM
(fun decl body => `(let $decl:letDecl; $body))
body
| _ => Macro.throwUnsupported
@[builtinTermElab «parser!»] def elabParserMacro : TermElab :=
adaptExpander $ fun stx => match_syntax stx with
| `(parser! $e) => do
some declName ← getDeclName?
| throwError stx "invalid `parser!` macro, it must be used in definitions";
match extractMacroScopes declName with
| { name := Name.str _ s _, scopes := scps, .. } => do
let kind := quote declName;
let s := quote s;
p ← `(Lean.Parser.leadingNode $kind $e);
if scps == [] then
-- TODO simplify the following quotation as soon as we have coercions
`(HasOrelse.orelse (Lean.Parser.mkAntiquot $s (some $kind)) $p)
else
-- if the parser decl is hidden by hygiene, it doesn't make sense to provide an antiquotation kind
`(HasOrelse.orelse (Lean.Parser.mkAntiquot $s none) $p)
| _ => throwError stx "invalid `parser!` macro, unexpected declaration name"
| _ => throwUnsupportedSyntax
@[builtinTermElab «tparser!»] def elabTParserMacro : TermElab :=
adaptExpander $ fun stx => match_syntax stx with
| `(tparser! $e) => do
declName? ← getDeclName?;
match declName? with
| some declName => let kind := quote declName; `(Lean.Parser.trailingNode $kind $e)
| none => throwError stx "invalid `tparser!` macro, it must be used in definitions"
| _ => throwUnsupportedSyntax
private def mkNativeReflAuxDecl (ref : Syntax) (type val : Expr) : TermElabM Name := do
auxName ← mkAuxName ref `_nativeRefl;
let decl := Declaration.defnDecl {
name := auxName, lparams := [], type := type, value := val,
hints := ReducibilityHints.abbrev,
isUnsafe := false };
addDecl ref decl;
compileDecl ref decl;
pure auxName
private def elabClosedTerm (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do
e ← elabTermAndSynthesize stx expectedType?;
when e.hasMVar $
throwError stx ("invalid macro application, term contains metavariables" ++ indentExpr e);
when e.hasFVar $
throwError stx ("invalid macro application, term contains free variables" ++ indentExpr e);
pure e
@[builtinTermElab «nativeRefl»] def elabNativeRefl : TermElab :=
fun stx _ => do
let arg := stx.getArg 1;
e ← elabClosedTerm arg none;
type ← inferType stx e;
type ← whnf stx type;
unless (type.isConstOf `Bool || type.isConstOf `Nat) $
throwError stx ("invalid `nativeRefl!` macro application, term must have type `Nat` or `Bool`" ++ indentExpr type);
auxDeclName ← mkNativeReflAuxDecl stx type e;
let isBool := type.isConstOf `Bool;
let reduceValFn := if isBool then `Lean.reduceBool else `Lean.reduceNat;
let reduceThm := if isBool then `Lean.ofReduceBool else `Lean.ofReduceNat;
let aux := Lean.mkConst auxDeclName;
let reduceVal := mkApp (Lean.mkConst reduceValFn) aux;
val? ← liftMetaM stx $ Meta.reduceNative? reduceVal;
match val? with
| none => throwError stx ("failed to reduce term at `nativeRefl!` macro application" ++ indentExpr e)
| some val => do
rflPrf ← liftMetaM stx $ Meta.mkEqRefl val;
let r := mkApp3 (Lean.mkConst reduceThm) aux val rflPrf;
eq ← liftMetaM stx $ Meta.mkEq e val;
mkExpectedTypeHint stx r eq
private def getPropToDecide (ref : Syntax) (arg : Syntax) (expectedType? : Option Expr) : TermElabM Expr :=
if arg.isOfKind `Lean.Parser.Term.hole then do
tryPostponeIfNoneOrMVar expectedType?;
match expectedType? with
| none => throwError ref "invalid macro, expected type is not available"
| some expectedType => do
expectedType ← instantiateMVars ref expectedType;
when (expectedType.hasFVar || expectedType.hasMVar) $
throwError ref ("expected type must not contain free or meta variables" ++ indentExpr expectedType);
pure expectedType
else
let prop := mkSort levelZero;
elabClosedTerm arg prop
@[builtinTermElab «nativeDecide»] def elabNativeDecide : TermElab :=
fun stx expectedType? => do
let arg := stx.getArg 1;
p ← getPropToDecide stx arg expectedType?;
d ← mkAppM stx `Decidable.decide #[p];
auxDeclName ← mkNativeReflAuxDecl stx (Lean.mkConst `Bool) d;
rflPrf ← liftMetaM stx $ Meta.mkEqRefl (toExpr true);
let r := mkApp3 (Lean.mkConst `Lean.ofReduceBool) (Lean.mkConst auxDeclName) (toExpr true) rflPrf;
mkExpectedTypeHint stx r p
@[builtinTermElab Lean.Parser.Term.decide] def elabDecide : TermElab :=
fun stx expectedType? => do
let arg := stx.getArg 1;
p ← getPropToDecide stx arg expectedType?;
d ← mkAppM stx `Decidable.decide #[p];
d ← instantiateMVars stx d;
let s := d.appArg!; -- get instance from `d`
rflPrf ← liftMetaM stx $ Meta.mkEqRefl (toExpr true);
pure $ mkApp3 (Lean.mkConst `ofDecideEqTrue) p s rflPrf
def elabInfix (f : Syntax) : Macro :=
fun stx => do
-- term `op` term
let a := stx.getArg 0;
let b := stx.getArg 2;
pure (mkAppStx f #[a, b])
def elabInfixOp (op : Name) : Macro :=
fun stx => elabInfix (mkCTermIdFrom (stx.getArg 1) op) stx
@[builtinMacro Lean.Parser.Term.prod] def elabProd : Macro := elabInfixOp `Prod
@[builtinMacro Lean.Parser.Term.fcomp] def ElabFComp : Macro := elabInfixOp `Function.comp
@[builtinMacro Lean.Parser.Term.add] def elabAdd : Macro := elabInfixOp `HasAdd.add
@[builtinMacro Lean.Parser.Term.sub] def elabSub : Macro := elabInfixOp `HasSub.sub
@[builtinMacro Lean.Parser.Term.mul] def elabMul : Macro := elabInfixOp `HasMul.mul
@[builtinMacro Lean.Parser.Term.div] def elabDiv : Macro := elabInfixOp `HasDiv.div
@[builtinMacro Lean.Parser.Term.mod] def elabMod : Macro := elabInfixOp `HasMod.mod
@[builtinMacro Lean.Parser.Term.modN] def elabModN : Macro := elabInfixOp `HasModN.modn
@[builtinMacro Lean.Parser.Term.pow] def elabPow : Macro := elabInfixOp `HasPow.pow
@[builtinMacro Lean.Parser.Term.le] def elabLE : Macro := elabInfixOp `HasLessEq.LessEq
@[builtinMacro Lean.Parser.Term.ge] def elabGE : Macro := elabInfixOp `GreaterEq
@[builtinMacro Lean.Parser.Term.lt] def elabLT : Macro := elabInfixOp `HasLess.Less
@[builtinMacro Lean.Parser.Term.gt] def elabGT : Macro := elabInfixOp `Greater
@[builtinMacro Lean.Parser.Term.eq] def elabEq : Macro := elabInfixOp `Eq
@[builtinMacro Lean.Parser.Term.ne] def elabNe : Macro := elabInfixOp `Ne
@[builtinMacro Lean.Parser.Term.beq] def elabBEq : Macro := elabInfixOp `HasBeq.beq
@[builtinMacro Lean.Parser.Term.bne] def elabBNe : Macro := elabInfixOp `bne
@[builtinMacro Lean.Parser.Term.heq] def elabHEq : Macro := elabInfixOp `HEq
@[builtinMacro Lean.Parser.Term.equiv] def elabEquiv : Macro := elabInfixOp `HasEquiv.Equiv
@[builtinMacro Lean.Parser.Term.and] def elabAnd : Macro := elabInfixOp `And
@[builtinMacro Lean.Parser.Term.or] def elabOr : Macro := elabInfixOp `Or
@[builtinMacro Lean.Parser.Term.iff] def elabIff : Macro := elabInfixOp `Iff
@[builtinMacro Lean.Parser.Term.band] def elabBAnd : Macro := elabInfixOp `and
@[builtinMacro Lean.Parser.Term.bor] def elabBOr : Macro := elabInfixOp `or
@[builtinMacro Lean.Parser.Term.append] def elabAppend : Macro := elabInfixOp `HasAppend.append
@[builtinMacro Lean.Parser.Term.cons] def elabCons : Macro := elabInfixOp `List.cons
@[builtinMacro Lean.Parser.Term.andthen] def elabAndThen : Macro := elabInfixOp `HasAndthen.andthen
@[builtinMacro Lean.Parser.Term.bindOp] def elabBind : Macro := elabInfixOp `HasBind.bind
@[builtinMacro Lean.Parser.Term.seq] def elabseq : Macro := elabInfixOp `HasSeq.seq
@[builtinMacro Lean.Parser.Term.seqLeft] def elabseqLeft : Macro := elabInfixOp `HasSeqLeft.seqLeft
@[builtinMacro Lean.Parser.Term.seqRight] def elabseqRight : Macro := elabInfixOp `HasSeqRight.seqRight
@[builtinMacro Lean.Parser.Term.map] def elabMap : Macro := elabInfixOp `Functor.map
@[builtinMacro Lean.Parser.Term.mapRev] def elabMapRev : Macro := elabInfixOp `Functor.mapRev
@[builtinMacro Lean.Parser.Term.mapConst] def elabMapConst : Macro := elabInfixOp `Functor.mapConst
@[builtinMacro Lean.Parser.Term.mapConstRev] def elabMapConstRev : Macro := elabInfixOp `Functor.mapConstRev
@[builtinMacro Lean.Parser.Term.orelse] def elabOrElse : Macro := elabInfixOp `HasOrelse.orelse
@[builtinMacro Lean.Parser.Term.orM] def elabOrM : Macro := elabInfixOp `orM
@[builtinMacro Lean.Parser.Term.andM] def elabAndM : Macro := elabInfixOp `andM
/-
TODO
@[builtinTermElab] def elabsubst : TermElab := elabInfixOp infixR " ▸ " 75
-/
end Term
end Elab
end Lean
|
7c838a82336728b952b060a9db692c19e5b6ad4d | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/data/nat/sqrt.lean | 6b2d5882a38f5e1f0a83f1ce19b51a7effc991f6 | [
"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 | 6,962 | 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.nat.basic algebra.ordered_group algebra.ring tactic.alias
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] },
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] },
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, 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 [pow_succ, mul_comm, mul_assoc] },
{ rw [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 [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
|
1efab3367dcee4d91bcdc0a6479cb27626280d71 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/list/basic.lean | b412966c2d3dc490ce168fb8145f8b5c27eb695c | [] | 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 | 152,539 | lean | /-
Copyright (c) 2014 Parikshit Khanna. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.order_functions
import Mathlib.control.monad.basic
import Mathlib.data.nat.choose.basic
import Mathlib.order.rel_classes
import Mathlib.PostPort
universes u v w u_1 u_2 u_3
namespace Mathlib
/-!
# Basic properties of lists
-/
namespace list
protected instance nil.is_left_id {α : Type u} : is_left_id (List α) append [] :=
is_left_id.mk nil_append
protected instance nil.is_right_id {α : Type u} : is_right_id (List α) append [] :=
is_right_id.mk append_nil
protected instance has_append.append.is_associative {α : Type u} : is_associative (List α) append :=
is_associative.mk append_assoc
theorem cons_ne_nil {α : Type u} (a : α) (l : List α) : a :: l ≠ [] :=
fun (ᾰ : a :: l = []) => eq.dcases_on ᾰ (fun (H_1 : [] = a :: l) => list.no_confusion H_1) (Eq.refl []) (HEq.refl ᾰ)
theorem cons_ne_self {α : Type u} (a : α) (l : List α) : a :: l ≠ l :=
mt (congr_arg length) (nat.succ_ne_self (length l))
theorem head_eq_of_cons_eq {α : Type u} {h₁ : α} {h₂ : α} {t₁ : List α} {t₂ : List α} : h₁ :: t₁ = h₂ :: t₂ → h₁ = h₂ :=
fun (Peq : h₁ :: t₁ = h₂ :: t₂) => list.no_confusion Peq fun (Pheq : h₁ = h₂) (Pteq : t₁ = t₂) => Pheq
theorem tail_eq_of_cons_eq {α : Type u} {h₁ : α} {h₂ : α} {t₁ : List α} {t₂ : List α} : h₁ :: t₁ = h₂ :: t₂ → t₁ = t₂ :=
fun (Peq : h₁ :: t₁ = h₂ :: t₂) => list.no_confusion Peq fun (Pheq : h₁ = h₂) (Pteq : t₁ = t₂) => Pteq
@[simp] theorem cons_injective {α : Type u} {a : α} : function.injective (List.cons a) :=
fun (l₁ l₂ : List α) (Pe : a :: l₁ = a :: l₂) => tail_eq_of_cons_eq Pe
theorem cons_inj {α : Type u} (a : α) {l : List α} {l' : List α} : a :: l = a :: l' ↔ l = l' :=
function.injective.eq_iff cons_injective
theorem exists_cons_of_ne_nil {α : Type u} {l : List α} (h : l ≠ []) : ∃ (b : α), ∃ (L : List α), l = b :: L := sorry
/-! ### mem -/
theorem mem_singleton_self {α : Type u} (a : α) : a ∈ [a] :=
mem_cons_self a []
theorem eq_of_mem_singleton {α : Type u} {a : α} {b : α} : a ∈ [b] → a = b :=
fun (this : a ∈ [b]) =>
or.elim (eq_or_mem_of_mem_cons this) (fun (this : a = b) => this) fun (this : a ∈ []) => absurd this (not_mem_nil a)
@[simp] theorem mem_singleton {α : Type u} {a : α} {b : α} : a ∈ [b] ↔ a = b :=
{ mp := eq_of_mem_singleton, mpr := Or.inl }
theorem mem_of_mem_cons_of_mem {α : Type u} {a : α} {b : α} {l : List α} : a ∈ b :: l → b ∈ l → a ∈ l := sorry
theorem eq_or_ne_mem_of_mem {α : Type u} {a : α} {b : α} {l : List α} (h : a ∈ b :: l) : a = b ∨ a ≠ b ∧ a ∈ l :=
classical.by_cases Or.inl
fun (this : a ≠ b) => or.elim h Or.inl fun (h : list.mem a l) => Or.inr { left := this, right := h }
theorem not_mem_append {α : Type u} {a : α} {s : List α} {t : List α} (h₁ : ¬a ∈ s) (h₂ : ¬a ∈ t) : ¬a ∈ s ++ t :=
mt (iff.mp mem_append) (iff.mpr not_or_distrib { left := h₁, right := h₂ })
theorem ne_nil_of_mem {α : Type u} {a : α} {l : List α} (h : a ∈ l) : l ≠ [] :=
id fun (e : l = []) => false.dcases_on (fun (h : a ∈ []) => False) (eq.mp (Eq._oldrec (Eq.refl (a ∈ l)) e) h)
theorem mem_split {α : Type u} {a : α} {l : List α} (h : a ∈ l) : ∃ (s : List α), ∃ (t : List α), l = s ++ a :: t := sorry
theorem mem_of_ne_of_mem {α : Type u} {a : α} {y : α} {l : List α} (h₁ : a ≠ y) (h₂ : a ∈ y :: l) : a ∈ l :=
or.elim (eq_or_mem_of_mem_cons h₂) (fun (e : a = y) => absurd e h₁) fun (r : a ∈ l) => r
theorem ne_of_not_mem_cons {α : Type u} {a : α} {b : α} {l : List α} : ¬a ∈ b :: l → a ≠ b :=
fun (nin : ¬a ∈ b :: l) (aeqb : a = b) => absurd (Or.inl aeqb) nin
theorem not_mem_of_not_mem_cons {α : Type u} {a : α} {b : α} {l : List α} : ¬a ∈ b :: l → ¬a ∈ l :=
fun (nin : ¬a ∈ b :: l) (nainl : a ∈ l) => absurd (Or.inr nainl) nin
theorem not_mem_cons_of_ne_of_not_mem {α : Type u} {a : α} {y : α} {l : List α} : a ≠ y → ¬a ∈ l → ¬a ∈ y :: l :=
fun (p1 : a ≠ y) (p2 : ¬a ∈ l) =>
not.intro fun (Pain : a ∈ y :: l) => absurd (eq_or_mem_of_mem_cons Pain) (not_or p1 p2)
theorem ne_and_not_mem_of_not_mem_cons {α : Type u} {a : α} {y : α} {l : List α} : ¬a ∈ y :: l → a ≠ y ∧ ¬a ∈ l :=
fun (p : ¬a ∈ y :: l) => { left := ne_of_not_mem_cons p, right := not_mem_of_not_mem_cons p }
theorem mem_map_of_mem {α : Type u} {β : Type v} (f : α → β) {a : α} {l : List α} (h : a ∈ l) : f a ∈ map f l := sorry
theorem exists_of_mem_map {α : Type u} {β : Type v} {f : α → β} {b : β} {l : List α} (h : b ∈ map f l) : ∃ (a : α), a ∈ l ∧ f a = b := sorry
@[simp] theorem mem_map {α : Type u} {β : Type v} {f : α → β} {b : β} {l : List α} : b ∈ map f l ↔ ∃ (a : α), a ∈ l ∧ f a = b := sorry
theorem mem_map_of_injective {α : Type u} {β : Type v} {f : α → β} (H : function.injective f) {a : α} {l : List α} : f a ∈ map f l ↔ a ∈ l := sorry
theorem forall_mem_map_iff {α : Type u} {β : Type v} {f : α → β} {l : List α} {P : β → Prop} : (∀ (i : β), i ∈ map f l → P i) ↔ ∀ (j : α), j ∈ l → P (f j) := sorry
@[simp] theorem map_eq_nil {α : Type u} {β : Type v} {f : α → β} {l : List α} : map f l = [] ↔ l = [] := sorry
@[simp] theorem mem_join {α : Type u} {a : α} {L : List (List α)} : a ∈ join L ↔ ∃ (l : List α), l ∈ L ∧ a ∈ l := sorry
theorem exists_of_mem_join {α : Type u} {a : α} {L : List (List α)} : a ∈ join L → ∃ (l : List α), l ∈ L ∧ a ∈ l :=
iff.mp mem_join
theorem mem_join_of_mem {α : Type u} {a : α} {L : List (List α)} {l : List α} (lL : l ∈ L) (al : a ∈ l) : a ∈ join L :=
iff.mpr mem_join (Exists.intro l { left := lL, right := al })
@[simp] theorem mem_bind {α : Type u} {β : Type v} {b : β} {l : List α} {f : α → List β} : b ∈ list.bind l f ↔ ∃ (a : α), ∃ (H : a ∈ l), b ∈ f a := sorry
theorem exists_of_mem_bind {α : Type u} {β : Type v} {b : β} {l : List α} {f : α → List β} : b ∈ list.bind l f → ∃ (a : α), ∃ (H : a ∈ l), b ∈ f a :=
iff.mp mem_bind
theorem mem_bind_of_mem {α : Type u} {β : Type v} {b : β} {l : List α} {f : α → List β} {a : α} (al : a ∈ l) (h : b ∈ f a) : b ∈ list.bind l f :=
iff.mpr mem_bind (Exists.intro a (Exists.intro al h))
theorem bind_map {α : Type u} {β : Type v} {γ : Type w} {g : α → List β} {f : β → γ} (l : List α) : map f (list.bind l g) = list.bind l fun (a : α) => map f (g a) := sorry
/-! ### length -/
theorem length_eq_zero {α : Type u} {l : List α} : length l = 0 ↔ l = [] :=
{ mp := eq_nil_of_length_eq_zero, mpr := fun (h : l = []) => Eq.symm h ▸ rfl }
@[simp] theorem length_singleton {α : Type u} (a : α) : length [a] = 1 :=
rfl
theorem length_pos_of_mem {α : Type u} {a : α} {l : List α} : a ∈ l → 0 < length l := sorry
theorem exists_mem_of_length_pos {α : Type u} {l : List α} : 0 < length l → ∃ (a : α), a ∈ l := sorry
theorem length_pos_iff_exists_mem {α : Type u} {l : List α} : 0 < length l ↔ ∃ (a : α), a ∈ l := sorry
theorem ne_nil_of_length_pos {α : Type u} {l : List α} : 0 < length l → l ≠ [] :=
fun (h1 : 0 < length l) (h2 : l = []) => lt_irrefl 0 (iff.mpr length_eq_zero h2 ▸ h1)
theorem length_pos_of_ne_nil {α : Type u} {l : List α} : l ≠ [] → 0 < length l :=
fun (h : l ≠ []) => iff.mpr pos_iff_ne_zero fun (h0 : length l = 0) => h (iff.mp length_eq_zero h0)
theorem length_pos_iff_ne_nil {α : Type u} {l : List α} : 0 < length l ↔ l ≠ [] :=
{ mp := ne_nil_of_length_pos, mpr := length_pos_of_ne_nil }
theorem length_eq_one {α : Type u} {l : List α} : length l = 1 ↔ ∃ (a : α), l = [a] := sorry
theorem exists_of_length_succ {α : Type u} {n : ℕ} (l : List α) : length l = n + 1 → ∃ (h : α), ∃ (t : List α), l = h :: t := sorry
@[simp] theorem length_injective_iff {α : Type u} : function.injective length ↔ subsingleton α := sorry
@[simp] theorem length_injective {α : Type u} [subsingleton α] : function.injective length :=
iff.mpr length_injective_iff _inst_1
/-! ### set-theoretic notation of lists -/
theorem empty_eq {α : Type u} : ∅ = [] :=
Eq.refl ∅
theorem singleton_eq {α : Type u} (x : α) : singleton x = [x] :=
rfl
theorem insert_neg {α : Type u} [DecidableEq α] {x : α} {l : List α} (h : ¬x ∈ l) : insert x l = x :: l :=
if_neg h
theorem insert_pos {α : Type u} [DecidableEq α] {x : α} {l : List α} (h : x ∈ l) : insert x l = l :=
if_pos h
theorem doubleton_eq {α : Type u} [DecidableEq α] {x : α} {y : α} (h : x ≠ y) : insert x (singleton y) = [x, y] := sorry
/-! ### bounded quantifiers over lists -/
theorem forall_mem_nil {α : Type u} (p : α → Prop) (x : α) (H : x ∈ []) : p x :=
false.dcases_on (fun (H : x ∈ []) => p x) H
theorem forall_mem_cons {α : Type u} {p : α → Prop} {a : α} {l : List α} : (∀ (x : α), x ∈ a :: l → p x) ↔ p a ∧ ∀ (x : α), x ∈ l → p x :=
ball_cons
theorem forall_mem_of_forall_mem_cons {α : Type u} {p : α → Prop} {a : α} {l : List α} (h : ∀ (x : α), x ∈ a :: l → p x) (x : α) (H : x ∈ l) : p x :=
and.right (iff.mp forall_mem_cons h)
theorem forall_mem_singleton {α : Type u} {p : α → Prop} {a : α} : (∀ (x : α), x ∈ [a] → p x) ↔ p a := sorry
theorem forall_mem_append {α : Type u} {p : α → Prop} {l₁ : List α} {l₂ : List α} : (∀ (x : α), x ∈ l₁ ++ l₂ → p x) ↔ (∀ (x : α), x ∈ l₁ → p x) ∧ ∀ (x : α), x ∈ l₂ → p x := sorry
theorem not_exists_mem_nil {α : Type u} (p : α → Prop) : ¬∃ (x : α), ∃ (H : x ∈ []), p x := sorry
theorem exists_mem_cons_of {α : Type u} {p : α → Prop} {a : α} (l : List α) (h : p a) : ∃ (x : α), ∃ (H : x ∈ a :: l), p x :=
bex.intro a (mem_cons_self a l) h
theorem exists_mem_cons_of_exists {α : Type u} {p : α → Prop} {a : α} {l : List α} (h : ∃ (x : α), ∃ (H : x ∈ l), p x) : ∃ (x : α), ∃ (H : x ∈ a :: l), p x :=
bex.elim h fun (x : α) (xl : x ∈ l) (px : p x) => bex.intro x (mem_cons_of_mem a xl) px
theorem or_exists_of_exists_mem_cons {α : Type u} {p : α → Prop} {a : α} {l : List α} (h : ∃ (x : α), ∃ (H : x ∈ a :: l), p x) : p a ∨ ∃ (x : α), ∃ (H : x ∈ l), p x := sorry
theorem exists_mem_cons_iff {α : Type u} (p : α → Prop) (a : α) (l : List α) : (∃ (x : α), ∃ (H : x ∈ a :: l), p x) ↔ p a ∨ ∃ (x : α), ∃ (H : x ∈ l), p x :=
{ mp := or_exists_of_exists_mem_cons,
mpr := fun (h : p a ∨ ∃ (x : α), ∃ (H : x ∈ l), p x) => or.elim h (exists_mem_cons_of l) exists_mem_cons_of_exists }
/-! ### list subset -/
theorem subset_def {α : Type u} {l₁ : List α} {l₂ : List α} : l₁ ⊆ l₂ ↔ ∀ {a : α}, a ∈ l₁ → a ∈ l₂ :=
iff.rfl
theorem subset_append_of_subset_left {α : Type u} (l : List α) (l₁ : List α) (l₂ : List α) : l ⊆ l₁ → l ⊆ l₁ ++ l₂ :=
fun (s : l ⊆ l₁) => subset.trans s (subset_append_left l₁ l₂)
theorem subset_append_of_subset_right {α : Type u} (l : List α) (l₁ : List α) (l₂ : List α) : l ⊆ l₂ → l ⊆ l₁ ++ l₂ :=
fun (s : l ⊆ l₂) => subset.trans s (subset_append_right l₁ l₂)
@[simp] theorem cons_subset {α : Type u} {a : α} {l : List α} {m : List α} : a :: l ⊆ m ↔ a ∈ m ∧ l ⊆ m := sorry
theorem cons_subset_of_subset_of_mem {α : Type u} {a : α} {l : List α} {m : List α} (ainm : a ∈ m) (lsubm : l ⊆ m) : a :: l ⊆ m :=
iff.mpr cons_subset { left := ainm, right := lsubm }
theorem append_subset_of_subset_of_subset {α : Type u} {l₁ : List α} {l₂ : List α} {l : List α} (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) : l₁ ++ l₂ ⊆ l :=
fun (a : α) (h : a ∈ l₁ ++ l₂) => or.elim (iff.mp mem_append h) l₁subl l₂subl
@[simp] theorem append_subset_iff {α : Type u} {l₁ : List α} {l₂ : List α} {l : List α} : l₁ ++ l₂ ⊆ l ↔ l₁ ⊆ l ∧ l₂ ⊆ l := sorry
theorem eq_nil_of_subset_nil {α : Type u} {l : List α} : l ⊆ [] → l = [] := sorry
theorem eq_nil_iff_forall_not_mem {α : Type u} {l : List α} : l = [] ↔ ∀ (a : α), ¬a ∈ l :=
(fun (this : l = [] ↔ l ⊆ []) => this) { mp := fun (e : l = []) => e ▸ subset.refl l, mpr := eq_nil_of_subset_nil }
theorem map_subset {α : Type u} {β : Type v} {l₁ : List α} {l₂ : List α} (f : α → β) (H : l₁ ⊆ l₂) : map f l₁ ⊆ map f l₂ := sorry
theorem map_subset_iff {α : Type u} {β : Type v} {l₁ : List α} {l₂ : List α} (f : α → β) (h : function.injective f) : map f l₁ ⊆ map f l₂ ↔ l₁ ⊆ l₂ := sorry
/-! ### append -/
theorem append_eq_has_append {α : Type u} {L₁ : List α} {L₂ : List α} : list.append L₁ L₂ = L₁ ++ L₂ :=
rfl
@[simp] theorem singleton_append {α : Type u} {x : α} {l : List α} : [x] ++ l = x :: l :=
rfl
theorem append_ne_nil_of_ne_nil_left {α : Type u} (s : List α) (t : List α) : s ≠ [] → s ++ t ≠ [] := sorry
theorem append_ne_nil_of_ne_nil_right {α : Type u} (s : List α) (t : List α) : t ≠ [] → s ++ t ≠ [] := sorry
@[simp] theorem append_eq_nil {α : Type u} {p : List α} {q : List α} : p ++ q = [] ↔ p = [] ∧ q = [] := sorry
@[simp] theorem nil_eq_append_iff {α : Type u} {a : List α} {b : List α} : [] = a ++ b ↔ a = [] ∧ b = [] :=
eq.mpr (id (Eq._oldrec (Eq.refl ([] = a ++ b ↔ a = [] ∧ b = [])) (propext eq_comm)))
(eq.mpr (id (Eq._oldrec (Eq.refl (a ++ b = [] ↔ a = [] ∧ b = [])) (propext append_eq_nil)))
(iff.refl (a = [] ∧ b = [])))
theorem append_eq_cons_iff {α : Type u} {a : List α} {b : List α} {c : List α} {x : α} : a ++ b = x :: c ↔ a = [] ∧ b = x :: c ∨ ∃ (a' : List α), a = x :: a' ∧ c = a' ++ b := sorry
theorem cons_eq_append_iff {α : Type u} {a : List α} {b : List α} {c : List α} {x : α} : x :: c = a ++ b ↔ a = [] ∧ b = x :: c ∨ ∃ (a' : List α), a = x :: a' ∧ c = a' ++ b := sorry
theorem append_eq_append_iff {α : Type u} {a : List α} {b : List α} {c : List α} {d : List α} : a ++ b = c ++ d ↔ (∃ (a' : List α), c = a ++ a' ∧ b = a' ++ d) ∨ ∃ (c' : List α), a = c ++ c' ∧ d = c' ++ b := sorry
@[simp] theorem split_at_eq_take_drop {α : Type u} (n : ℕ) (l : List α) : split_at n l = (take n l, drop n l) := sorry
@[simp] theorem take_append_drop {α : Type u} (n : ℕ) (l : List α) : take n l ++ drop n l = l := sorry
-- TODO(Leo): cleanup proof after arith dec proc
theorem append_inj {α : Type u} {s₁ : List α} {s₂ : List α} {t₁ : List α} {t₂ : List α} : s₁ ++ t₁ = s₂ ++ t₂ → length s₁ = length s₂ → s₁ = s₂ ∧ t₁ = t₂ := sorry
theorem append_inj_right {α : Type u} {s₁ : List α} {s₂ : List α} {t₁ : List α} {t₂ : List α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : t₁ = t₂ :=
and.right (append_inj h hl)
theorem append_inj_left {α : Type u} {s₁ : List α} {s₂ : List α} {t₁ : List α} {t₂ : List α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : s₁ = s₂ :=
and.left (append_inj h hl)
theorem append_inj' {α : Type u} {s₁ : List α} {s₂ : List α} {t₁ : List α} {t₂ : List α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ ∧ t₁ = t₂ := sorry
theorem append_inj_right' {α : Type u} {s₁ : List α} {s₂ : List α} {t₁ : List α} {t₂ : List α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : t₁ = t₂ :=
and.right (append_inj' h hl)
theorem append_inj_left' {α : Type u} {s₁ : List α} {s₂ : List α} {t₁ : List α} {t₂ : List α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ :=
and.left (append_inj' h hl)
theorem append_left_cancel {α : Type u} {s : List α} {t₁ : List α} {t₂ : List α} (h : s ++ t₁ = s ++ t₂) : t₁ = t₂ :=
append_inj_right h rfl
theorem append_right_cancel {α : Type u} {s₁ : List α} {s₂ : List α} {t : List α} (h : s₁ ++ t = s₂ ++ t) : s₁ = s₂ :=
append_inj_left' h rfl
theorem append_right_injective {α : Type u} (s : List α) : function.injective fun (t : List α) => s ++ t :=
fun (t₁ t₂ : List α) => append_left_cancel
theorem append_right_inj {α : Type u} {t₁ : List α} {t₂ : List α} (s : List α) : s ++ t₁ = s ++ t₂ ↔ t₁ = t₂ :=
function.injective.eq_iff (append_right_injective s)
theorem append_left_injective {α : Type u} (t : List α) : function.injective fun (s : List α) => s ++ t :=
fun (s₁ s₂ : List α) => append_right_cancel
theorem append_left_inj {α : Type u} {s₁ : List α} {s₂ : List α} (t : List α) : s₁ ++ t = s₂ ++ t ↔ s₁ = s₂ :=
function.injective.eq_iff (append_left_injective t)
theorem map_eq_append_split {α : Type u} {β : Type v} {f : α → β} {l : List α} {s₁ : List β} {s₂ : List β} (h : map f l = s₁ ++ s₂) : ∃ (l₁ : List α), ∃ (l₂ : List α), l = l₁ ++ l₂ ∧ map f l₁ = s₁ ∧ map f l₂ = s₂ := sorry
/-! ### repeat -/
@[simp] theorem repeat_succ {α : Type u} (a : α) (n : ℕ) : repeat a (n + 1) = a :: repeat a n :=
rfl
theorem eq_of_mem_repeat {α : Type u} {a : α} {b : α} {n : ℕ} : b ∈ repeat a n → b = a := sorry
theorem eq_repeat_of_mem {α : Type u} {a : α} {l : List α} : (∀ (b : α), b ∈ l → b = a) → l = repeat a (length l) := sorry
theorem eq_repeat' {α : Type u} {a : α} {l : List α} : l = repeat a (length l) ↔ ∀ (b : α), b ∈ l → b = a :=
{ mp := fun (h : l = repeat a (length l)) => Eq.symm h ▸ fun (b : α) => eq_of_mem_repeat, mpr := eq_repeat_of_mem }
theorem eq_repeat {α : Type u} {a : α} {n : ℕ} {l : List α} : l = repeat a n ↔ length l = n ∧ ∀ (b : α), b ∈ l → b = a := sorry
theorem repeat_add {α : Type u} (a : α) (m : ℕ) (n : ℕ) : repeat a (m + n) = repeat a m ++ repeat a n := sorry
theorem repeat_subset_singleton {α : Type u} (a : α) (n : ℕ) : repeat a n ⊆ [a] :=
fun (b : α) (h : b ∈ repeat a n) => iff.mpr mem_singleton (eq_of_mem_repeat h)
@[simp] theorem map_const {α : Type u} {β : Type v} (l : List α) (b : β) : map (function.const α b) l = repeat b (length l) := sorry
theorem eq_of_mem_map_const {α : Type u} {β : Type v} {b₁ : β} {b₂ : β} {l : List α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ :=
eq_of_mem_repeat (eq.mp (Eq._oldrec (Eq.refl (b₁ ∈ map (function.const α b₂) l)) (map_const l b₂)) h)
@[simp] theorem map_repeat {α : Type u} {β : Type v} (f : α → β) (a : α) (n : ℕ) : map f (repeat a n) = repeat (f a) n := sorry
@[simp] theorem tail_repeat {α : Type u} (a : α) (n : ℕ) : tail (repeat a n) = repeat a (Nat.pred n) :=
nat.cases_on n (Eq.refl (tail (repeat a 0))) fun (n : ℕ) => Eq.refl (tail (repeat a (Nat.succ n)))
@[simp] theorem join_repeat_nil {α : Type u} (n : ℕ) : join (repeat [] n) = [] := sorry
/-! ### pure -/
@[simp] theorem mem_pure {α : Type u_1} (x : α) (y : α) : x ∈ pure y ↔ x = y := sorry
/-! ### bind -/
@[simp] theorem bind_eq_bind {α : Type u_1} {β : Type u_1} (f : α → List β) (l : List α) : l >>= f = list.bind l f :=
rfl
@[simp] theorem bind_append {α : Type u} {β : Type v} (f : α → List β) (l₁ : List α) (l₂ : List α) : list.bind (l₁ ++ l₂) f = list.bind l₁ f ++ list.bind l₂ f :=
append_bind l₁ l₂ f
@[simp] theorem bind_singleton {α : Type u} {β : Type v} (f : α → List β) (x : α) : list.bind [x] f = f x :=
append_nil (f x)
/-! ### concat -/
theorem concat_nil {α : Type u} (a : α) : concat [] a = [a] :=
rfl
theorem concat_cons {α : Type u} (a : α) (b : α) (l : List α) : concat (a :: l) b = a :: concat l b :=
rfl
@[simp] theorem concat_eq_append {α : Type u} (a : α) (l : List α) : concat l a = l ++ [a] := sorry
theorem init_eq_of_concat_eq {α : Type u} {a : α} {l₁ : List α} {l₂ : List α} : concat l₁ a = concat l₂ a → l₁ = l₂ := sorry
theorem last_eq_of_concat_eq {α : Type u} {a : α} {b : α} {l : List α} : concat l a = concat l b → a = b := sorry
theorem concat_ne_nil {α : Type u} (a : α) (l : List α) : concat l a ≠ [] := sorry
theorem concat_append {α : Type u} (a : α) (l₁ : List α) (l₂ : List α) : concat l₁ a ++ l₂ = l₁ ++ a :: l₂ := sorry
theorem length_concat {α : Type u} (a : α) (l : List α) : length (concat l a) = Nat.succ (length l) := sorry
theorem append_concat {α : Type u} (a : α) (l₁ : List α) (l₂ : List α) : l₁ ++ concat l₂ a = concat (l₁ ++ l₂) a := sorry
/-! ### reverse -/
@[simp] theorem reverse_nil {α : Type u} : reverse [] = [] :=
rfl
@[simp] theorem reverse_cons {α : Type u} (a : α) (l : List α) : reverse (a :: l) = reverse l ++ [a] := sorry
theorem reverse_core_eq {α : Type u} (l₁ : List α) (l₂ : List α) : reverse_core l₁ l₂ = reverse l₁ ++ l₂ := sorry
theorem reverse_cons' {α : Type u} (a : α) (l : List α) : reverse (a :: l) = concat (reverse l) a := sorry
@[simp] theorem reverse_singleton {α : Type u} (a : α) : reverse [a] = [a] :=
rfl
@[simp] theorem reverse_append {α : Type u} (s : List α) (t : List α) : reverse (s ++ t) = reverse t ++ reverse s := sorry
theorem reverse_concat {α : Type u} (l : List α) (a : α) : reverse (concat l a) = a :: reverse l := sorry
@[simp] theorem reverse_reverse {α : Type u} (l : List α) : reverse (reverse l) = l := sorry
@[simp] theorem reverse_involutive {α : Type u} : function.involutive reverse :=
fun (l : List α) => reverse_reverse l
@[simp] theorem reverse_injective {α : Type u} : function.injective reverse :=
function.involutive.injective reverse_involutive
@[simp] theorem reverse_inj {α : Type u} {l₁ : List α} {l₂ : List α} : reverse l₁ = reverse l₂ ↔ l₁ = l₂ :=
function.injective.eq_iff reverse_injective
@[simp] theorem reverse_eq_nil {α : Type u} {l : List α} : reverse l = [] ↔ l = [] :=
reverse_inj
theorem concat_eq_reverse_cons {α : Type u} (a : α) (l : List α) : concat l a = reverse (a :: reverse l) := sorry
@[simp] theorem length_reverse {α : Type u} (l : List α) : length (reverse l) = length l := sorry
@[simp] theorem map_reverse {α : Type u} {β : Type v} (f : α → β) (l : List α) : map f (reverse l) = reverse (map f l) := sorry
theorem map_reverse_core {α : Type u} {β : Type v} (f : α → β) (l₁ : List α) (l₂ : List α) : map f (reverse_core l₁ l₂) = reverse_core (map f l₁) (map f l₂) := sorry
@[simp] theorem mem_reverse {α : Type u} {a : α} {l : List α} : a ∈ reverse l ↔ a ∈ l := sorry
@[simp] theorem reverse_repeat {α : Type u} (a : α) (n : ℕ) : reverse (repeat a n) = repeat a n := sorry
/-! ### is_nil -/
theorem is_nil_iff_eq_nil {α : Type u} {l : List α} : ↥(is_nil l) ↔ l = [] := sorry
/-! ### init -/
@[simp] theorem length_init {α : Type u} (l : List α) : length (init l) = length l - 1 := sorry
/-! ### last -/
@[simp] theorem last_cons {α : Type u} {a : α} {l : List α} (h₁ : a :: l ≠ []) (h₂ : l ≠ []) : last (a :: l) h₁ = last l h₂ := sorry
@[simp] theorem last_append {α : Type u} {a : α} (l : List α) (h : l ++ [a] ≠ []) : last (l ++ [a]) h = a := sorry
theorem last_concat {α : Type u} {a : α} (l : List α) (h : concat l a ≠ []) : last (concat l a) h = a := sorry
@[simp] theorem last_singleton {α : Type u} (a : α) (h : [a] ≠ []) : last [a] h = a :=
rfl
@[simp] theorem last_cons_cons {α : Type u} (a₁ : α) (a₂ : α) (l : List α) (h : a₁ :: a₂ :: l ≠ []) : last (a₁ :: a₂ :: l) h = last (a₂ :: l) (cons_ne_nil a₂ l) :=
rfl
theorem init_append_last {α : Type u} {l : List α} (h : l ≠ []) : init l ++ [last l h] = l := sorry
theorem last_congr {α : Type u} {l₁ : List α} {l₂ : List α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) : last l₁ h₁ = last l₂ h₂ :=
Eq._oldrec (fun (h₁ : l₂ ≠ []) => Eq.refl (last l₂ h₁)) (Eq.symm h₃) h₁
theorem last_mem {α : Type u} {l : List α} (h : l ≠ []) : last l h ∈ l := sorry
theorem last_repeat_succ (a : ℕ) (m : ℕ) : last (repeat a (Nat.succ m))
(ne_nil_of_length_eq_succ
((fun (this : length (repeat a (Nat.succ m)) = Nat.succ m) => this)
(eq.mpr (id (Eq._oldrec (Eq.refl (length (repeat a (Nat.succ m)) = Nat.succ m)) (length_repeat a (Nat.succ m))))
(Eq.refl (Nat.succ m))))) =
a := sorry
/-! ### last' -/
@[simp] theorem last'_is_none {α : Type u} {l : List α} : ↥(option.is_none (last' l)) ↔ l = [] := sorry
@[simp] theorem last'_is_some {α : Type u} {l : List α} : ↥(option.is_some (last' l)) ↔ l ≠ [] := sorry
theorem mem_last'_eq_last {α : Type u} {l : List α} {x : α} : x ∈ last' l → ∃ (h : l ≠ []), x = last l h := sorry
theorem mem_of_mem_last' {α : Type u} {l : List α} {a : α} (ha : a ∈ last' l) : a ∈ l := sorry
theorem init_append_last' {α : Type u} {l : List α} (a : α) (H : a ∈ last' l) : init l ++ [a] = l := sorry
theorem ilast_eq_last' {α : Type u} [Inhabited α] (l : List α) : ilast l = option.iget (last' l) := sorry
@[simp] theorem last'_append_cons {α : Type u} (l₁ : List α) (a : α) (l₂ : List α) : last' (l₁ ++ a :: l₂) = last' (a :: l₂) := sorry
theorem last'_append_of_ne_nil {α : Type u} (l₁ : List α) {l₂ : List α} (hl₂ : l₂ ≠ []) : last' (l₁ ++ l₂) = last' l₂ := sorry
/-! ### head(') and tail -/
theorem head_eq_head' {α : Type u} [Inhabited α] (l : List α) : head l = option.iget (head' l) :=
list.cases_on l (Eq.refl (head [])) fun (l_hd : α) (l_tl : List α) => Eq.refl (head (l_hd :: l_tl))
theorem mem_of_mem_head' {α : Type u} {x : α} {l : List α} : x ∈ head' l → x ∈ l := sorry
@[simp] theorem head_cons {α : Type u} [Inhabited α] (a : α) (l : List α) : head (a :: l) = a :=
rfl
@[simp] theorem tail_nil {α : Type u} : tail [] = [] :=
rfl
@[simp] theorem tail_cons {α : Type u} (a : α) (l : List α) : tail (a :: l) = l :=
rfl
@[simp] theorem head_append {α : Type u} [Inhabited α] (t : List α) {s : List α} (h : s ≠ []) : head (s ++ t) = head s := sorry
theorem tail_append_singleton_of_ne_nil {α : Type u} {a : α} {l : List α} (h : l ≠ []) : tail (l ++ [a]) = tail l ++ [a] := sorry
theorem cons_head'_tail {α : Type u} {l : List α} {a : α} (h : a ∈ head' l) : a :: tail l = l := sorry
theorem head_mem_head' {α : Type u} [Inhabited α] {l : List α} (h : l ≠ []) : head l ∈ head' l :=
list.cases_on l (fun (h : [] ≠ []) => idRhs (head [] ∈ head' []) (absurd (Eq.refl []) h))
(fun (l_hd : α) (l_tl : List α) (h : l_hd :: l_tl ≠ []) => idRhs (head' (l_hd :: l_tl) = head' (l_hd :: l_tl)) rfl) h
theorem cons_head_tail {α : Type u} [Inhabited α] {l : List α} (h : l ≠ []) : head l :: tail l = l :=
cons_head'_tail (head_mem_head' h)
@[simp] theorem head'_map {α : Type u} {β : Type v} (f : α → β) (l : List α) : head' (map f l) = option.map f (head' l) :=
list.cases_on l (Eq.refl (head' (map f []))) fun (l_hd : α) (l_tl : List α) => Eq.refl (head' (map f (l_hd :: l_tl)))
/-! ### Induction from the right -/
/-- Induction principle from the right for lists: if a property holds for the empty list, and
for `l ++ [a]` if it holds for `l`, then it holds for all lists. The principle is given for
a `Sort`-valued predicate, i.e., it can also be used to construct data. -/
def reverse_rec_on {α : Type u} {C : List α → Sort u_1} (l : List α) (H0 : C []) (H1 : (l : List α) → (a : α) → C l → C (l ++ [a])) : C l :=
eq.mpr sorry
(List.rec H0 (fun (hd : α) (tl : List α) (ih : C (reverse tl)) => eq.mpr sorry (H1 (reverse tl) hd ih)) (reverse l))
/-- Bidirectional induction principle for lists: if a property holds for the empty list, the
singleton list, and `a :: (l ++ [b])` from `l`, then it holds for all lists. This can be used to
prove statements about palindromes. The principle is given for a `Sort`-valued predicate, i.e., it
can also be used to construct data. -/
def bidirectional_rec {α : Type u} {C : List α → Sort u_1} (H0 : C []) (H1 : (a : α) → C [a]) (Hn : (a : α) → (l : List α) → (b : α) → C l → C (a :: (l ++ [b]))) (l : List α) : C l :=
sorry
/-- Like `bidirectional_rec`, but with the list parameter placed first. -/
def bidirectional_rec_on {α : Type u} {C : List α → Sort u_1} (l : List α) (H0 : C []) (H1 : (a : α) → C [a]) (Hn : (a : α) → (l : List α) → (b : α) → C l → C (a :: (l ++ [b]))) : C l :=
bidirectional_rec H0 H1 Hn l
/-! ### sublists -/
@[simp] theorem nil_sublist {α : Type u} (l : List α) : [] <+ l := sorry
@[simp] theorem sublist.refl {α : Type u} (l : List α) : l <+ l := sorry
theorem sublist.trans {α : Type u} {l₁ : List α} {l₂ : List α} {l₃ : List α} (h₁ : l₁ <+ l₂) (h₂ : l₂ <+ l₃) : l₁ <+ l₃ := sorry
@[simp] theorem sublist_cons {α : Type u} (a : α) (l : List α) : l <+ a :: l :=
sublist.cons l l a (sublist.refl l)
theorem sublist_of_cons_sublist {α : Type u} {a : α} {l₁ : List α} {l₂ : List α} : a :: l₁ <+ l₂ → l₁ <+ l₂ :=
sublist.trans (sublist_cons a l₁)
theorem cons_sublist_cons {α : Type u} {l₁ : List α} {l₂ : List α} (a : α) (s : l₁ <+ l₂) : a :: l₁ <+ a :: l₂ :=
sublist.cons2 l₁ l₂ a s
@[simp] theorem sublist_append_left {α : Type u} (l₁ : List α) (l₂ : List α) : l₁ <+ l₁ ++ l₂ := sorry
@[simp] theorem sublist_append_right {α : Type u} (l₁ : List α) (l₂ : List α) : l₂ <+ l₁ ++ l₂ := sorry
theorem sublist_cons_of_sublist {α : Type u} (a : α) {l₁ : List α} {l₂ : List α} : l₁ <+ l₂ → l₁ <+ a :: l₂ :=
sublist.cons l₁ l₂ a
theorem sublist_append_of_sublist_left {α : Type u} {l : List α} {l₁ : List α} {l₂ : List α} (s : l <+ l₁) : l <+ l₁ ++ l₂ :=
sublist.trans s (sublist_append_left l₁ l₂)
theorem sublist_append_of_sublist_right {α : Type u} {l : List α} {l₁ : List α} {l₂ : List α} (s : l <+ l₂) : l <+ l₁ ++ l₂ :=
sublist.trans s (sublist_append_right l₁ l₂)
theorem sublist_of_cons_sublist_cons {α : Type u} {l₁ : List α} {l₂ : List α} {a : α} : a :: l₁ <+ a :: l₂ → l₁ <+ l₂ := sorry
theorem cons_sublist_cons_iff {α : Type u} {l₁ : List α} {l₂ : List α} {a : α} : a :: l₁ <+ a :: l₂ ↔ l₁ <+ l₂ :=
{ mp := sublist_of_cons_sublist_cons, mpr := cons_sublist_cons a }
@[simp] theorem append_sublist_append_left {α : Type u} {l₁ : List α} {l₂ : List α} (l : List α) : l ++ l₁ <+ l ++ l₂ ↔ l₁ <+ l₂ := sorry
theorem sublist.append_right {α : Type u} {l₁ : List α} {l₂ : List α} (h : l₁ <+ l₂) (l : List α) : l₁ ++ l <+ l₂ ++ l :=
sublist.drec (sublist.refl ([] ++ l))
(fun (h_l₁ h_l₂ : List α) (a : α) (h_ᾰ : h_l₁ <+ h_l₂) (ih : h_l₁ ++ l <+ h_l₂ ++ l) => sublist_cons_of_sublist a ih)
(fun (h_l₁ h_l₂ : List α) (a : α) (h_ᾰ : h_l₁ <+ h_l₂) (ih : h_l₁ ++ l <+ h_l₂ ++ l) => cons_sublist_cons a ih) h
theorem sublist_or_mem_of_sublist {α : Type u} {l : List α} {l₁ : List α} {l₂ : List α} {a : α} (h : l <+ l₁ ++ a :: l₂) : l <+ l₁ ++ l₂ ∨ a ∈ l := sorry
theorem sublist.reverse {α : Type u} {l₁ : List α} {l₂ : List α} (h : l₁ <+ l₂) : reverse l₁ <+ reverse l₂ := sorry
@[simp] theorem reverse_sublist_iff {α : Type u} {l₁ : List α} {l₂ : List α} : reverse l₁ <+ reverse l₂ ↔ l₁ <+ l₂ :=
{ mp := fun (h : reverse l₁ <+ reverse l₂) => reverse_reverse l₁ ▸ reverse_reverse l₂ ▸ sublist.reverse h,
mpr := sublist.reverse }
@[simp] theorem append_sublist_append_right {α : Type u} {l₁ : List α} {l₂ : List α} (l : List α) : l₁ ++ l <+ l₂ ++ l ↔ l₁ <+ l₂ := sorry
theorem sublist.append {α : Type u} {l₁ : List α} {l₂ : List α} {r₁ : List α} {r₂ : List α} (hl : l₁ <+ l₂) (hr : r₁ <+ r₂) : l₁ ++ r₁ <+ l₂ ++ r₂ :=
sublist.trans (sublist.append_right hl r₁) (iff.mpr (append_sublist_append_left l₂) hr)
theorem sublist.subset {α : Type u} {l₁ : List α} {l₂ : List α} : l₁ <+ l₂ → l₁ ⊆ l₂ := sorry
theorem singleton_sublist {α : Type u} {a : α} {l : List α} : [a] <+ l ↔ a ∈ l := sorry
theorem eq_nil_of_sublist_nil {α : Type u} {l : List α} (s : l <+ []) : l = [] :=
eq_nil_of_subset_nil (sublist.subset s)
theorem repeat_sublist_repeat {α : Type u} (a : α) {m : ℕ} {n : ℕ} : repeat a m <+ repeat a n ↔ m ≤ n := sorry
theorem eq_of_sublist_of_length_eq {α : Type u} {l₁ : List α} {l₂ : List α} : l₁ <+ l₂ → length l₁ = length l₂ → l₁ = l₂ := sorry
theorem eq_of_sublist_of_length_le {α : Type u} {l₁ : List α} {l₂ : List α} (s : l₁ <+ l₂) (h : length l₂ ≤ length l₁) : l₁ = l₂ :=
eq_of_sublist_of_length_eq s (le_antisymm (length_le_of_sublist s) h)
theorem sublist.antisymm {α : Type u} {l₁ : List α} {l₂ : List α} (s₁ : l₁ <+ l₂) (s₂ : l₂ <+ l₁) : l₁ = l₂ :=
eq_of_sublist_of_length_le s₁ (length_le_of_sublist s₂)
protected instance decidable_sublist {α : Type u} [DecidableEq α] (l₁ : List α) (l₂ : List α) : Decidable (l₁ <+ l₂) :=
sorry
/-! ### index_of -/
@[simp] theorem index_of_nil {α : Type u} [DecidableEq α] (a : α) : index_of a [] = 0 :=
rfl
theorem index_of_cons {α : Type u} [DecidableEq α] (a : α) (b : α) (l : List α) : index_of a (b :: l) = ite (a = b) 0 (Nat.succ (index_of a l)) :=
rfl
theorem index_of_cons_eq {α : Type u} [DecidableEq α] {a : α} {b : α} (l : List α) : a = b → index_of a (b :: l) = 0 :=
fun (e : a = b) => if_pos e
@[simp] theorem index_of_cons_self {α : Type u} [DecidableEq α] (a : α) (l : List α) : index_of a (a :: l) = 0 :=
index_of_cons_eq l rfl
@[simp] theorem index_of_cons_ne {α : Type u} [DecidableEq α] {a : α} {b : α} (l : List α) : a ≠ b → index_of a (b :: l) = Nat.succ (index_of a l) :=
fun (n : a ≠ b) => if_neg n
theorem index_of_eq_length {α : Type u} [DecidableEq α] {a : α} {l : List α} : index_of a l = length l ↔ ¬a ∈ l := sorry
@[simp] theorem index_of_of_not_mem {α : Type u} [DecidableEq α] {l : List α} {a : α} : ¬a ∈ l → index_of a l = length l :=
iff.mpr index_of_eq_length
theorem index_of_le_length {α : Type u} [DecidableEq α] {a : α} {l : List α} : index_of a l ≤ length l := sorry
theorem index_of_lt_length {α : Type u} [DecidableEq α] {a : α} {l : List α} : index_of a l < length l ↔ a ∈ l := sorry
/-! ### nth element -/
theorem nth_le_of_mem {α : Type u} {a : α} {l : List α} : a ∈ l → ∃ (n : ℕ), ∃ (h : n < length l), nth_le l n h = a := sorry
theorem nth_le_nth {α : Type u} {l : List α} {n : ℕ} (h : n < length l) : nth l n = some (nth_le l n h) := sorry
theorem nth_len_le {α : Type u} {l : List α} {n : ℕ} : length l ≤ n → nth l n = none := sorry
theorem nth_eq_some {α : Type u} {l : List α} {n : ℕ} {a : α} : nth l n = some a ↔ ∃ (h : n < length l), nth_le l n h = a := sorry
@[simp] theorem nth_eq_none_iff {α : Type u} {l : List α} {n : ℕ} : nth l n = none ↔ length l ≤ n := sorry
theorem nth_of_mem {α : Type u} {a : α} {l : List α} (h : a ∈ l) : ∃ (n : ℕ), nth l n = some a := sorry
theorem nth_le_mem {α : Type u} (l : List α) (n : ℕ) (h : n < length l) : nth_le l n h ∈ l := sorry
theorem nth_mem {α : Type u} {l : List α} {n : ℕ} {a : α} (e : nth l n = some a) : a ∈ l := sorry
theorem mem_iff_nth_le {α : Type u} {a : α} {l : List α} : a ∈ l ↔ ∃ (n : ℕ), ∃ (h : n < length l), nth_le l n h = a := sorry
theorem mem_iff_nth {α : Type u} {a : α} {l : List α} : a ∈ l ↔ ∃ (n : ℕ), nth l n = some a :=
iff.trans mem_iff_nth_le (exists_congr fun (n : ℕ) => iff.symm nth_eq_some)
theorem nth_zero {α : Type u} (l : List α) : nth l 0 = head' l :=
list.cases_on l (Eq.refl (nth [] 0)) fun (l_hd : α) (l_tl : List α) => Eq.refl (nth (l_hd :: l_tl) 0)
theorem nth_injective {α : Type u} {xs : List α} {i : ℕ} {j : ℕ} (h₀ : i < length xs) (h₁ : nodup xs) (h₂ : nth xs i = nth xs j) : i = j := sorry
@[simp] theorem nth_map {α : Type u} {β : Type v} (f : α → β) (l : List α) (n : ℕ) : nth (map f l) n = option.map f (nth l n) := sorry
theorem nth_le_map {α : Type u} {β : Type v} (f : α → β) {l : List α} {n : ℕ} (H1 : n < length (map f l)) (H2 : n < length l) : nth_le (map f l) n H1 = f (nth_le l n H2) := sorry
/-- A version of `nth_le_map` that can be used for rewriting. -/
theorem nth_le_map_rev {α : Type u} {β : Type v} (f : α → β) {l : List α} {n : ℕ} (H : n < length l) : f (nth_le l n H) = nth_le (map f l) n (Eq.symm (length_map f l) ▸ H) :=
Eq.symm (nth_le_map f (Eq.symm (length_map f l) ▸ H) H)
@[simp] theorem nth_le_map' {α : Type u} {β : Type v} (f : α → β) {l : List α} {n : ℕ} (H : n < length (map f l)) : nth_le (map f l) n H = f (nth_le l n (length_map f l ▸ H)) :=
nth_le_map f H (length_map f l ▸ H)
/-- If one has `nth_le L i hi` in a formula and `h : L = L'`, one can not `rw h` in the formula as
`hi` gives `i < L.length` and not `i < L'.length`. The lemma `nth_le_of_eq` can be used to make
such a rewrite, with `rw (nth_le_of_eq h)`. -/
theorem nth_le_of_eq {α : Type u} {L : List α} {L' : List α} (h : L = L') {i : ℕ} (hi : i < length L) : nth_le L i hi = nth_le L' i (h ▸ hi) := sorry
@[simp] theorem nth_le_singleton {α : Type u} (a : α) {n : ℕ} (hn : n < 1) : nth_le [a] n hn = a :=
(fun (hn0 : n = 0) => Eq._oldrec (fun (hn : 0 < 1) => Eq.refl (nth_le [a] 0 hn)) (Eq.symm hn0) hn)
(iff.mp nat.le_zero_iff (nat.le_of_lt_succ hn))
theorem nth_le_zero {α : Type u} [Inhabited α] {L : List α} (h : 0 < length L) : nth_le L 0 h = head L := sorry
theorem nth_le_append {α : Type u} {l₁ : List α} {l₂ : List α} {n : ℕ} (hn₁ : n < length (l₁ ++ l₂)) (hn₂ : n < length l₁) : nth_le (l₁ ++ l₂) n hn₁ = nth_le l₁ n hn₂ := sorry
theorem nth_le_append_right_aux {α : Type u} {l₁ : List α} {l₂ : List α} {n : ℕ} (h₁ : length l₁ ≤ n) (h₂ : n < length (l₁ ++ l₂)) : n - length l₁ < length l₂ := sorry
theorem nth_le_append_right {α : Type u} {l₁ : List α} {l₂ : List α} {n : ℕ} (h₁ : length l₁ ≤ n) (h₂ : n < length (l₁ ++ l₂)) : nth_le (l₁ ++ l₂) n h₂ = nth_le l₂ (n - length l₁) (nth_le_append_right_aux h₁ h₂) := sorry
@[simp] theorem nth_le_repeat {α : Type u} (a : α) {n : ℕ} {m : ℕ} (h : m < length (repeat a n)) : nth_le (repeat a n) m h = a :=
eq_of_mem_repeat (nth_le_mem (repeat a n) m h)
theorem nth_append {α : Type u} {l₁ : List α} {l₂ : List α} {n : ℕ} (hn : n < length l₁) : nth (l₁ ++ l₂) n = nth l₁ n := sorry
theorem nth_append_right {α : Type u} {l₁ : List α} {l₂ : List α} {n : ℕ} (hn : length l₁ ≤ n) : nth (l₁ ++ l₂) n = nth l₂ (n - length l₁) := sorry
theorem last_eq_nth_le {α : Type u} (l : List α) (h : l ≠ []) : last l h = nth_le l (length l - 1) (nat.sub_lt (length_pos_of_ne_nil h) nat.one_pos) := sorry
@[simp] theorem nth_concat_length {α : Type u} (l : List α) (a : α) : nth (l ++ [a]) (length l) = some a := sorry
theorem ext {α : Type u} {l₁ : List α} {l₂ : List α} : (∀ (n : ℕ), nth l₁ n = nth l₂ n) → l₁ = l₂ := sorry
theorem ext_le {α : Type u} {l₁ : List α} {l₂ : List α} (hl : length l₁ = length l₂) (h : ∀ (n : ℕ) (h₁ : n < length l₁) (h₂ : n < length l₂), nth_le l₁ n h₁ = nth_le l₂ n h₂) : l₁ = l₂ := sorry
@[simp] theorem index_of_nth_le {α : Type u} [DecidableEq α] {a : α} {l : List α} (h : index_of a l < length l) : nth_le l (index_of a l) h = a := sorry
@[simp] theorem index_of_nth {α : Type u} [DecidableEq α] {a : α} {l : List α} (h : a ∈ l) : nth l (index_of a l) = some a := sorry
theorem nth_le_reverse_aux1 {α : Type u} (l : List α) (r : List α) (i : ℕ) (h1 : i + length l < length (reverse_core l r)) (h2 : i < length r) : nth_le (reverse_core l r) (i + length l) h1 = nth_le r i h2 := sorry
theorem index_of_inj {α : Type u} [DecidableEq α] {l : List α} {x : α} {y : α} (hx : x ∈ l) (hy : y ∈ l) : index_of x l = index_of y l ↔ x = y := sorry
theorem nth_le_reverse_aux2 {α : Type u} (l : List α) (r : List α) (i : ℕ) (h1 : length l - 1 - i < length (reverse_core l r)) (h2 : i < length l) : nth_le (reverse_core l r) (length l - 1 - i) h1 = nth_le l i h2 := sorry
@[simp] theorem nth_le_reverse {α : Type u} (l : List α) (i : ℕ) (h1 : length l - 1 - i < length (reverse l)) (h2 : i < length l) : nth_le (reverse l) (length l - 1 - i) h1 = nth_le l i h2 :=
nth_le_reverse_aux2 l [] i h1 h2
theorem eq_cons_of_length_one {α : Type u} {l : List α} (h : length l = 1) : l = [nth_le l 0 (Eq.symm h ▸ zero_lt_one)] := sorry
theorem modify_nth_tail_modify_nth_tail {α : Type u} {f : List α → List α} {g : List α → List α} (m : ℕ) (n : ℕ) (l : List α) : modify_nth_tail g (m + n) (modify_nth_tail f n l) = modify_nth_tail (fun (l : List α) => modify_nth_tail g m (f l)) n l := sorry
theorem modify_nth_tail_modify_nth_tail_le {α : Type u} {f : List α → List α} {g : List α → List α} (m : ℕ) (n : ℕ) (l : List α) (h : n ≤ m) : modify_nth_tail g m (modify_nth_tail f n l) = modify_nth_tail (fun (l : List α) => modify_nth_tail g (m - n) (f l)) n l := sorry
theorem modify_nth_tail_modify_nth_tail_same {α : Type u} {f : List α → List α} {g : List α → List α} (n : ℕ) (l : List α) : modify_nth_tail g n (modify_nth_tail f n l) = modify_nth_tail (g ∘ f) n l := sorry
theorem modify_nth_tail_id {α : Type u} (n : ℕ) (l : List α) : modify_nth_tail id n l = l := sorry
theorem remove_nth_eq_nth_tail {α : Type u} (n : ℕ) (l : List α) : remove_nth l n = modify_nth_tail tail n l := sorry
theorem update_nth_eq_modify_nth {α : Type u} (a : α) (n : ℕ) (l : List α) : update_nth l n a = modify_nth (fun (_x : α) => a) n l := sorry
theorem modify_nth_eq_update_nth {α : Type u} (f : α → α) (n : ℕ) (l : List α) : modify_nth f n l = option.get_or_else ((fun (a : α) => update_nth l n (f a)) <$> nth l n) l := sorry
theorem nth_modify_nth {α : Type u} (f : α → α) (n : ℕ) (l : List α) (m : ℕ) : nth (modify_nth f n l) m = (fun (a : α) => ite (n = m) (f a) a) <$> nth l m := sorry
theorem modify_nth_tail_length {α : Type u} (f : List α → List α) (H : ∀ (l : List α), length (f l) = length l) (n : ℕ) (l : List α) : length (modify_nth_tail f n l) = length l := sorry
@[simp] theorem modify_nth_length {α : Type u} (f : α → α) (n : ℕ) (l : List α) : length (modify_nth f n l) = length l := sorry
@[simp] theorem update_nth_length {α : Type u} (l : List α) (n : ℕ) (a : α) : length (update_nth l n a) = length l := sorry
@[simp] theorem nth_modify_nth_eq {α : Type u} (f : α → α) (n : ℕ) (l : List α) : nth (modify_nth f n l) n = f <$> nth l n := sorry
@[simp] theorem nth_modify_nth_ne {α : Type u} (f : α → α) {m : ℕ} {n : ℕ} (l : List α) (h : m ≠ n) : nth (modify_nth f m l) n = nth l n := sorry
theorem nth_update_nth_eq {α : Type u} (a : α) (n : ℕ) (l : List α) : nth (update_nth l n a) n = (fun (_x : α) => a) <$> nth l n := sorry
theorem nth_update_nth_of_lt {α : Type u} (a : α) {n : ℕ} {l : List α} (h : n < length l) : nth (update_nth l n a) n = some a :=
eq.mpr (id (Eq._oldrec (Eq.refl (nth (update_nth l n a) n = some a)) (nth_update_nth_eq a n l)))
(eq.mpr (id (Eq._oldrec (Eq.refl ((fun (_x : α) => a) <$> nth l n = some a)) (nth_le_nth h)))
(Eq.refl ((fun (_x : α) => a) <$> some (nth_le l n h))))
theorem nth_update_nth_ne {α : Type u} (a : α) {m : ℕ} {n : ℕ} (l : List α) (h : m ≠ n) : nth (update_nth l m a) n = nth l n := sorry
@[simp] theorem nth_le_update_nth_eq {α : Type u} (l : List α) (i : ℕ) (a : α) (h : i < length (update_nth l i a)) : nth_le (update_nth l i a) i h = a := sorry
@[simp] theorem nth_le_update_nth_of_ne {α : Type u} {l : List α} {i : ℕ} {j : ℕ} (h : i ≠ j) (a : α) (hj : j < length (update_nth l i a)) : nth_le (update_nth l i a) j hj =
nth_le l j
(eq.mpr (id (Eq.refl (j < length l)))
(eq.mp
((fun (ᾰ ᾰ_1 : ℕ) (e_2 : ᾰ = ᾰ_1) (ᾰ_2 ᾰ_3 : ℕ) (e_3 : ᾰ_2 = ᾰ_3) => congr (congr_arg Less e_2) e_3) j j
(Eq.refl j) (length (update_nth l i a)) (length l) (update_nth_length l i a))
hj)) := sorry
theorem mem_or_eq_of_mem_update_nth {α : Type u} {l : List α} {n : ℕ} {a : α} {b : α} (h : a ∈ update_nth l n b) : a ∈ l ∨ a = b := sorry
@[simp] theorem insert_nth_nil {α : Type u} (a : α) : insert_nth 0 a [] = [a] :=
rfl
@[simp] theorem insert_nth_succ_nil {α : Type u} (n : ℕ) (a : α) : insert_nth (n + 1) a [] = [] :=
rfl
theorem length_insert_nth {α : Type u} {a : α} (n : ℕ) (as : List α) : n ≤ length as → length (insert_nth n a as) = length as + 1 := sorry
theorem remove_nth_insert_nth {α : Type u} {a : α} (n : ℕ) (l : List α) : remove_nth (insert_nth n a l) n = l := sorry
theorem insert_nth_remove_nth_of_ge {α : Type u} {a : α} (n : ℕ) (m : ℕ) (as : List α) : n < length as → n ≤ m → insert_nth m a (remove_nth as n) = remove_nth (insert_nth (m + 1) a as) n := sorry
theorem insert_nth_remove_nth_of_le {α : Type u} {a : α} (n : ℕ) (m : ℕ) (as : List α) : n < length as → m ≤ n → insert_nth m a (remove_nth as n) = remove_nth (insert_nth m a as) (n + 1) := sorry
theorem insert_nth_comm {α : Type u} (a : α) (b : α) (i : ℕ) (j : ℕ) (l : List α) (h : i ≤ j) (hj : j ≤ length l) : insert_nth (j + 1) b (insert_nth i a l) = insert_nth i a (insert_nth j b l) := sorry
theorem mem_insert_nth {α : Type u} {a : α} {b : α} {n : ℕ} {l : List α} (hi : n ≤ length l) : a ∈ insert_nth n b l ↔ a = b ∨ a ∈ l := sorry
/-! ### map -/
@[simp] theorem map_nil {α : Type u} {β : Type v} (f : α → β) : map f [] = [] :=
rfl
theorem map_eq_foldr {α : Type u} {β : Type v} (f : α → β) (l : List α) : map f l = foldr (fun (a : α) (bs : List β) => f a :: bs) [] l := sorry
theorem map_congr {α : Type u} {β : Type v} {f : α → β} {g : α → β} {l : List α} : (∀ (x : α), x ∈ l → f x = g x) → map f l = map g l := sorry
theorem map_eq_map_iff {α : Type u} {β : Type v} {f : α → β} {g : α → β} {l : List α} : map f l = map g l ↔ ∀ (x : α), x ∈ l → f x = g x := sorry
theorem map_concat {α : Type u} {β : Type v} (f : α → β) (a : α) (l : List α) : map f (concat l a) = concat (map f l) (f a) := sorry
theorem map_id' {α : Type u} {f : α → α} (h : ∀ (x : α), f x = x) (l : List α) : map f l = l := sorry
theorem eq_nil_of_map_eq_nil {α : Type u} {β : Type v} {f : α → β} {l : List α} (h : map f l = []) : l = [] :=
eq_nil_of_length_eq_zero
(eq.mpr (id (Eq._oldrec (Eq.refl (length l = 0)) (Eq.symm (length_map f l))))
(eq.mpr (id (Eq._oldrec (Eq.refl (length (map f l) = 0)) h)) (Eq.refl (length []))))
@[simp] theorem map_join {α : Type u} {β : Type v} (f : α → β) (L : List (List α)) : map f (join L) = join (map (map f) L) := sorry
theorem bind_ret_eq_map {α : Type u} {β : Type v} (f : α → β) (l : List α) : list.bind l (list.ret ∘ f) = map f l := sorry
@[simp] theorem map_eq_map {α : Type u_1} {β : Type u_1} (f : α → β) (l : List α) : f <$> l = map f l :=
rfl
@[simp] theorem map_tail {α : Type u} {β : Type v} (f : α → β) (l : List α) : map f (tail l) = tail (map f l) :=
list.cases_on l (Eq.refl (map f (tail []))) fun (l_hd : α) (l_tl : List α) => Eq.refl (map f (tail (l_hd :: l_tl)))
@[simp] theorem map_injective_iff {α : Type u} {β : Type v} {f : α → β} : function.injective (map f) ↔ function.injective f := sorry
/--
A single `list.map` of a composition of functions is equal to
composing a `list.map` with another `list.map`, fully applied.
This is the reverse direction of `list.map_map`.
-/
theorem comp_map {α : Type u} {β : Type v} {γ : Type w} (h : β → γ) (g : α → β) (l : List α) : map (h ∘ g) l = map h (map g l) :=
Eq.symm (map_map h g l)
/--
Composing a `list.map` with another `list.map` is equal to
a single `list.map` of composed functions.
-/
@[simp] theorem map_comp_map {α : Type u} {β : Type v} {γ : Type w} (g : β → γ) (f : α → β) : map g ∘ map f = map (g ∘ f) := sorry
theorem map_filter_eq_foldr {α : Type u} {β : Type v} (f : α → β) (p : α → Prop) [decidable_pred p] (as : List α) : map f (filter p as) = foldr (fun (a : α) (bs : List β) => ite (p a) (f a :: bs) bs) [] as := sorry
theorem last_map {α : Type u} {β : Type v} (f : α → β) {l : List α} (hl : l ≠ []) : last (map f l) (mt eq_nil_of_map_eq_nil hl) = f (last l hl) := sorry
/-! ### map₂ -/
theorem nil_map₂ {α : Type u} {β : Type v} {γ : Type w} (f : α → β → γ) (l : List β) : map₂ f [] l = [] :=
list.cases_on l (Eq.refl (map₂ f [] [])) fun (l_hd : β) (l_tl : List β) => Eq.refl (map₂ f [] (l_hd :: l_tl))
theorem map₂_nil {α : Type u} {β : Type v} {γ : Type w} (f : α → β → γ) (l : List α) : map₂ f l [] = [] :=
list.cases_on l (Eq.refl (map₂ f [] [])) fun (l_hd : α) (l_tl : List α) => Eq.refl (map₂ f (l_hd :: l_tl) [])
@[simp] theorem map₂_flip {α : Type u} {β : Type v} {γ : Type w} (f : α → β → γ) (as : List α) (bs : List β) : map₂ (flip f) bs as = map₂ f as bs := sorry
/-! ### take, drop -/
@[simp] theorem take_zero {α : Type u} (l : List α) : take 0 l = [] :=
rfl
@[simp] theorem take_nil {α : Type u} (n : ℕ) : take n [] = [] :=
nat.cases_on n (idRhs (take 0 [] = take 0 []) rfl) fun (n : ℕ) => idRhs (take (n + 1) [] = take (n + 1) []) rfl
theorem take_cons {α : Type u} (n : ℕ) (a : α) (l : List α) : take (Nat.succ n) (a :: l) = a :: take n l :=
rfl
@[simp] theorem take_length {α : Type u} (l : List α) : take (length l) l = l := sorry
theorem take_all_of_le {α : Type u} {n : ℕ} {l : List α} : length l ≤ n → take n l = l := sorry
@[simp] theorem take_left {α : Type u} (l₁ : List α) (l₂ : List α) : take (length l₁) (l₁ ++ l₂) = l₁ := sorry
theorem take_left' {α : Type u} {l₁ : List α} {l₂ : List α} {n : ℕ} (h : length l₁ = n) : take n (l₁ ++ l₂) = l₁ :=
eq.mpr (id (Eq._oldrec (Eq.refl (take n (l₁ ++ l₂) = l₁)) (Eq.symm h))) (take_left l₁ l₂)
theorem take_take {α : Type u} (n : ℕ) (m : ℕ) (l : List α) : take n (take m l) = take (min n m) l := sorry
theorem take_repeat {α : Type u} (a : α) (n : ℕ) (m : ℕ) : take n (repeat a m) = repeat a (min n m) := sorry
theorem map_take {α : Type u_1} {β : Type u_2} (f : α → β) (L : List α) (i : ℕ) : map f (take i L) = take i (map f L) := sorry
theorem take_append_of_le_length {α : Type u} {l₁ : List α} {l₂ : List α} {n : ℕ} : n ≤ length l₁ → take n (l₁ ++ l₂) = take n l₁ := sorry
/-- Taking the first `l₁.length + i` elements in `l₁ ++ l₂` is the same as appending the first
`i` elements of `l₂` to `l₁`. -/
theorem take_append {α : Type u} {l₁ : List α} {l₂ : List α} (i : ℕ) : take (length l₁ + i) (l₁ ++ l₂) = l₁ ++ take i l₂ := sorry
/-- The `i`-th element of a list coincides with the `i`-th element of any of its prefixes of
length `> i`. Version designed to rewrite from the big list to the small list. -/
theorem nth_le_take {α : Type u} (L : List α) {i : ℕ} {j : ℕ} (hi : i < length L) (hj : i < j) : nth_le L i hi =
nth_le (take j L) i (eq.mpr (id (Eq._oldrec (Eq.refl (i < length (take j L))) (length_take j L))) (lt_min hj hi)) := sorry
/-- The `i`-th element of a list coincides with the `i`-th element of any of its prefixes of
length `> i`. Version designed to rewrite from the small list to the big list. -/
theorem nth_le_take' {α : Type u} (L : List α) {i : ℕ} {j : ℕ} (hi : i < length (take j L)) : nth_le (take j L) i hi =
nth_le L i
(lt_of_lt_of_le hi
(eq.mpr
(id
(Eq.trans
(Eq.trans
(Eq.trans
((fun (ᾰ ᾰ_1 : ℕ) (e_2 : ᾰ = ᾰ_1) (ᾰ_2 ᾰ_3 : ℕ) (e_3 : ᾰ_2 = ᾰ_3) => congr (congr_arg LessEq e_2) e_3)
(length (take j L)) (min j (length L)) (length_take j L) (length L) (length L) (Eq.refl (length L)))
(propext min_le_iff))
((fun (a a_1 : Prop) (e_1 : a = a_1) (b b_1 : Prop) (e_2 : b = b_1) => congr (congr_arg Or e_1) e_2)
(j ≤ length L) (j ≤ length L) (Eq.refl (j ≤ length L)) (length L ≤ length L) True
(propext ((fun {α : Type} (a : α) => iff_true_intro (le_refl a)) (length L)))))
(propext (or_true (j ≤ length L)))))
trivial)) := sorry
theorem nth_take {α : Type u} {l : List α} {n : ℕ} {m : ℕ} (h : m < n) : nth (take n l) m = nth l m := sorry
@[simp] theorem nth_take_of_succ {α : Type u} {l : List α} {n : ℕ} : nth (take (n + 1) l) n = nth l n :=
nth_take (nat.lt_succ_self n)
theorem take_succ {α : Type u} {l : List α} {n : ℕ} : take (n + 1) l = take n l ++ option.to_list (nth l n) := sorry
@[simp] theorem drop_nil {α : Type u} (n : ℕ) : drop n [] = [] :=
nat.cases_on n (idRhs (drop 0 [] = drop 0 []) rfl) fun (n : ℕ) => idRhs (drop (n + 1) [] = drop (n + 1) []) rfl
theorem mem_of_mem_drop {α : Type u_1} {n : ℕ} {l : List α} {x : α} (h : x ∈ drop n l) : x ∈ l := sorry
@[simp] theorem drop_one {α : Type u} (l : List α) : drop 1 l = tail l :=
list.cases_on l (idRhs (drop 1 [] = drop 1 []) rfl)
fun (l_hd : α) (l_tl : List α) => idRhs (drop 1 (l_hd :: l_tl) = drop 1 (l_hd :: l_tl)) rfl
theorem drop_add {α : Type u} (m : ℕ) (n : ℕ) (l : List α) : drop (m + n) l = drop m (drop n l) := sorry
@[simp] theorem drop_left {α : Type u} (l₁ : List α) (l₂ : List α) : drop (length l₁) (l₁ ++ l₂) = l₂ := sorry
theorem drop_left' {α : Type u} {l₁ : List α} {l₂ : List α} {n : ℕ} (h : length l₁ = n) : drop n (l₁ ++ l₂) = l₂ :=
eq.mpr (id (Eq._oldrec (Eq.refl (drop n (l₁ ++ l₂) = l₂)) (Eq.symm h))) (drop_left l₁ l₂)
theorem drop_eq_nth_le_cons {α : Type u} {n : ℕ} {l : List α} (h : n < length l) : drop n l = nth_le l n h :: drop (n + 1) l := sorry
@[simp] theorem drop_length {α : Type u} (l : List α) : drop (length l) l = [] := sorry
theorem drop_append_of_le_length {α : Type u} {l₁ : List α} {l₂ : List α} {n : ℕ} : n ≤ length l₁ → drop n (l₁ ++ l₂) = drop n l₁ ++ l₂ := sorry
/-- Dropping the elements up to `l₁.length + i` in `l₁ + l₂` is the same as dropping the elements
up to `i` in `l₂`. -/
theorem drop_append {α : Type u} {l₁ : List α} {l₂ : List α} (i : ℕ) : drop (length l₁ + i) (l₁ ++ l₂) = drop i l₂ := sorry
/-- The `i + j`-th element of a list coincides with the `j`-th element of the list obtained by
dropping the first `i` elements. Version designed to rewrite from the big list to the small list. -/
theorem nth_le_drop {α : Type u} (L : List α) {i : ℕ} {j : ℕ} (h : i + j < length L) : nth_le L (i + j) h =
nth_le (drop i L) j
(eq.mpr (id (Eq.refl (j < length (drop i L))))
(eq.mp
(Eq.trans
((fun (ᾰ ᾰ_1 : ℕ) (e_2 : ᾰ = ᾰ_1) (ᾰ_2 ᾰ_3 : ℕ) (e_3 : ᾰ_2 = ᾰ_3) => congr (congr_arg Less e_2) e_3) (i + j)
(i + j) (Eq.refl (i + j)) (length (take i L ++ drop i L)) (i + length (drop i L))
(Eq.trans (length_append (take i L) (drop i L))
((fun (ᾰ ᾰ_1 : ℕ) (e_2 : ᾰ = ᾰ_1) (ᾰ_2 ᾰ_3 : ℕ) (e_3 : ᾰ_2 = ᾰ_3) => congr (congr_arg Add.add e_2) e_3)
(length (take i L)) i
(Eq.trans (length_take i L)
(min_eq_left (iff.mpr (iff_true_intro (le_of_lt (lt_of_le_of_lt (nat.le.intro rfl) h))) True.intro)))
(length (drop i L)) (length (drop i L)) (Eq.refl (length (drop i L))))))
(propext (add_lt_add_iff_left i)))
(eq.mp (Eq._oldrec (Eq.refl (i + j < length L)) (Eq.symm (take_append_drop i L))) h))) := sorry
/-- The `i + j`-th element of a list coincides with the `j`-th element of the list obtained by
dropping the first `i` elements. Version designed to rewrite from the small list to the big list. -/
theorem nth_le_drop' {α : Type u} (L : List α) {i : ℕ} {j : ℕ} (h : j < length (drop i L)) : nth_le (drop i L) j h = nth_le L (i + j) (nat.add_lt_of_lt_sub_left (length_drop i L ▸ h)) := sorry
@[simp] theorem drop_drop {α : Type u} (n : ℕ) (m : ℕ) (l : List α) : drop n (drop m l) = drop (n + m) l := sorry
theorem drop_take {α : Type u} (m : ℕ) (n : ℕ) (l : List α) : drop m (take (m + n) l) = take n (drop m l) := sorry
theorem map_drop {α : Type u_1} {β : Type u_2} (f : α → β) (L : List α) (i : ℕ) : map f (drop i L) = drop i (map f L) := sorry
theorem modify_nth_tail_eq_take_drop {α : Type u} (f : List α → List α) (H : f [] = []) (n : ℕ) (l : List α) : modify_nth_tail f n l = take n l ++ f (drop n l) := sorry
theorem modify_nth_eq_take_drop {α : Type u} (f : α → α) (n : ℕ) (l : List α) : modify_nth f n l = take n l ++ modify_head f (drop n l) :=
modify_nth_tail_eq_take_drop (modify_head f) rfl
theorem modify_nth_eq_take_cons_drop {α : Type u} (f : α → α) {n : ℕ} {l : List α} (h : n < length l) : modify_nth f n l = take n l ++ f (nth_le l n h) :: drop (n + 1) l := sorry
theorem update_nth_eq_take_cons_drop {α : Type u} (a : α) {n : ℕ} {l : List α} (h : n < length l) : update_nth l n a = take n l ++ a :: drop (n + 1) l := sorry
theorem reverse_take {α : Type u_1} {xs : List α} (n : ℕ) (h : n ≤ length xs) : take n (reverse xs) = reverse (drop (length xs - n) xs) := sorry
@[simp] theorem update_nth_eq_nil {α : Type u} (l : List α) (n : ℕ) (a : α) : update_nth l n a = [] ↔ l = [] := sorry
@[simp] theorem take'_length {α : Type u} [Inhabited α] (n : ℕ) (l : List α) : length (take' n l) = n := sorry
@[simp] theorem take'_nil {α : Type u} [Inhabited α] (n : ℕ) : take' n [] = repeat Inhabited.default n := sorry
theorem take'_eq_take {α : Type u} [Inhabited α] {n : ℕ} {l : List α} : n ≤ length l → take' n l = take n l := sorry
@[simp] theorem take'_left {α : Type u} [Inhabited α] (l₁ : List α) (l₂ : List α) : take' (length l₁) (l₁ ++ l₂) = l₁ := sorry
theorem take'_left' {α : Type u} [Inhabited α] {l₁ : List α} {l₂ : List α} {n : ℕ} (h : length l₁ = n) : take' n (l₁ ++ l₂) = l₁ :=
eq.mpr (id (Eq._oldrec (Eq.refl (take' n (l₁ ++ l₂) = l₁)) (Eq.symm h))) (take'_left l₁ l₂)
/-! ### foldl, foldr -/
theorem foldl_ext {α : Type u} {β : Type v} (f : α → β → α) (g : α → β → α) (a : α) {l : List β} (H : ∀ (a : α) (b : β), b ∈ l → f a b = g a b) : foldl f a l = foldl g a l := sorry
theorem foldr_ext {α : Type u} {β : Type v} (f : α → β → β) (g : α → β → β) (b : β) {l : List α} (H : ∀ (a : α), a ∈ l → ∀ (b : β), f a b = g a b) : foldr f b l = foldr g b l := sorry
@[simp] theorem foldl_nil {α : Type u} {β : Type v} (f : α → β → α) (a : α) : foldl f a [] = a :=
rfl
@[simp] theorem foldl_cons {α : Type u} {β : Type v} (f : α → β → α) (a : α) (b : β) (l : List β) : foldl f a (b :: l) = foldl f (f a b) l :=
rfl
@[simp] theorem foldr_nil {α : Type u} {β : Type v} (f : α → β → β) (b : β) : foldr f b [] = b :=
rfl
@[simp] theorem foldr_cons {α : Type u} {β : Type v} (f : α → β → β) (b : β) (a : α) (l : List α) : foldr f b (a :: l) = f a (foldr f b l) :=
rfl
@[simp] theorem foldl_append {α : Type u} {β : Type v} (f : α → β → α) (a : α) (l₁ : List β) (l₂ : List β) : foldl f a (l₁ ++ l₂) = foldl f (foldl f a l₁) l₂ := sorry
@[simp] theorem foldr_append {α : Type u} {β : Type v} (f : α → β → β) (b : β) (l₁ : List α) (l₂ : List α) : foldr f b (l₁ ++ l₂) = foldr f (foldr f b l₂) l₁ := sorry
@[simp] theorem foldl_join {α : Type u} {β : Type v} (f : α → β → α) (a : α) (L : List (List β)) : foldl f a (join L) = foldl (foldl f) a L := sorry
@[simp] theorem foldr_join {α : Type u} {β : Type v} (f : α → β → β) (b : β) (L : List (List α)) : foldr f b (join L) = foldr (fun (l : List α) (b : β) => foldr f b l) b L := sorry
theorem foldl_reverse {α : Type u} {β : Type v} (f : α → β → α) (a : α) (l : List β) : foldl f a (reverse l) = foldr (fun (x : β) (y : α) => f y x) a l := sorry
theorem foldr_reverse {α : Type u} {β : Type v} (f : α → β → β) (a : β) (l : List α) : foldr f a (reverse l) = foldl (fun (x : β) (y : α) => f y x) a l := sorry
@[simp] theorem foldr_eta {α : Type u} (l : List α) : foldr List.cons [] l = l := sorry
@[simp] theorem reverse_foldl {α : Type u} {l : List α} : reverse (foldl (fun (t : List α) (h : α) => h :: t) [] l) = l := sorry
@[simp] theorem foldl_map {α : Type u} {β : Type v} {γ : Type w} (g : β → γ) (f : α → γ → α) (a : α) (l : List β) : foldl f a (map g l) = foldl (fun (x : α) (y : β) => f x (g y)) a l := sorry
@[simp] theorem foldr_map {α : Type u} {β : Type v} {γ : Type w} (g : β → γ) (f : γ → α → α) (a : α) (l : List β) : foldr f a (map g l) = foldr (f ∘ g) a l := sorry
theorem foldl_map' {α : Type u} {β : Type u} (g : α → β) (f : α → α → α) (f' : β → β → β) (a : α) (l : List α) (h : ∀ (x y : α), f' (g x) (g y) = g (f x y)) : foldl f' (g a) (map g l) = g (foldl f a l) := sorry
theorem foldr_map' {α : Type u} {β : Type u} (g : α → β) (f : α → α → α) (f' : β → β → β) (a : α) (l : List α) (h : ∀ (x y : α), f' (g x) (g y) = g (f x y)) : foldr f' (g a) (map g l) = g (foldr f a l) := sorry
theorem foldl_hom {α : Type u} {β : Type v} {γ : Type w} (l : List γ) (f : α → β) (op : α → γ → α) (op' : β → γ → β) (a : α) (h : ∀ (a : α) (x : γ), f (op a x) = op' (f a) x) : foldl op' (f a) l = f (foldl op a l) := sorry
theorem foldr_hom {α : Type u} {β : Type v} {γ : Type w} (l : List γ) (f : α → β) (op : γ → α → α) (op' : γ → β → β) (a : α) (h : ∀ (x : γ) (a : α), f (op x a) = op' x (f a)) : foldr op' (f a) l = f (foldr op a l) := sorry
theorem injective_foldl_comp {α : Type u_1} {l : List (α → α)} {f : α → α} (hl : ∀ (f : α → α), f ∈ l → function.injective f) (hf : function.injective f) : function.injective (foldl function.comp f l) := sorry
/- scanl -/
theorem length_scanl {α : Type u} {β : Type v} {f : β → α → β} (a : β) (l : List α) : length (scanl f a l) = length l + 1 := sorry
@[simp] theorem scanl_nil {α : Type u} {β : Type v} {f : β → α → β} (b : β) : scanl f b [] = [b] :=
rfl
@[simp] theorem scanl_cons {α : Type u} {β : Type v} {f : β → α → β} {b : β} {a : α} {l : List α} : scanl f b (a :: l) = [b] ++ scanl f (f b a) l := sorry
@[simp] theorem nth_zero_scanl {α : Type u} {β : Type v} {f : β → α → β} {b : β} {l : List α} : nth (scanl f b l) 0 = some b := sorry
@[simp] theorem nth_le_zero_scanl {α : Type u} {β : Type v} {f : β → α → β} {b : β} {l : List α} {h : 0 < length (scanl f b l)} : nth_le (scanl f b l) 0 h = b := sorry
theorem nth_succ_scanl {α : Type u} {β : Type v} {f : β → α → β} {b : β} {l : List α} {i : ℕ} : nth (scanl f b l) (i + 1) = option.bind (nth (scanl f b l) i) fun (x : β) => option.map (fun (y : α) => f x y) (nth l i) := sorry
theorem nth_le_succ_scanl {α : Type u} {β : Type v} {f : β → α → β} {b : β} {l : List α} {i : ℕ} {h : i + 1 < length (scanl f b l)} : nth_le (scanl f b l) (i + 1) h =
f (nth_le (scanl f b l) i (nat.lt_of_succ_lt h))
(nth_le l i (nat.lt_of_succ_lt_succ (lt_of_lt_of_le h (le_of_eq (length_scanl b l))))) := sorry
/- scanr -/
@[simp] theorem scanr_nil {α : Type u} {β : Type v} (f : α → β → β) (b : β) : scanr f b [] = [b] :=
rfl
@[simp] theorem scanr_aux_cons {α : Type u} {β : Type v} (f : α → β → β) (b : β) (a : α) (l : List α) : scanr_aux f b (a :: l) = (foldr f b (a :: l), scanr f b l) := sorry
@[simp] theorem scanr_cons {α : Type u} {β : Type v} (f : α → β → β) (b : β) (a : α) (l : List α) : scanr f b (a :: l) = foldr f b (a :: l) :: scanr f b l := sorry
-- foldl and foldr coincide when f is commutative and associative
theorem foldl1_eq_foldr1 {α : Type u} {f : α → α → α} (hassoc : associative f) (a : α) (b : α) (l : List α) : foldl f a (l ++ [b]) = foldr f b (a :: l) := sorry
theorem foldl_eq_of_comm_of_assoc {α : Type u} {f : α → α → α} (hcomm : commutative f) (hassoc : associative f) (a : α) (b : α) (l : List α) : foldl f a (b :: l) = f b (foldl f a l) := sorry
theorem foldl_eq_foldr {α : Type u} {f : α → α → α} (hcomm : commutative f) (hassoc : associative f) (a : α) (l : List α) : foldl f a l = foldr f a l := sorry
theorem foldl_eq_of_comm' {α : Type u} {β : Type v} {f : α → β → α} (hf : ∀ (a : α) (b c : β), f (f a b) c = f (f a c) b) (a : α) (b : β) (l : List β) : foldl f a (b :: l) = f (foldl f a l) b := sorry
theorem foldl_eq_foldr' {α : Type u} {β : Type v} {f : α → β → α} (hf : ∀ (a : α) (b c : β), f (f a b) c = f (f a c) b) (a : α) (l : List β) : foldl f a l = foldr (flip f) a l := sorry
theorem foldr_eq_of_comm' {α : Type u} {β : Type v} {f : α → β → β} (hf : ∀ (a b : α) (c : β), f a (f b c) = f b (f a c)) (a : β) (b : α) (l : List α) : foldr f a (b :: l) = foldr f (f b a) l := sorry
theorem foldl_assoc {α : Type u} {op : α → α → α} [ha : is_associative α op] {l : List α} {a₁ : α} {a₂ : α} : foldl op (op a₁ a₂) l = op a₁ (foldl op a₂ l) := sorry
theorem foldl_op_eq_op_foldr_assoc {α : Type u} {op : α → α → α} [ha : is_associative α op] {l : List α} {a₁ : α} {a₂ : α} : op (foldl op a₁ l) a₂ = op a₁ (foldr op a₂ l) := sorry
theorem foldl_assoc_comm_cons {α : Type u} {op : α → α → α} [ha : is_associative α op] [hc : is_commutative α op] {l : List α} {a₁ : α} {a₂ : α} : foldl op a₂ (a₁ :: l) = op a₁ (foldl op a₂ l) := sorry
/-! ### mfoldl, mfoldr, mmap -/
@[simp] theorem mfoldl_nil {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : β → α → m β) {b : β} : mfoldl f b [] = pure b :=
rfl
@[simp] theorem mfoldr_nil {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : α → β → m β) {b : β} : mfoldr f b [] = pure b :=
rfl
@[simp] theorem mfoldl_cons {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] {f : β → α → m β} {b : β} {a : α} {l : List α} : mfoldl f b (a :: l) =
do
let b' ← f b a
mfoldl f b' l :=
rfl
@[simp] theorem mfoldr_cons {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] {f : α → β → m β} {b : β} {a : α} {l : List α} : mfoldr f b (a :: l) = mfoldr f b l >>= f a :=
rfl
theorem mfoldr_eq_foldr {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : α → β → m β) (b : β) (l : List α) : mfoldr f b l = foldr (fun (a : α) (mb : m β) => mb >>= f a) (pure b) l := sorry
theorem mfoldl_eq_foldl {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] [is_lawful_monad m] (f : β → α → m β) (b : β) (l : List α) : mfoldl f b l =
foldl
(fun (mb : m β) (a : α) =>
do
let b ← mb
f b a)
(pure b) l := sorry
@[simp] theorem mfoldl_append {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] [is_lawful_monad m] {f : β → α → m β} {b : β} {l₁ : List α} {l₂ : List α} : mfoldl f b (l₁ ++ l₂) =
do
let x ← mfoldl f b l₁
mfoldl f x l₂ := sorry
@[simp] theorem mfoldr_append {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] [is_lawful_monad m] {f : α → β → m β} {b : β} {l₁ : List α} {l₂ : List α} : mfoldr f b (l₁ ++ l₂) =
do
let x ← mfoldr f b l₂
mfoldr f x l₁ := sorry
/-! ### prod and sum -/
-- list.sum was already defined in defs.lean, but we couldn't tag it with `to_additive` yet.
@[simp] theorem sum_nil {α : Type u} [add_monoid α] : sum [] = 0 :=
rfl
theorem sum_singleton {α : Type u} [add_monoid α] {a : α} : sum [a] = a :=
zero_add a
@[simp] theorem prod_cons {α : Type u} [monoid α] {l : List α} {a : α} : prod (a :: l) = a * prod l := sorry
@[simp] theorem sum_append {α : Type u} [add_monoid α] {l₁ : List α} {l₂ : List α} : sum (l₁ ++ l₂) = sum l₁ + sum l₂ := sorry
@[simp] theorem sum_join {α : Type u} [add_monoid α] {l : List (List α)} : sum (join l) = sum (map sum l) := sorry
theorem prod_ne_zero {R : Type u_1} [domain R] {L : List R} : (∀ (x : R), x ∈ L → x ≠ 0) → prod L ≠ 0 := sorry
theorem prod_eq_foldr {α : Type u} [monoid α] {l : List α} : prod l = foldr Mul.mul 1 l := sorry
theorem prod_hom_rel {α : Type u_1} {β : Type u_2} {γ : Type u_3} [monoid β] [monoid γ] (l : List α) {r : β → γ → Prop} {f : α → β} {g : α → γ} (h₁ : r 1 1) (h₂ : ∀ {a : α} {b : β} {c : γ}, r b c → r (f a * b) (g a * c)) : r (prod (map f l)) (prod (map g l)) := sorry
theorem prod_hom {α : Type u} {β : Type v} [monoid α] [monoid β] (l : List α) (f : α →* β) : prod (map (⇑f) l) = coe_fn f (prod l) := sorry
-- `to_additive` chokes on the next few lemmas, so we do them by hand below
@[simp] theorem prod_take_mul_prod_drop {α : Type u} [monoid α] (L : List α) (i : ℕ) : prod (take i L) * prod (drop i L) = prod L := sorry
@[simp] theorem prod_take_succ {α : Type u} [monoid α] (L : List α) (i : ℕ) (p : i < length L) : prod (take (i + 1) L) = prod (take i L) * nth_le L i p := sorry
/-- A list with product not one must have positive length. -/
theorem length_pos_of_prod_ne_one {α : Type u} [monoid α] (L : List α) (h : prod L ≠ 1) : 0 < length L := sorry
theorem prod_update_nth {α : Type u} [monoid α] (L : List α) (n : ℕ) (a : α) : prod (update_nth L n a) = prod (take n L) * ite (n < length L) a 1 * prod (drop (n + 1) L) := sorry
/-- This is the `list.prod` version of `mul_inv_rev` -/
theorem sum_neg_reverse {α : Type u} [add_group α] (L : List α) : -sum L = sum (reverse (map (fun (x : α) => -x) L)) := sorry
/-- A non-commutative variant of `list.prod_reverse` -/
theorem prod_reverse_noncomm {α : Type u} [group α] (L : List α) : prod (reverse L) = (prod (map (fun (x : α) => x⁻¹) L)⁻¹) := sorry
/-- This is the `list.prod` version of `mul_inv` -/
theorem sum_neg {α : Type u} [add_comm_group α] (L : List α) : -sum L = sum (map (fun (x : α) => -x) L) := sorry
@[simp] theorem sum_take_add_sum_drop {α : Type u} [add_monoid α] (L : List α) (i : ℕ) : sum (take i L) + sum (drop i L) = sum L := sorry
@[simp] theorem sum_take_succ {α : Type u} [add_monoid α] (L : List α) (i : ℕ) (p : i < length L) : sum (take (i + 1) L) = sum (take i L) + nth_le L i p := sorry
theorem eq_of_sum_take_eq {α : Type u} [add_left_cancel_monoid α] {L : List α} {L' : List α} (h : length L = length L') (h' : ∀ (i : ℕ), i ≤ length L → sum (take i L) = sum (take i L')) : L = L' := sorry
theorem monotone_sum_take {α : Type u} [canonically_ordered_add_monoid α] (L : List α) : monotone fun (i : ℕ) => sum (take i L) := sorry
theorem one_le_prod_of_one_le {α : Type u} [ordered_comm_monoid α] {l : List α} (hl₁ : ∀ (x : α), x ∈ l → 1 ≤ x) : 1 ≤ prod l := sorry
theorem single_le_prod {α : Type u} [ordered_comm_monoid α] {l : List α} (hl₁ : ∀ (x : α), x ∈ l → 1 ≤ x) (x : α) (H : x ∈ l) : x ≤ prod l := sorry
theorem all_zero_of_le_zero_le_of_sum_eq_zero {α : Type u} [ordered_add_comm_monoid α] {l : List α} (hl₁ : ∀ (x : α), x ∈ l → 0 ≤ x) (hl₂ : sum l = 0) (x : α) (H : x ∈ l) : x = 0 :=
le_antisymm (hl₂ ▸ single_le_sum hl₁ x hx) (hl₁ x hx)
theorem sum_eq_zero_iff {α : Type u} [canonically_ordered_add_monoid α] (l : List α) : sum l = 0 ↔ ∀ (x : α), x ∈ l → x = 0 := sorry
/-- A list with sum not zero must have positive length. -/
theorem length_pos_of_sum_ne_zero {α : Type u} [add_monoid α] (L : List α) (h : sum L ≠ 0) : 0 < length L := sorry
/-- If all elements in a list are bounded below by `1`, then the length of the list is bounded
by the sum of the elements. -/
theorem length_le_sum_of_one_le (L : List ℕ) (h : ∀ (i : ℕ), i ∈ L → 1 ≤ i) : length L ≤ sum L := sorry
-- Now we tie those lemmas back to their multiplicative versions.
/-- A list with positive sum must have positive length. -/
-- This is an easy consequence of `length_pos_of_sum_ne_zero`, but often useful in applications.
theorem length_pos_of_sum_pos {α : Type u} [ordered_cancel_add_comm_monoid α] (L : List α) (h : 0 < sum L) : 0 < length L :=
length_pos_of_sum_ne_zero L (ne_of_gt h)
@[simp] theorem prod_erase {α : Type u} [DecidableEq α] [comm_monoid α] {a : α} {l : List α} : a ∈ l → a * prod (list.erase l a) = prod l := sorry
theorem dvd_prod {α : Type u} [comm_monoid α] {a : α} {l : List α} (ha : a ∈ l) : a ∣ prod l := sorry
@[simp] theorem sum_const_nat (m : ℕ) (n : ℕ) : sum (repeat m n) = m * n := sorry
theorem dvd_sum {α : Type u} [comm_semiring α] {a : α} {l : List α} (h : ∀ (x : α), x ∈ l → a ∣ x) : a ∣ sum l := sorry
@[simp] theorem length_join {α : Type u} (L : List (List α)) : length (join L) = sum (map length L) := sorry
@[simp] theorem length_bind {α : Type u} {β : Type v} (l : List α) (f : α → List β) : length (list.bind l f) = sum (map (length ∘ f) l) := sorry
theorem exists_lt_of_sum_lt {α : Type u} {β : Type v} [linear_ordered_cancel_add_comm_monoid β] {l : List α} (f : α → β) (g : α → β) (h : sum (map f l) < sum (map g l)) : ∃ (x : α), ∃ (H : x ∈ l), f x < g x := sorry
theorem exists_le_of_sum_le {α : Type u} {β : Type v} [linear_ordered_cancel_add_comm_monoid β] {l : List α} (hl : l ≠ []) (f : α → β) (g : α → β) (h : sum (map f l) ≤ sum (map g l)) : ∃ (x : α), ∃ (H : x ∈ l), f x ≤ g x := sorry
-- Several lemmas about sum/head/tail for `list ℕ`.
-- These are hard to generalize well, as they rely on the fact that `default ℕ = 0`.
-- We'd like to state this as `L.head * L.tail.prod = L.prod`,
-- but because `L.head` relies on an inhabited instances and
-- returns a garbage value for the empty list, this is not possible.
-- Instead we write the statement in terms of `(L.nth 0).get_or_else 1`,
-- and below, restate the lemma just for `ℕ`.
theorem head_mul_tail_prod' {α : Type u} [monoid α] (L : List α) : option.get_or_else (nth L 0) 1 * prod (tail L) = prod L := sorry
theorem head_add_tail_sum (L : List ℕ) : head L + sum (tail L) = sum L := sorry
theorem head_le_sum (L : List ℕ) : head L ≤ sum L :=
nat.le.intro (head_add_tail_sum L)
theorem tail_sum (L : List ℕ) : sum (tail L) = sum L - head L := sorry
@[simp] theorem alternating_prod_nil {G : Type u_1} [comm_group G] : alternating_prod [] = 1 :=
rfl
@[simp] theorem alternating_sum_singleton {G : Type u_1} [add_comm_group G] (g : G) : alternating_sum [g] = g :=
rfl
@[simp] theorem alternating_sum_cons_cons' {G : Type u_1} [add_comm_group G] (g : G) (h : G) (l : List G) : alternating_sum (g :: h :: l) = g + -h + alternating_sum l :=
rfl
theorem alternating_sum_cons_cons {G : Type u_1} [add_comm_group G] (g : G) (h : G) (l : List G) : alternating_sum (g :: h :: l) = g - h + alternating_sum l := sorry
/-! ### join -/
theorem join_eq_nil {α : Type u} {L : List (List α)} : join L = [] ↔ ∀ (l : List α), l ∈ L → l = [] := sorry
@[simp] theorem join_append {α : Type u} (L₁ : List (List α)) (L₂ : List (List α)) : join (L₁ ++ L₂) = join L₁ ++ join L₂ := sorry
theorem join_join {α : Type u} (l : List (List (List α))) : join (join l) = join (map join l) := sorry
/-- In a join, taking the first elements up to an index which is the sum of the lengths of the
first `i` sublists, is the same as taking the join of the first `i` sublists. -/
theorem take_sum_join {α : Type u} (L : List (List α)) (i : ℕ) : take (sum (take i (map length L))) (join L) = join (take i L) := sorry
/-- In a join, dropping all the elements up to an index which is the sum of the lengths of the
first `i` sublists, is the same as taking the join after dropping the first `i` sublists. -/
theorem drop_sum_join {α : Type u} (L : List (List α)) (i : ℕ) : drop (sum (take i (map length L))) (join L) = join (drop i L) := sorry
/-- Taking only the first `i+1` elements in a list, and then dropping the first `i` ones, one is
left with a list of length `1` made of the `i`-th element of the original list. -/
theorem drop_take_succ_eq_cons_nth_le {α : Type u} (L : List α) {i : ℕ} (hi : i < length L) : drop i (take (i + 1) L) = [nth_le L i hi] := sorry
/-- In a join of sublists, taking the slice between the indices `A` and `B - 1` gives back the
original sublist of index `i` if `A` is the sum of the lenghts of sublists of index `< i`, and
`B` is the sum of the lengths of sublists of index `≤ i`. -/
theorem drop_take_succ_join_eq_nth_le {α : Type u} (L : List (List α)) {i : ℕ} (hi : i < length L) : drop (sum (take i (map length L))) (take (sum (take (i + 1) (map length L))) (join L)) = nth_le L i hi := sorry
/-- Auxiliary lemma to control elements in a join. -/
theorem sum_take_map_length_lt1 {α : Type u} (L : List (List α)) {i : ℕ} {j : ℕ} (hi : i < length L) (hj : j < length (nth_le L i hi)) : sum (take i (map length L)) + j < sum (take (i + 1) (map length L)) := sorry
/-- Auxiliary lemma to control elements in a join. -/
theorem sum_take_map_length_lt2 {α : Type u} (L : List (List α)) {i : ℕ} {j : ℕ} (hi : i < length L) (hj : j < length (nth_le L i hi)) : sum (take i (map length L)) + j < length (join L) := sorry
/-- The `n`-th element in a join of sublists is the `j`-th element of the `i`th sublist,
where `n` can be obtained in terms of `i` and `j` by adding the lengths of all the sublists
of index `< i`, and adding `j`. -/
theorem nth_le_join {α : Type u} (L : List (List α)) {i : ℕ} {j : ℕ} (hi : i < length L) (hj : j < length (nth_le L i hi)) : nth_le (join L) (sum (take i (map length L)) + j) (sum_take_map_length_lt2 L hi hj) = nth_le (nth_le L i hi) j hj := sorry
/-- Two lists of sublists are equal iff their joins coincide, as well as the lengths of the
sublists. -/
theorem eq_iff_join_eq {α : Type u} (L : List (List α)) (L' : List (List α)) : L = L' ↔ join L = join L' ∧ map length L = map length L' := sorry
/-! ### lexicographic ordering -/
/-- Given a strict order `<` on `α`, the lexicographic strict order on `list α`, for which
`[a0, ..., an] < [b0, ..., b_k]` if `a0 < b0` or `a0 = b0` and `[a1, ..., an] < [b1, ..., bk]`.
The definition is given for any relation `r`, not only strict orders. -/
inductive lex {α : Type u} (r : α → α → Prop) : List α → List α → Prop
where
| nil : ∀ {a : α} {l : List α}, lex r [] (a :: l)
| cons : ∀ {a : α} {l₁ l₂ : List α}, lex r l₁ l₂ → lex r (a :: l₁) (a :: l₂)
| rel : ∀ {a₁ : α} {l₁ : List α} {a₂ : α} {l₂ : List α}, r a₁ a₂ → lex r (a₁ :: l₁) (a₂ :: l₂)
namespace lex
theorem cons_iff {α : Type u} {r : α → α → Prop} [is_irrefl α r] {a : α} {l₁ : List α} {l₂ : List α} : lex r (a :: l₁) (a :: l₂) ↔ lex r l₁ l₂ := sorry
@[simp] theorem not_nil_right {α : Type u} (r : α → α → Prop) (l : List α) : ¬lex r l [] := sorry
protected instance is_order_connected {α : Type u} (r : α → α → Prop) [is_order_connected α r] [is_trichotomous α r] : is_order_connected (List α) (lex r) :=
is_order_connected.mk fun (l₁ : List α) => sorry
protected instance is_trichotomous {α : Type u} (r : α → α → Prop) [is_trichotomous α r] : is_trichotomous (List α) (lex r) :=
is_trichotomous.mk fun (l₁ : List α) => sorry
protected instance is_asymm {α : Type u} (r : α → α → Prop) [is_asymm α r] : is_asymm (List α) (lex r) :=
is_asymm.mk fun (l₁ : List α) => sorry
protected instance is_strict_total_order {α : Type u} (r : α → α → Prop) [is_strict_total_order' α r] : is_strict_total_order' (List α) (lex r) :=
is_strict_total_order'.mk
protected instance decidable_rel {α : Type u} [DecidableEq α] (r : α → α → Prop) [DecidableRel r] : DecidableRel (lex r) :=
sorry
theorem append_right {α : Type u} (r : α → α → Prop) {s₁ : List α} {s₂ : List α} (t : List α) : lex r s₁ s₂ → lex r s₁ (s₂ ++ t) := sorry
theorem append_left {α : Type u} (R : α → α → Prop) {t₁ : List α} {t₂ : List α} (h : lex R t₁ t₂) (s : List α) : lex R (s ++ t₁) (s ++ t₂) := sorry
theorem imp {α : Type u} {r : α → α → Prop} {s : α → α → Prop} (H : ∀ (a b : α), r a b → s a b) (l₁ : List α) (l₂ : List α) : lex r l₁ l₂ → lex s l₁ l₂ := sorry
theorem to_ne {α : Type u} {l₁ : List α} {l₂ : List α} : lex ne l₁ l₂ → l₁ ≠ l₂ := sorry
theorem ne_iff {α : Type u} {l₁ : List α} {l₂ : List α} (H : length l₁ ≤ length l₂) : lex ne l₁ l₂ ↔ l₁ ≠ l₂ := sorry
end lex
--Note: this overrides an instance in core lean
protected instance has_lt' {α : Type u} [HasLess α] : HasLess (List α) :=
{ Less := lex Less }
theorem nil_lt_cons {α : Type u} [HasLess α] (a : α) (l : List α) : [] < a :: l :=
lex.nil
protected instance linear_order {α : Type u} [linear_order α] : linear_order (List α) :=
linear_order_of_STO' (lex Less)
--Note: this overrides an instance in core lean
protected instance has_le' {α : Type u} [linear_order α] : HasLessEq (List α) :=
preorder.to_has_le (List α)
/-! ### all & any -/
@[simp] theorem all_nil {α : Type u} (p : α → Bool) : all [] p = tt :=
rfl
@[simp] theorem all_cons {α : Type u} (p : α → Bool) (a : α) (l : List α) : all (a :: l) p = p a && all l p :=
rfl
theorem all_iff_forall {α : Type u} {p : α → Bool} {l : List α} : ↥(all l p) ↔ ∀ (a : α), a ∈ l → ↥(p a) := sorry
theorem all_iff_forall_prop {α : Type u} {p : α → Prop} [decidable_pred p] {l : List α} : ↥(all l fun (a : α) => to_bool (p a)) ↔ ∀ (a : α), a ∈ l → p a := sorry
@[simp] theorem any_nil {α : Type u} (p : α → Bool) : any [] p = false :=
rfl
@[simp] theorem any_cons {α : Type u} (p : α → Bool) (a : α) (l : List α) : any (a :: l) p = p a || any l p :=
rfl
theorem any_iff_exists {α : Type u} {p : α → Bool} {l : List α} : ↥(any l p) ↔ ∃ (a : α), ∃ (H : a ∈ l), ↥(p a) := sorry
theorem any_iff_exists_prop {α : Type u} {p : α → Prop} [decidable_pred p] {l : List α} : ↥(any l fun (a : α) => to_bool (p a)) ↔ ∃ (a : α), ∃ (H : a ∈ l), p a := sorry
theorem any_of_mem {α : Type u} {p : α → Bool} {a : α} {l : List α} (h₁ : a ∈ l) (h₂ : ↥(p a)) : ↥(any l p) :=
iff.mpr any_iff_exists (Exists.intro a (Exists.intro h₁ h₂))
protected instance decidable_forall_mem {α : Type u} {p : α → Prop} [decidable_pred p] (l : List α) : Decidable (∀ (x : α), x ∈ l → p x) :=
decidable_of_iff ↥(all l fun (a : α) => to_bool (p a)) sorry
protected instance decidable_exists_mem {α : Type u} {p : α → Prop} [decidable_pred p] (l : List α) : Decidable (∃ (x : α), ∃ (H : x ∈ l), p x) :=
decidable_of_iff ↥(any l fun (a : α) => to_bool (p a)) sorry
/-! ### map for partial functions -/
/-- Partial map. If `f : Π a, p a → β` is a partial function defined on
`a : α` satisfying `p`, then `pmap f l h` is essentially the same as `map f l`
but is defined only when all members of `l` satisfy `p`, using the proof
to apply `f`. -/
@[simp] def pmap {α : Type u} {β : Type v} {p : α → Prop} (f : (a : α) → p a → β) (l : List α) : (∀ (a : α), a ∈ l → p a) → List β :=
sorry
/-- "Attach" the proof that the elements of `l` are in `l` to produce a new list
with the same elements but in the type `{x // x ∈ l}`. -/
def attach {α : Type u} (l : List α) : List (Subtype fun (x : α) => x ∈ l) :=
pmap Subtype.mk l sorry
theorem sizeof_lt_sizeof_of_mem {α : Type u} [SizeOf α] {x : α} {l : List α} (hx : x ∈ l) : sizeof x < sizeof l := sorry
theorem pmap_eq_map {α : Type u} {β : Type v} (p : α → Prop) (f : α → β) (l : List α) (H : ∀ (a : α), a ∈ l → p a) : pmap (fun (a : α) (_x : p a) => f a) l H = map f l := sorry
theorem pmap_congr {α : Type u} {β : Type v} {p : α → Prop} {q : α → Prop} {f : (a : α) → p a → β} {g : (a : α) → q a → β} (l : List α) {H₁ : ∀ (a : α), a ∈ l → p a} {H₂ : ∀ (a : α), a ∈ l → q a} (h : ∀ (a : α) (h₁ : p a) (h₂ : q a), f a h₁ = g a h₂) : pmap f l H₁ = pmap g l H₂ := sorry
theorem map_pmap {α : Type u} {β : Type v} {γ : Type w} {p : α → Prop} (g : β → γ) (f : (a : α) → p a → β) (l : List α) (H : ∀ (a : α), a ∈ l → p a) : map g (pmap f l H) = pmap (fun (a : α) (h : p a) => g (f a h)) l H := sorry
theorem pmap_map {α : Type u} {β : Type v} {γ : Type w} {p : β → Prop} (g : (b : β) → p b → γ) (f : α → β) (l : List α) (H : ∀ (a : β), a ∈ map f l → p a) : pmap g (map f l) H =
pmap (fun (a : α) (h : p (f a)) => g (f a) h) l fun (a : α) (h : a ∈ l) => H (f a) (mem_map_of_mem f h) := sorry
theorem pmap_eq_map_attach {α : Type u} {β : Type v} {p : α → Prop} (f : (a : α) → p a → β) (l : List α) (H : ∀ (a : α), a ∈ l → p a) : pmap f l H =
map (fun (x : Subtype fun (x : α) => x ∈ l) => f (subtype.val x) (H (subtype.val x) (subtype.property x))) (attach l) := sorry
theorem attach_map_val {α : Type u} (l : List α) : map subtype.val (attach l) = l := sorry
@[simp] theorem mem_attach {α : Type u} (l : List α) (x : Subtype fun (x : α) => x ∈ l) : x ∈ attach l := sorry
@[simp] theorem mem_pmap {α : Type u} {β : Type v} {p : α → Prop} {f : (a : α) → p a → β} {l : List α} {H : ∀ (a : α), a ∈ l → p a} {b : β} : b ∈ pmap f l H ↔ ∃ (a : α), ∃ (h : a ∈ l), f a (H a h) = b := sorry
@[simp] theorem length_pmap {α : Type u} {β : Type v} {p : α → Prop} {f : (a : α) → p a → β} {l : List α} {H : ∀ (a : α), a ∈ l → p a} : length (pmap f l H) = length l := sorry
@[simp] theorem length_attach {α : Type u} (L : List α) : length (attach L) = length L :=
length_pmap
@[simp] theorem pmap_eq_nil {α : Type u} {β : Type v} {p : α → Prop} {f : (a : α) → p a → β} {l : List α} {H : ∀ (a : α), a ∈ l → p a} : pmap f l H = [] ↔ l = [] :=
eq.mpr (id (Eq._oldrec (Eq.refl (pmap f l H = [] ↔ l = [])) (Eq.symm (propext length_eq_zero))))
(eq.mpr (id (Eq._oldrec (Eq.refl (length (pmap f l H) = 0 ↔ l = [])) length_pmap))
(eq.mpr (id (Eq._oldrec (Eq.refl (length l = 0 ↔ l = [])) (propext length_eq_zero))) (iff.refl (l = []))))
@[simp] theorem attach_eq_nil {α : Type u} (l : List α) : attach l = [] ↔ l = [] :=
pmap_eq_nil
theorem last_pmap {α : Type u_1} {β : Type u_2} (p : α → Prop) (f : (a : α) → p a → β) (l : List α) (hl₁ : ∀ (a : α), a ∈ l → p a) (hl₂ : l ≠ []) : last (pmap f l hl₁) (mt (iff.mp pmap_eq_nil) hl₂) = f (last l hl₂) (hl₁ (last l hl₂) (last_mem hl₂)) := sorry
theorem nth_pmap {α : Type u} {β : Type v} {p : α → Prop} (f : (a : α) → p a → β) {l : List α} (h : ∀ (a : α), a ∈ l → p a) (n : ℕ) : nth (pmap f l h) n = option.pmap f (nth l n) fun (x : α) (H : x ∈ nth l n) => h x (nth_mem H) := sorry
theorem nth_le_pmap {α : Type u} {β : Type v} {p : α → Prop} (f : (a : α) → p a → β) {l : List α} (h : ∀ (a : α), a ∈ l → p a) {n : ℕ} (hn : n < length (pmap f l h)) : nth_le (pmap f l h) n hn =
f (nth_le l n (length_pmap ▸ hn)) (h (nth_le l n (length_pmap ▸ hn)) (nth_le_mem l n (length_pmap ▸ hn))) := sorry
/-! ### find -/
@[simp] theorem find_nil {α : Type u} (p : α → Prop) [decidable_pred p] : find p [] = none :=
rfl
@[simp] theorem find_cons_of_pos {α : Type u} {p : α → Prop} [decidable_pred p] {a : α} (l : List α) (h : p a) : find p (a :: l) = some a :=
if_pos h
@[simp] theorem find_cons_of_neg {α : Type u} {p : α → Prop} [decidable_pred p] {a : α} (l : List α) (h : ¬p a) : find p (a :: l) = find p l :=
if_neg h
@[simp] theorem find_eq_none {α : Type u} {p : α → Prop} [decidable_pred p] {l : List α} : find p l = none ↔ ∀ (x : α), x ∈ l → ¬p x := sorry
theorem find_some {α : Type u} {p : α → Prop} [decidable_pred p] {l : List α} {a : α} (H : find p l = some a) : p a := sorry
@[simp] theorem find_mem {α : Type u} {p : α → Prop} [decidable_pred p] {l : List α} {a : α} (H : find p l = some a) : a ∈ l := sorry
/-! ### lookmap -/
@[simp] theorem lookmap_nil {α : Type u} (f : α → Option α) : lookmap f [] = [] :=
rfl
@[simp] theorem lookmap_cons_none {α : Type u} (f : α → Option α) {a : α} (l : List α) (h : f a = none) : lookmap f (a :: l) = a :: lookmap f l := sorry
@[simp] theorem lookmap_cons_some {α : Type u} (f : α → Option α) {a : α} {b : α} (l : List α) (h : f a = some b) : lookmap f (a :: l) = b :: l := sorry
theorem lookmap_some {α : Type u} (l : List α) : lookmap some l = l :=
list.cases_on l (idRhs (lookmap some [] = lookmap some []) rfl)
fun (l_hd : α) (l_tl : List α) => idRhs (lookmap some (l_hd :: l_tl) = lookmap some (l_hd :: l_tl)) rfl
theorem lookmap_none {α : Type u} (l : List α) : lookmap (fun (_x : α) => none) l = l := sorry
theorem lookmap_congr {α : Type u} {f : α → Option α} {g : α → Option α} {l : List α} : (∀ (a : α), a ∈ l → f a = g a) → lookmap f l = lookmap g l := sorry
theorem lookmap_of_forall_not {α : Type u} (f : α → Option α) {l : List α} (H : ∀ (a : α), a ∈ l → f a = none) : lookmap f l = l :=
Eq.trans (lookmap_congr H) (lookmap_none l)
theorem lookmap_map_eq {α : Type u} {β : Type v} (f : α → Option α) (g : α → β) (h : ∀ (a b : α), b ∈ f a → g a = g b) (l : List α) : map g (lookmap f l) = map g l := sorry
theorem lookmap_id' {α : Type u} (f : α → Option α) (h : ∀ (a b : α), b ∈ f a → a = b) (l : List α) : lookmap f l = l :=
eq.mpr (id (Eq._oldrec (Eq.refl (lookmap f l = l)) (Eq.symm (map_id (lookmap f l)))))
(eq.mpr (id (Eq._oldrec (Eq.refl (map id (lookmap f l) = l)) (lookmap_map_eq f id h l)))
(eq.mpr (id (Eq._oldrec (Eq.refl (map id l = l)) (map_id l))) (Eq.refl l)))
theorem length_lookmap {α : Type u} (f : α → Option α) (l : List α) : length (lookmap f l) = length l := sorry
/-! ### filter_map -/
@[simp] theorem filter_map_nil {α : Type u} {β : Type v} (f : α → Option β) : filter_map f [] = [] :=
rfl
@[simp] theorem filter_map_cons_none {α : Type u} {β : Type v} {f : α → Option β} (a : α) (l : List α) (h : f a = none) : filter_map f (a :: l) = filter_map f l := sorry
@[simp] theorem filter_map_cons_some {α : Type u} {β : Type v} (f : α → Option β) (a : α) (l : List α) {b : β} (h : f a = some b) : filter_map f (a :: l) = b :: filter_map f l := sorry
theorem filter_map_append {α : Type u_1} {β : Type u_2} (l : List α) (l' : List α) (f : α → Option β) : filter_map f (l ++ l') = filter_map f l ++ filter_map f l' := sorry
theorem filter_map_eq_map {α : Type u} {β : Type v} (f : α → β) : filter_map (some ∘ f) = map f := sorry
theorem filter_map_eq_filter {α : Type u} (p : α → Prop) [decidable_pred p] : filter_map (option.guard p) = filter p := sorry
theorem filter_map_filter_map {α : Type u} {β : Type v} {γ : Type w} (f : α → Option β) (g : β → Option γ) (l : List α) : filter_map g (filter_map f l) = filter_map (fun (x : α) => option.bind (f x) g) l := sorry
theorem map_filter_map {α : Type u} {β : Type v} {γ : Type w} (f : α → Option β) (g : β → γ) (l : List α) : map g (filter_map f l) = filter_map (fun (x : α) => option.map g (f x)) l := sorry
theorem filter_map_map {α : Type u} {β : Type v} {γ : Type w} (f : α → β) (g : β → Option γ) (l : List α) : filter_map g (map f l) = filter_map (g ∘ f) l := sorry
theorem filter_filter_map {α : Type u} {β : Type v} (f : α → Option β) (p : β → Prop) [decidable_pred p] (l : List α) : filter p (filter_map f l) = filter_map (fun (x : α) => option.filter p (f x)) l := sorry
theorem filter_map_filter {α : Type u} {β : Type v} (p : α → Prop) [decidable_pred p] (f : α → Option β) (l : List α) : filter_map f (filter p l) = filter_map (fun (x : α) => ite (p x) (f x) none) l := sorry
@[simp] theorem filter_map_some {α : Type u} (l : List α) : filter_map some l = l :=
eq.mpr (id (Eq._oldrec (Eq.refl (filter_map some l = l)) (filter_map_eq_map fun (x : α) => x))) (map_id l)
@[simp] theorem mem_filter_map {α : Type u} {β : Type v} (f : α → Option β) (l : List α) {b : β} : b ∈ filter_map f l ↔ ∃ (a : α), a ∈ l ∧ f a = some b := sorry
theorem map_filter_map_of_inv {α : Type u} {β : Type v} (f : α → Option β) (g : β → α) (H : ∀ (x : α), option.map g (f x) = some x) (l : List α) : map g (filter_map f l) = l := sorry
theorem sublist.filter_map {α : Type u} {β : Type v} (f : α → Option β) {l₁ : List α} {l₂ : List α} (s : l₁ <+ l₂) : filter_map f l₁ <+ filter_map f l₂ := sorry
theorem sublist.map {α : Type u} {β : Type v} (f : α → β) {l₁ : List α} {l₂ : List α} (s : l₁ <+ l₂) : map f l₁ <+ map f l₂ :=
filter_map_eq_map f ▸ sublist.filter_map (some ∘ f) s
/-! ### reduce_option -/
@[simp] theorem reduce_option_cons_of_some {α : Type u} (x : α) (l : List (Option α)) : reduce_option (some x :: l) = x :: reduce_option l := sorry
@[simp] theorem reduce_option_cons_of_none {α : Type u} (l : List (Option α)) : reduce_option (none :: l) = reduce_option l := sorry
@[simp] theorem reduce_option_nil {α : Type u} : reduce_option [] = [] :=
rfl
@[simp] theorem reduce_option_map {α : Type u} {β : Type v} {l : List (Option α)} {f : α → β} : reduce_option (map (option.map f) l) = map f (reduce_option l) := sorry
theorem reduce_option_append {α : Type u} (l : List (Option α)) (l' : List (Option α)) : reduce_option (l ++ l') = reduce_option l ++ reduce_option l' :=
filter_map_append l l' id
theorem reduce_option_length_le {α : Type u} (l : List (Option α)) : length (reduce_option l) ≤ length l := sorry
theorem reduce_option_length_eq_iff {α : Type u} {l : List (Option α)} : length (reduce_option l) = length l ↔ ∀ (x : Option α), x ∈ l → ↥(option.is_some x) := sorry
theorem reduce_option_length_lt_iff {α : Type u} {l : List (Option α)} : length (reduce_option l) < length l ↔ none ∈ l := sorry
theorem reduce_option_singleton {α : Type u} (x : Option α) : reduce_option [x] = option.to_list x :=
option.cases_on x (Eq.refl (reduce_option [none])) fun (x : α) => Eq.refl (reduce_option [some x])
theorem reduce_option_concat {α : Type u} (l : List (Option α)) (x : Option α) : reduce_option (concat l x) = reduce_option l ++ option.to_list x := sorry
theorem reduce_option_concat_of_some {α : Type u} (l : List (Option α)) (x : α) : reduce_option (concat l (some x)) = concat (reduce_option l) x := sorry
theorem reduce_option_mem_iff {α : Type u} {l : List (Option α)} {x : α} : x ∈ reduce_option l ↔ some x ∈ l := sorry
theorem reduce_option_nth_iff {α : Type u} {l : List (Option α)} {x : α} : (∃ (i : ℕ), nth l i = some (some x)) ↔ ∃ (i : ℕ), nth (reduce_option l) i = some x := sorry
/-! ### filter -/
theorem filter_eq_foldr {α : Type u} (p : α → Prop) [decidable_pred p] (l : List α) : filter p l = foldr (fun (a : α) (out : List α) => ite (p a) (a :: out) out) [] l := sorry
theorem filter_congr {α : Type u} {p : α → Prop} {q : α → Prop} [decidable_pred p] [decidable_pred q] {l : List α} : (∀ (x : α), x ∈ l → (p x ↔ q x)) → filter p l = filter q l := sorry
@[simp] theorem filter_subset {α : Type u} {p : α → Prop} [decidable_pred p] (l : List α) : filter p l ⊆ l :=
sublist.subset (filter_sublist l)
theorem of_mem_filter {α : Type u} {p : α → Prop} [decidable_pred p] {a : α} {l : List α} : a ∈ filter p l → p a := sorry
theorem mem_of_mem_filter {α : Type u} {p : α → Prop} [decidable_pred p] {a : α} {l : List α} (h : a ∈ filter p l) : a ∈ l :=
filter_subset l h
theorem mem_filter_of_mem {α : Type u} {p : α → Prop} [decidable_pred p] {a : α} {l : List α} : a ∈ l → p a → a ∈ filter p l := sorry
@[simp] theorem mem_filter {α : Type u} {p : α → Prop} [decidable_pred p] {a : α} {l : List α} : a ∈ filter p l ↔ a ∈ l ∧ p a := sorry
theorem filter_eq_self {α : Type u} {p : α → Prop} [decidable_pred p] {l : List α} : filter p l = l ↔ ∀ (a : α), a ∈ l → p a := sorry
theorem filter_eq_nil {α : Type u} {p : α → Prop} [decidable_pred p] {l : List α} : filter p l = [] ↔ ∀ (a : α), a ∈ l → ¬p a := sorry
theorem filter_sublist_filter {α : Type u} (p : α → Prop) [decidable_pred p] {l₁ : List α} {l₂ : List α} (s : l₁ <+ l₂) : filter p l₁ <+ filter p l₂ :=
filter_map_eq_filter p ▸ sublist.filter_map (option.guard p) s
theorem filter_of_map {α : Type u} {β : Type v} (p : α → Prop) [decidable_pred p] (f : β → α) (l : List β) : filter p (map f l) = map f (filter (p ∘ f) l) := sorry
@[simp] theorem filter_filter {α : Type u} (p : α → Prop) [decidable_pred p] (q : α → Prop) [decidable_pred q] (l : List α) : filter p (filter q l) = filter (fun (a : α) => p a ∧ q a) l := sorry
@[simp] theorem filter_true {α : Type u} {h : decidable_pred fun (a : α) => True} (l : List α) : filter (fun (a : α) => True) l = l := sorry
@[simp] theorem filter_false {α : Type u} {h : decidable_pred fun (a : α) => False} (l : List α) : filter (fun (a : α) => False) l = [] := sorry
@[simp] theorem span_eq_take_drop {α : Type u} (p : α → Prop) [decidable_pred p] (l : List α) : span p l = (take_while p l, drop_while p l) := sorry
@[simp] theorem take_while_append_drop {α : Type u} (p : α → Prop) [decidable_pred p] (l : List α) : take_while p l ++ drop_while p l = l := sorry
@[simp] theorem countp_nil {α : Type u} (p : α → Prop) [decidable_pred p] : countp p [] = 0 :=
rfl
@[simp] theorem countp_cons_of_pos {α : Type u} (p : α → Prop) [decidable_pred p] {a : α} (l : List α) (pa : p a) : countp p (a :: l) = countp p l + 1 :=
if_pos pa
@[simp] theorem countp_cons_of_neg {α : Type u} (p : α → Prop) [decidable_pred p] {a : α} (l : List α) (pa : ¬p a) : countp p (a :: l) = countp p l :=
if_neg pa
theorem countp_eq_length_filter {α : Type u} (p : α → Prop) [decidable_pred p] (l : List α) : countp p l = length (filter p l) := sorry
@[simp] theorem countp_append {α : Type u} (p : α → Prop) [decidable_pred p] (l₁ : List α) (l₂ : List α) : countp p (l₁ ++ l₂) = countp p l₁ + countp p l₂ := sorry
theorem countp_pos {α : Type u} (p : α → Prop) [decidable_pred p] {l : List α} : 0 < countp p l ↔ ∃ (a : α), ∃ (H : a ∈ l), p a := sorry
theorem countp_le_of_sublist {α : Type u} (p : α → Prop) [decidable_pred p] {l₁ : List α} {l₂ : List α} (s : l₁ <+ l₂) : countp p l₁ ≤ countp p l₂ := sorry
@[simp] theorem countp_filter {α : Type u} (p : α → Prop) [decidable_pred p] {q : α → Prop} [decidable_pred q] (l : List α) : countp p (filter q l) = countp (fun (a : α) => p a ∧ q a) l := sorry
/-! ### count -/
@[simp] theorem count_nil {α : Type u} [DecidableEq α] (a : α) : count a [] = 0 :=
rfl
theorem count_cons {α : Type u} [DecidableEq α] (a : α) (b : α) (l : List α) : count a (b :: l) = ite (a = b) (Nat.succ (count a l)) (count a l) :=
rfl
theorem count_cons' {α : Type u} [DecidableEq α] (a : α) (b : α) (l : List α) : count a (b :: l) = count a l + ite (a = b) 1 0 := sorry
@[simp] theorem count_cons_self {α : Type u} [DecidableEq α] (a : α) (l : List α) : count a (a :: l) = Nat.succ (count a l) :=
if_pos rfl
@[simp] theorem count_cons_of_ne {α : Type u} [DecidableEq α] {a : α} {b : α} (h : a ≠ b) (l : List α) : count a (b :: l) = count a l :=
if_neg h
theorem count_tail {α : Type u} [DecidableEq α] (l : List α) (a : α) (h : 0 < length l) : count a (tail l) = count a l - ite (a = nth_le l 0 h) 1 0 := sorry
theorem count_le_of_sublist {α : Type u} [DecidableEq α] (a : α) {l₁ : List α} {l₂ : List α} : l₁ <+ l₂ → count a l₁ ≤ count a l₂ :=
countp_le_of_sublist (Eq a)
theorem count_le_count_cons {α : Type u} [DecidableEq α] (a : α) (b : α) (l : List α) : count a l ≤ count a (b :: l) :=
count_le_of_sublist a (sublist_cons b l)
theorem count_singleton {α : Type u} [DecidableEq α] (a : α) : count a [a] = 1 :=
if_pos rfl
@[simp] theorem count_append {α : Type u} [DecidableEq α] (a : α) (l₁ : List α) (l₂ : List α) : count a (l₁ ++ l₂) = count a l₁ + count a l₂ :=
countp_append (Eq a)
theorem count_concat {α : Type u} [DecidableEq α] (a : α) (l : List α) : count a (concat l a) = Nat.succ (count a l) := sorry
theorem count_pos {α : Type u} [DecidableEq α] {a : α} {l : List α} : 0 < count a l ↔ a ∈ l := sorry
@[simp] theorem count_eq_zero_of_not_mem {α : Type u} [DecidableEq α] {a : α} {l : List α} (h : ¬a ∈ l) : count a l = 0 :=
by_contradiction fun (h' : ¬count a l = 0) => h (iff.mp count_pos (nat.pos_of_ne_zero h'))
theorem not_mem_of_count_eq_zero {α : Type u} [DecidableEq α] {a : α} {l : List α} (h : count a l = 0) : ¬a ∈ l :=
fun (h' : a ∈ l) => ne_of_gt (iff.mpr count_pos h') h
@[simp] theorem count_repeat {α : Type u} [DecidableEq α] (a : α) (n : ℕ) : count a (repeat a n) = n := sorry
theorem le_count_iff_repeat_sublist {α : Type u} [DecidableEq α] {a : α} {l : List α} {n : ℕ} : n ≤ count a l ↔ repeat a n <+ l := sorry
theorem repeat_count_eq_of_count_eq_length {α : Type u} [DecidableEq α] {a : α} {l : List α} (h : count a l = length l) : repeat a (count a l) = l :=
eq_of_sublist_of_length_eq (iff.mp le_count_iff_repeat_sublist (le_refl (count a l)))
(Eq.trans (length_repeat a (count a l)) h)
@[simp] theorem count_filter {α : Type u} [DecidableEq α] {p : α → Prop} [decidable_pred p] {a : α} {l : List α} (h : p a) : count a (filter p l) = count a l := sorry
/-! ### prefix, suffix, infix -/
@[simp] theorem prefix_append {α : Type u} (l₁ : List α) (l₂ : List α) : l₁ <+: l₁ ++ l₂ :=
Exists.intro l₂ rfl
@[simp] theorem suffix_append {α : Type u} (l₁ : List α) (l₂ : List α) : l₂ <:+ l₁ ++ l₂ :=
Exists.intro l₁ rfl
theorem infix_append {α : Type u} (l₁ : List α) (l₂ : List α) (l₃ : List α) : l₂ <:+: l₁ ++ l₂ ++ l₃ :=
Exists.intro l₁ (Exists.intro l₃ rfl)
@[simp] theorem infix_append' {α : Type u} (l₁ : List α) (l₂ : List α) (l₃ : List α) : l₂ <:+: l₁ ++ (l₂ ++ l₃) :=
eq.mpr (id (Eq._oldrec (Eq.refl (l₂ <:+: l₁ ++ (l₂ ++ l₃))) (Eq.symm (append_assoc l₁ l₂ l₃)))) (infix_append l₁ l₂ l₃)
theorem nil_prefix {α : Type u} (l : List α) : [] <+: l :=
Exists.intro l rfl
theorem nil_suffix {α : Type u} (l : List α) : [] <:+ l :=
Exists.intro l (append_nil l)
theorem prefix_refl {α : Type u} (l : List α) : l <+: l :=
Exists.intro [] (append_nil l)
theorem suffix_refl {α : Type u} (l : List α) : l <:+ l :=
Exists.intro [] rfl
@[simp] theorem suffix_cons {α : Type u} (a : α) (l : List α) : l <:+ a :: l :=
suffix_append [a]
theorem prefix_concat {α : Type u} (a : α) (l : List α) : l <+: concat l a := sorry
theorem infix_of_prefix {α : Type u} {l₁ : List α} {l₂ : List α} : l₁ <+: l₂ → l₁ <:+: l₂ := sorry
theorem infix_of_suffix {α : Type u} {l₁ : List α} {l₂ : List α} : l₁ <:+ l₂ → l₁ <:+: l₂ := sorry
theorem infix_refl {α : Type u} (l : List α) : l <:+: l :=
infix_of_prefix (prefix_refl l)
theorem nil_infix {α : Type u} (l : List α) : [] <:+: l :=
infix_of_prefix (nil_prefix l)
theorem infix_cons {α : Type u} {L₁ : List α} {L₂ : List α} {x : α} : L₁ <:+: L₂ → L₁ <:+: x :: L₂ := sorry
theorem is_prefix.trans {α : Type u} {l₁ : List α} {l₂ : List α} {l₃ : List α} : l₁ <+: l₂ → l₂ <+: l₃ → l₁ <+: l₃ := sorry
theorem is_suffix.trans {α : Type u} {l₁ : List α} {l₂ : List α} {l₃ : List α} : l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃ := sorry
theorem is_infix.trans {α : Type u} {l₁ : List α} {l₂ : List α} {l₃ : List α} : l₁ <:+: l₂ → l₂ <:+: l₃ → l₁ <:+: l₃ := sorry
theorem sublist_of_infix {α : Type u} {l₁ : List α} {l₂ : List α} : l₁ <:+: l₂ → l₁ <+ l₂ := sorry
theorem sublist_of_prefix {α : Type u} {l₁ : List α} {l₂ : List α} : l₁ <+: l₂ → l₁ <+ l₂ :=
sublist_of_infix ∘ infix_of_prefix
theorem sublist_of_suffix {α : Type u} {l₁ : List α} {l₂ : List α} : l₁ <:+ l₂ → l₁ <+ l₂ :=
sublist_of_infix ∘ infix_of_suffix
theorem reverse_suffix {α : Type u} {l₁ : List α} {l₂ : List α} : reverse l₁ <:+ reverse l₂ ↔ l₁ <+: l₂ := sorry
theorem reverse_prefix {α : Type u} {l₁ : List α} {l₂ : List α} : reverse l₁ <+: reverse l₂ ↔ l₁ <:+ l₂ := sorry
theorem length_le_of_infix {α : Type u} {l₁ : List α} {l₂ : List α} (s : l₁ <:+: l₂) : length l₁ ≤ length l₂ :=
length_le_of_sublist (sublist_of_infix s)
theorem eq_nil_of_infix_nil {α : Type u} {l : List α} (s : l <:+: []) : l = [] :=
eq_nil_of_sublist_nil (sublist_of_infix s)
theorem eq_nil_of_prefix_nil {α : Type u} {l : List α} (s : l <+: []) : l = [] :=
eq_nil_of_infix_nil (infix_of_prefix s)
theorem eq_nil_of_suffix_nil {α : Type u} {l : List α} (s : l <:+ []) : l = [] :=
eq_nil_of_infix_nil (infix_of_suffix s)
theorem infix_iff_prefix_suffix {α : Type u} (l₁ : List α) (l₂ : List α) : l₁ <:+: l₂ ↔ ∃ (t : List α), l₁ <+: t ∧ t <:+ l₂ := sorry
theorem eq_of_infix_of_length_eq {α : Type u} {l₁ : List α} {l₂ : List α} (s : l₁ <:+: l₂) : length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq (sublist_of_infix s)
theorem eq_of_prefix_of_length_eq {α : Type u} {l₁ : List α} {l₂ : List α} (s : l₁ <+: l₂) : length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq (sublist_of_prefix s)
theorem eq_of_suffix_of_length_eq {α : Type u} {l₁ : List α} {l₂ : List α} (s : l₁ <:+ l₂) : length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq (sublist_of_suffix s)
theorem prefix_of_prefix_length_le {α : Type u} {l₁ : List α} {l₂ : List α} {l₃ : List α} : l₁ <+: l₃ → l₂ <+: l₃ → length l₁ ≤ length l₂ → l₁ <+: l₂ := sorry
theorem prefix_or_prefix_of_prefix {α : Type u} {l₁ : List α} {l₂ : List α} {l₃ : List α} (h₁ : l₁ <+: l₃) (h₂ : l₂ <+: l₃) : l₁ <+: l₂ ∨ l₂ <+: l₁ :=
or.imp (prefix_of_prefix_length_le h₁ h₂) (prefix_of_prefix_length_le h₂ h₁) (le_total (length l₁) (length l₂))
theorem suffix_of_suffix_length_le {α : Type u} {l₁ : List α} {l₂ : List α} {l₃ : List α} (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) (ll : length l₁ ≤ length l₂) : l₁ <:+ l₂ := sorry
theorem suffix_or_suffix_of_suffix {α : Type u} {l₁ : List α} {l₂ : List α} {l₃ : List α} (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) : l₁ <:+ l₂ ∨ l₂ <:+ l₁ :=
or.imp (iff.mp reverse_prefix) (iff.mp reverse_prefix)
(prefix_or_prefix_of_prefix (iff.mpr reverse_prefix h₁) (iff.mpr reverse_prefix h₂))
theorem infix_of_mem_join {α : Type u} {L : List (List α)} {l : List α} : l ∈ L → l <:+: join L := sorry
theorem prefix_append_right_inj {α : Type u} {l₁ : List α} {l₂ : List α} (l : List α) : l ++ l₁ <+: l ++ l₂ ↔ l₁ <+: l₂ := sorry
theorem prefix_cons_inj {α : Type u} {l₁ : List α} {l₂ : List α} (a : α) : a :: l₁ <+: a :: l₂ ↔ l₁ <+: l₂ :=
prefix_append_right_inj [a]
theorem take_prefix {α : Type u} (n : ℕ) (l : List α) : take n l <+: l :=
Exists.intro (drop n l) (take_append_drop n l)
theorem drop_suffix {α : Type u} (n : ℕ) (l : List α) : drop n l <:+ l :=
Exists.intro (take n l) (take_append_drop n l)
theorem tail_suffix {α : Type u} (l : List α) : tail l <:+ l :=
eq.mpr (id (Eq._oldrec (Eq.refl (tail l <:+ l)) (Eq.symm (drop_one l)))) (drop_suffix 1 l)
theorem tail_subset {α : Type u} (l : List α) : tail l ⊆ l :=
sublist.subset (sublist_of_suffix (tail_suffix l))
theorem prefix_iff_eq_append {α : Type u} {l₁ : List α} {l₂ : List α} : l₁ <+: l₂ ↔ l₁ ++ drop (length l₁) l₂ = l₂ := sorry
theorem suffix_iff_eq_append {α : Type u} {l₁ : List α} {l₂ : List α} : l₁ <:+ l₂ ↔ take (length l₂ - length l₁) l₂ ++ l₁ = l₂ := sorry
theorem prefix_iff_eq_take {α : Type u} {l₁ : List α} {l₂ : List α} : l₁ <+: l₂ ↔ l₁ = take (length l₁) l₂ := sorry
theorem suffix_iff_eq_drop {α : Type u} {l₁ : List α} {l₂ : List α} : l₁ <:+ l₂ ↔ l₁ = drop (length l₂ - length l₁) l₂ := sorry
protected instance decidable_prefix {α : Type u} [DecidableEq α] (l₁ : List α) (l₂ : List α) : Decidable (l₁ <+: l₂) :=
sorry
-- Alternatively, use mem_tails
protected instance decidable_suffix {α : Type u} [DecidableEq α] (l₁ : List α) (l₂ : List α) : Decidable (l₁ <:+ l₂) :=
sorry
theorem prefix_take_le_iff {α : Type u} {L : List (List (Option α))} {m : ℕ} {n : ℕ} (hm : m < length L) : take m L <+: take n L ↔ m ≤ n := sorry
theorem cons_prefix_iff {α : Type u} {l : List α} {l' : List α} {x : α} {y : α} : x :: l <+: y :: l' ↔ x = y ∧ l <+: l' := sorry
theorem map_prefix {α : Type u} {β : Type v} {l : List α} {l' : List α} (f : α → β) (h : l <+: l') : map f l <+: map f l' := sorry
theorem is_prefix.filter_map {α : Type u} {β : Type v} {l : List α} {l' : List α} (h : l <+: l') (f : α → Option β) : filter_map f l <+: filter_map f l' := sorry
theorem is_prefix.reduce_option {α : Type u} {l : List (Option α)} {l' : List (Option α)} (h : l <+: l') : reduce_option l <+: reduce_option l' :=
is_prefix.filter_map h id
@[simp] theorem mem_inits {α : Type u} (s : List α) (t : List α) : s ∈ inits t ↔ s <+: t := sorry
@[simp] theorem mem_tails {α : Type u} (s : List α) (t : List α) : s ∈ tails t ↔ s <:+ t := sorry
theorem inits_cons {α : Type u} (a : α) (l : List α) : inits (a :: l) = [] :: map (fun (t : List α) => a :: t) (inits l) := sorry
theorem tails_cons {α : Type u} (a : α) (l : List α) : tails (a :: l) = (a :: l) :: tails l := sorry
@[simp] theorem inits_append {α : Type u} (s : List α) (t : List α) : inits (s ++ t) = inits s ++ map (fun (l : List α) => s ++ l) (tail (inits t)) := sorry
@[simp] theorem tails_append {α : Type u} (s : List α) (t : List α) : tails (s ++ t) = map (fun (l : List α) => l ++ t) (tails s) ++ tail (tails t) := sorry
-- the lemma names `inits_eq_tails` and `tails_eq_inits` are like `sublists_eq_sublists'`
theorem inits_eq_tails {α : Type u} (l : List α) : inits l = reverse (map reverse (tails (reverse l))) := sorry
theorem tails_eq_inits {α : Type u} (l : List α) : tails l = reverse (map reverse (inits (reverse l))) := sorry
theorem inits_reverse {α : Type u} (l : List α) : inits (reverse l) = reverse (map reverse (tails l)) := sorry
theorem tails_reverse {α : Type u} (l : List α) : tails (reverse l) = reverse (map reverse (inits l)) := sorry
theorem map_reverse_inits {α : Type u} (l : List α) : map reverse (inits l) = reverse (tails (reverse l)) := sorry
theorem map_reverse_tails {α : Type u} (l : List α) : map reverse (tails l) = reverse (inits (reverse l)) := sorry
protected instance decidable_infix {α : Type u} [DecidableEq α] (l₁ : List α) (l₂ : List α) : Decidable (l₁ <:+: l₂) :=
sorry
/-! ### sublists -/
@[simp] theorem sublists'_nil {α : Type u} : sublists' [] = [[]] :=
rfl
@[simp] theorem sublists'_singleton {α : Type u} (a : α) : sublists' [a] = [[], [a]] :=
rfl
theorem map_sublists'_aux {α : Type u} {β : Type v} {γ : Type w} (g : List β → List γ) (l : List α) (f : List α → List β) (r : List (List β)) : map g (sublists'_aux l f r) = sublists'_aux l (g ∘ f) (map g r) := sorry
theorem sublists'_aux_append {α : Type u} {β : Type v} (r' : List (List β)) (l : List α) (f : List α → List β) (r : List (List β)) : sublists'_aux l f (r ++ r') = sublists'_aux l f r ++ r' := sorry
theorem sublists'_aux_eq_sublists' {α : Type u} {β : Type v} (l : List α) (f : List α → List β) (r : List (List β)) : sublists'_aux l f r = map f (sublists' l) ++ r := sorry
@[simp] theorem sublists'_cons {α : Type u} (a : α) (l : List α) : sublists' (a :: l) = sublists' l ++ map (List.cons a) (sublists' l) := sorry
@[simp] theorem mem_sublists' {α : Type u} {s : List α} {t : List α} : s ∈ sublists' t ↔ s <+ t := sorry
@[simp] theorem length_sublists' {α : Type u} (l : List α) : length (sublists' l) = bit0 1 ^ length l := sorry
@[simp] theorem sublists_nil {α : Type u} : sublists [] = [[]] :=
rfl
@[simp] theorem sublists_singleton {α : Type u} (a : α) : sublists [a] = [[], [a]] :=
rfl
theorem sublists_aux₁_eq_sublists_aux {α : Type u} {β : Type v} (l : List α) (f : List α → List β) : sublists_aux₁ l f = sublists_aux l fun (ys : List α) (r : List β) => f ys ++ r := sorry
theorem sublists_aux_cons_eq_sublists_aux₁ {α : Type u} (l : List α) : sublists_aux l List.cons = sublists_aux₁ l fun (x : List α) => [x] := sorry
theorem sublists_aux_eq_foldr.aux {α : Type u} {β : Type v} {a : α} {l : List α} (IH₁ : ∀ (f : List α → List β → List β), sublists_aux l f = foldr f [] (sublists_aux l List.cons)) (IH₂ : ∀ (f : List α → List (List α) → List (List α)), sublists_aux l f = foldr f [] (sublists_aux l List.cons)) (f : List α → List β → List β) : sublists_aux (a :: l) f = foldr f [] (sublists_aux (a :: l) List.cons) := sorry
theorem sublists_aux_eq_foldr {α : Type u} {β : Type v} (l : List α) (f : List α → List β → List β) : sublists_aux l f = foldr f [] (sublists_aux l List.cons) := sorry
theorem sublists_aux_cons_cons {α : Type u} (l : List α) (a : α) : sublists_aux (a :: l) List.cons =
[a] :: foldr (fun (ys : List α) (r : List (List α)) => ys :: (a :: ys) :: r) [] (sublists_aux l List.cons) := sorry
theorem sublists_aux₁_append {α : Type u} {β : Type v} (l₁ : List α) (l₂ : List α) (f : List α → List β) : sublists_aux₁ (l₁ ++ l₂) f =
sublists_aux₁ l₁ f ++ sublists_aux₁ l₂ fun (x : List α) => f x ++ sublists_aux₁ l₁ (f ∘ fun (_x : List α) => _x ++ x) := sorry
theorem sublists_aux₁_concat {α : Type u} {β : Type v} (l : List α) (a : α) (f : List α → List β) : sublists_aux₁ (l ++ [a]) f = sublists_aux₁ l f ++ f [a] ++ sublists_aux₁ l fun (x : List α) => f (x ++ [a]) := sorry
theorem sublists_aux₁_bind {α : Type u} {β : Type v} {γ : Type w} (l : List α) (f : List α → List β) (g : β → List γ) : list.bind (sublists_aux₁ l f) g = sublists_aux₁ l fun (x : List α) => list.bind (f x) g := sorry
theorem sublists_aux_cons_append {α : Type u} (l₁ : List α) (l₂ : List α) : sublists_aux (l₁ ++ l₂) List.cons =
sublists_aux l₁ List.cons ++
do
let x ← sublists_aux l₂ List.cons
(fun (_x : List α) => _x ++ x) <$> sublists l₁ := sorry
theorem sublists_append {α : Type u} (l₁ : List α) (l₂ : List α) : sublists (l₁ ++ l₂) =
do
let x ← sublists l₂
(fun (_x : List α) => _x ++ x) <$> sublists l₁ := sorry
@[simp] theorem sublists_concat {α : Type u} (l : List α) (a : α) : sublists (l ++ [a]) = sublists l ++ map (fun (x : List α) => x ++ [a]) (sublists l) := sorry
theorem sublists_reverse {α : Type u} (l : List α) : sublists (reverse l) = map reverse (sublists' l) := sorry
theorem sublists_eq_sublists' {α : Type u} (l : List α) : sublists l = map reverse (sublists' (reverse l)) := sorry
theorem sublists'_reverse {α : Type u} (l : List α) : sublists' (reverse l) = map reverse (sublists l) := sorry
theorem sublists'_eq_sublists {α : Type u} (l : List α) : sublists' l = map reverse (sublists (reverse l)) := sorry
theorem sublists_aux_ne_nil {α : Type u} (l : List α) : ¬[] ∈ sublists_aux l List.cons := sorry
@[simp] theorem mem_sublists {α : Type u} {s : List α} {t : List α} : s ∈ sublists t ↔ s <+ t := sorry
@[simp] theorem length_sublists {α : Type u} (l : List α) : length (sublists l) = bit0 1 ^ length l := sorry
theorem map_ret_sublist_sublists {α : Type u} (l : List α) : map list.ret l <+ sublists l := sorry
/-! ### sublists_len -/
/-- Auxiliary function to construct the list of all sublists of a given length. Given an
integer `n`, a list `l`, a function `f` and an auxiliary list `L`, it returns the list made of
of `f` applied to all sublists of `l` of length `n`, concatenated with `L`. -/
def sublists_len_aux {α : Type u_1} {β : Type u_2} : ℕ → List α → (List α → β) → List β → List β :=
sorry
/-- The list of all sublists of a list `l` that are of length `n`. For instance, for
`l = [0, 1, 2, 3]` and `n = 2`, one gets
`[[2, 3], [1, 3], [1, 2], [0, 3], [0, 2], [0, 1]]`. -/
def sublists_len {α : Type u_1} (n : ℕ) (l : List α) : List (List α) :=
sublists_len_aux n l id []
theorem sublists_len_aux_append {α : Type u_1} {β : Type u_2} {γ : Type u_3} (n : ℕ) (l : List α) (f : List α → β) (g : β → γ) (r : List β) (s : List γ) : sublists_len_aux n l (g ∘ f) (map g r ++ s) = map g (sublists_len_aux n l f r) ++ s := sorry
theorem sublists_len_aux_eq {α : Type u_1} {β : Type u_2} (l : List α) (n : ℕ) (f : List α → β) (r : List β) : sublists_len_aux n l f r = map f (sublists_len n l) ++ r := sorry
theorem sublists_len_aux_zero {β : Type v} {α : Type u_1} (l : List α) (f : List α → β) (r : List β) : sublists_len_aux 0 l f r = f [] :: r :=
list.cases_on l (Eq.refl (sublists_len_aux 0 [] f r))
fun (l_hd : α) (l_tl : List α) => Eq.refl (sublists_len_aux 0 (l_hd :: l_tl) f r)
@[simp] theorem sublists_len_zero {α : Type u_1} (l : List α) : sublists_len 0 l = [[]] :=
sublists_len_aux_zero l id []
@[simp] theorem sublists_len_succ_nil {α : Type u_1} (n : ℕ) : sublists_len (n + 1) [] = [] :=
rfl
@[simp] theorem sublists_len_succ_cons {α : Type u_1} (n : ℕ) (a : α) (l : List α) : sublists_len (n + 1) (a :: l) = sublists_len (n + 1) l ++ map (List.cons a) (sublists_len n l) := sorry
@[simp] theorem length_sublists_len {α : Type u_1} (n : ℕ) (l : List α) : length (sublists_len n l) = nat.choose (length l) n := sorry
theorem sublists_len_sublist_sublists' {α : Type u_1} (n : ℕ) (l : List α) : sublists_len n l <+ sublists' l := sorry
theorem sublists_len_sublist_of_sublist {α : Type u_1} (n : ℕ) {l₁ : List α} {l₂ : List α} (h : l₁ <+ l₂) : sublists_len n l₁ <+ sublists_len n l₂ := sorry
theorem length_of_sublists_len {α : Type u_1} {n : ℕ} {l : List α} {l' : List α} : l' ∈ sublists_len n l → length l' = n := sorry
theorem mem_sublists_len_self {α : Type u_1} {l : List α} {l' : List α} (h : l' <+ l) : l' ∈ sublists_len (length l') l := sorry
@[simp] theorem mem_sublists_len {α : Type u_1} {n : ℕ} {l : List α} {l' : List α} : l' ∈ sublists_len n l ↔ l' <+ l ∧ length l' = n := sorry
/-! ### permutations -/
@[simp] theorem permutations_aux_nil {α : Type u} (is : List α) : permutations_aux [] is = [] := sorry
@[simp] theorem permutations_aux_cons {α : Type u} (t : α) (ts : List α) (is : List α) : permutations_aux (t :: ts) is =
foldr (fun (y : List α) (r : List (List α)) => prod.snd (permutations_aux2 t ts r y id))
(permutations_aux ts (t :: is)) (permutations is) := sorry
/-! ### insert -/
@[simp] theorem insert_nil {α : Type u} [DecidableEq α] (a : α) : insert a [] = [a] :=
rfl
theorem insert.def {α : Type u} [DecidableEq α] (a : α) (l : List α) : insert a l = ite (a ∈ l) l (a :: l) :=
rfl
@[simp] theorem insert_of_mem {α : Type u} [DecidableEq α] {a : α} {l : List α} (h : a ∈ l) : insert a l = l := sorry
@[simp] theorem insert_of_not_mem {α : Type u} [DecidableEq α] {a : α} {l : List α} (h : ¬a ∈ l) : insert a l = a :: l := sorry
@[simp] theorem mem_insert_iff {α : Type u} [DecidableEq α] {a : α} {b : α} {l : List α} : a ∈ insert b l ↔ a = b ∨ a ∈ l := sorry
@[simp] theorem suffix_insert {α : Type u} [DecidableEq α] (a : α) (l : List α) : l <:+ insert a l := sorry
@[simp] theorem mem_insert_self {α : Type u} [DecidableEq α] (a : α) (l : List α) : a ∈ insert a l :=
iff.mpr mem_insert_iff (Or.inl rfl)
theorem mem_insert_of_mem {α : Type u} [DecidableEq α] {a : α} {b : α} {l : List α} (h : a ∈ l) : a ∈ insert b l :=
iff.mpr mem_insert_iff (Or.inr h)
theorem eq_or_mem_of_mem_insert {α : Type u} [DecidableEq α] {a : α} {b : α} {l : List α} (h : a ∈ insert b l) : a = b ∨ a ∈ l :=
iff.mp mem_insert_iff h
@[simp] theorem length_insert_of_mem {α : Type u} [DecidableEq α] {a : α} {l : List α} (h : a ∈ l) : length (insert a l) = length l :=
eq.mpr (id (Eq._oldrec (Eq.refl (length (insert a l) = length l)) (insert_of_mem h))) (Eq.refl (length l))
@[simp] theorem length_insert_of_not_mem {α : Type u} [DecidableEq α] {a : α} {l : List α} (h : ¬a ∈ l) : length (insert a l) = length l + 1 :=
eq.mpr (id (Eq._oldrec (Eq.refl (length (insert a l) = length l + 1)) (insert_of_not_mem h)))
(Eq.refl (length (a :: l)))
/-! ### erasep -/
@[simp] theorem erasep_nil {α : Type u} {p : α → Prop} [decidable_pred p] : erasep p [] = [] :=
rfl
theorem erasep_cons {α : Type u} {p : α → Prop} [decidable_pred p] (a : α) (l : List α) : erasep p (a :: l) = ite (p a) l (a :: erasep p l) :=
rfl
@[simp] theorem erasep_cons_of_pos {α : Type u} {p : α → Prop} [decidable_pred p] {a : α} {l : List α} (h : p a) : erasep p (a :: l) = l := sorry
@[simp] theorem erasep_cons_of_neg {α : Type u} {p : α → Prop} [decidable_pred p] {a : α} {l : List α} (h : ¬p a) : erasep p (a :: l) = a :: erasep p l := sorry
theorem erasep_of_forall_not {α : Type u} {p : α → Prop} [decidable_pred p] {l : List α} (h : ∀ (a : α), a ∈ l → ¬p a) : erasep p l = l := sorry
theorem exists_of_erasep {α : Type u} {p : α → Prop} [decidable_pred p] {l : List α} {a : α} (al : a ∈ l) (pa : p a) : ∃ (a : α),
∃ (l₁ : List α), ∃ (l₂ : List α), (∀ (b : α), b ∈ l₁ → ¬p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ erasep p l = l₁ ++ l₂ := sorry
theorem exists_or_eq_self_of_erasep {α : Type u} (p : α → Prop) [decidable_pred p] (l : List α) : erasep p l = l ∨
∃ (a : α),
∃ (l₁ : List α), ∃ (l₂ : List α), (∀ (b : α), b ∈ l₁ → ¬p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ erasep p l = l₁ ++ l₂ := sorry
@[simp] theorem length_erasep_of_mem {α : Type u} {p : α → Prop} [decidable_pred p] {l : List α} {a : α} (al : a ∈ l) (pa : p a) : length (erasep p l) = Nat.pred (length l) := sorry
theorem erasep_append_left {α : Type u} {p : α → Prop} [decidable_pred p] {a : α} (pa : p a) {l₁ : List α} (l₂ : List α) : a ∈ l₁ → erasep p (l₁ ++ l₂) = erasep p l₁ ++ l₂ := sorry
theorem erasep_append_right {α : Type u} {p : α → Prop} [decidable_pred p] {l₁ : List α} (l₂ : List α) : (∀ (b : α), b ∈ l₁ → ¬p b) → erasep p (l₁ ++ l₂) = l₁ ++ erasep p l₂ := sorry
theorem erasep_sublist {α : Type u} {p : α → Prop} [decidable_pred p] (l : List α) : erasep p l <+ l := sorry
theorem erasep_subset {α : Type u} {p : α → Prop} [decidable_pred p] (l : List α) : erasep p l ⊆ l :=
sublist.subset (erasep_sublist l)
theorem sublist.erasep {α : Type u} {p : α → Prop} [decidable_pred p] {l₁ : List α} {l₂ : List α} (s : l₁ <+ l₂) : erasep p l₁ <+ erasep p l₂ := sorry
theorem mem_of_mem_erasep {α : Type u} {p : α → Prop} [decidable_pred p] {a : α} {l : List α} : a ∈ erasep p l → a ∈ l :=
erasep_subset l
@[simp] theorem mem_erasep_of_neg {α : Type u} {p : α → Prop} [decidable_pred p] {a : α} {l : List α} (pa : ¬p a) : a ∈ erasep p l ↔ a ∈ l := sorry
theorem erasep_map {α : Type u} {β : Type v} {p : α → Prop} [decidable_pred p] (f : β → α) (l : List β) : erasep p (map f l) = map f (erasep (p ∘ f) l) := sorry
@[simp] theorem extractp_eq_find_erasep {α : Type u} {p : α → Prop} [decidable_pred p] (l : List α) : extractp p l = (find p l, erasep p l) := sorry
/-! ### erase -/
@[simp] theorem erase_nil {α : Type u} [DecidableEq α] (a : α) : list.erase [] a = [] :=
rfl
theorem erase_cons {α : Type u} [DecidableEq α] (a : α) (b : α) (l : List α) : list.erase (b :: l) a = ite (b = a) l (b :: list.erase l a) :=
rfl
@[simp] theorem erase_cons_head {α : Type u} [DecidableEq α] (a : α) (l : List α) : list.erase (a :: l) a = l := sorry
@[simp] theorem erase_cons_tail {α : Type u} [DecidableEq α] {a : α} {b : α} (l : List α) (h : b ≠ a) : list.erase (b :: l) a = b :: list.erase l a := sorry
theorem erase_eq_erasep {α : Type u} [DecidableEq α] (a : α) (l : List α) : list.erase l a = erasep (Eq a) l := sorry
@[simp] theorem erase_of_not_mem {α : Type u} [DecidableEq α] {a : α} {l : List α} (h : ¬a ∈ l) : list.erase l a = l := sorry
theorem exists_erase_eq {α : Type u} [DecidableEq α] {a : α} {l : List α} (h : a ∈ l) : ∃ (l₁ : List α), ∃ (l₂ : List α), ¬a ∈ l₁ ∧ l = l₁ ++ a :: l₂ ∧ list.erase l a = l₁ ++ l₂ := sorry
@[simp] theorem length_erase_of_mem {α : Type u} [DecidableEq α] {a : α} {l : List α} (h : a ∈ l) : length (list.erase l a) = Nat.pred (length l) :=
eq.mpr (id (Eq._oldrec (Eq.refl (length (list.erase l a) = Nat.pred (length l))) (erase_eq_erasep a l)))
(length_erasep_of_mem h rfl)
theorem erase_append_left {α : Type u} [DecidableEq α] {a : α} {l₁ : List α} (l₂ : List α) (h : a ∈ l₁) : list.erase (l₁ ++ l₂) a = list.erase l₁ a ++ l₂ := sorry
theorem erase_append_right {α : Type u} [DecidableEq α] {a : α} {l₁ : List α} (l₂ : List α) (h : ¬a ∈ l₁) : list.erase (l₁ ++ l₂) a = l₁ ++ list.erase l₂ a := sorry
theorem erase_sublist {α : Type u} [DecidableEq α] (a : α) (l : List α) : list.erase l a <+ l :=
eq.mpr (id (Eq._oldrec (Eq.refl (list.erase l a <+ l)) (erase_eq_erasep a l))) (erasep_sublist l)
theorem erase_subset {α : Type u} [DecidableEq α] (a : α) (l : List α) : list.erase l a ⊆ l :=
sublist.subset (erase_sublist a l)
theorem sublist.erase {α : Type u} [DecidableEq α] (a : α) {l₁ : List α} {l₂ : List α} (h : l₁ <+ l₂) : list.erase l₁ a <+ list.erase l₂ a := sorry
theorem mem_of_mem_erase {α : Type u} [DecidableEq α] {a : α} {b : α} {l : List α} : a ∈ list.erase l b → a ∈ l :=
erase_subset b l
@[simp] theorem mem_erase_of_ne {α : Type u} [DecidableEq α] {a : α} {b : α} {l : List α} (ab : a ≠ b) : a ∈ list.erase l b ↔ a ∈ l :=
eq.mpr (id (Eq._oldrec (Eq.refl (a ∈ list.erase l b ↔ a ∈ l)) (erase_eq_erasep b l))) (mem_erasep_of_neg (ne.symm ab))
theorem erase_comm {α : Type u} [DecidableEq α] (a : α) (b : α) (l : List α) : list.erase (list.erase l a) b = list.erase (list.erase l b) a := sorry
theorem map_erase {α : Type u} {β : Type v} [DecidableEq α] [DecidableEq β] {f : α → β} (finj : function.injective f) {a : α} (l : List α) : map f (list.erase l a) = list.erase (map f l) (f a) := sorry
theorem map_foldl_erase {α : Type u} {β : Type v} [DecidableEq α] [DecidableEq β] {f : α → β} (finj : function.injective f) {l₁ : List α} {l₂ : List α} : map f (foldl list.erase l₁ l₂) = foldl (fun (l : List β) (a : α) => list.erase l (f a)) (map f l₁) l₂ := sorry
@[simp] theorem count_erase_self {α : Type u} [DecidableEq α] (a : α) (s : List α) : count a (list.erase s a) = Nat.pred (count a s) := sorry
@[simp] theorem count_erase_of_ne {α : Type u} [DecidableEq α] {a : α} {b : α} (ab : a ≠ b) (s : List α) : count a (list.erase s b) = count a s := sorry
/-! ### diff -/
@[simp] theorem diff_nil {α : Type u} [DecidableEq α] (l : List α) : list.diff l [] = l :=
rfl
@[simp] theorem diff_cons {α : Type u} [DecidableEq α] (l₁ : List α) (l₂ : List α) (a : α) : list.diff l₁ (a :: l₂) = list.diff (list.erase l₁ a) l₂ := sorry
theorem diff_cons_right {α : Type u} [DecidableEq α] (l₁ : List α) (l₂ : List α) (a : α) : list.diff l₁ (a :: l₂) = list.erase (list.diff l₁ l₂) a := sorry
theorem diff_erase {α : Type u} [DecidableEq α] (l₁ : List α) (l₂ : List α) (a : α) : list.erase (list.diff l₁ l₂) a = list.diff (list.erase l₁ a) l₂ := sorry
@[simp] theorem nil_diff {α : Type u} [DecidableEq α] (l : List α) : list.diff [] l = [] := sorry
theorem diff_eq_foldl {α : Type u} [DecidableEq α] (l₁ : List α) (l₂ : List α) : list.diff l₁ l₂ = foldl list.erase l₁ l₂ := sorry
@[simp] theorem diff_append {α : Type u} [DecidableEq α] (l₁ : List α) (l₂ : List α) (l₃ : List α) : list.diff l₁ (l₂ ++ l₃) = list.diff (list.diff l₁ l₂) l₃ := sorry
@[simp] theorem map_diff {α : Type u} {β : Type v} [DecidableEq α] [DecidableEq β] {f : α → β} (finj : function.injective f) {l₁ : List α} {l₂ : List α} : map f (list.diff l₁ l₂) = list.diff (map f l₁) (map f l₂) := sorry
theorem diff_sublist {α : Type u} [DecidableEq α] (l₁ : List α) (l₂ : List α) : list.diff l₁ l₂ <+ l₁ := sorry
theorem diff_subset {α : Type u} [DecidableEq α] (l₁ : List α) (l₂ : List α) : list.diff l₁ l₂ ⊆ l₁ :=
sublist.subset (diff_sublist l₁ l₂)
theorem mem_diff_of_mem {α : Type u} [DecidableEq α] {a : α} {l₁ : List α} {l₂ : List α} : a ∈ l₁ → ¬a ∈ l₂ → a ∈ list.diff l₁ l₂ := sorry
theorem sublist.diff_right {α : Type u} [DecidableEq α] {l₁ : List α} {l₂ : List α} {l₃ : List α} : l₁ <+ l₂ → list.diff l₁ l₃ <+ list.diff l₂ l₃ := sorry
theorem erase_diff_erase_sublist_of_sublist {α : Type u} [DecidableEq α] {a : α} {l₁ : List α} {l₂ : List α} : l₁ <+ l₂ → list.diff (list.erase l₂ a) (list.erase l₁ a) <+ list.diff l₂ l₁ := sorry
/-! ### enum -/
theorem length_enum_from {α : Type u} (n : ℕ) (l : List α) : length (enum_from n l) = length l := sorry
theorem length_enum {α : Type u} (l : List α) : length (enum l) = length l :=
length_enum_from 0
@[simp] theorem enum_from_nth {α : Type u} (n : ℕ) (l : List α) (m : ℕ) : nth (enum_from n l) m = (fun (a : α) => (n + m, a)) <$> nth l m := sorry
@[simp] theorem enum_nth {α : Type u} (l : List α) (n : ℕ) : nth (enum l) n = (fun (a : α) => (n, a)) <$> nth l n := sorry
@[simp] theorem enum_from_map_snd {α : Type u} (n : ℕ) (l : List α) : map prod.snd (enum_from n l) = l := sorry
@[simp] theorem enum_map_snd {α : Type u} (l : List α) : map prod.snd (enum l) = l :=
enum_from_map_snd 0
theorem mem_enum_from {α : Type u} {x : α} {i : ℕ} {j : ℕ} (xs : List α) : (i, x) ∈ enum_from j xs → j ≤ i ∧ i < j + length xs ∧ x ∈ xs := sorry
/-! ### product -/
@[simp] theorem nil_product {α : Type u} {β : Type v} (l : List β) : product [] l = [] :=
rfl
@[simp] theorem product_cons {α : Type u} {β : Type v} (a : α) (l₁ : List α) (l₂ : List β) : product (a :: l₁) l₂ = map (fun (b : β) => (a, b)) l₂ ++ product l₁ l₂ :=
rfl
@[simp] theorem product_nil {α : Type u} {β : Type v} (l : List α) : product l [] = [] := sorry
@[simp] theorem mem_product {α : Type u} {β : Type v} {l₁ : List α} {l₂ : List β} {a : α} {b : β} : (a, b) ∈ product l₁ l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ := sorry
theorem length_product {α : Type u} {β : Type v} (l₁ : List α) (l₂ : List β) : length (product l₁ l₂) = length l₁ * length l₂ := sorry
/-! ### sigma -/
@[simp] theorem nil_sigma {α : Type u} {σ : α → Type u_1} (l : (a : α) → List (σ a)) : list.sigma [] l = [] :=
rfl
@[simp] theorem sigma_cons {α : Type u} {σ : α → Type u_1} (a : α) (l₁ : List α) (l₂ : (a : α) → List (σ a)) : list.sigma (a :: l₁) l₂ = map (sigma.mk a) (l₂ a) ++ list.sigma l₁ l₂ :=
rfl
@[simp] theorem sigma_nil {α : Type u} {σ : α → Type u_1} (l : List α) : (list.sigma l fun (a : α) => []) = [] := sorry
@[simp] theorem mem_sigma {α : Type u} {σ : α → Type u_1} {l₁ : List α} {l₂ : (a : α) → List (σ a)} {a : α} {b : σ a} : sigma.mk a b ∈ list.sigma l₁ l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ a := sorry
theorem length_sigma {α : Type u} {σ : α → Type u_1} (l₁ : List α) (l₂ : (a : α) → List (σ a)) : length (list.sigma l₁ l₂) = sum (map (fun (a : α) => length (l₂ a)) l₁) := sorry
/-! ### disjoint -/
theorem disjoint.symm {α : Type u} {l₁ : List α} {l₂ : List α} (d : disjoint l₁ l₂) : disjoint l₂ l₁ :=
fun {a : α} (ᾰ : a ∈ l₂) (ᾰ_1 : a ∈ l₁) => idRhs False (d ᾰ_1 ᾰ)
theorem disjoint_comm {α : Type u} {l₁ : List α} {l₂ : List α} : disjoint l₁ l₂ ↔ disjoint l₂ l₁ :=
{ mp := disjoint.symm, mpr := disjoint.symm }
theorem disjoint_left {α : Type u} {l₁ : List α} {l₂ : List α} : disjoint l₁ l₂ ↔ ∀ {a : α}, a ∈ l₁ → ¬a ∈ l₂ :=
iff.rfl
theorem disjoint_right {α : Type u} {l₁ : List α} {l₂ : List α} : disjoint l₁ l₂ ↔ ∀ {a : α}, a ∈ l₂ → ¬a ∈ l₁ :=
disjoint_comm
theorem disjoint_iff_ne {α : Type u} {l₁ : List α} {l₂ : List α} : disjoint l₁ l₂ ↔ ∀ (a : α), a ∈ l₁ → ∀ (b : α), b ∈ l₂ → a ≠ b := sorry
theorem disjoint_of_subset_left {α : Type u} {l₁ : List α} {l₂ : List α} {l : List α} (ss : l₁ ⊆ l) (d : disjoint l l₂) : disjoint l₁ l₂ :=
fun {a : α} (ᾰ : a ∈ l₁) => idRhs (a ∈ l₂ → False) (d (ss ᾰ))
theorem disjoint_of_subset_right {α : Type u} {l₁ : List α} {l₂ : List α} {l : List α} (ss : l₂ ⊆ l) (d : disjoint l₁ l) : disjoint l₁ l₂ :=
fun {a : α} (ᾰ : a ∈ l₁) (ᾰ_1 : a ∈ l₂) => idRhs False (d ᾰ (ss ᾰ_1))
theorem disjoint_of_disjoint_cons_left {α : Type u} {a : α} {l₁ : List α} {l₂ : List α} : disjoint (a :: l₁) l₂ → disjoint l₁ l₂ :=
disjoint_of_subset_left (subset_cons a l₁)
theorem disjoint_of_disjoint_cons_right {α : Type u} {a : α} {l₁ : List α} {l₂ : List α} : disjoint l₁ (a :: l₂) → disjoint l₁ l₂ :=
disjoint_of_subset_right (subset_cons a l₂)
@[simp] theorem disjoint_nil_left {α : Type u} (l : List α) : disjoint [] l :=
fun {a : α} => idRhs (a ∈ [] → a ∈ l → False) (not.elim (not_mem_nil a))
@[simp] theorem disjoint_nil_right {α : Type u} (l : List α) : disjoint l [] :=
eq.mpr (id (Eq._oldrec (Eq.refl (disjoint l [])) (propext disjoint_comm))) (disjoint_nil_left l)
@[simp] theorem singleton_disjoint {α : Type u} {l : List α} {a : α} : disjoint [a] l ↔ ¬a ∈ l := sorry
@[simp] theorem disjoint_singleton {α : Type u} {l : List α} {a : α} : disjoint l [a] ↔ ¬a ∈ l := sorry
@[simp] theorem disjoint_append_left {α : Type u} {l₁ : List α} {l₂ : List α} {l : List α} : disjoint (l₁ ++ l₂) l ↔ disjoint l₁ l ∧ disjoint l₂ l := sorry
@[simp] theorem disjoint_append_right {α : Type u} {l₁ : List α} {l₂ : List α} {l : List α} : disjoint l (l₁ ++ l₂) ↔ disjoint l l₁ ∧ disjoint l l₂ := sorry
@[simp] theorem disjoint_cons_left {α : Type u} {a : α} {l₁ : List α} {l₂ : List α} : disjoint (a :: l₁) l₂ ↔ ¬a ∈ l₂ ∧ disjoint l₁ l₂ := sorry
@[simp] theorem disjoint_cons_right {α : Type u} {a : α} {l₁ : List α} {l₂ : List α} : disjoint l₁ (a :: l₂) ↔ ¬a ∈ l₁ ∧ disjoint l₁ l₂ := sorry
theorem disjoint_of_disjoint_append_left_left {α : Type u} {l₁ : List α} {l₂ : List α} {l : List α} (d : disjoint (l₁ ++ l₂) l) : disjoint l₁ l :=
and.left (iff.mp disjoint_append_left d)
theorem disjoint_of_disjoint_append_left_right {α : Type u} {l₁ : List α} {l₂ : List α} {l : List α} (d : disjoint (l₁ ++ l₂) l) : disjoint l₂ l :=
and.right (iff.mp disjoint_append_left d)
theorem disjoint_of_disjoint_append_right_left {α : Type u} {l₁ : List α} {l₂ : List α} {l : List α} (d : disjoint l (l₁ ++ l₂)) : disjoint l l₁ :=
and.left (iff.mp disjoint_append_right d)
theorem disjoint_of_disjoint_append_right_right {α : Type u} {l₁ : List α} {l₂ : List α} {l : List α} (d : disjoint l (l₁ ++ l₂)) : disjoint l l₂ :=
and.right (iff.mp disjoint_append_right d)
theorem disjoint_take_drop {α : Type u} {l : List α} {m : ℕ} {n : ℕ} (hl : nodup l) (h : m ≤ n) : disjoint (take m l) (drop n l) := sorry
/-! ### union -/
@[simp] theorem nil_union {α : Type u} [DecidableEq α] (l : List α) : [] ∪ l = l :=
rfl
@[simp] theorem cons_union {α : Type u} [DecidableEq α] (l₁ : List α) (l₂ : List α) (a : α) : a :: l₁ ∪ l₂ = insert a (l₁ ∪ l₂) :=
rfl
@[simp] theorem mem_union {α : Type u} [DecidableEq α] {l₁ : List α} {l₂ : List α} {a : α} : a ∈ l₁ ∪ l₂ ↔ a ∈ l₁ ∨ a ∈ l₂ := sorry
theorem mem_union_left {α : Type u} [DecidableEq α] {a : α} {l₁ : List α} (h : a ∈ l₁) (l₂ : List α) : a ∈ l₁ ∪ l₂ :=
iff.mpr mem_union (Or.inl h)
theorem mem_union_right {α : Type u} [DecidableEq α] {a : α} (l₁ : List α) {l₂ : List α} (h : a ∈ l₂) : a ∈ l₁ ∪ l₂ :=
iff.mpr mem_union (Or.inr h)
theorem sublist_suffix_of_union {α : Type u} [DecidableEq α] (l₁ : List α) (l₂ : List α) : ∃ (t : List α), t <+ l₁ ∧ t ++ l₂ = l₁ ∪ l₂ := sorry
theorem suffix_union_right {α : Type u} [DecidableEq α] (l₁ : List α) (l₂ : List α) : l₂ <:+ l₁ ∪ l₂ :=
Exists.imp (fun (a : List α) => and.right) (sublist_suffix_of_union l₁ l₂)
theorem union_sublist_append {α : Type u} [DecidableEq α] (l₁ : List α) (l₂ : List α) : l₁ ∪ l₂ <+ l₁ ++ l₂ := sorry
theorem forall_mem_union {α : Type u} [DecidableEq α] {p : α → Prop} {l₁ : List α} {l₂ : List α} : (∀ (x : α), x ∈ l₁ ∪ l₂ → p x) ↔ (∀ (x : α), x ∈ l₁ → p x) ∧ ∀ (x : α), x ∈ l₂ → p x := sorry
theorem forall_mem_of_forall_mem_union_left {α : Type u} [DecidableEq α] {p : α → Prop} {l₁ : List α} {l₂ : List α} (h : ∀ (x : α), x ∈ l₁ ∪ l₂ → p x) (x : α) (H : x ∈ l₁) : p x :=
and.left (iff.mp forall_mem_union h)
theorem forall_mem_of_forall_mem_union_right {α : Type u} [DecidableEq α] {p : α → Prop} {l₁ : List α} {l₂ : List α} (h : ∀ (x : α), x ∈ l₁ ∪ l₂ → p x) (x : α) (H : x ∈ l₂) : p x :=
and.right (iff.mp forall_mem_union h)
/-! ### inter -/
@[simp] theorem inter_nil {α : Type u} [DecidableEq α] (l : List α) : [] ∩ l = [] :=
rfl
@[simp] theorem inter_cons_of_mem {α : Type u} [DecidableEq α] {a : α} (l₁ : List α) {l₂ : List α} (h : a ∈ l₂) : (a :: l₁) ∩ l₂ = a :: l₁ ∩ l₂ :=
if_pos h
@[simp] theorem inter_cons_of_not_mem {α : Type u} [DecidableEq α] {a : α} (l₁ : List α) {l₂ : List α} (h : ¬a ∈ l₂) : (a :: l₁) ∩ l₂ = l₁ ∩ l₂ :=
if_neg h
theorem mem_of_mem_inter_left {α : Type u} [DecidableEq α] {l₁ : List α} {l₂ : List α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₁ :=
mem_of_mem_filter
theorem mem_of_mem_inter_right {α : Type u} [DecidableEq α] {l₁ : List α} {l₂ : List α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₂ :=
of_mem_filter
theorem mem_inter_of_mem_of_mem {α : Type u} [DecidableEq α] {l₁ : List α} {l₂ : List α} {a : α} : a ∈ l₁ → a ∈ l₂ → a ∈ l₁ ∩ l₂ :=
mem_filter_of_mem
@[simp] theorem mem_inter {α : Type u} [DecidableEq α] {a : α} {l₁ : List α} {l₂ : List α} : a ∈ l₁ ∩ l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ :=
mem_filter
theorem inter_subset_left {α : Type u} [DecidableEq α] (l₁ : List α) (l₂ : List α) : l₁ ∩ l₂ ⊆ l₁ :=
filter_subset l₁
theorem inter_subset_right {α : Type u} [DecidableEq α] (l₁ : List α) (l₂ : List α) : l₁ ∩ l₂ ⊆ l₂ :=
fun (a : α) => mem_of_mem_inter_right
theorem subset_inter {α : Type u} [DecidableEq α] {l : List α} {l₁ : List α} {l₂ : List α} (h₁ : l ⊆ l₁) (h₂ : l ⊆ l₂) : l ⊆ l₁ ∩ l₂ :=
fun (a : α) (h : a ∈ l) => iff.mpr mem_inter { left := h₁ h, right := h₂ h }
theorem inter_eq_nil_iff_disjoint {α : Type u} [DecidableEq α] {l₁ : List α} {l₂ : List α} : l₁ ∩ l₂ = [] ↔ disjoint l₁ l₂ := sorry
theorem forall_mem_inter_of_forall_left {α : Type u} [DecidableEq α] {p : α → Prop} {l₁ : List α} (h : ∀ (x : α), x ∈ l₁ → p x) (l₂ : List α) (x : α) : x ∈ l₁ ∩ l₂ → p x :=
ball.imp_left (fun (x : α) => mem_of_mem_inter_left) h
theorem forall_mem_inter_of_forall_right {α : Type u} [DecidableEq α] {p : α → Prop} (l₁ : List α) {l₂ : List α} (h : ∀ (x : α), x ∈ l₂ → p x) (x : α) : x ∈ l₁ ∩ l₂ → p x :=
ball.imp_left (fun (x : α) => mem_of_mem_inter_right) h
@[simp] theorem inter_reverse {α : Type u} [DecidableEq α] {xs : List α} {ys : List α} : list.inter xs (reverse ys) = list.inter xs ys := sorry
theorem choose_spec {α : Type u} (p : α → Prop) [decidable_pred p] (l : List α) (hp : ∃ (a : α), a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) :=
subtype.property (choose_x p l hp)
theorem choose_mem {α : Type u} (p : α → Prop) [decidable_pred p] (l : List α) (hp : ∃ (a : α), a ∈ l ∧ p a) : choose p l hp ∈ l :=
and.left (choose_spec p l hp)
theorem choose_property {α : Type u} (p : α → Prop) [decidable_pred p] (l : List α) (hp : ∃ (a : α), a ∈ l ∧ p a) : p (choose p l hp) :=
and.right (choose_spec p l hp)
/-! ### map₂_left' -/
-- The definitional equalities for `map₂_left'` can already be used by the
-- simplifie because `map₂_left'` is marked `@[simp]`.
@[simp] theorem map₂_left'_nil_right {α : Type u} {β : Type v} {γ : Type w} (f : α → Option β → γ) (as : List α) : map₂_left' f as [] = (map (fun (a : α) => f a none) as, []) :=
list.cases_on as (Eq.refl (map₂_left' f [] []))
fun (as_hd : α) (as_tl : List α) => Eq.refl (map₂_left' f (as_hd :: as_tl) [])
/-! ### map₂_right' -/
@[simp] theorem map₂_right'_nil_left {α : Type u} {β : Type v} {γ : Type w} (f : Option α → β → γ) (bs : List β) : map₂_right' f [] bs = (map (f none) bs, []) :=
list.cases_on bs (Eq.refl (map₂_right' f [] []))
fun (bs_hd : β) (bs_tl : List β) => Eq.refl (map₂_right' f [] (bs_hd :: bs_tl))
@[simp] theorem map₂_right'_nil_right {α : Type u} {β : Type v} {γ : Type w} (f : Option α → β → γ) (as : List α) : map₂_right' f as [] = ([], as) :=
rfl
@[simp] theorem map₂_right'_nil_cons {α : Type u} {β : Type v} {γ : Type w} (f : Option α → β → γ) (b : β) (bs : List β) : map₂_right' f [] (b :: bs) = (f none b :: map (f none) bs, []) :=
rfl
@[simp] theorem map₂_right'_cons_cons {α : Type u} {β : Type v} {γ : Type w} (f : Option α → β → γ) (a : α) (as : List α) (b : β) (bs : List β) : map₂_right' f (a :: as) (b :: bs) =
let rec : List γ × List α := map₂_right' f as bs;
(f (some a) b :: prod.fst rec, prod.snd rec) :=
rfl
/-! ### zip_left' -/
@[simp] theorem zip_left'_nil_right {α : Type u} {β : Type v} (as : List α) : zip_left' as [] = (map (fun (a : α) => (a, none)) as, []) :=
list.cases_on as (Eq.refl (zip_left' [] [])) fun (as_hd : α) (as_tl : List α) => Eq.refl (zip_left' (as_hd :: as_tl) [])
@[simp] theorem zip_left'_nil_left {α : Type u} {β : Type v} (bs : List β) : zip_left' [] bs = ([], bs) :=
rfl
@[simp] theorem zip_left'_cons_nil {α : Type u} {β : Type v} (a : α) (as : List α) : zip_left' (a :: as) [] = ((a, none) :: map (fun (a : α) => (a, none)) as, []) :=
rfl
@[simp] theorem zip_left'_cons_cons {α : Type u} {β : Type v} (a : α) (as : List α) (b : β) (bs : List β) : zip_left' (a :: as) (b :: bs) =
let rec : List (α × Option β) × List β := zip_left' as bs;
((a, some b) :: prod.fst rec, prod.snd rec) :=
rfl
/-! ### zip_right' -/
@[simp] theorem zip_right'_nil_left {α : Type u} {β : Type v} (bs : List β) : zip_right' [] bs = (map (fun (b : β) => (none, b)) bs, []) :=
list.cases_on bs (Eq.refl (zip_right' [] []))
fun (bs_hd : β) (bs_tl : List β) => Eq.refl (zip_right' [] (bs_hd :: bs_tl))
@[simp] theorem zip_right'_nil_right {α : Type u} {β : Type v} (as : List α) : zip_right' as [] = ([], as) :=
rfl
@[simp] theorem zip_right'_nil_cons {α : Type u} {β : Type v} (b : β) (bs : List β) : zip_right' [] (b :: bs) = ((none, b) :: map (fun (b : β) => (none, b)) bs, []) :=
rfl
@[simp] theorem zip_right'_cons_cons {α : Type u} {β : Type v} (a : α) (as : List α) (b : β) (bs : List β) : zip_right' (a :: as) (b :: bs) =
let rec : List (Option α × β) × List α := zip_right' as bs;
((some a, b) :: prod.fst rec, prod.snd rec) :=
rfl
/-! ### map₂_left -/
-- The definitional equalities for `map₂_left` can already be used by the
-- simplifier because `map₂_left` is marked `@[simp]`.
@[simp] theorem map₂_left_nil_right {α : Type u} {β : Type v} {γ : Type w} (f : α → Option β → γ) (as : List α) : map₂_left f as [] = map (fun (a : α) => f a none) as :=
list.cases_on as (Eq.refl (map₂_left f [] []))
fun (as_hd : α) (as_tl : List α) => Eq.refl (map₂_left f (as_hd :: as_tl) [])
theorem map₂_left_eq_map₂_left' {α : Type u} {β : Type v} {γ : Type w} (f : α → Option β → γ) (as : List α) (bs : List β) : map₂_left f as bs = prod.fst (map₂_left' f as bs) := sorry
theorem map₂_left_eq_map₂ {α : Type u} {β : Type v} {γ : Type w} (f : α → Option β → γ) (as : List α) (bs : List β) : length as ≤ length bs → map₂_left f as bs = map₂ (fun (a : α) (b : β) => f a (some b)) as bs := sorry
/-! ### map₂_right -/
@[simp] theorem map₂_right_nil_left {α : Type u} {β : Type v} {γ : Type w} (f : Option α → β → γ) (bs : List β) : map₂_right f [] bs = map (f none) bs :=
list.cases_on bs (Eq.refl (map₂_right f [] []))
fun (bs_hd : β) (bs_tl : List β) => Eq.refl (map₂_right f [] (bs_hd :: bs_tl))
@[simp] theorem map₂_right_nil_right {α : Type u} {β : Type v} {γ : Type w} (f : Option α → β → γ) (as : List α) : map₂_right f as [] = [] :=
rfl
@[simp] theorem map₂_right_nil_cons {α : Type u} {β : Type v} {γ : Type w} (f : Option α → β → γ) (b : β) (bs : List β) : map₂_right f [] (b :: bs) = f none b :: map (f none) bs :=
rfl
@[simp] theorem map₂_right_cons_cons {α : Type u} {β : Type v} {γ : Type w} (f : Option α → β → γ) (a : α) (as : List α) (b : β) (bs : List β) : map₂_right f (a :: as) (b :: bs) = f (some a) b :: map₂_right f as bs :=
rfl
theorem map₂_right_eq_map₂_right' {α : Type u} {β : Type v} {γ : Type w} (f : Option α → β → γ) (as : List α) (bs : List β) : map₂_right f as bs = prod.fst (map₂_right' f as bs) := sorry
theorem map₂_right_eq_map₂ {α : Type u} {β : Type v} {γ : Type w} (f : Option α → β → γ) (as : List α) (bs : List β) (h : length bs ≤ length as) : map₂_right f as bs = map₂ (fun (a : α) (b : β) => f (some a) b) as bs := sorry
/-! ### zip_left -/
@[simp] theorem zip_left_nil_right {α : Type u} {β : Type v} (as : List α) : zip_left as [] = map (fun (a : α) => (a, none)) as :=
list.cases_on as (Eq.refl (zip_left [] [])) fun (as_hd : α) (as_tl : List α) => Eq.refl (zip_left (as_hd :: as_tl) [])
@[simp] theorem zip_left_nil_left {α : Type u} {β : Type v} (bs : List β) : zip_left [] bs = [] :=
rfl
@[simp] theorem zip_left_cons_nil {α : Type u} {β : Type v} (a : α) (as : List α) : zip_left (a :: as) [] = (a, none) :: map (fun (a : α) => (a, none)) as :=
rfl
@[simp] theorem zip_left_cons_cons {α : Type u} {β : Type v} (a : α) (as : List α) (b : β) (bs : List β) : zip_left (a :: as) (b :: bs) = (a, some b) :: zip_left as bs :=
rfl
theorem zip_left_eq_zip_left' {α : Type u} {β : Type v} (as : List α) (bs : List β) : zip_left as bs = prod.fst (zip_left' as bs) := sorry
/-! ### zip_right -/
@[simp] theorem zip_right_nil_left {α : Type u} {β : Type v} (bs : List β) : zip_right [] bs = map (fun (b : β) => (none, b)) bs :=
list.cases_on bs (Eq.refl (zip_right [] [])) fun (bs_hd : β) (bs_tl : List β) => Eq.refl (zip_right [] (bs_hd :: bs_tl))
@[simp] theorem zip_right_nil_right {α : Type u} {β : Type v} (as : List α) : zip_right as [] = [] :=
rfl
@[simp] theorem zip_right_nil_cons {α : Type u} {β : Type v} (b : β) (bs : List β) : zip_right [] (b :: bs) = (none, b) :: map (fun (b : β) => (none, b)) bs :=
rfl
@[simp] theorem zip_right_cons_cons {α : Type u} {β : Type v} (a : α) (as : List α) (b : β) (bs : List β) : zip_right (a :: as) (b :: bs) = (some a, b) :: zip_right as bs :=
rfl
theorem zip_right_eq_zip_right' {α : Type u} {β : Type v} (as : List α) (bs : List β) : zip_right as bs = prod.fst (zip_right' as bs) := sorry
/-! ### Miscellaneous lemmas -/
theorem ilast'_mem {α : Type u} (a : α) (l : List α) : ilast' a l ∈ a :: l := sorry
@[simp] theorem nth_le_attach {α : Type u} (L : List α) (i : ℕ) (H : i < length (attach L)) : subtype.val (nth_le (attach L) i H) = nth_le L i (length_attach L ▸ H) := sorry
end list
theorem monoid_hom.map_list_prod {α : Type u_1} {β : Type u_2} [monoid α] [monoid β] (f : α →* β) (l : List α) : coe_fn f (list.prod l) = list.prod (list.map (⇑f) l) :=
Eq.symm (list.prod_hom l f)
namespace list
theorem sum_map_hom {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_monoid β] [add_monoid γ] (L : List α) (f : α → β) (g : β →+ γ) : sum (map (⇑g ∘ f) L) = coe_fn g (sum (map f L)) := sorry
theorem sum_map_mul_left {α : Type u_1} [semiring α] {β : Type u_2} (L : List β) (f : β → α) (r : α) : sum (map (fun (b : β) => r * f b) L) = r * sum (map f L) :=
sum_map_hom L f (add_monoid_hom.mul_left r)
theorem sum_map_mul_right {α : Type u_1} [semiring α] {β : Type u_2} (L : List β) (f : β → α) (r : α) : sum (map (fun (b : β) => f b * r) L) = sum (map f L) * r :=
sum_map_hom L f (add_monoid_hom.mul_right r)
@[simp] theorem mem_map_swap {α : Type u} {β : Type v} (x : α) (y : β) (xs : List (α × β)) : (y, x) ∈ map prod.swap xs ↔ (x, y) ∈ xs := sorry
theorem slice_eq {α : Type u_1} (xs : List α) (n : ℕ) (m : ℕ) : slice n m xs = take n xs ++ drop (n + m) xs := sorry
theorem sizeof_slice_lt {α : Type u_1} [SizeOf α] (i : ℕ) (j : ℕ) (hj : 0 < j) (xs : List α) (hi : i < length xs) : sizeof (slice i j xs) < sizeof xs := sorry
|
9ca0c4645ab48fa9cd33a7869065ec9372af5b33 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/tactic/simp_rw_auto.lean | d19d29789f23cec095f3392a1e49b77b024e6999 | [] | 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,923 | lean | /-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen
The `simp_rw` tactic, a mix of `simp` and `rewrite`.
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.core
import Mathlib.PostPort
namespace Mathlib
/-!
# The `simp_rw` tactic
This module defines a tactic `simp_rw` which functions as a mix of `simp` and
`rw`. Like `rw`, it applies each rewrite rule in the given order, but like
`simp` it repeatedly applies these rules and also under binders like `∀ x, ...`,
`∃ x, ...` and `λ x, ...`.
## Implementation notes
The tactic works by taking each rewrite rule in turn and applying `simp only` to
it. Arguments to `simp_rw` are of the format used by `rw` and are translated to
their equivalents for `simp`.
-/
namespace tactic.interactive
/--
`simp_rw` functions as a mix of `simp` and `rw`. Like `rw`, it applies each
rewrite rule in the given order, but like `simp` it repeatedly applies these
rules and also under binders like `∀ x, ...`, `∃ x, ...` and `λ x, ...`.
Usage:
- `simp_rw [lemma_1, ..., lemma_n]` will rewrite the goal by applying the
lemmas in that order. A lemma preceded by `←` is applied in the reverse direction.
- `simp_rw [lemma_1, ..., lemma_n] at h₁ ... hₙ` will rewrite the given hypotheses.
- `simp_rw [...] at ⊢ h₁ ... hₙ` rewrites the goal as well as the given hypotheses.
- `simp_rw [...] at *` rewrites in the whole context: all hypotheses and the goal.
Lemmas passed to `simp_rw` must be expressions that are valid arguments to `simp`.
For example, neither `simp` nor `rw` can solve the following, but `simp_rw` can:
```lean
example {α β : Type} {f : α → β} {t : set β} : (∀ s, f '' s ⊆ t) = ∀ s : set α, ∀ x ∈ s, x ∈ f ⁻¹' t :=
by simp_rw [set.image_subset_iff, set.subset_def]
```
-/
end Mathlib |
f02b7130c926ecccc6be9e0e652e9379dfd1b3b9 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/init/control/combinators.lean | b01932f98f673b5e0d01e4acad86111f4719430b | [] | 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,859 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura
Monad combinators, as in Haskell's Control.Monad.
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.control.monad
import Mathlib.Lean3Lib.init.control.alternative
import Mathlib.Lean3Lib.init.data.list.basic
universes u v w u_1 u_2 u_3
namespace Mathlib
def list.mmap {m : Type u → Type v} [Monad m] {α : Type w} {β : Type u} (f : α → m β) : List α → m (List β) :=
sorry
def list.mmap' {m : Type → Type v} [Monad m] {α : Type u} {β : Type} (f : α → m β) : List α → m Unit :=
sorry
def mjoin {m : Type u → Type u} [Monad m] {α : Type u} (a : m (m α)) : m α :=
a >>= id
def list.mfilter {m : Type → Type v} [Monad m] {α : Type} (f : α → m Bool) : List α → m (List α) :=
sorry
def list.mfoldl {m : Type u → Type v} [Monad m] {s : Type u} {α : Type w} : (s → α → m s) → s → List α → m s :=
sorry
def list.mfoldr {m : Type u → Type v} [Monad m] {s : Type u} {α : Type w} : (α → s → m s) → s → List α → m s :=
sorry
def list.mfirst {m : Type u → Type v} [Monad m] [alternative m] {α : Type w} {β : Type u} (f : α → m β) : List α → m β :=
sorry
def when {m : Type → Type} [Monad m] (c : Prop) [h : Decidable c] (t : m Unit) : m Unit :=
ite c t (pure Unit.unit)
def mcond {m : Type → Type} [Monad m] {α : Type} (mbool : m Bool) (tm : m α) (fm : m α) : m α :=
do
let b ← mbool
cond b tm fm
def mwhen {m : Type → Type} [Monad m] (c : m Bool) (t : m Unit) : m Unit :=
mcond c t (return Unit.unit)
namespace monad
def mapm {m : Type u_1 → Type u_2} [Monad m] {α : Type u_3} {β : Type u_1} (f : α → m β) : List α → m (List β) :=
mmap
def mapm' {m : Type → Type u_1} [Monad m] {α : Type u_2} {β : Type} (f : α → m β) : List α → m Unit :=
mmap'
def join {m : Type u_1 → Type u_1} [Monad m] {α : Type u_1} (a : m (m α)) : m α :=
mjoin
def filter {m : Type → Type u_1} [Monad m] {α : Type} (f : α → m Bool) : List α → m (List α) :=
mfilter
def foldl {m : Type u_1 → Type u_2} [Monad m] {s : Type u_1} {α : Type u_3} : (s → α → m s) → s → List α → m s :=
mfoldl
def cond {m : Type → Type} [Monad m] {α : Type} (mbool : m Bool) (tm : m α) (fm : m α) : m α :=
mcond
def sequence {m : Type u → Type v} [Monad m] {α : Type u} : List (m α) → m (List α) :=
sorry
def sequence' {m : Type → Type u} [Monad m] {α : Type} : List (m α) → m Unit :=
sorry
def whenb {m : Type → Type} [Monad m] (b : Bool) (t : m Unit) : m Unit :=
cond b t (return Unit.unit)
def unlessb {m : Type → Type} [Monad m] (b : Bool) (t : m Unit) : m Unit :=
cond b (return Unit.unit) t
|
1c910443e511a8ff62328ccd50c26a7978e8642a | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/tactic/zify.lean | ffd8ab2c14b6901dd9ec9c26680c60270d46ebed | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 5,438 | lean | /-
Copyright (c) 2020 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Y. Lewis
-/
import data.int.cast.lemmas -- used by clients
import data.int.char_zero
import tactic.norm_cast
/-!
# A tactic to shift `ℕ` goals to `ℤ`
It is often easier to work in `ℤ`, where subtraction is well behaved, than in `ℕ` where it isn't.
`zify` is a tactic that casts goals and hypotheses about natural numbers to ones about integers.
It makes use of `push_cast`, part of the `norm_cast` family, to simplify these goals.
## Implementation notes
`zify` is extensible, using the attribute `@[zify]` to label lemmas used for moving propositions
from `ℕ` to `ℤ`.
`zify` lemmas should have the form `∀ a₁ ... aₙ : ℕ, Pz (a₁ : ℤ) ... (aₙ : ℤ) ↔ Pn a₁ ... aₙ`.
For example, `int.coe_nat_le_coe_nat_iff : ∀ (m n : ℕ), ↑m ≤ ↑n ↔ m ≤ n` is a `zify` lemma.
`zify` is very nearly just `simp only with zify push_cast`. There are a few minor differences:
* `zify` lemmas are used in the opposite order of the standard simp form.
E.g. we will rewrite with `int.coe_nat_le_coe_nat_iff` from right to left.
* `zify` should fail if no `zify` lemma applies (i.e. it was unable to shift any proposition to ℤ).
However, once this succeeds, it does not necessarily need to rewrite with any `push_cast` rules.
-/
open tactic
namespace zify
/--
The `zify` attribute is used by the `zify` tactic. It applies to lemmas that shift propositions
between `nat` and `int`.
`zify` lemmas should have the form `∀ a₁ ... aₙ : ℕ, Pz (a₁ : ℤ) ... (aₙ : ℤ) ↔ Pn a₁ ... aₙ`.
For example, `int.coe_nat_le_coe_nat_iff : ∀ (m n : ℕ), ↑m ≤ ↑n ↔ m ≤ n` is a `zify` lemma.
-/
@[user_attribute]
meta def zify_attr : user_attribute simp_lemmas unit :=
{ name := `zify,
descr := "Used to tag lemmas for use in the `zify` tactic",
cache_cfg :=
{ mk_cache :=
λ ns, mmap (λ n, do c ← mk_const n, return (c, tt)) ns >>= simp_lemmas.mk.append_with_symm,
dependencies := [] } }
/--
Given an expression `e`, `lift_to_z e` looks for subterms of `e` that are propositions "about"
natural numbers and change them to propositions about integers.
Returns an expression `e'` and a proof that `e = e'`.
Includes `ge_iff_le` and `gt_iff_lt` in the simp set. These can't be tagged with `zify` as we
want to use them in the "forward", not "backward", direction.
-/
meta def lift_to_z (e : expr) : tactic (expr × expr) :=
do sl ← zify_attr.get_cache,
sl ← sl.add_simp `ge_iff_le, sl ← sl.add_simp `gt_iff_lt,
(e', prf, _) ← simplify sl [] e,
return (e', prf)
attribute [zify] int.coe_nat_le_coe_nat_iff int.coe_nat_lt_coe_nat_iff int.coe_nat_eq_coe_nat_iff
end zify
@[zify] lemma int.coe_nat_ne_coe_nat_iff (a b : ℕ) : (a : ℤ) ≠ b ↔ a ≠ b :=
by simp
/--
`zify extra_lems e` is used to shift propositions in `e` from `ℕ` to `ℤ`.
This is often useful since `ℤ` has well-behaved subtraction.
The list of extra lemmas is used in the `push_cast` step.
Returns an expression `e'` and a proof that `e = e'`.-/
meta def tactic.zify (extra_lems : list simp_arg_type) : expr → tactic (expr × expr) := λ z,
do (z1, p1) ← zify.lift_to_z z <|> fail "failed to find an applicable zify lemma",
(z2, p2) ← norm_cast.derive_push_cast extra_lems z1,
prod.mk z2 <$> mk_eq_trans p1 p2
/--
A variant of `tactic.zify` that takes `h`, a proof of a proposition about natural numbers,
and returns a proof of the zified version of that propositon.
-/
meta def tactic.zify_proof (extra_lems : list simp_arg_type) (h : expr) : tactic expr :=
do (_, pf) ← infer_type h >>= tactic.zify extra_lems,
mk_eq_mp pf h
section
setup_tactic_parser
/--
The `zify` tactic is used to shift propositions from `ℕ` to `ℤ`.
This is often useful since `ℤ` has well-behaved subtraction.
```lean
example (a b c x y z : ℕ) (h : ¬ x*y*z < 0) : c < a + 3*b :=
begin
zify,
zify at h,
/-
h : ¬↑x * ↑y * ↑z < 0
⊢ ↑c < ↑a + 3 * ↑b
-/
end
```
`zify` can be given extra lemmas to use in simplification. This is especially useful in the
presence of nat subtraction: passing `≤` arguments will allow `push_cast` to do more work.
```
example (a b c : ℕ) (h : a - b < c) (hab : b ≤ a) : false :=
begin
zify [hab] at h,
/- h : ↑a - ↑b < ↑c -/
end
```
`zify` makes use of the `@[zify]` attribute to move propositions,
and the `push_cast` tactic to simplify the `ℤ`-valued expressions.
`zify` is in some sense dual to the `lift` tactic. `lift (z : ℤ) to ℕ` will change the type of an
integer `z` (in the supertype) to `ℕ` (the subtype), given a proof that `z ≥ 0`;
propositions concerning `z` will still be over `ℤ`. `zify` changes propositions about `ℕ` (the
subtype) to propositions about `ℤ` (the supertype), without changing the type of any variable.
-/
meta def tactic.interactive.zify (sl : parse simp_arg_list) (l : parse location) : tactic unit :=
do locs ← l.get_locals,
replace_at (tactic.zify sl) locs l.include_goal >>= guardb
end
add_tactic_doc
{ name := "zify",
category := doc_category.attr,
decl_names := [`zify.zify_attr],
tags := ["coercions", "transport"] }
add_tactic_doc
{ name := "zify",
category := doc_category.tactic,
decl_names := [`tactic.interactive.zify],
tags := ["coercions", "transport"] }
|
34368b079136c199e62a4f2e99be5354b12cac36 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/number_theory/legendre_symbol/norm_num.lean | 00cfe5eb881ffb054d25b5af685e84ff95d4da51 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 20,360 | 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 number_theory.legendre_symbol.jacobi_symbol
/-!
# A `norm_num` extension for Jacobi and Legendre symbols
We extend the `tactic.interactive.norm_num` tactic so that it can be used to provably compute
the value of the Jacobi symbol `J(a | b)` or the Legendre symbol `legendre_sym p a` when
the arguments are numerals.
## Implementation notes
We use the Law of Quadratic Reciprocity for the Jacobi symbol to compute the value of `J(a | b)`
efficiently, roughly comparable in effort with the euclidean algorithm for the computation
of the gcd of `a` and `b`. More precisely, the computation is done in the following steps.
* Use `J(a | 0) = 1` (an artifact of the definition) and `J(a | 1) = 1` to deal
with corner cases.
* Use `J(a | b) = J(a % b | b)` to reduce to the case that `a` is a natural number.
We define a version of the Jacobi symbol restricted to natural numbers for use in
the following steps; see `norm_num.jacobi_sym_nat`. (But we'll continue to write `J(a | b)`
in this description.)
* Remove powers of two from `b`. This is done via `J(2a | 2b) = 0` and
`J(2a+1 | 2b) = J(2a+1 | b)` (another artifact of the definition).
* Now `0 ≤ a < b` and `b` is odd. If `b = 1`, then the value is `1`.
If `a = 0` (and `b > 1`), then the value is `0`. Otherwise, we remove powers of two from `a`
via `J(4a | b) = J(a | b)` and `J(2a | b) = ±J(a | b)`, where the sign is determined
by the residue class of `b` mod 8, to reduce to `a` odd.
* Once `a` is odd, we use Quadratic Reciprocity (QR) in the form
`J(a | b) = ±J(b % a | a)`, where the sign is determined by the residue classes
of `a` and `b` mod 4. We are then back in the previous case.
We provide customized versions of these results for the various reduction steps,
where we encode the residue classes mod 2, mod 4, or mod 8 by using terms like
`bit1 (bit0 a)`. In this way, the only divisions we have to compute and prove
are the ones occurring in the use of QR above.
-/
section lemmas
namespace norm_num
/-- The Jacobi symbol restricted to natural numbers in both arguments. -/
def jacobi_sym_nat (a b : ℕ) : ℤ := jacobi_sym a b
/-!
### API Lemmas
We repeat part of the API for `jacobi_sym` with `norm_num.jacobi_sym_nat` and without implicit
arguments, in a form that is suitable for constructing proofs in `norm_num`.
-/
/-- Base cases: `b = 0`, `b = 1`, `a = 0`, `a = 1`. -/
lemma jacobi_sym_nat.zero_right (a : ℕ) : jacobi_sym_nat a 0 = 1 :=
by rwa [jacobi_sym_nat, jacobi_sym.zero_right]
lemma jacobi_sym_nat.one_right (a : ℕ) : jacobi_sym_nat a 1 = 1 :=
by rwa [jacobi_sym_nat, jacobi_sym.one_right]
lemma jacobi_sym_nat.zero_left_even (b : ℕ) (hb : b ≠ 0) : jacobi_sym_nat 0 (bit0 b) = 0 :=
by rw [jacobi_sym_nat, nat.cast_zero, jacobi_sym.zero_left (nat.one_lt_bit0 hb)]
lemma jacobi_sym_nat.zero_left_odd (b : ℕ) (hb : b ≠ 0) : jacobi_sym_nat 0 (bit1 b) = 0 :=
by rw [jacobi_sym_nat, nat.cast_zero, jacobi_sym.zero_left (nat.one_lt_bit1 hb)]
lemma jacobi_sym_nat.one_left_even (b : ℕ) : jacobi_sym_nat 1 (bit0 b) = 1 :=
by rw [jacobi_sym_nat, nat.cast_one, jacobi_sym.one_left]
lemma jacobi_sym_nat.one_left_odd (b : ℕ) : jacobi_sym_nat 1 (bit1 b) = 1 :=
by rw [jacobi_sym_nat, nat.cast_one, jacobi_sym.one_left]
/-- Turn a Legendre symbol into a Jacobi symbol. -/
lemma legendre_sym.to_jacobi_sym (p : ℕ) (pp : fact (p.prime)) (a r : ℤ) (hr : jacobi_sym a p = r) :
legendre_sym p a = r :=
by rwa [@legendre_sym.to_jacobi_sym p pp a]
/-- The value depends only on the residue class of `a` mod `b`. -/
lemma jacobi_sym.mod_left (a : ℤ) (b ab' : ℕ) (ab r b' : ℤ) (hb' : (b : ℤ) = b')
(hab : a % b' = ab) (h : (ab' : ℤ) = ab) (hr : jacobi_sym_nat ab' b = r) :
jacobi_sym a b = r :=
by rw [← hr, jacobi_sym_nat, jacobi_sym.mod_left, hb', hab, ← h]
lemma jacobi_sym_nat.mod_left (a b ab : ℕ) (r : ℤ) (hab : a % b = ab)
(hr : jacobi_sym_nat ab b = r) :
jacobi_sym_nat a b = r :=
by { rw [← hr, jacobi_sym_nat, jacobi_sym_nat, _root_.jacobi_sym.mod_left a b, ← hab], refl, }
/-- The symbol vanishes when both entries are even (and `b ≠ 0`). -/
lemma jacobi_sym_nat.even_even (a b : ℕ) (hb₀ : b ≠ 0) :
jacobi_sym_nat (bit0 a) (bit0 b) = 0 :=
begin
refine jacobi_sym.eq_zero_iff.mpr ⟨nat.bit0_ne_zero hb₀, λ hf, _⟩,
have h : 2 ∣ (bit0 a).gcd (bit0 b) := nat.dvd_gcd two_dvd_bit0 two_dvd_bit0,
change 2 ∣ (bit0 a : ℤ).gcd (bit0 b) at h,
rw [← nat.cast_bit0, ← nat.cast_bit0, hf, ← even_iff_two_dvd] at h,
exact nat.not_even_one h,
end
/-- When `a` is odd and `b` is even, we can replace `b` by `b / 2`. -/
lemma jacobi_sym_nat.odd_even (a b : ℕ) (r : ℤ) (hr : jacobi_sym_nat (bit1 a) b = r) :
jacobi_sym_nat (bit1 a) (bit0 b) = r :=
begin
have ha : legendre_sym 2 (bit1 a) = 1 :=
by simp only [legendre_sym, quadratic_char_apply, quadratic_char_fun_one, int.cast_bit1,
char_two.bit1_eq_one, pi.one_apply],
cases eq_or_ne b 0 with hb hb,
{ rw [← hr, hb, jacobi_sym_nat.zero_right], },
{ haveI : ne_zero b := ⟨hb⟩, -- for `jacobi_sym.mul_right`
rwa [bit0_eq_two_mul b, jacobi_sym_nat, jacobi_sym.mul_right,
← _root_.legendre_sym.to_jacobi_sym, nat.cast_bit1, ha, one_mul], }
end
/-- If `a` is divisible by `4` and `b` is odd, then we can remove the factor `4` from `a`. -/
lemma jacobi_sym_nat.double_even (a b : ℕ) (r : ℤ) (hr : jacobi_sym_nat a (bit1 b) = r) :
jacobi_sym_nat (bit0 (bit0 a)) (bit1 b) = r :=
begin
have : ((2 : ℕ) : ℤ).gcd ((bit1 b) : ℕ) = 1,
{ rw [int.coe_nat_gcd, nat.bit1_eq_succ_bit0, bit0_eq_two_mul b, nat.succ_eq_add_one,
nat.gcd_mul_left_add_right, nat.gcd_one_right], },
rwa [bit0_eq_two_mul a, bit0_eq_two_mul (2 * a), ← mul_assoc, ← pow_two, jacobi_sym_nat,
nat.cast_mul, nat.cast_pow, jacobi_sym.mul_left, jacobi_sym.sq_one' this, one_mul],
end
/-- If `a` is even and `b` is odd, then we can remove a factor `2` from `a`,
but we may have to change the sign, depending on `b % 8`.
We give one version for each of the four odd residue classes mod `8`. -/
lemma jacobi_sym_nat.even_odd₁ (a b : ℕ) (r : ℤ)
(hr : jacobi_sym_nat a (bit1 (bit0 (bit0 b))) = r) :
jacobi_sym_nat (bit0 a) (bit1 (bit0 (bit0 b))) = r :=
begin
have hb : (bit1 (bit0 (bit0 b))) % 8 = 1,
{ rw [nat.bit1_mod_bit0, nat.bit0_mod_bit0, nat.bit0_mod_two], },
rw [jacobi_sym_nat, bit0_eq_two_mul a, nat.cast_mul, jacobi_sym.mul_left,
nat.cast_two, jacobi_sym.at_two (odd_bit1 _), zmod.χ₈_nat_mod_eight, hb],
norm_num,
exact hr,
end
lemma jacobi_sym_nat.even_odd₇ (a b : ℕ) (r : ℤ)
(hr : jacobi_sym_nat a (bit1 (bit1 (bit1 b))) = r) :
jacobi_sym_nat (bit0 a) (bit1 (bit1 (bit1 b))) = r :=
begin
have hb : (bit1 (bit1 (bit1 b))) % 8 = 7,
{ rw [nat.bit1_mod_bit0, nat.bit1_mod_bit0, nat.bit1_mod_two], },
rw [jacobi_sym_nat, bit0_eq_two_mul a, nat.cast_mul, jacobi_sym.mul_left,
nat.cast_two, jacobi_sym.at_two (odd_bit1 _), zmod.χ₈_nat_mod_eight, hb],
norm_num,
exact hr,
end
lemma jacobi_sym_nat.even_odd₃ (a b : ℕ) (r : ℤ)
(hr : jacobi_sym_nat a (bit1 (bit1 (bit0 b))) = r) :
jacobi_sym_nat (bit0 a) (bit1 (bit1 (bit0 b))) = -r :=
begin
have hb : (bit1 (bit1 (bit0 b))) % 8 = 3,
{ rw [nat.bit1_mod_bit0, nat.bit1_mod_bit0, nat.bit0_mod_two], },
rw [jacobi_sym_nat, bit0_eq_two_mul a, nat.cast_mul, jacobi_sym.mul_left,
nat.cast_two, jacobi_sym.at_two (odd_bit1 _), zmod.χ₈_nat_mod_eight, hb],
norm_num,
exact hr,
end
lemma jacobi_sym_nat.even_odd₅ (a b : ℕ) (r : ℤ)
(hr : jacobi_sym_nat a (bit1 (bit0 (bit1 b))) = r) :
jacobi_sym_nat (bit0 a) (bit1 (bit0 (bit1 b))) = -r :=
begin
have hb : (bit1 (bit0 (bit1 b))) % 8 = 5,
{ rw [nat.bit1_mod_bit0, nat.bit0_mod_bit0, nat.bit1_mod_two], },
rw [jacobi_sym_nat, bit0_eq_two_mul a, nat.cast_mul, jacobi_sym.mul_left,
nat.cast_two, jacobi_sym.at_two (odd_bit1 _), zmod.χ₈_nat_mod_eight, hb],
norm_num,
exact hr,
end
/-- Use quadratic reciproity to reduce to smaller `b`. -/
lemma jacobi_sym_nat.qr₁ (a b : ℕ) (r : ℤ) (hr : jacobi_sym_nat (bit1 b) (bit1 (bit0 a)) = r) :
jacobi_sym_nat (bit1 (bit0 a)) (bit1 b) = r :=
begin
have ha : (bit1 (bit0 a)) % 4 = 1,
{ rw [nat.bit1_mod_bit0, nat.bit0_mod_two], },
have hb := nat.bit1_mod_two,
rwa [jacobi_sym_nat, jacobi_sym.quadratic_reciprocity_one_mod_four ha (nat.odd_iff.mpr hb)],
end
lemma jacobi_sym_nat.qr₁_mod (a b ab : ℕ) (r : ℤ) (hab : (bit1 b) % (bit1 (bit0 a)) = ab)
(hr : jacobi_sym_nat ab (bit1 (bit0 a)) = r) :
jacobi_sym_nat (bit1 (bit0 a)) (bit1 b) = r :=
jacobi_sym_nat.qr₁ _ _ _ $ jacobi_sym_nat.mod_left _ _ ab r hab hr
lemma jacobi_sym_nat.qr₁' (a b : ℕ) (r : ℤ) (hr : jacobi_sym_nat (bit1 (bit0 b)) (bit1 a) = r) :
jacobi_sym_nat (bit1 a) (bit1 (bit0 b)) = r :=
begin
have hb : (bit1 (bit0 b)) % 4 = 1,
{ rw [nat.bit1_mod_bit0, nat.bit0_mod_two], },
have ha := nat.bit1_mod_two,
rwa [jacobi_sym_nat, ← jacobi_sym.quadratic_reciprocity_one_mod_four hb (nat.odd_iff.mpr ha)]
end
lemma jacobi_sym_nat.qr₁'_mod (a b ab : ℕ) (r : ℤ) (hab : (bit1 (bit0 b)) % (bit1 a) = ab)
(hr : jacobi_sym_nat ab (bit1 a) = r) :
jacobi_sym_nat (bit1 a) (bit1 (bit0 b)) = r :=
jacobi_sym_nat.qr₁' _ _ _ $ jacobi_sym_nat.mod_left _ _ ab r hab hr
lemma jacobi_sym_nat.qr₃ (a b : ℕ) (r : ℤ)
(hr : jacobi_sym_nat (bit1 (bit1 b)) (bit1 (bit1 a)) = r) :
jacobi_sym_nat (bit1 (bit1 a)) (bit1 (bit1 b)) = -r :=
begin
have hb : (bit1 (bit1 b)) % 4 = 3,
{ rw [nat.bit1_mod_bit0, nat.bit1_mod_two], },
have ha : (bit1 (bit1 a)) % 4 = 3,
{ rw [nat.bit1_mod_bit0, nat.bit1_mod_two], },
rwa [jacobi_sym_nat, jacobi_sym.quadratic_reciprocity_three_mod_four ha hb, neg_inj]
end
lemma jacobi_sym_nat.qr₃_mod (a b ab : ℕ) (r : ℤ) (hab : (bit1 (bit1 b)) % (bit1 (bit1 a)) = ab)
(hr : jacobi_sym_nat ab (bit1 (bit1 a)) = r) :
jacobi_sym_nat (bit1 (bit1 a)) (bit1 (bit1 b)) = -r :=
jacobi_sym_nat.qr₃ _ _ _ $ jacobi_sym_nat.mod_left _ _ ab r hab hr
end norm_num
end lemmas
section evaluation
/-!
### Certified evaluation of the Jacobi symbol
The following functions recursively evaluate a Jacobi symbol and construct the
corresponding proof term.
-/
namespace norm_num
open tactic
/-- This evaluates `r := jacobi_sym_nat a b` recursively using quadratic reciprocity
and produces a proof term for the equality, assuming that `a < b` and `b` is odd. -/
meta def prove_jacobi_sym_odd : instance_cache → instance_cache → expr → expr →
tactic (instance_cache × instance_cache × expr × expr)
| zc nc ea eb := do
match match_numeral eb with
| match_numeral_result.one := -- `b = 1`, result is `1`
pure (zc, nc, `(1 : ℤ), `(jacobi_sym_nat.one_right).mk_app [ea])
| match_numeral_result.bit1 eb₁ := do -- `b > 1` (recall that `b` is odd)
match match_numeral ea with
| match_numeral_result.zero := do -- `a = 0`, result is `0`
b ← eb₁.to_nat,
(nc, phb₀) ← prove_ne nc eb₁ `(0 : ℕ) b 0, -- proof of `b ≠ 0`
pure (zc, nc, `(0 : ℤ), `(jacobi_sym_nat.zero_left_odd).mk_app [eb₁, phb₀])
| match_numeral_result.one := do -- `a = 1`, result is `1`
pure (zc, nc, `(1 : ℤ), `(jacobi_sym_nat.one_left_odd).mk_app [eb₁])
| match_numeral_result.bit0 ea₁ := do -- `a` is even; check if divisible by `4`
match match_numeral ea₁ with
| match_numeral_result.bit0 ea₂ := do
(zc, nc, er, p) ← prove_jacobi_sym_odd zc nc ea₂ eb, -- compute `jacobi_sym_nat (a / 4) b`
pure (zc, nc, er, `(jacobi_sym_nat.double_even).mk_app [ea₂, eb₁, er, p])
| _ := do -- reduce to `a / 2`; need to consider `b % 8`
(zc, nc, er, p) ← prove_jacobi_sym_odd zc nc ea₁ eb, -- compute `jacobi_sym_nat (a / 2) b`
match match_numeral eb₁ with
-- | match_numeral_result.zero := -- `b = 1`, not reached
| match_numeral_result.one := do -- `b = 3`
r ← er.to_int,
(zc, er') ← zc.of_int (- r),
pure (zc, nc, er', `(jacobi_sym_nat.even_odd₃).mk_app [ea₁, `(0 : ℕ), er, p])
| match_numeral_result.bit0 eb₂ := do -- `b % 4 = 1`
match match_numeral eb₂ with
-- | match_numeral_result.zero := -- not reached
| match_numeral_result.one := do -- `b = 5`
r ← er.to_int,
(zc, er') ← zc.of_int (- r),
pure (zc, nc, er', `(jacobi_sym_nat.even_odd₅).mk_app [ea₁, `(0 : ℕ), er, p])
| match_numeral_result.bit0 eb₃ := do -- `b % 8 = 1`
pure (zc, nc, er, `(jacobi_sym_nat.even_odd₁).mk_app [ea₁, eb₃, er, p])
| match_numeral_result.bit1 eb₃ := do -- `b % 8 = 5`
r ← er.to_int,
(zc, er') ← zc.of_int (- r),
pure (zc, nc, er', `(jacobi_sym_nat.even_odd₅).mk_app [ea₁, eb₃, er, p])
| _ := failed
end
| match_numeral_result.bit1 eb₂ := do -- `b % 4 = 3`
match match_numeral eb₂ with
-- | match_numeral_result.zero := -- not reached
| match_numeral_result.one := do -- `b = 7`
pure (zc, nc, er, `(jacobi_sym_nat.even_odd₇).mk_app [ea₁, `(0 : ℕ), er, p])
| match_numeral_result.bit0 eb₃ := do -- `b % 8 = 3`
r ← er.to_int,
(zc, er') ← zc.of_int (- r),
pure (zc, nc, er', `(jacobi_sym_nat.even_odd₃).mk_app [ea₁, eb₃, er, p])
| match_numeral_result.bit1 eb₃ := do -- `b % 8 = 7`
pure (zc, nc, er, `(jacobi_sym_nat.even_odd₇).mk_app [ea₁, eb₃, er, p])
| _ := failed
end
| _ := failed
end
end
| match_numeral_result.bit1 ea₁ := do -- `a` is odd
-- use Quadratic Reciprocity; look at `a` and `b` mod `4`
(nc, bma, phab) ← prove_div_mod nc eb ea tt, -- compute `b % a`
(zc, nc, er, p) ← prove_jacobi_sym_odd zc nc bma ea, -- compute `jacobi_sym_nat (b % a) a`
match match_numeral ea₁ with
-- | match_numeral_result.zero := -- `a = 1`, not reached
| match_numeral_result.one := do -- `a = 3`; need to consider `b`
match match_numeral eb₁ with
-- | match_numeral_result.zero := -- `b = 1`, not reached
-- | match_numeral_result.one := -- `b = 3`, not reached, since `a < b`
| match_numeral_result.bit0 eb₂ := do -- `b % 4 = 1`
pure (zc, nc, er, `(jacobi_sym_nat.qr₁'_mod).mk_app [ea₁, eb₂, bma, er, phab, p])
| match_numeral_result.bit1 eb₂ := do -- `b % 4 = 3`
r ← er.to_int,
(zc, er') ← zc.of_int (- r),
pure (zc, nc, er', `(jacobi_sym_nat.qr₃_mod).mk_app [`(0 : ℕ), eb₂, bma, er, phab, p])
| _ := failed
end
| match_numeral_result.bit0 ea₂ := do -- `a % 4 = 1`
pure (zc, nc, er, `(jacobi_sym_nat.qr₁_mod).mk_app [ea₂, eb₁, bma, er, phab, p])
| match_numeral_result.bit1 ea₂ := do -- `a % 4 = 3`; need to consider `b`
match match_numeral eb₁ with
-- | match_numeral_result.zero := do -- `b = 1`, not reached
-- | match_numeral_result.one := do -- `b = 3`, not reached, since `a < b`
| match_numeral_result.bit0 eb₂ := do -- `b % 4 = 1`
pure (zc, nc, er, `(jacobi_sym_nat.qr₁'_mod).mk_app [ea₁, eb₂, bma, er, phab, p])
| match_numeral_result.bit1 eb₂ := do -- `b % 4 = 3`
r ← er.to_int,
(zc, er') ← zc.of_int (- r),
pure (zc, nc, er', `(jacobi_sym_nat.qr₃_mod).mk_app [ea₂, eb₂, bma, er, phab, p])
| _ := failed
end
| _ := failed
end
| _ := failed
end
| _ := failed
end
/-- This evaluates `r := jacobi_sym_nat a b` and produces a proof term for the equality
by removing powers of `2` from `b` and then calling `prove_jacobi_sym_odd`. -/
meta def prove_jacobi_sym_nat : instance_cache → instance_cache → expr → expr →
tactic (instance_cache × instance_cache × expr × expr)
| zc nc ea eb := do
match match_numeral eb with
| match_numeral_result.zero := -- `b = 0`, result is `1`
pure (zc, nc, `(1 : ℤ), `(jacobi_sym_nat.zero_right).mk_app [ea])
| match_numeral_result.one := -- `b = 1`, result is `1`
pure (zc, nc, `(1 : ℤ), `(jacobi_sym_nat.one_right).mk_app [ea])
| match_numeral_result.bit0 eb₁ := -- `b` is even and nonzero
match match_numeral ea with
| match_numeral_result.zero := do -- `a = 0`, result is `0`
b ← eb₁.to_nat,
(nc, phb₀) ← prove_ne nc eb₁ `(0 : ℕ) b 0, -- proof of `b ≠ 0`
pure (zc, nc, `(0 : ℤ), `(jacobi_sym_nat.zero_left_even).mk_app [eb₁, phb₀])
| match_numeral_result.one := do -- `a = 1`, result is `1`
pure (zc, nc, `(1 : ℤ), `(jacobi_sym_nat.one_left_even).mk_app [eb₁])
| match_numeral_result.bit0 ea₁ := do -- `a` is even, result is `0`
b ← eb₁.to_nat,
(nc, phb₀) ← prove_ne nc eb₁ `(0 : ℕ) b 0, -- proof of `b ≠ 0`
let er : expr := `(0 : ℤ),
pure (zc, nc, er, `(jacobi_sym_nat.even_even).mk_app [ea₁, eb₁, phb₀])
| match_numeral_result.bit1 ea₁ := do -- `a` is odd, reduce to `b / 2`
(zc, nc, er, p) ← prove_jacobi_sym_nat zc nc ea eb₁,
pure (zc, nc, er, `(jacobi_sym_nat.odd_even).mk_app [ea₁, eb₁, er, p])
| _ := failed
end
| match_numeral_result.bit1 eb₁ := do -- `b` is odd
a ← ea.to_nat,
b ← eb.to_nat,
if b ≤ a then do -- reduce to `jacobi_sym_nat (a % b) b`
(nc, amb, phab) ← prove_div_mod nc ea eb tt, -- compute `a % b`
(zc, nc, er, p) ← prove_jacobi_sym_odd zc nc amb eb, -- compute `jacobi_sym_nat (a % b) b`
pure (zc, nc, er, `(jacobi_sym_nat.mod_left).mk_app [ea, eb, amb, er, phab, p])
else
prove_jacobi_sym_odd zc nc ea eb
| _ := failed
end
/-- This evaluates `r := jacobi_sym a b` and produces a proof term for the equality.
This is done by reducing to `r := jacobi_sym_nat (a % b) b`. -/
meta def prove_jacobi_sym : instance_cache → instance_cache → expr → expr
→ tactic (instance_cache × instance_cache × expr × expr)
| zc nc ea eb := do
match match_numeral eb with -- deal with simple cases right away
| match_numeral_result.zero := pure (zc, nc, `(1 : ℤ), `(jacobi_sym.zero_right).mk_app [ea])
| match_numeral_result.one := pure (zc, nc, `(1 : ℤ), `(jacobi_sym.one_right).mk_app [ea])
| _ := do -- Now `1 < b`. Compute `jacobi_sym_nat (a % b) b` instead.
b ← eb.to_nat,
(zc, eb') ← zc.of_int (b : ℤ),
-- Get the proof that `(b : ℤ) = b'` (where `eb'` is the numeral representing `b'`).
-- This is important to avoid inefficient matching between the two.
(zc, nc, eb₁, pb') ← prove_nat_uncast zc nc eb',
(zc, amb, phab) ← prove_div_mod zc ea eb' tt, -- compute `a % b`
(zc, nc, amb', phab') ← prove_nat_uncast zc nc amb, -- `a % b` as a natural number
(zc, nc, er, p) ← prove_jacobi_sym_nat zc nc amb' eb₁, -- compute `jacobi_sym_nat (a % b) b`
pure (zc, nc, er,
`(jacobi_sym.mod_left).mk_app [ea, eb₁, amb', amb, er, eb', pb', phab, phab', p])
end
end norm_num
end evaluation
section tactic
/-!
### The `norm_num` plug-in
-/
namespace tactic
namespace norm_num
/-- This is the `norm_num` plug-in that evaluates Jacobi and Legendre symbols. -/
@[norm_num] meta def eval_jacobi_sym : expr → tactic (expr × expr)
| `(jacobi_sym %%ea %%eb) := do -- Jacobi symbol
zc ← mk_instance_cache `(ℤ),
nc ← mk_instance_cache `(ℕ),
(prod.snd ∘ prod.snd) <$> norm_num.prove_jacobi_sym zc nc ea eb
| `(norm_num.jacobi_sym_nat %%ea %%eb) := do -- Jacobi symbol on natural numbers
zc ← mk_instance_cache `(ℤ),
nc ← mk_instance_cache `(ℕ),
(prod.snd ∘ prod.snd) <$> norm_num.prove_jacobi_sym_nat zc nc ea eb
| `(@legendre_sym %%ep %%inst %%ea) := do -- Legendre symbol
zc ← mk_instance_cache `(ℤ),
nc ← mk_instance_cache `(ℕ),
(zc, nc, er, pf) ← norm_num.prove_jacobi_sym zc nc ea ep,
pure (er, `(norm_num.legendre_sym.to_jacobi_sym).mk_app [ep, inst, ea, er, pf])
| _ := failed
end norm_num
end tactic
end tactic
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.