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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0cee745aa566758b7b0386485687df231af85db9 | f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58 | /algebra/ordered_ring.lean | 9e8b12f8ddeda2724f7b9fbc2c5d14adaf16ba8c | [
"Apache-2.0"
] | permissive | semorrison/mathlib | 1be6f11086e0d24180fec4b9696d3ec58b439d10 | 20b4143976dad48e664c4847b75a85237dca0a89 | refs/heads/master | 1,583,799,212,170 | 1,535,634,130,000 | 1,535,730,505,000 | 129,076,205 | 0 | 0 | Apache-2.0 | 1,551,697,998,000 | 1,523,442,265,000 | Lean | UTF-8 | Lean | false | false | 13,935 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import order.basic algebra.order algebra.ordered_group algebra.ring
universe u
variable {α : Type u}
-- TODO: this is necessary additionally to mul_nonneg otherwise the simplifier can not match
lemma zero_le_mul [ordered_semiring α] {a b : α} : 0 ≤ a → 0 ≤ b → 0 ≤ a * b :=
mul_nonneg
section linear_ordered_semiring
variable [linear_ordered_semiring α]
@[simp] lemma mul_le_mul_left {a b c : α} (h : 0 < c) : c * a ≤ c * b ↔ a ≤ b :=
⟨λ h', le_of_mul_le_mul_left h' h, λ h', mul_le_mul_of_nonneg_left h' (le_of_lt h)⟩
@[simp] lemma mul_le_mul_right {a b c : α} (h : 0 < c) : a * c ≤ b * c ↔ a ≤ b :=
⟨λ h', le_of_mul_le_mul_right h' h, λ h', mul_le_mul_of_nonneg_right h' (le_of_lt h)⟩
@[simp] lemma mul_lt_mul_left {a b c : α} (h : 0 < c) : c * a < c * b ↔ a < b :=
⟨λ h', lt_of_mul_lt_mul_left h' (le_of_lt h), λ h', mul_lt_mul_of_pos_left h' h⟩
@[simp] lemma mul_lt_mul_right {a b c : α} (h : 0 < c) : a * c < b * c ↔ a < b :=
⟨λ h', lt_of_mul_lt_mul_right h' (le_of_lt h), λ h', mul_lt_mul_of_pos_right h' h⟩
lemma mul_lt_mul'' {a b c d : α} (h1 : a < c) (h2 : b < d) (h3 : 0 ≤ a) (h4 : 0 ≤ b) :
a * b < c * d :=
(lt_or_eq_of_le h4).elim
(λ b0, mul_lt_mul h1 (le_of_lt h2) b0 (le_trans h3 (le_of_lt h1)))
(λ b0, by rw [← b0, mul_zero]; exact
mul_pos (lt_of_le_of_lt h3 h1) (lt_of_le_of_lt h4 h2))
lemma le_mul_iff_one_le_left {a b : α} (hb : b > 0) : b ≤ a * b ↔ 1 ≤ a :=
suffices 1 * b ≤ a * b ↔ 1 ≤ a, by rwa one_mul at this,
mul_le_mul_right hb
lemma lt_mul_iff_one_lt_left {a b : α} (hb : b > 0) : b < a * b ↔ 1 < a :=
suffices 1 * b < a * b ↔ 1 < a, by rwa one_mul at this,
mul_lt_mul_right hb
lemma le_mul_iff_one_le_right {a b : α} (hb : b > 0) : b ≤ b * a ↔ 1 ≤ a :=
suffices b * 1 ≤ b * a ↔ 1 ≤ a, by rwa mul_one at this,
mul_le_mul_left hb
lemma lt_mul_iff_one_lt_right {a b : α} (hb : b > 0) : b < b * a ↔ 1 < a :=
suffices b * 1 < b * a ↔ 1 < a, by rwa mul_one at this,
mul_lt_mul_left hb
lemma lt_mul_of_gt_one_right' {a b : α} (hb : b > 0) : a > 1 → b < b * a :=
(lt_mul_iff_one_lt_right hb).2
lemma le_mul_of_ge_one_right' {a b : α} (hb : b ≥ 0) (h : a ≥ 1) : b ≤ b * a :=
suffices b * 1 ≤ b * a, by rwa mul_one at this,
mul_le_mul_of_nonneg_left h hb
lemma le_mul_of_ge_one_left' {a b : α} (hb : b ≥ 0) (h : a ≥ 1) : b ≤ a * b :=
suffices 1 * b ≤ a * b, by rwa one_mul at this,
mul_le_mul_of_nonneg_right h hb
theorem mul_nonneg_iff_right_nonneg_of_pos {a b : α} (h : 0 < a) : 0 ≤ b * a ↔ 0 ≤ b :=
⟨assume : 0 ≤ b * a, nonneg_of_mul_nonneg_right this h, assume : 0 ≤ b, mul_nonneg this $ le_of_lt h⟩
lemma bit1_pos {a : α} (h : 0 ≤ a) : 0 < bit1 a :=
lt_add_of_le_of_pos (add_nonneg h h) zero_lt_one
lemma bit1_pos' {a : α} (h : 0 < a) : 0 < bit1 a :=
bit1_pos (le_of_lt h)
lemma lt_add_one (a : α) : a < a + 1 :=
lt_add_of_le_of_pos (le_refl _) zero_lt_one
lemma one_lt_two : 1 < (2 : α) := lt_add_one _
end linear_ordered_semiring
instance linear_ordered_semiring.to_no_top_order {α : Type*} [linear_ordered_semiring α] :
no_top_order α :=
⟨assume a, ⟨a + 1, lt_add_of_pos_right _ zero_lt_one⟩⟩
instance linear_ordered_semiring.to_no_bot_order {α : Type*} [linear_ordered_ring α] :
no_bot_order α :=
⟨assume a, ⟨a - 1, sub_lt_iff_lt_add.mpr $ lt_add_of_pos_right _ zero_lt_one⟩⟩
instance to_domain [s : linear_ordered_ring α] : domain α :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := @linear_ordered_ring.eq_zero_or_eq_zero_of_mul_eq_zero α s,
..s }
section linear_ordered_ring
variable [linear_ordered_ring α]
@[simp] lemma mul_le_mul_left_of_neg {a b c : α} (h : c < 0) : c * a ≤ c * b ↔ b ≤ a :=
⟨le_imp_le_iff_lt_imp_lt.2 $ λ h', mul_lt_mul_of_neg_left h' h,
λ h', mul_le_mul_of_nonpos_left h' (le_of_lt h)⟩
@[simp] lemma mul_le_mul_right_of_neg {a b c : α} (h : c < 0) : a * c ≤ b * c ↔ b ≤ a :=
⟨le_imp_le_iff_lt_imp_lt.2 $ λ h', mul_lt_mul_of_neg_right h' h,
λ h', mul_le_mul_of_nonpos_right h' (le_of_lt h)⟩
@[simp] lemma mul_lt_mul_left_of_neg {a b c : α} (h : c < 0) : c * a < c * b ↔ b < a :=
le_iff_le_iff_lt_iff_lt.1 (mul_le_mul_left_of_neg h)
@[simp] lemma mul_lt_mul_right_of_neg {a b c : α} (h : c < 0) : a * c < b * c ↔ b < a :=
le_iff_le_iff_lt_iff_lt.1 (mul_le_mul_right_of_neg h)
lemma sub_one_lt (a : α) : a - 1 < a :=
sub_lt_iff_lt_add.2 (lt_add_one a)
lemma mul_le_one {α : Type*} [linear_ordered_semiring α] {a b : α} (ha : a ≤ 1) (hb' : 0 ≤ b)
(hb : b ≤ 1) : a * b ≤ 1 :=
begin rw ←one_mul (1 : α), apply mul_le_mul; {assumption <|> apply zero_le_one} end
end linear_ordered_ring
set_option old_structure_cmd true
/-- Extend `nonneg_comm_group` to support ordered rings
specified by their nonnegative elements -/
class nonneg_ring (α : Type*)
extends ring α, zero_ne_one_class α, nonneg_comm_group α :=
(mul_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a * b))
(mul_pos : ∀ {a b}, pos a → pos b → pos (a * b))
/-- Extend `nonneg_comm_group` to support linearly ordered rings
specified by their nonnegative elements -/
class linear_nonneg_ring (α : Type*) extends domain α, nonneg_comm_group α :=
(mul_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a * b))
(nonneg_total : ∀ a, nonneg a ∨ nonneg (-a))
namespace nonneg_ring
open nonneg_comm_group
variable [s : nonneg_ring α]
instance to_ordered_ring : ordered_ring α :=
{ le := (≤),
lt := (<),
lt_iff_le_not_le := @lt_iff_le_not_le _ _,
le_refl := @le_refl _ _,
le_trans := @le_trans _ _,
le_antisymm := @le_antisymm _ _,
add_lt_add_left := @add_lt_add_left _ _,
add_le_add_left := @add_le_add_left _ _,
mul_nonneg := λ a b, by simp [nonneg_def.symm]; exact mul_nonneg,
mul_pos := λ a b, by simp [pos_def.symm]; exact mul_pos,
..s }
def nonneg_ring.to_linear_nonneg_ring
(nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a))
: linear_nonneg_ring α :=
{ nonneg_total := nonneg_total,
eq_zero_or_eq_zero_of_mul_eq_zero :=
suffices ∀ {a} b : α, nonneg a → a * b = 0 → a = 0 ∨ b = 0,
from λ a b, (nonneg_total a).elim (this b)
(λ na, by simpa using this b na),
suffices ∀ {a b : α}, nonneg a → nonneg b → a * b = 0 → a = 0 ∨ b = 0,
from λ a b na, (nonneg_total b).elim (this na)
(λ nb, by simpa using this na nb),
λ a b na nb z, classical.by_cases
(λ nna : nonneg (-a), or.inl (nonneg_antisymm na nna))
(λ pa, classical.by_cases
(λ nnb : nonneg (-b), or.inr (nonneg_antisymm nb nnb))
(λ pb, absurd z $ ne_of_gt $ pos_def.1 $ mul_pos
((pos_iff _ _).2 ⟨na, pa⟩)
((pos_iff _ _).2 ⟨nb, pb⟩))),
..s }
end nonneg_ring
namespace linear_nonneg_ring
open nonneg_comm_group
variable [s : linear_nonneg_ring α]
instance to_nonneg_ring : nonneg_ring α :=
{ mul_pos := λ a b pa pb,
let ⟨a1, a2⟩ := (pos_iff α a).1 pa,
⟨b1, b2⟩ := (pos_iff α b).1 pb in
have ab : nonneg (a * b), from mul_nonneg a1 b1,
(pos_iff α _).2 ⟨ab, λ hn,
have a * b = 0, from nonneg_antisymm ab hn,
(eq_zero_or_eq_zero_of_mul_eq_zero _ _ this).elim
(ne_of_gt (pos_def.1 pa))
(ne_of_gt (pos_def.1 pb))⟩,
..s }
instance to_linear_order : linear_order α :=
{ le := (≤),
lt := (<),
lt_iff_le_not_le := @lt_iff_le_not_le _ _,
le_refl := @le_refl _ _,
le_trans := @le_trans _ _,
le_antisymm := @le_antisymm _ _,
le_total := nonneg_total_iff.1 nonneg_total,
..s }
instance to_linear_ordered_ring : linear_ordered_ring α :=
{ le := (≤),
lt := (<),
lt_iff_le_not_le := @lt_iff_le_not_le _ _,
le_refl := @le_refl _ _,
le_trans := @le_trans _ _,
le_antisymm := @le_antisymm _ _,
le_total := @le_total _ _,
add_lt_add_left := @add_lt_add_left _ _,
add_le_add_left := @add_le_add_left _ _,
mul_nonneg := by simp [nonneg_def.symm]; exact @mul_nonneg _ _,
mul_pos := by simp [pos_def.symm]; exact @nonneg_ring.mul_pos _ _,
zero_lt_one := lt_of_not_ge $ λ (h : nonneg (0 - 1)), begin
rw [zero_sub] at h,
have := mul_nonneg h h, simp at this,
exact zero_ne_one _ (nonneg_antisymm this h).symm
end, ..s }
instance to_decidable_linear_ordered_comm_ring
[decidable_pred (@nonneg α _)]
[comm : @is_commutative α (*)]
: decidable_linear_ordered_comm_ring α :=
{ decidable_le := by apply_instance,
decidable_eq := by apply_instance,
decidable_lt := by apply_instance,
mul_comm := is_commutative.comm (*),
..@linear_nonneg_ring.to_linear_ordered_ring _ s }
end linear_nonneg_ring
class canonically_ordered_comm_semiring (α : Type*) extends
canonically_ordered_monoid α, comm_semiring α, zero_ne_one_class α :=
(mul_eq_zero_iff (a b : α) : a * b = 0 ↔ a = 0 ∨ b = 0)
namespace canonically_ordered_semiring
open canonically_ordered_monoid
lemma mul_le_mul [canonically_ordered_comm_semiring α] {a b c d : α} (hab : a ≤ b) (hcd : c ≤ d) :
a * c ≤ b * d :=
begin
rcases (le_iff_exists_add _ _).1 hab with ⟨b, rfl⟩,
rcases (le_iff_exists_add _ _).1 hcd with ⟨d, rfl⟩,
suffices : a * c ≤ a * c + (a * d + b * c + b * d), by simpa [mul_add, add_mul],
exact (le_iff_exists_add _ _).2 ⟨_, rfl⟩
end
end canonically_ordered_semiring
instance : canonically_ordered_comm_semiring ℕ :=
{ le_iff_exists_add := assume a b,
⟨assume h, let ⟨c, hc⟩ := nat.le.dest h in ⟨c, hc.symm⟩,
assume ⟨c, hc⟩, hc.symm ▸ nat.le_add_right _ _⟩,
zero_ne_one := ne_of_lt zero_lt_one,
mul_eq_zero_iff := assume a b,
iff.intro nat.eq_zero_of_mul_eq_zero (by simp [or_imp_distrib] {contextual := tt}),
.. (infer_instance : ordered_comm_monoid ℕ),
.. (infer_instance : linear_ordered_semiring ℕ),
.. (infer_instance : comm_semiring ℕ) }
namespace with_top
variables [canonically_ordered_comm_semiring α] [decidable_eq α]
instance : mul_zero_class (with_top α) :=
{ zero := 0,
mul := λm n, if m = 0 ∨ n = 0 then 0 else m.bind (λa, n.bind $ λb, ↑(a * b)),
zero_mul := assume a, if_pos $ or.inl rfl,
mul_zero := assume a, if_pos $ or.inr rfl }
instance : has_one (with_top α) := ⟨↑(1:α)⟩
lemma mul_def {a b : with_top α} :
a * b = if a = 0 ∨ b = 0 then 0 else a.bind (λa, b.bind $ λb, ↑(a * b)) := rfl
@[simp] theorem top_ne_zero [partial_order α] : ⊤ ≠ (0 : with_top α) .
@[simp] theorem zero_ne_top [partial_order α] : (0 : with_top α) ≠ ⊤ .
@[simp] theorem coe_eq_zero [partial_order α] {a : α} : (a : with_top α) = 0 ↔ a = 0 :=
iff.intro
(assume h, match a, h with _, rfl := rfl end)
(assume h, h.symm ▸ rfl)
@[simp] theorem zero_eq_coe [partial_order α] {a : α} : 0 = (a : with_top α) ↔ a = 0 :=
by rw [eq_comm, coe_eq_zero]
@[simp] theorem coe_zero [partial_order α] : ↑(0 : α) = (0 : with_top α) := rfl
@[simp] lemma mul_top {a : with_top α} (h : a ≠ 0) : a * ⊤ = ⊤ :=
by cases a; simp [mul_def, h]; refl
@[simp] lemma top_mul {a : with_top α} (h : a ≠ 0) : ⊤ * a = ⊤ :=
by cases a; simp [mul_def, h]; refl
@[simp] lemma top_mul_top : (⊤ * ⊤ : with_top α) = ⊤ :=
top_mul top_ne_zero
lemma coe_mul {a b : α} : (↑(a * b) : with_top α) = a * b :=
decidable.by_cases (assume : a = 0, by simp [this]) $ assume ha,
decidable.by_cases (assume : b = 0, by simp [this]) $ assume hb,
by simp [*, mul_def]; refl
lemma mul_coe {b : α} (hb : b ≠ 0) : ∀{a : with_top α}, a * b = a.bind (λa:α, ↑(a * b))
| none := show (if (⊤:with_top α) = 0 ∨ (b:with_top α) = 0 then 0 else ⊤ : with_top α) = ⊤,
by simp [hb]
| (some a) := show ↑a * ↑b = ↑(a * b), from coe_mul.symm
private lemma comm (a b : with_top α) : a * b = b * a :=
begin
by_cases ha : a = 0, { simp [ha] },
by_cases hb : b = 0, { simp [hb] },
simp [ha, hb, mul_def, option.bind_comm a b, mul_comm]
end
private lemma distrib' (a b c : with_top α) : (a + b) * c = a * c + b * c :=
begin
cases c,
{ show (a + b) * ⊤ = a * ⊤ + b * ⊤,
by_cases ha : a = 0; simp [ha] },
{ show (a + b) * c = a * c + b * c,
by_cases hc : c = 0, { simp [hc] },
simp [mul_coe hc], cases a; cases b,
repeat { refl <|> exact congr_arg some (add_mul _ _ _) } }
end
private lemma mul_eq_zero (a b : with_top α) : a * b = 0 ↔ a = 0 ∨ b = 0 :=
by cases a; cases b; dsimp [mul_def]; split_ifs;
simp [*, none_eq_top, some_eq_coe, canonically_ordered_comm_semiring.mul_eq_zero_iff] at *
private lemma assoc (a b c : with_top α) : (a * b) * c = a * (b * c) :=
begin
cases a,
{ by_cases hb : b = 0; by_cases hc : c = 0;
simp [*, none_eq_top, mul_eq_zero b c] },
cases b,
{ by_cases ha : a = 0; by_cases hc : c = 0;
simp [*, none_eq_top, some_eq_coe, mul_eq_zero ↑a c] },
cases c,
{ by_cases ha : a = 0; by_cases hb : b = 0;
simp [*, none_eq_top, some_eq_coe, mul_eq_zero ↑a ↑b] },
simp [some_eq_coe, coe_mul.symm, mul_assoc]
end
private lemma one_mul' : ∀a : with_top α, 1 * a = a
| none := show ((1:α) : with_top α) * ⊤ = ⊤, by simp
| (some a) := show ((1:α) : with_top α) * a = a, by simp [coe_mul.symm]
instance [canonically_ordered_comm_semiring α] [decidable_eq α] :
canonically_ordered_comm_semiring (with_top α) :=
{ one := (1 : α),
right_distrib := distrib',
left_distrib := assume a b c, by rw [comm, distrib', comm b, comm c]; refl,
mul_assoc := assoc,
mul_comm := comm,
mul_eq_zero_iff := mul_eq_zero,
one_mul := one_mul',
mul_one := assume a, by rw [comm, one_mul'],
zero_ne_one := assume h, @zero_ne_one α _ $ option.some.inj h,
.. with_top.add_comm_monoid, .. with_top.mul_zero_class, .. with_top.canonically_ordered_monoid }
end with_top
|
5f3c5c3171826bb6432b1969b6384bb7b0b0e216 | 5883d9218e6f144e20eee6ca1dab8529fa1a97c0 | /src/aeq/default.lean | f3024408e256a3171e96c4df8bb5a448b12411be | [] | no_license | spl/alpha-conversion-is-easy | 0d035bc570e52a6345d4890e4d0c9e3f9b8126c1 | ed937fe85d8495daffd9412a5524c77b9fcda094 | refs/heads/master | 1,607,649,280,020 | 1,517,380,240,000 | 1,517,380,240,000 | 52,174,747 | 4 | 0 | null | 1,456,052,226,000 | 1,456,001,163,000 | Lean | UTF-8 | Lean | false | false | 83 | lean | import .type
import .map
import .equiv
import .id
import .subst
import .properties
|
87ca707ca7be48f7e0525d945cf9d3cf5e15e9fc | 94e33a31faa76775069b071adea97e86e218a8ee | /src/topology/metric_space/kuratowski.lean | d832d6b4cb81bc9c2fcbf262384dbf118879e8cf | [
"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 | 5,221 | lean | /-
Copyright (c) 2018 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import analysis.normed_space.lp_space
import topology.sets.compacts
/-!
# The Kuratowski embedding
Any separable metric space can be embedded isometrically in `ℓ^∞(ℝ)`.
-/
noncomputable theory
open set metric topological_space
open_locale ennreal
local notation `ℓ_infty_ℝ`:= lp (λ n : ℕ, ℝ) ∞
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
namespace Kuratowski_embedding
/-! ### Any separable metric space can be embedded isometrically in ℓ^∞(ℝ) -/
variables {f g : ℓ_infty_ℝ} {n : ℕ} {C : ℝ} [metric_space α] (x : ℕ → α) (a b : α)
/-- A metric space can be embedded in `l^∞(ℝ)` via the distances to points in
a fixed countable set, if this set is dense. This map is given in `Kuratowski_embedding`,
without density assumptions. -/
def embedding_of_subset : ℓ_infty_ℝ :=
⟨ λ n, dist a (x n) - dist (x 0) (x n),
begin
apply mem_ℓp_infty,
use dist a (x 0),
rintros - ⟨n, rfl⟩,
exact abs_dist_sub_le _ _ _
end ⟩
lemma embedding_of_subset_coe : embedding_of_subset x a n = dist a (x n) - dist (x 0) (x n) := rfl
/-- The embedding map is always a semi-contraction. -/
lemma embedding_of_subset_dist_le (a b : α) :
dist (embedding_of_subset x a) (embedding_of_subset x b) ≤ dist a b :=
begin
refine lp.norm_le_of_forall_le dist_nonneg (λn, _),
simp only [lp.coe_fn_sub, pi.sub_apply, embedding_of_subset_coe, real.dist_eq],
convert abs_dist_sub_le a b (x n) using 2,
ring
end
/-- When the reference set is dense, the embedding map is an isometry on its image. -/
lemma embedding_of_subset_isometry (H : dense_range x) : isometry (embedding_of_subset x) :=
begin
refine isometry_emetric_iff_metric.2 (λa b, _),
refine (embedding_of_subset_dist_le x a b).antisymm (le_of_forall_pos_le_add (λe epos, _)),
/- First step: find n with dist a (x n) < e -/
rcases metric.mem_closure_range_iff.1 (H a) (e/2) (half_pos epos) with ⟨n, hn⟩,
/- Second step: use the norm control at index n to conclude -/
have C : dist b (x n) - dist a (x n) = embedding_of_subset x b n - embedding_of_subset x a n :=
by { simp only [embedding_of_subset_coe, sub_sub_sub_cancel_right] },
have := calc
dist a b ≤ dist a (x n) + dist (x n) b : dist_triangle _ _ _
... = 2 * dist a (x n) + (dist b (x n) - dist a (x n)) : by { simp [dist_comm], ring }
... ≤ 2 * dist a (x n) + |dist b (x n) - dist a (x n)| :
by apply_rules [add_le_add_left, le_abs_self]
... ≤ 2 * (e/2) + |embedding_of_subset x b n - embedding_of_subset x a n| :
begin rw C, apply_rules [add_le_add, mul_le_mul_of_nonneg_left, hn.le, le_refl], norm_num end
... ≤ 2 * (e/2) + dist (embedding_of_subset x b) (embedding_of_subset x a) :
begin
have : |embedding_of_subset x b n - embedding_of_subset x a n|
≤ dist (embedding_of_subset x b) (embedding_of_subset x a),
{ simpa [dist_eq_norm] using lp.norm_apply_le_norm ennreal.top_ne_zero
(embedding_of_subset x b - embedding_of_subset x a) n },
nlinarith,
end
... = dist (embedding_of_subset x b) (embedding_of_subset x a) + e : by ring,
simpa [dist_comm] using this
end
/-- Every separable metric space embeds isometrically in `ℓ_infty_ℝ`. -/
theorem exists_isometric_embedding (α : Type u) [metric_space α] [separable_space α] :
∃(f : α → ℓ_infty_ℝ), isometry f :=
begin
cases (univ : set α).eq_empty_or_nonempty with h h,
{ use (λ_, 0), assume x, exact absurd h (nonempty.ne_empty ⟨x, mem_univ x⟩) },
{ /- We construct a map x : ℕ → α with dense image -/
rcases h with ⟨basepoint⟩,
haveI : inhabited α := ⟨basepoint⟩,
have : ∃s:set α, s.countable ∧ dense s := exists_countable_dense α,
rcases this with ⟨S, ⟨S_countable, S_dense⟩⟩,
rcases set.countable_iff_exists_surjective.1 S_countable with ⟨x, x_range⟩,
/- Use embedding_of_subset to construct the desired isometry -/
exact ⟨embedding_of_subset x, embedding_of_subset_isometry x (S_dense.mono x_range)⟩ }
end
end Kuratowski_embedding
open topological_space Kuratowski_embedding
/-- The Kuratowski embedding is an isometric embedding of a separable metric space in `ℓ^∞(ℝ)`. -/
def Kuratowski_embedding (α : Type u) [metric_space α] [separable_space α] : α → ℓ_infty_ℝ :=
classical.some (Kuratowski_embedding.exists_isometric_embedding α)
/-- The Kuratowski embedding is an isometry. -/
protected lemma Kuratowski_embedding.isometry (α : Type u) [metric_space α] [separable_space α] :
isometry (Kuratowski_embedding α) :=
classical.some_spec (exists_isometric_embedding α)
/-- Version of the Kuratowski embedding for nonempty compacts -/
def nonempty_compacts.Kuratowski_embedding (α : Type u) [metric_space α] [compact_space α]
[nonempty α] :
nonempty_compacts ℓ_infty_ℝ :=
{ carrier := range (Kuratowski_embedding α),
compact' := is_compact_range (Kuratowski_embedding.isometry α).continuous,
nonempty' := range_nonempty _ }
|
f12917fa05d3185c1bbd47bac6240f05c53a7f68 | fd71e7836e9a5d14548f6d3291653cbb6c608dbe | /src/test/slim_check/default.lean | eff2ea7878afec6e09e1d4647a43355e2855d7f8 | [] | no_license | cipher1024/slim_check | 382c80a98aed105a97eeac84f590a06dca4d8c7d | 5969b7f72e01fdd46f2502ed0cbf69c0699061d4 | refs/heads/master | 1,625,514,334,828 | 1,574,118,572,000 | 1,574,118,572,000 | 101,538,155 | 2 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 32 | lean |
import test.slim_check.tactics
|
2d9277885c4e87975f6766faf35e23cc4525226b | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/order/min_max.lean | 6703101a0346788df9e4d4a098ac2c8e10dfff98 | [
"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,282 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import order.lattice
/-!
# `max` and `min`
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file proves basic properties about maxima and minima on a `linear_order`.
## Tags
min, max
-/
universes u v
variables {α : Type u} {β : Type v}
attribute [simp] max_eq_left max_eq_right min_eq_left min_eq_right
section
variables [linear_order α] [linear_order β] {f : α → β} {s : set α} {a b c d : α}
-- translate from lattices to linear orders (sup → max, inf → min)
@[simp] lemma le_min_iff : c ≤ min a b ↔ c ≤ a ∧ c ≤ b := le_inf_iff
@[simp] lemma le_max_iff : a ≤ max b c ↔ a ≤ b ∨ a ≤ c := le_sup_iff
@[simp] lemma min_le_iff : min a b ≤ c ↔ a ≤ c ∨ b ≤ c := inf_le_iff
@[simp] lemma max_le_iff : max a b ≤ c ↔ a ≤ c ∧ b ≤ c := sup_le_iff
@[simp] lemma lt_min_iff : a < min b c ↔ a < b ∧ a < c := lt_inf_iff
@[simp] lemma lt_max_iff : a < max b c ↔ a < b ∨ a < c := lt_sup_iff
@[simp] lemma min_lt_iff : min a b < c ↔ a < c ∨ b < c := inf_lt_iff
@[simp] lemma max_lt_iff : max a b < c ↔ a < c ∧ b < c := sup_lt_iff
lemma max_le_max : a ≤ c → b ≤ d → max a b ≤ max c d := sup_le_sup
lemma min_le_min : a ≤ c → b ≤ d → min a b ≤ min c d := inf_le_inf
lemma le_max_of_le_left : a ≤ b → a ≤ max b c := le_sup_of_le_left
lemma le_max_of_le_right : a ≤ c → a ≤ max b c := le_sup_of_le_right
lemma lt_max_of_lt_left (h : a < b) : a < max b c := h.trans_le (le_max_left b c)
lemma lt_max_of_lt_right (h : a < c) : a < max b c := h.trans_le (le_max_right b c)
lemma min_le_of_left_le : a ≤ c → min a b ≤ c := inf_le_of_left_le
lemma min_le_of_right_le : b ≤ c → min a b ≤ c := inf_le_of_right_le
lemma min_lt_of_left_lt (h : a < c) : min a b < c := (min_le_left a b).trans_lt h
lemma min_lt_of_right_lt (h : b < c) : min a b < c := (min_le_right a b).trans_lt h
lemma max_min_distrib_left : max a (min b c) = min (max a b) (max a c) := sup_inf_left
lemma max_min_distrib_right : max (min a b) c = min (max a c) (max b c) := sup_inf_right
lemma min_max_distrib_left : min a (max b c) = max (min a b) (min a c) := inf_sup_left
lemma min_max_distrib_right : min (max a b) c = max (min a c) (min b c) := inf_sup_right
lemma min_le_max : min a b ≤ max a b := le_trans (min_le_left a b) (le_max_left a b)
@[simp] lemma min_eq_left_iff : min a b = a ↔ a ≤ b := inf_eq_left
@[simp] lemma min_eq_right_iff : min a b = b ↔ b ≤ a := inf_eq_right
@[simp] lemma max_eq_left_iff : max a b = a ↔ b ≤ a := sup_eq_left
@[simp] lemma max_eq_right_iff : max a b = b ↔ a ≤ b := sup_eq_right
/-- For elements `a` and `b` of a linear order, either `min a b = a` and `a ≤ b`,
or `min a b = b` and `b < a`.
Use cases on this lemma to automate linarith in inequalities -/
lemma min_cases (a b : α) : min a b = a ∧ a ≤ b ∨ min a b = b ∧ b < a :=
begin
by_cases a ≤ b,
{ left,
exact ⟨min_eq_left h, h⟩ },
{ right,
exact ⟨min_eq_right (le_of_lt (not_le.mp h)), (not_le.mp h)⟩ }
end
/-- For elements `a` and `b` of a linear order, either `max a b = a` and `b ≤ a`,
or `max a b = b` and `a < b`.
Use cases on this lemma to automate linarith in inequalities -/
lemma max_cases (a b : α) : max a b = a ∧ b ≤ a ∨ max a b = b ∧ a < b := @min_cases αᵒᵈ _ a b
lemma min_eq_iff : min a b = c ↔ a = c ∧ a ≤ b ∨ b = c ∧ b ≤ a :=
begin
split,
{ intro h,
refine or.imp (λ h', _) (λ h', _) (le_total a b);
exact ⟨by simpa [h'] using h, h'⟩ },
{ rintro (⟨rfl, h⟩|⟨rfl, h⟩);
simp [h] }
end
lemma max_eq_iff : max a b = c ↔ a = c ∧ b ≤ a ∨ b = c ∧ a ≤ b := @min_eq_iff αᵒᵈ _ a b c
lemma min_lt_min_left_iff : min a c < min b c ↔ a < b ∧ a < c :=
by { simp_rw [lt_min_iff, min_lt_iff, or_iff_left (lt_irrefl _)],
exact and_congr_left (λ h, or_iff_left_of_imp h.trans) }
lemma min_lt_min_right_iff : min a b < min a c ↔ b < c ∧ b < a :=
by simp_rw [min_comm a, min_lt_min_left_iff]
lemma max_lt_max_left_iff : max a c < max b c ↔ a < b ∧ c < b := @min_lt_min_left_iff αᵒᵈ _ _ _ _
lemma max_lt_max_right_iff : max a b < max a c ↔ b < c ∧ a < c := @min_lt_min_right_iff αᵒᵈ _ _ _ _
/-- An instance asserting that `max a a = a` -/
instance max_idem : is_idempotent α max := by apply_instance -- short-circuit type class inference
/-- An instance asserting that `min a a = a` -/
instance min_idem : is_idempotent α min := by apply_instance -- short-circuit type class inference
lemma min_lt_max : min a b < max a b ↔ a ≠ b := inf_lt_sup
lemma max_lt_max (h₁ : a < c) (h₂ : b < d) : max a b < max c d :=
by simp [lt_max_iff, max_lt_iff, *]
lemma min_lt_min (h₁ : a < c) (h₂ : b < d) : min a b < min c d := @max_lt_max αᵒᵈ _ _ _ _ _ h₁ h₂
theorem min_right_comm (a b c : α) : min (min a b) c = min (min a c) b :=
right_comm min min_comm min_assoc a b c
theorem max.left_comm (a b c : α) : max a (max b c) = max b (max a c) :=
left_comm max max_comm max_assoc a b c
theorem max.right_comm (a b c : α) : max (max a b) c = max (max a c) b :=
right_comm max max_comm max_assoc a b c
lemma monotone_on.map_max (hf : monotone_on f s) (ha : a ∈ s) (hb : b ∈ s) :
f (max a b) = max (f a) (f b) :=
by cases le_total a b; simp only [max_eq_right, max_eq_left, hf ha hb, hf hb ha, h]
lemma monotone_on.map_min (hf : monotone_on f s) (ha : a ∈ s) (hb : b ∈ s) :
f (min a b) = min (f a) (f b) :=
hf.dual.map_max ha hb
lemma antitone_on.map_max (hf : antitone_on f s) (ha : a ∈ s) (hb : b ∈ s) :
f (max a b) = min (f a) (f b) :=
hf.dual_right.map_max ha hb
lemma antitone_on.map_min (hf : antitone_on f s) (ha : a ∈ s) (hb : b ∈ s) :
f (min a b) = max (f a) (f b) :=
hf.dual.map_max ha hb
lemma monotone.map_max (hf : monotone f) : f (max a b) = max (f a) (f b) :=
by cases le_total a b; simp [h, hf h]
lemma monotone.map_min (hf : monotone f) : f (min a b) = min (f a) (f b) :=
hf.dual.map_max
lemma antitone.map_max (hf : antitone f) : f (max a b) = min (f a) (f b) :=
by cases le_total a b; simp [h, hf h]
lemma antitone.map_min (hf : antitone f) : f (min a b) = max (f a) (f b) :=
hf.dual.map_max
theorem min_choice (a b : α) : min a b = a ∨ min a b = b :=
by cases le_total a b; simp *
theorem max_choice (a b : α) : max a b = a ∨ max a b = b :=
@min_choice αᵒᵈ _ a b
lemma le_of_max_le_left {a b c : α} (h : max a b ≤ c) : a ≤ c :=
le_trans (le_max_left _ _) h
lemma le_of_max_le_right {a b c : α} (h : max a b ≤ c) : b ≤ c :=
le_trans (le_max_right _ _) h
lemma max_commutative : commutative (max : α → α → α) :=
max_comm
lemma max_associative : associative (max : α → α → α) :=
max_assoc
lemma max_left_commutative : left_commutative (max : α → α → α) :=
max_left_comm
lemma min_commutative : commutative (min : α → α → α) :=
min_comm
lemma min_associative : associative (min : α → α → α) :=
min_assoc
lemma min_left_commutative : left_commutative (min : α → α → α) :=
min_left_comm
end
|
369aac56705463ca32088024f5693985360032f4 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/using_expr.lean | 2b67b830fcaabfe79043bb68afe6e60242e7b6d9 | [
"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 | 216 | lean | example (p q : Prop) (H : p ∧ q) : p ∧ q ∧ p :=
have Hp : p, from and.elim_left H,
have Hq : q, from and.elim_right H,
using Hp Hq,
begin
apply and.intro, assumption,
apply and.intro, repeat assumption
end
|
65815a797a2d9bf1c6a4c787799559ed132f4256 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/algebra/big_operators/ring_auto.lean | 0d5d66b864232959b875b43612375f4b0a34d83d | [] | 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 | 4,962 | 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 Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.big_operators.basic
import Mathlib.data.finset.pi
import Mathlib.data.finset.powerset
import Mathlib.PostPort
universes u v u_1 u_2
namespace Mathlib
/-!
# Results about big operators with values in a (semi)ring
We prove results about big operators that involve some interaction between
multiplicative and additive structures on the values being combined.
-/
namespace finset
theorem sum_mul {α : Type u} {β : Type v} {s : finset α} {b : β} {f : α → β} [semiring β] :
(finset.sum s fun (x : α) => f x) * b = finset.sum s fun (x : α) => f x * b :=
Eq.symm (sum_hom s fun (x : β) => x * b)
theorem mul_sum {α : Type u} {β : Type v} {s : finset α} {b : β} {f : α → β} [semiring β] :
(b * finset.sum s fun (x : α) => f x) = finset.sum s fun (x : α) => b * f x :=
Eq.symm (sum_hom s (Mul.mul b))
theorem sum_mul_boole {α : Type u} {β : Type v} [semiring β] [DecidableEq α] (s : finset α)
(f : α → β) (a : α) :
(finset.sum s fun (x : α) => f x * ite (a = x) 1 0) = ite (a ∈ s) (f a) 0 :=
sorry
theorem sum_boole_mul {α : Type u} {β : Type v} [semiring β] [DecidableEq α] (s : finset α)
(f : α → β) (a : α) :
(finset.sum s fun (x : α) => ite (a = x) 1 0 * f x) = ite (a ∈ s) (f a) 0 :=
sorry
theorem sum_div {α : Type u} {β : Type v} [division_ring β] {s : finset α} {f : α → β} {b : β} :
(finset.sum s fun (x : α) => f x) / b = finset.sum s fun (x : α) => f x / b :=
sorry
/-- The product over a sum can be written as a sum over the product of sets, `finset.pi`.
`finset.prod_univ_sum` is an alternative statement when the product is over `univ`. -/
theorem prod_sum {α : Type u} {β : Type v} [comm_semiring β] {δ : α → Type u_1} [DecidableEq α]
[(a : α) → DecidableEq (δ a)] {s : finset α} {t : (a : α) → finset (δ a)}
{f : (a : α) → δ a → β} :
(finset.prod s fun (a : α) => finset.sum (t a) fun (b : δ a) => f a b) =
finset.sum (pi s t)
fun (p : (a : α) → a ∈ s → δ a) =>
finset.prod (attach s)
fun (x : Subtype fun (x : α) => x ∈ s) =>
f (subtype.val x) (p (subtype.val x) (subtype.property x)) :=
sorry
theorem sum_mul_sum {β : Type v} [comm_semiring β] {ι₁ : Type u_1} {ι₂ : Type u_2} (s₁ : finset ι₁)
(s₂ : finset ι₂) (f₁ : ι₁ → β) (f₂ : ι₂ → β) :
((finset.sum s₁ fun (x₁ : ι₁) => f₁ x₁) * finset.sum s₂ fun (x₂ : ι₂) => f₂ x₂) =
finset.sum (finset.product s₁ s₂) fun (p : ι₁ × ι₂) => f₁ (prod.fst p) * f₂ (prod.snd p) :=
sorry
/-- The product of `f a + g a` over all of `s` is the sum
over the powerset of `s` of the product of `f` over a subset `t` times
the product of `g` over the complement of `t` -/
theorem prod_add {α : Type u} {β : Type v} [comm_semiring β] (f : α → β) (g : α → β)
(s : finset α) :
(finset.prod s fun (a : α) => f a + g a) =
finset.sum (powerset s)
fun (t : finset α) =>
(finset.prod t fun (a : α) => f a) * finset.prod (s \ t) fun (a : α) => g a :=
sorry
/-- Summing `a^s.card * b^(n-s.card)` over all finite subsets `s` of a `finset`
gives `(a + b)^s.card`.-/
theorem sum_pow_mul_eq_add_pow {α : Type u_1} {R : Type u_2} [comm_semiring R] (a : R) (b : R)
(s : finset α) :
(finset.sum (powerset s) fun (t : finset α) => a ^ card t * b ^ (card s - card t)) =
(a + b) ^ card s :=
sorry
theorem prod_pow_eq_pow_sum {α : Type u} {β : Type v} [comm_semiring β] {x : β} {f : α → ℕ}
{s : finset α} : (finset.prod s fun (i : α) => x ^ f i) = x ^ finset.sum s fun (x : α) => f x :=
sorry
theorem dvd_sum {α : Type u} {β : Type v} [comm_semiring β] {b : β} {s : finset α} {f : α → β}
(h : ∀ (x : α), x ∈ s → b ∣ f x) : b ∣ finset.sum s fun (x : α) => f x :=
sorry
theorem prod_nat_cast {α : Type u} {β : Type v} [comm_semiring β] (s : finset α) (f : α → ℕ) :
↑(finset.prod s fun (x : α) => f x) = finset.prod s fun (x : α) => ↑(f x) :=
ring_hom.map_prod (nat.cast_ring_hom β) f s
/-- A product over all subsets of `s ∪ {x}` is obtained by multiplying the product over all subsets
of `s`, and over all subsets of `s` to which one adds `x`. -/
theorem prod_powerset_insert {α : Type u} {β : Type v} [DecidableEq α] [comm_monoid β]
{s : finset α} {x : α} (h : ¬x ∈ s) (f : finset α → β) :
(finset.prod (powerset (insert x s)) fun (a : finset α) => f a) =
(finset.prod (powerset s) fun (a : finset α) => f a) *
finset.prod (powerset s) fun (t : finset α) => f (insert x t) :=
sorry
end Mathlib |
39237f4b9d29f68a42bebc405806d3399365e281 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/local_shadowing_projection.lean | 067e26039971774ac021b3559255809381441701 | [
"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 | 220 | lean | instance : has_lt (nat × nat) := { lt := λ a b, a.1 < b.1 ∨ a.1 = b.1 ∧ a.2 < b.2 }
def prod.cmp (a b : nat × nat) : ordering :=
cmp a b
namespace prod
def foo (a : nat × nat) (cmp : nat) :=
a.cmp
end prod
|
26ccaff0a349d4788f1350b88572ce56b0b6664f | 4d3f29a7b2eff44af8fd0d3176232e039acb9ee3 | /LAMR.lean | feaa8db40367aa26f7289b0fc382767d16ecf606 | [] | no_license | marijnheule/lamr | 5fc5d69d326ff92e321242cfd7f72e78d7f99d7e | 28cc4114c7361059bb54f407fa312bf38b48728b | refs/heads/main | 1,689,338,013,620 | 1,630,359,632,000 | 1,630,359,632,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 47 | lean | import Mathlib
import LAMR.Util.Propositional
|
6b89745102a92fa40e4468590ac4663da5dbee37 | 367134ba5a65885e863bdc4507601606690974c1 | /src/category_theory/monoidal/category.lean | a9ea8ac9d2d8454138378be9e21dba2f679a1a2f | [
"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 | 20,941 | lean | /-
Copyright (c) 2018 Michael Jendrusch. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Michael Jendrusch, Scott Morrison
-/
import category_theory.products.basic
/-!
# Monoidal categories
A monoidal category is a category equipped with a tensor product, unitors, and an associator.
In the definition, we provide the tensor product as a pair of functions
* `tensor_obj : C → C → C`
* `tensor_hom : (X₁ ⟶ Y₁) → (X₂ ⟶ Y₂) → ((X₁ ⊗ X₂) ⟶ (Y₁ ⊗ Y₂))`
and allow use of the overloaded notation `⊗` for both.
The unitors and associator are provided componentwise.
The tensor product can be expressed as a functor via `tensor : C × C ⥤ C`.
The unitors and associator are gathered together as natural
isomorphisms in `left_unitor_nat_iso`, `right_unitor_nat_iso` and `associator_nat_iso`.
Some consequences of the definition are proved in other files,
e.g. `(λ_ (𝟙_ C)).hom = (ρ_ (𝟙_ C)).hom` in `category_theory.monoidal.unitors_equal`.
## Implementation
Dealing with unitors and associators is painful, and at this stage we do not have a useful
implementation of coherence for monoidal categories.
In an effort to lessen the pain, we put some effort into choosing the right `simp` lemmas.
Generally, the rule is that the component index of a natural transformation "weighs more"
in considering the complexity of an expression than does a structural isomorphism (associator, etc).
As an example when we prove Proposition 2.2.4 of
<http://www-math.mit.edu/~etingof/egnobookfinal.pdf>
we state it as a `@[simp]` lemma as
```
(λ_ (X ⊗ Y)).hom = (α_ (𝟙_ C) X Y).inv ≫ (λ_ X).hom ⊗ (𝟙 Y)
```
This is far from completely effective, but seems to prove a useful principle.
## References
* Tensor categories, Etingof, Gelaki, Nikshych, Ostrik,
http://www-math.mit.edu/~etingof/egnobookfinal.pdf
* https://stacks.math.columbia.edu/tag/0FFK.
-/
open category_theory
universes v u
open category_theory
open category_theory.category
open category_theory.iso
namespace category_theory
/--
In a monoidal category, we can take the tensor product of objects, `X ⊗ Y` and of morphisms `f ⊗ g`.
Tensor product does not need to be strictly associative on objects, but there is a
specified associator, `α_ X Y Z : (X ⊗ Y) ⊗ Z ≅ X ⊗ (Y ⊗ Z)`. There is a tensor unit `𝟙_ C`,
with specified left and right unitor isomorphisms `λ_ X : 𝟙_ C ⊗ X ≅ X` and `ρ_ X : X ⊗ 𝟙_ C ≅ X`.
These associators and unitors satisfy the pentagon and triangle equations.
See https://stacks.math.columbia.edu/tag/0FFK.
-/
class monoidal_category (C : Type u) [𝒞 : category.{v} C] :=
-- curried tensor product of objects:
(tensor_obj : C → C → C)
(infixr ` ⊗ `:70 := tensor_obj) -- This notation is only temporary
-- curried tensor product of morphisms:
(tensor_hom :
Π {X₁ Y₁ X₂ Y₂ : C}, (X₁ ⟶ Y₁) → (X₂ ⟶ Y₂) → ((X₁ ⊗ X₂) ⟶ (Y₁ ⊗ Y₂)))
(infixr ` ⊗' `:69 := tensor_hom) -- This notation is only temporary
-- tensor product laws:
(tensor_id' :
∀ (X₁ X₂ : C), (𝟙 X₁) ⊗' (𝟙 X₂) = 𝟙 (X₁ ⊗ X₂) . obviously)
(tensor_comp' :
∀ {X₁ Y₁ Z₁ X₂ Y₂ Z₂ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (g₁ : Y₁ ⟶ Z₁) (g₂ : Y₂ ⟶ Z₂),
(f₁ ≫ g₁) ⊗' (f₂ ≫ g₂) = (f₁ ⊗' f₂) ≫ (g₁ ⊗' g₂) . obviously)
-- tensor unit:
(tensor_unit [] : C)
(notation `𝟙_` := tensor_unit)
-- associator:
(associator :
Π X Y Z : C, (X ⊗ Y) ⊗ Z ≅ X ⊗ (Y ⊗ Z))
(notation `α_` := associator)
(associator_naturality' :
∀ {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃),
((f₁ ⊗' f₂) ⊗' f₃) ≫ (α_ Y₁ Y₂ Y₃).hom = (α_ X₁ X₂ X₃).hom ≫ (f₁ ⊗' (f₂ ⊗' f₃)) . obviously)
-- left unitor:
(left_unitor : Π X : C, 𝟙_ ⊗ X ≅ X)
(notation `λ_` := left_unitor)
(left_unitor_naturality' :
∀ {X Y : C} (f : X ⟶ Y), ((𝟙 𝟙_) ⊗' f) ≫ (λ_ Y).hom = (λ_ X).hom ≫ f . obviously)
-- right unitor:
(right_unitor : Π X : C, X ⊗ 𝟙_ ≅ X)
(notation `ρ_` := right_unitor)
(right_unitor_naturality' :
∀ {X Y : C} (f : X ⟶ Y), (f ⊗' (𝟙 𝟙_)) ≫ (ρ_ Y).hom = (ρ_ X).hom ≫ f . obviously)
-- pentagon identity:
(pentagon' : ∀ W X Y Z : C,
((α_ W X Y).hom ⊗' (𝟙 Z)) ≫ (α_ W (X ⊗ Y) Z).hom ≫ ((𝟙 W) ⊗' (α_ X Y Z).hom)
= (α_ (W ⊗ X) Y Z).hom ≫ (α_ W X (Y ⊗ Z)).hom . obviously)
-- triangle identity:
(triangle' :
∀ X Y : C, (α_ X 𝟙_ Y).hom ≫ ((𝟙 X) ⊗' (λ_ Y).hom) = (ρ_ X).hom ⊗' (𝟙 Y) . obviously)
restate_axiom monoidal_category.tensor_id'
attribute [simp] monoidal_category.tensor_id
restate_axiom monoidal_category.tensor_comp'
attribute [reassoc] monoidal_category.tensor_comp -- This would be redundant in the simp set.
attribute [simp] monoidal_category.tensor_comp
restate_axiom monoidal_category.associator_naturality'
attribute [reassoc] monoidal_category.associator_naturality
restate_axiom monoidal_category.left_unitor_naturality'
attribute [reassoc] monoidal_category.left_unitor_naturality
restate_axiom monoidal_category.right_unitor_naturality'
attribute [reassoc] monoidal_category.right_unitor_naturality
restate_axiom monoidal_category.pentagon'
restate_axiom monoidal_category.triangle'
attribute [simp, reassoc] monoidal_category.triangle
open monoidal_category
infixr ` ⊗ `:70 := tensor_obj
infixr ` ⊗ `:70 := tensor_hom
notation `𝟙_` := tensor_unit
notation `α_` := associator
notation `λ_` := left_unitor
notation `ρ_` := right_unitor
/-- The tensor product of two isomorphisms is an isomorphism. -/
@[simps]
def tensor_iso {C : Type u} {X Y X' Y' : C} [category.{v} C] [monoidal_category.{v} C]
(f : X ≅ Y) (g : X' ≅ Y') :
X ⊗ X' ≅ Y ⊗ Y' :=
{ hom := f.hom ⊗ g.hom,
inv := f.inv ⊗ g.inv,
hom_inv_id' := by rw [←tensor_comp, iso.hom_inv_id, iso.hom_inv_id, ←tensor_id],
inv_hom_id' := by rw [←tensor_comp, iso.inv_hom_id, iso.inv_hom_id, ←tensor_id] }
infixr ` ⊗ `:70 := tensor_iso
namespace monoidal_category
section
variables {C : Type u} [category.{v} C] [monoidal_category.{v} C]
instance tensor_is_iso {W X Y Z : C} (f : W ⟶ X) [is_iso f] (g : Y ⟶ Z) [is_iso g] :
is_iso (f ⊗ g) :=
{ ..(as_iso f ⊗ as_iso g) }
@[simp] lemma inv_tensor {W X Y Z : C} (f : W ⟶ X) [is_iso f] (g : Y ⟶ Z) [is_iso g] :
inv (f ⊗ g) = inv f ⊗ inv g := rfl
variables {U V W X Y Z : C}
-- When `rewrite_search` lands, add @[search] attributes to
-- monoidal_category.tensor_id monoidal_category.tensor_comp monoidal_category.associator_naturality
-- monoidal_category.left_unitor_naturality monoidal_category.right_unitor_naturality
-- monoidal_category.pentagon monoidal_category.triangle
-- tensor_comp_id tensor_id_comp comp_id_tensor_tensor_id
-- triangle_assoc_comp_left triangle_assoc_comp_right
-- triangle_assoc_comp_left_inv triangle_assoc_comp_right_inv
-- left_unitor_tensor left_unitor_tensor_inv
-- right_unitor_tensor right_unitor_tensor_inv
-- pentagon_inv
-- associator_inv_naturality
-- left_unitor_inv_naturality
-- right_unitor_inv_naturality
@[simp] lemma comp_tensor_id (f : W ⟶ X) (g : X ⟶ Y) :
(f ≫ g) ⊗ (𝟙 Z) = (f ⊗ (𝟙 Z)) ≫ (g ⊗ (𝟙 Z)) :=
by { rw ←tensor_comp, simp }
@[simp] lemma id_tensor_comp (f : W ⟶ X) (g : X ⟶ Y) :
(𝟙 Z) ⊗ (f ≫ g) = (𝟙 Z ⊗ f) ≫ (𝟙 Z ⊗ g) :=
by { rw ←tensor_comp, simp }
@[simp, reassoc] lemma id_tensor_comp_tensor_id (f : W ⟶ X) (g : Y ⟶ Z) :
((𝟙 Y) ⊗ f) ≫ (g ⊗ (𝟙 X)) = g ⊗ f :=
by { rw [←tensor_comp], simp }
@[simp, reassoc] lemma tensor_id_comp_id_tensor (f : W ⟶ X) (g : Y ⟶ Z) :
(g ⊗ (𝟙 W)) ≫ ((𝟙 Z) ⊗ f) = g ⊗ f :=
by { rw [←tensor_comp], simp }
lemma left_unitor_inv_naturality {X X' : C} (f : X ⟶ X') :
f ≫ (λ_ X').inv = (λ_ X).inv ≫ (𝟙 _ ⊗ f) :=
begin
apply (cancel_mono (λ_ X').hom).1,
simp only [assoc, comp_id, iso.inv_hom_id],
rw [left_unitor_naturality, ←category.assoc, iso.inv_hom_id, category.id_comp]
end
lemma right_unitor_inv_naturality {X X' : C} (f : X ⟶ X') :
f ≫ (ρ_ X').inv = (ρ_ X).inv ≫ (f ⊗ 𝟙 _) :=
begin
apply (cancel_mono (ρ_ X').hom).1,
simp only [assoc, comp_id, iso.inv_hom_id],
rw [right_unitor_naturality, ←category.assoc, iso.inv_hom_id, category.id_comp]
end
@[simp]
lemma right_unitor_conjugation {X Y : C} (f : X ⟶ Y) :
(ρ_ X).inv ≫ (f ⊗ (𝟙 (𝟙_ C))) ≫ (ρ_ Y).hom = f :=
by rw [right_unitor_naturality, ←category.assoc, iso.inv_hom_id, category.id_comp]
@[simp]
lemma left_unitor_conjugation {X Y : C} (f : X ⟶ Y) :
(λ_ X).inv ≫ ((𝟙 (𝟙_ C)) ⊗ f) ≫ (λ_ Y).hom = f :=
by rw [left_unitor_naturality, ←category.assoc, iso.inv_hom_id, category.id_comp]
@[simp] lemma tensor_left_iff
{X Y : C} (f g : X ⟶ Y) :
((𝟙 (𝟙_ C)) ⊗ f = (𝟙 (𝟙_ C)) ⊗ g) ↔ (f = g) :=
begin
split,
{ intro h,
have h' := congr_arg (λ k, (λ_ _).inv ≫ k) h,
dsimp at h',
rw [←left_unitor_inv_naturality, ←left_unitor_inv_naturality] at h',
exact (cancel_mono _).1 h', },
{ intro h, subst h, }
end
@[simp] lemma tensor_right_iff
{X Y : C} (f g : X ⟶ Y) :
(f ⊗ (𝟙 (𝟙_ C)) = g ⊗ (𝟙 (𝟙_ C))) ↔ (f = g) :=
begin
split,
{ intro h,
have h' := congr_arg (λ k, (ρ_ _).inv ≫ k) h,
dsimp at h',
rw [←right_unitor_inv_naturality, ←right_unitor_inv_naturality] at h',
exact (cancel_mono _).1 h' },
{ intro h, subst h, }
end
-- We now prove:
-- ((α_ (𝟙_ C) X Y).hom) ≫
-- ((λ_ (X ⊗ Y)).hom)
-- = ((λ_ X).hom ⊗ (𝟙 Y))
-- (and the corresponding fact for right unitors)
-- following the proof on nLab:
-- Lemma 2.2 at <https://ncatlab.org/nlab/revision/monoidal+category/115>
lemma left_unitor_product_aux_perimeter (X Y : C) :
((α_ (𝟙_ C) (𝟙_ C) X).hom ⊗ (𝟙 Y)) ≫
(α_ (𝟙_ C) ((𝟙_ C) ⊗ X) Y).hom ≫
((𝟙 (𝟙_ C)) ⊗ (α_ (𝟙_ C) X Y).hom) ≫
((𝟙 (𝟙_ C)) ⊗ (λ_ (X ⊗ Y)).hom)
= (((ρ_ (𝟙_ C)).hom ⊗ (𝟙 X)) ⊗ (𝟙 Y)) ≫
(α_ (𝟙_ C) X Y).hom :=
begin
conv_lhs { congr, skip, rw [←category.assoc] },
rw [←category.assoc, monoidal_category.pentagon, associator_naturality, tensor_id,
←monoidal_category.triangle, ←category.assoc]
end
lemma left_unitor_product_aux_triangle (X Y : C) :
((α_ (𝟙_ C) (𝟙_ C) X).hom ⊗ (𝟙 Y)) ≫
(((𝟙 (𝟙_ C)) ⊗ (λ_ X).hom) ⊗ (𝟙 Y))
= ((ρ_ (𝟙_ C)).hom ⊗ (𝟙 X)) ⊗ (𝟙 Y) :=
by rw [←comp_tensor_id, ←monoidal_category.triangle]
lemma left_unitor_product_aux_square (X Y : C) :
(α_ (𝟙_ C) ((𝟙_ C) ⊗ X) Y).hom ≫
((𝟙 (𝟙_ C)) ⊗ (λ_ X).hom ⊗ (𝟙 Y))
= (((𝟙 (𝟙_ C)) ⊗ (λ_ X).hom) ⊗ (𝟙 Y)) ≫
(α_ (𝟙_ C) X Y).hom :=
by rw associator_naturality
lemma left_unitor_product_aux (X Y : C) :
((𝟙 (𝟙_ C)) ⊗ (α_ (𝟙_ C) X Y).hom) ≫
((𝟙 (𝟙_ C)) ⊗ (λ_ (X ⊗ Y)).hom)
= (𝟙 (𝟙_ C)) ⊗ ((λ_ X).hom ⊗ (𝟙 Y)) :=
begin
rw ←(cancel_epi (α_ (𝟙_ C) ((𝟙_ C) ⊗ X) Y).hom),
rw left_unitor_product_aux_square,
rw ←(cancel_epi ((α_ (𝟙_ C) (𝟙_ C) X).hom ⊗ (𝟙 Y))),
slice_rhs 1 2 { rw left_unitor_product_aux_triangle },
conv_lhs { rw [left_unitor_product_aux_perimeter] }
end
lemma right_unitor_product_aux_perimeter (X Y : C) :
((α_ X Y (𝟙_ C)).hom ⊗ (𝟙 (𝟙_ C))) ≫
(α_ X (Y ⊗ (𝟙_ C)) (𝟙_ C)).hom ≫
((𝟙 X) ⊗ (α_ Y (𝟙_ C) (𝟙_ C)).hom) ≫
((𝟙 X) ⊗ (𝟙 Y) ⊗ (λ_ (𝟙_ C)).hom)
= ((ρ_ (X ⊗ Y)).hom ⊗ (𝟙 (𝟙_ C))) ≫
(α_ X Y (𝟙_ C)).hom :=
begin
transitivity (((α_ X Y _).hom ⊗ 𝟙 _) ≫ (α_ X _ _).hom ≫
(𝟙 X ⊗ (α_ Y _ _).hom)) ≫
(𝟙 X ⊗ 𝟙 Y ⊗ (λ_ _).hom),
{ conv_lhs { congr, skip, rw [←category.assoc] },
conv_rhs { rw [category.assoc] } },
{ conv_lhs { congr, rw [monoidal_category.pentagon] },
conv_rhs { congr, rw [←monoidal_category.triangle] },
conv_rhs { rw [category.assoc] },
conv_rhs { congr, skip, congr, congr, rw [←tensor_id] },
conv_rhs { congr, skip, rw [associator_naturality] },
conv_rhs { rw [←category.assoc] } }
end
lemma right_unitor_product_aux_triangle (X Y : C) :
((𝟙 X) ⊗ (α_ Y (𝟙_ C) (𝟙_ C)).hom) ≫
((𝟙 X) ⊗ (𝟙 Y) ⊗ (λ_ (𝟙_ C)).hom)
= (𝟙 X) ⊗ (ρ_ Y).hom ⊗ (𝟙 (𝟙_ C)) :=
by rw [←id_tensor_comp, ←monoidal_category.triangle]
lemma right_unitor_product_aux_square (X Y : C) :
(α_ X (Y ⊗ (𝟙_ C)) (𝟙_ C)).hom ≫
((𝟙 X) ⊗ (ρ_ Y).hom ⊗ (𝟙 (𝟙_ C)))
= (((𝟙 X) ⊗ (ρ_ Y).hom) ⊗ (𝟙 (𝟙_ C))) ≫
(α_ X Y (𝟙_ C)).hom :=
by rw [associator_naturality]
lemma right_unitor_product_aux (X Y : C) :
((α_ X Y (𝟙_ C)).hom ⊗ (𝟙 (𝟙_ C))) ≫
(((𝟙 X) ⊗ (ρ_ Y).hom) ⊗ (𝟙 (𝟙_ C)))
= ((ρ_ (X ⊗ Y)).hom ⊗ (𝟙 (𝟙_ C))) :=
begin
rw ←(cancel_mono (α_ X Y (𝟙_ C)).hom),
slice_lhs 2 3 { rw ←right_unitor_product_aux_square },
rw [←right_unitor_product_aux_triangle, ←right_unitor_product_aux_perimeter],
end
-- See Proposition 2.2.4 of <http://www-math.mit.edu/~etingof/egnobookfinal.pdf>
lemma left_unitor_tensor' (X Y : C) :
((α_ (𝟙_ C) X Y).hom) ≫ ((λ_ (X ⊗ Y)).hom) = ((λ_ X).hom ⊗ (𝟙 Y)) :=
by rw [←tensor_left_iff, id_tensor_comp, left_unitor_product_aux]
@[simp]
lemma left_unitor_tensor (X Y : C) :
((λ_ (X ⊗ Y)).hom) = ((α_ (𝟙_ C) X Y).inv) ≫ ((λ_ X).hom ⊗ (𝟙 Y)) :=
by { rw [←left_unitor_tensor'], simp }
lemma left_unitor_tensor_inv' (X Y : C) :
((λ_ (X ⊗ Y)).inv) ≫ ((α_ (𝟙_ C) X Y).inv) = ((λ_ X).inv ⊗ (𝟙 Y)) :=
eq_of_inv_eq_inv (by simp)
@[simp]
lemma left_unitor_tensor_inv (X Y : C) :
((λ_ (X ⊗ Y)).inv) = ((λ_ X).inv ⊗ (𝟙 Y)) ≫ ((α_ (𝟙_ C) X Y).hom) :=
by { rw [←left_unitor_tensor_inv'], simp }
@[simp]
lemma right_unitor_tensor (X Y : C) :
((ρ_ (X ⊗ Y)).hom) = ((α_ X Y (𝟙_ C)).hom) ≫ ((𝟙 X) ⊗ (ρ_ Y).hom) :=
by rw [←tensor_right_iff, comp_tensor_id, right_unitor_product_aux]
@[simp]
lemma right_unitor_tensor_inv (X Y : C) :
((ρ_ (X ⊗ Y)).inv) = ((𝟙 X) ⊗ (ρ_ Y).inv) ≫ ((α_ X Y (𝟙_ C)).inv) :=
eq_of_inv_eq_inv (by simp)
lemma associator_inv_naturality {X Y Z X' Y' Z' : C} (f : X ⟶ X') (g : Y ⟶ Y') (h : Z ⟶ Z') :
(f ⊗ (g ⊗ h)) ≫ (α_ X' Y' Z').inv = (α_ X Y Z).inv ≫ ((f ⊗ g) ⊗ h) :=
begin
apply (cancel_mono (α_ X' Y' Z').hom).1,
simp only [assoc, comp_id, iso.inv_hom_id],
rw [associator_naturality, ←category.assoc, iso.inv_hom_id, category.id_comp]
end
lemma pentagon_inv (W X Y Z : C) :
((𝟙 W) ⊗ (α_ X Y Z).inv) ≫ (α_ W (X ⊗ Y) Z).inv ≫ ((α_ W X Y).inv ⊗ (𝟙 Z))
= (α_ W X (Y ⊗ Z)).inv ≫ (α_ (W ⊗ X) Y Z).inv :=
begin
apply category_theory.eq_of_inv_eq_inv,
dsimp,
rw [category.assoc, monoidal_category.pentagon]
end
lemma triangle_assoc_comp_left (X Y : C) :
(α_ X (𝟙_ C) Y).hom ≫ ((𝟙 X) ⊗ (λ_ Y).hom) = (ρ_ X).hom ⊗ 𝟙 Y :=
monoidal_category.triangle X Y
@[simp] lemma triangle_assoc_comp_right (X Y : C) :
(α_ X (𝟙_ C) Y).inv ≫ ((ρ_ X).hom ⊗ 𝟙 Y) = ((𝟙 X) ⊗ (λ_ Y).hom) :=
by rw [←triangle_assoc_comp_left, ←category.assoc, iso.inv_hom_id, category.id_comp]
@[simp] lemma triangle_assoc_comp_right_inv (X Y : C) :
((ρ_ X).inv ⊗ 𝟙 Y) ≫ (α_ X (𝟙_ C) Y).hom = ((𝟙 X) ⊗ (λ_ Y).inv) :=
begin
apply (cancel_mono (𝟙 X ⊗ (λ_ Y).hom)).1,
simp only [assoc, triangle_assoc_comp_left],
rw [←comp_tensor_id, iso.inv_hom_id, ←id_tensor_comp, iso.inv_hom_id]
end
@[simp] lemma triangle_assoc_comp_left_inv (X Y : C) :
((𝟙 X) ⊗ (λ_ Y).inv) ≫ (α_ X (𝟙_ C) Y).inv = ((ρ_ X).inv ⊗ 𝟙 Y) :=
begin
apply (cancel_mono ((ρ_ X).hom ⊗ 𝟙 Y)).1,
simp only [triangle_assoc_comp_right, assoc],
rw [←id_tensor_comp, iso.inv_hom_id, ←comp_tensor_id, iso.inv_hom_id]
end
end
section
variables (C : Type u) [category.{v} C] [monoidal_category.{v} C]
/-- The tensor product expressed as a functor. -/
def tensor : (C × C) ⥤ C :=
{ obj := λ X, X.1 ⊗ X.2,
map := λ {X Y : C × C} (f : X ⟶ Y), f.1 ⊗ f.2 }
/-- The left-associated triple tensor product as a functor. -/
def left_assoc_tensor : (C × C × C) ⥤ C :=
{ obj := λ X, (X.1 ⊗ X.2.1) ⊗ X.2.2,
map := λ {X Y : C × C × C} (f : X ⟶ Y), (f.1 ⊗ f.2.1) ⊗ f.2.2 }
@[simp] lemma left_assoc_tensor_obj (X) :
(left_assoc_tensor C).obj X = (X.1 ⊗ X.2.1) ⊗ X.2.2 := rfl
@[simp] lemma left_assoc_tensor_map {X Y} (f : X ⟶ Y) :
(left_assoc_tensor C).map f = (f.1 ⊗ f.2.1) ⊗ f.2.2 := rfl
/-- The right-associated triple tensor product as a functor. -/
def right_assoc_tensor : (C × C × C) ⥤ C :=
{ obj := λ X, X.1 ⊗ (X.2.1 ⊗ X.2.2),
map := λ {X Y : C × C × C} (f : X ⟶ Y), f.1 ⊗ (f.2.1 ⊗ f.2.2) }
@[simp] lemma right_assoc_tensor_obj (X) :
(right_assoc_tensor C).obj X = X.1 ⊗ (X.2.1 ⊗ X.2.2) := rfl
@[simp] lemma right_assoc_tensor_map {X Y} (f : X ⟶ Y) :
(right_assoc_tensor C).map f = f.1 ⊗ (f.2.1 ⊗ f.2.2) := rfl
/-- The functor `λ X, 𝟙_ C ⊗ X`. -/
def tensor_unit_left : C ⥤ C :=
{ obj := λ X, 𝟙_ C ⊗ X,
map := λ {X Y : C} (f : X ⟶ Y), (𝟙 (𝟙_ C)) ⊗ f }
/-- The functor `λ X, X ⊗ 𝟙_ C`. -/
def tensor_unit_right : C ⥤ C :=
{ obj := λ X, X ⊗ 𝟙_ C,
map := λ {X Y : C} (f : X ⟶ Y), f ⊗ (𝟙 (𝟙_ C)) }
-- We can express the associator and the unitors, given componentwise above,
-- as natural isomorphisms.
/-- The associator as a natural isomorphism. -/
@[simps]
def associator_nat_iso :
left_assoc_tensor C ≅ right_assoc_tensor C :=
nat_iso.of_components
(by { intros, apply monoidal_category.associator })
(by { intros, apply monoidal_category.associator_naturality })
/-- The left unitor as a natural isomorphism. -/
@[simps]
def left_unitor_nat_iso :
tensor_unit_left C ≅ 𝟭 C :=
nat_iso.of_components
(by { intros, apply monoidal_category.left_unitor })
(by { intros, apply monoidal_category.left_unitor_naturality })
/-- The right unitor as a natural isomorphism. -/
@[simps]
def right_unitor_nat_iso :
tensor_unit_right C ≅ 𝟭 C :=
nat_iso.of_components
(by { intros, apply monoidal_category.right_unitor })
(by { intros, apply monoidal_category.right_unitor_naturality })
section
variables {C}
/-- Tensoring on the left with a fixed object, as a functor. -/
@[simps]
def tensor_left (X : C) : C ⥤ C :=
{ obj := λ Y, X ⊗ Y,
map := λ Y Y' f, (𝟙 X) ⊗ f, }
/--
Tensoring on the left with `X ⊗ Y` is naturally isomorphic to
tensoring on the left with `Y`, and then again with `X`.
-/
def tensor_left_tensor (X Y : C) : tensor_left (X ⊗ Y) ≅ tensor_left Y ⋙ tensor_left X :=
nat_iso.of_components
(associator _ _)
(λ Z Z' f, by { dsimp, rw[←tensor_id], apply associator_naturality })
@[simp] lemma tensor_left_tensor_hom_app (X Y Z : C) :
(tensor_left_tensor X Y).hom.app Z = (associator X Y Z).hom :=
rfl
@[simp] lemma tensor_left_tensor_inv_app (X Y Z : C) :
(tensor_left_tensor X Y).inv.app Z = (associator X Y Z).inv :=
rfl
/-- Tensoring on the right with a fixed object, as a functor. -/
@[simps]
def tensor_right (X : C) : C ⥤ C :=
{ obj := λ Y, Y ⊗ X,
map := λ Y Y' f, f ⊗ (𝟙 X), }
variables (C)
/--
Tensoring on the right, as a functor from `C` into endofunctors of `C`.
We later show this is a monoidal functor.
-/
@[simps]
def tensoring_right : C ⥤ (C ⥤ C) :=
{ obj := tensor_right,
map := λ X Y f,
{ app := λ Z, (𝟙 Z) ⊗ f } }
instance : faithful (tensoring_right C) :=
{ map_injective' := λ X Y f g h,
begin
injections with h,
replace h := congr_fun h (𝟙_ C),
simpa using h,
end }
variables {C}
/--
Tensoring on the right with `X ⊗ Y` is naturally isomorphic to
tensoring on the right with `X`, and then again with `Y`.
-/
def tensor_right_tensor (X Y : C) : tensor_right (X ⊗ Y) ≅ tensor_right X ⋙ tensor_right Y :=
nat_iso.of_components
(λ Z, (associator Z X Y).symm)
(λ Z Z' f, by { dsimp, rw[←tensor_id], apply associator_inv_naturality })
@[simp] lemma tensor_right_tensor_hom_app (X Y Z : C) :
(tensor_right_tensor X Y).hom.app Z = (associator Z X Y).inv :=
rfl
@[simp] lemma tensor_right_tensor_inv_app (X Y Z : C) :
(tensor_right_tensor X Y).inv.app Z = (associator Z X Y).hom :=
rfl
end
end
end monoidal_category
end category_theory
|
a170bb4edecdee80eb75ac6819bd94f477b8a5fc | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/rat_rfl.lean | 8ba14931d2f21fe4ca86405db98e8614f54cd1b6 | [
"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 | 86 | lean | import data.rat
open rat
example : (1:rat) + 2⁻¹ + 3 = 3 + 2⁻¹ + 1⁻¹ :=
rfl
|
4cb64483e697f280f16e54a213ee2813f0caddad | bb31430994044506fa42fd667e2d556327e18dfe | /src/data/multiset/powerset.lean | 9cf07ef3c243042c8b0bf58cd2bc75e0a3ef5ba9 | [
"Apache-2.0"
] | permissive | sgouezel/mathlib | 0cb4e5335a2ba189fa7af96d83a377f83270e503 | 00638177efd1b2534fc5269363ebf42a7871df9a | refs/heads/master | 1,674,527,483,042 | 1,673,665,568,000 | 1,673,665,568,000 | 119,598,202 | 0 | 0 | null | 1,517,348,647,000 | 1,517,348,646,000 | null | UTF-8 | Lean | false | false | 11,204 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.list.sublists
import data.multiset.nodup
/-!
# The powerset of a multiset
-/
namespace multiset
open list
variables {α : Type*}
/-! ### powerset -/
/-- A helper function for the powerset of a multiset. Given a list `l`, returns a list
of sublists of `l` (using `sublists_aux`), as multisets. -/
def powerset_aux (l : list α) : list (multiset α) :=
0 :: sublists_aux l (λ x y, x :: y)
theorem powerset_aux_eq_map_coe {l : list α} :
powerset_aux l = (sublists l).map coe :=
by simp [powerset_aux, sublists];
rw [← show @sublists_aux₁ α (multiset α) l (λ x, [↑x]) =
sublists_aux l (λ x, list.cons ↑x),
from sublists_aux₁_eq_sublists_aux _ _,
sublists_aux_cons_eq_sublists_aux₁,
← bind_ret_eq_map, sublists_aux₁_bind]; refl
@[simp] theorem mem_powerset_aux {l : list α} {s} :
s ∈ powerset_aux l ↔ s ≤ ↑l :=
quotient.induction_on s $
by simp [powerset_aux_eq_map_coe, subperm, and.comm]
/-- Helper function for the powerset of a multiset. Given a list `l`, returns a list
of sublists of `l` (using `sublists'`), as multisets. -/
def powerset_aux' (l : list α) : list (multiset α) := (sublists' l).map coe
theorem powerset_aux_perm_powerset_aux' {l : list α} :
powerset_aux l ~ powerset_aux' l :=
by rw powerset_aux_eq_map_coe; exact (sublists_perm_sublists' _).map _
@[simp] theorem powerset_aux'_nil : powerset_aux' (@nil α) = [0] := rfl
@[simp] theorem powerset_aux'_cons (a : α) (l : list α) :
powerset_aux' (a::l) = powerset_aux' l ++ list.map (cons a) (powerset_aux' l) :=
by simp [powerset_aux']; refl
theorem powerset_aux'_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) :
powerset_aux' l₁ ~ powerset_aux' l₂ :=
begin
induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp},
{ simp, exact IH.append (IH.map _) },
{ simp, apply perm.append_left,
rw [← append_assoc, ← append_assoc,
(by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)],
exact perm_append_comm.append_right _ },
{ exact IH₁.trans IH₂ }
end
theorem powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) :
powerset_aux l₁ ~ powerset_aux l₂ :=
powerset_aux_perm_powerset_aux'.trans $
(powerset_aux'_perm p).trans powerset_aux_perm_powerset_aux'.symm
/-- The power set of a multiset. -/
def powerset (s : multiset α) : multiset (multiset α) :=
quot.lift_on s
(λ l, (powerset_aux l : multiset (multiset α)))
(λ l₁ l₂ h, quot.sound (powerset_aux_perm h))
theorem powerset_coe (l : list α) :
@powerset α l = ((sublists l).map coe : list (multiset α)) :=
congr_arg coe powerset_aux_eq_map_coe
@[simp] theorem powerset_coe' (l : list α) :
@powerset α l = ((sublists' l).map coe : list (multiset α)) :=
quot.sound powerset_aux_perm_powerset_aux'
@[simp] theorem powerset_zero : @powerset α 0 = {0} := rfl
@[simp] theorem powerset_cons (a : α) (s) :
powerset (a ::ₘ s) = powerset s + map (cons a) (powerset s) :=
quotient.induction_on s $ λ l, by simp; refl
@[simp] theorem mem_powerset {s t : multiset α} :
s ∈ powerset t ↔ s ≤ t :=
quotient.induction_on₂ s t $ by simp [subperm, and.comm]
theorem map_single_le_powerset (s : multiset α) :
s.map singleton ≤ powerset s :=
quotient.induction_on s $ λ l, begin
simp only [powerset_coe, quot_mk_to_coe, coe_le, coe_map],
show l.map (coe ∘ list.ret) <+~ (sublists l).map coe,
rw ← list.map_map,
exact ((map_ret_sublist_sublists _).map _).subperm
end
@[simp] theorem card_powerset (s : multiset α) :
card (powerset s) = 2 ^ card s :=
quotient.induction_on s $ by simp
theorem revzip_powerset_aux {l : list α} ⦃x⦄
(h : x ∈ revzip (powerset_aux l)) : x.1 + x.2 = ↑l :=
begin
rw [revzip, powerset_aux_eq_map_coe, ← map_reverse, zip_map, ← revzip] at h,
simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩,
exact quot.sound (revzip_sublists _ _ _ h)
end
theorem revzip_powerset_aux' {l : list α} ⦃x⦄
(h : x ∈ revzip (powerset_aux' l)) : x.1 + x.2 = ↑l :=
begin
rw [revzip, powerset_aux', ← map_reverse, zip_map, ← revzip] at h,
simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩,
exact quot.sound (revzip_sublists' _ _ _ h)
end
theorem revzip_powerset_aux_lemma [decidable_eq α] (l : list α)
{l' : list (multiset α)} (H : ∀ ⦃x : _ × _⦄, x ∈ revzip l' → x.1 + x.2 = ↑l) :
revzip l' = l'.map (λ x, (x, ↑l - x)) :=
begin
have : forall₂ (λ (p : multiset α × multiset α) (s : multiset α), p = (s, ↑l - s))
(revzip l') ((revzip l').map prod.fst),
{ rw [forall₂_map_right_iff, forall₂_same],
rintro ⟨s, t⟩ h,
dsimp, rw [← H h, add_tsub_cancel_left] },
rw [← forall₂_eq_eq_eq, forall₂_map_right_iff], simpa
end
theorem revzip_powerset_aux_perm_aux' {l : list α} :
revzip (powerset_aux l) ~ revzip (powerset_aux' l) :=
begin
haveI := classical.dec_eq α,
rw [revzip_powerset_aux_lemma l revzip_powerset_aux,
revzip_powerset_aux_lemma l revzip_powerset_aux'],
exact powerset_aux_perm_powerset_aux'.map _
end
theorem revzip_powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) :
revzip (powerset_aux l₁) ~ revzip (powerset_aux l₂) :=
begin
haveI := classical.dec_eq α,
simp [λ l:list α, revzip_powerset_aux_lemma l revzip_powerset_aux, coe_eq_coe.2 p],
exact (powerset_aux_perm p).map _
end
/-! ### powerset_len -/
/-- Helper function for `powerset_len`. Given a list `l`, `powerset_len_aux n l` is the list
of sublists of length `n`, as multisets. -/
def powerset_len_aux (n : ℕ) (l : list α) : list (multiset α) :=
sublists_len_aux n l coe []
theorem powerset_len_aux_eq_map_coe {n} {l : list α} :
powerset_len_aux n l = (sublists_len n l).map coe :=
by rw [powerset_len_aux, sublists_len_aux_eq, append_nil]
@[simp] theorem mem_powerset_len_aux {n} {l : list α} {s} :
s ∈ powerset_len_aux n l ↔ s ≤ ↑l ∧ card s = n :=
quotient.induction_on s $
by simp [powerset_len_aux_eq_map_coe, subperm]; exact
λ l₁, ⟨λ ⟨l₂, ⟨s, e⟩, p⟩, ⟨⟨_, p, s⟩, p.symm.length_eq.trans e⟩,
λ ⟨⟨l₂, p, s⟩, e⟩, ⟨_, ⟨s, p.length_eq.trans e⟩, p⟩⟩
@[simp] theorem powerset_len_aux_zero (l : list α) :
powerset_len_aux 0 l = [0] :=
by simp [powerset_len_aux_eq_map_coe]
@[simp] theorem powerset_len_aux_nil (n : ℕ) :
powerset_len_aux (n+1) (@nil α) = [] := rfl
@[simp] theorem powerset_len_aux_cons (n : ℕ) (a : α) (l : list α) :
powerset_len_aux (n+1) (a::l) =
powerset_len_aux (n+1) l ++ list.map (cons a) (powerset_len_aux n l) :=
by simp [powerset_len_aux_eq_map_coe]; refl
theorem powerset_len_aux_perm {n} {l₁ l₂ : list α} (p : l₁ ~ l₂) :
powerset_len_aux n l₁ ~ powerset_len_aux n l₂ :=
begin
induction n with n IHn generalizing l₁ l₂, {simp},
induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {refl},
{ simp, exact IH.append ((IHn p).map _) },
{ simp, apply perm.append_left,
cases n, {simp, apply perm.swap},
simp,
rw [← append_assoc, ← append_assoc,
(by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)],
exact perm_append_comm.append_right _ },
{ exact IH₁.trans IH₂ }
end
/-- `powerset_len n s` is the multiset of all submultisets of `s` of length `n`. -/
def powerset_len (n : ℕ) (s : multiset α) : multiset (multiset α) :=
quot.lift_on s
(λ l, (powerset_len_aux n l : multiset (multiset α)))
(λ l₁ l₂ h, quot.sound (powerset_len_aux_perm h))
theorem powerset_len_coe' (n) (l : list α) :
@powerset_len α n l = powerset_len_aux n l := rfl
theorem powerset_len_coe (n) (l : list α) :
@powerset_len α n l = ((sublists_len n l).map coe : list (multiset α)) :=
congr_arg coe powerset_len_aux_eq_map_coe
@[simp] theorem powerset_len_zero_left (s : multiset α) :
powerset_len 0 s = {0} :=
quotient.induction_on s $ λ l, by simp [powerset_len_coe']; refl
theorem powerset_len_zero_right (n : ℕ) :
@powerset_len α (n + 1) 0 = 0 := rfl
@[simp] theorem powerset_len_cons (n : ℕ) (a : α) (s) :
powerset_len (n + 1) (a ::ₘ s) =
powerset_len (n + 1) s + map (cons a) (powerset_len n s) :=
quotient.induction_on s $ λ l, by simp [powerset_len_coe']; refl
@[simp] theorem mem_powerset_len {n : ℕ} {s t : multiset α} :
s ∈ powerset_len n t ↔ s ≤ t ∧ card s = n :=
quotient.induction_on t $ λ l, by simp [powerset_len_coe']
@[simp] theorem card_powerset_len (n : ℕ) (s : multiset α) :
card (powerset_len n s) = nat.choose (card s) n :=
quotient.induction_on s $ by simp [powerset_len_coe]
theorem powerset_len_le_powerset (n : ℕ) (s : multiset α) :
powerset_len n s ≤ powerset s :=
quotient.induction_on s $ λ l, by simp [powerset_len_coe]; exact
((sublists_len_sublist_sublists' _ _).map _).subperm
theorem powerset_len_mono (n : ℕ) {s t : multiset α} (h : s ≤ t) :
powerset_len n s ≤ powerset_len n t :=
le_induction_on h $ λ l₁ l₂ h, by simp [powerset_len_coe]; exact
((sublists_len_sublist_of_sublist _ h).map _).subperm
@[simp] theorem powerset_len_empty {α : Type*} (n : ℕ) {s : multiset α} (h : s.card < n) :
powerset_len n s = 0 :=
card_eq_zero.mp (nat.choose_eq_zero_of_lt h ▸ card_powerset_len _ _)
@[simp]
lemma powerset_len_card_add (s : multiset α) {i : ℕ} (hi : 0 < i) :
s.powerset_len (s.card + i) = 0 :=
powerset_len_empty _ (lt_add_of_pos_right (card s) hi)
theorem powerset_len_map {β : Type*} (f : α → β) (n : ℕ) (s : multiset α) :
powerset_len n (s.map f) = (powerset_len n s).map (map f) :=
begin
induction s using multiset.induction with t s ih generalizing n,
{ cases n; simp [powerset_len_zero_left, powerset_len_zero_right], },
{ cases n; simp [ih, map_comp_cons], },
end
lemma pairwise_disjoint_powerset_len (s : multiset α) :
_root_.pairwise (λ i j, multiset.disjoint (s.powerset_len i) (s.powerset_len j)) :=
λ i j h x hi hj, h (eq.trans (multiset.mem_powerset_len.mp hi).right.symm
(multiset.mem_powerset_len.mp hj).right)
lemma bind_powerset_len {α : Type*} (S : multiset α) :
bind (multiset.range (S.card + 1)) (λ k, S.powerset_len k) = S.powerset :=
begin
induction S using quotient.induction_on,
simp_rw [quot_mk_to_coe, powerset_coe', powerset_len_coe, ←coe_range, coe_bind, ←list.bind_map,
coe_card],
exact coe_eq_coe.mpr ((list.range_bind_sublists_len_perm S).map _),
end
@[simp] theorem nodup_powerset {s : multiset α} : nodup (powerset s) ↔ nodup s :=
⟨λ h, (nodup_of_le (map_single_le_powerset _) h).of_map _,
quotient.induction_on s $ λ l h,
by simp; refine (nodup_sublists'.2 h).map_on _ ; exact
λ x sx y sy e,
(h.sublist_ext (mem_sublists'.1 sx) (mem_sublists'.1 sy)).1
(quotient.exact e)⟩
alias nodup_powerset ↔ nodup.of_powerset nodup.powerset
protected lemma nodup.powerset_len {n : ℕ} {s : multiset α} (h : nodup s) :
nodup (powerset_len n s) :=
nodup_of_le (powerset_len_le_powerset _ _) (nodup_powerset.2 h)
end multiset
|
f9da9348c0798bc6339a37ff7620473f4d76f266 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/algebra/order_functions.lean | ba566f4ba60a2a212c74b942b257bba0f64fb341 | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 3,640 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import algebra.order
import order.lattice
/-!
# `max` and `min`
This file proves basic properties about maxima and minima on a `linear_order`.
## Tags
min, max
-/
universes u v
variables {α : Type u} {β : Type v}
attribute [simp] max_eq_left max_eq_right min_eq_left min_eq_right
section
variables [linear_order α] [linear_order β] {f : α → β} {a b c d : α}
-- translate from lattices to linear orders (sup → max, inf → min)
@[simp] lemma le_min_iff : c ≤ min a b ↔ c ≤ a ∧ c ≤ b := le_inf_iff
@[simp] lemma max_le_iff : max a b ≤ c ↔ a ≤ c ∧ b ≤ c := sup_le_iff
lemma max_le_max : a ≤ c → b ≤ d → max a b ≤ max c d := sup_le_sup
lemma min_le_min : a ≤ c → b ≤ d → min a b ≤ min c d := inf_le_inf
lemma le_max_left_of_le : a ≤ b → a ≤ max b c := le_sup_left_of_le
lemma le_max_right_of_le : a ≤ c → a ≤ max b c := le_sup_right_of_le
lemma min_le_left_of_le : a ≤ c → min a b ≤ c := inf_le_left_of_le
lemma min_le_right_of_le : b ≤ c → min a b ≤ c := inf_le_right_of_le
lemma max_min_distrib_left : max a (min b c) = min (max a b) (max a c) := sup_inf_left
lemma max_min_distrib_right : max (min a b) c = min (max a c) (max b c) := sup_inf_right
lemma min_max_distrib_left : min a (max b c) = max (min a b) (min a c) := inf_sup_left
lemma min_max_distrib_right : min (max a b) c = max (min a c) (min b c) := inf_sup_right
lemma min_le_max : min a b ≤ max a b := le_trans (min_le_left a b) (le_max_left a b)
/-- An instance asserting that `max a a = a` -/
instance max_idem : is_idempotent α max := by apply_instance -- short-circuit type class inference
/-- An instance asserting that `min a a = a` -/
instance min_idem : is_idempotent α min := by apply_instance -- short-circuit type class inference
@[simp] lemma max_lt_iff : max a b < c ↔ (a < c ∧ b < c) :=
sup_lt_iff
@[simp] lemma lt_min_iff : a < min b c ↔ (a < b ∧ a < c) :=
lt_inf_iff
@[simp] lemma lt_max_iff : a < max b c ↔ a < b ∨ a < c :=
lt_sup_iff
@[simp] lemma min_lt_iff : min a b < c ↔ a < c ∨ b < c :=
@lt_max_iff (order_dual α) _ _ _ _
@[simp] lemma min_le_iff : min a b ≤ c ↔ a ≤ c ∨ b ≤ c :=
inf_le_iff
@[simp] lemma le_max_iff : a ≤ max b c ↔ a ≤ b ∨ a ≤ c :=
@min_le_iff (order_dual α) _ _ _ _
lemma max_lt_max (h₁ : a < c) (h₂ : b < d) : max a b < max c d :=
by simp [lt_max_iff, max_lt_iff, *]
lemma min_lt_min (h₁ : a < c) (h₂ : b < d) : min a b < min c d :=
@max_lt_max (order_dual α) _ _ _ _ _ h₁ h₂
theorem min_right_comm (a b c : α) : min (min a b) c = min (min a c) b :=
right_comm min min_comm min_assoc a b c
theorem max.left_comm (a b c : α) : max a (max b c) = max b (max a c) :=
left_comm max max_comm max_assoc a b c
theorem max.right_comm (a b c : α) : max (max a b) c = max (max a c) b :=
right_comm max max_comm max_assoc a b c
lemma monotone.map_max (hf : monotone f) : f (max a b) = max (f a) (f b) :=
by cases le_total a b; simp [h, hf h]
lemma monotone.map_min (hf : monotone f) : f (min a b) = min (f a) (f b) :=
hf.order_dual.map_max
theorem min_choice (a b : α) : min a b = a ∨ min a b = b :=
by cases le_total a b; simp *
theorem max_choice (a b : α) : max a b = a ∨ max a b = b :=
@min_choice (order_dual α) _ a b
lemma le_of_max_le_left {a b c : α} (h : max a b ≤ c) : a ≤ c :=
le_trans (le_max_left _ _) h
lemma le_of_max_le_right {a b c : α} (h : max a b ≤ c) : b ≤ c :=
le_trans (le_max_right _ _) h
end
|
ba914148f6ab61e114ebe464eb3ad2a8ae185b0a | ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5 | /stage0/src/Leanpkg.lean | a37b3a337fe06a8a6a97aef2cffae54ccf62ae20 | [
"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 | 5,020 | 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 configure : IO String := 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"]
}
System.FilePath.searchPathSeparator.toString.intercalate <| paths.map (· ++ "/build")
def build (leanArgs : List String) : IO Unit := do
let manifest ← readManifest
let path ← configure
let leanArgs := (match manifest.timeout with | some t => ["-T", toString t] | none => []) ++ leanArgs
let mut spawnArgs := {
cmd := "leanmake"
cwd := manifest.effectivePath
args := #[s!"LEAN_OPTS={" ".intercalate leanArgs}", s!"LEAN_PATH={path}"]
}
if System.Platform.isWindows then
spawnArgs := { spawnArgs with cmd := "sh", args := #[s!"{← IO.appDir}\\{spawnArgs.cmd}"] ++ spawnArgs.args }
execCmd spawnArgs
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.println "WARNING: failed to initialize git repository"
def init (n : String) := initPkg n false
def usage :=
"Lean package manager, version " ++ uiLeanVersionString ++ "
Usage: leanpkg <command>
configure download and build dependencies and print resulting LEAN_PATH
build [-- <Lean-args>] configure and build *.olean files
init <name> create a Lean package in the current directory
See `leanpkg help <command>` for more information on a specific command."
def main : (cmd : String) → (leanpkgArgs leanArgs : List String) → IO Unit
| "configure", [], [] => configure >>= IO.println
| "build", _, leanArgs => build leanArgs
| "init", [Name], [] => init Name
| "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 [-- <lean-args>]
This command invokes `Leanpkg configure` followed by
`Leanmake <lean-args>`, building the package's Lean files as well as
(transitively) imported files of dependencies. If defined, the `package.timeout`
configuration value is passed to Lean via its `-T` parameter."
| "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
|
62753761cf427748f70e79a03b444a0e4046aa77 | f4bff2062c030df03d65e8b69c88f79b63a359d8 | /src/game/topology/inter_closed_sets.lean | cde2ec8742d5be5c74e7c37bf842d978155112ee | [
"Apache-2.0"
] | permissive | adastra7470/real-number-game | 776606961f52db0eb824555ed2f8e16f92216ea3 | f9dcb7d9255a79b57e62038228a23346c2dc301b | refs/heads/master | 1,669,221,575,893 | 1,594,669,800,000 | 1,594,669,800,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 489 | lean | import data.real.basic
import data.set.lattice
import topology.basic
import game.topology.union_closed_sets
open set
--begin hide
namespace xena
-- Work in progress
-- end hide
-- begin hide
-- Checking mathlib definitions
variable β : Type*
-- end hide
/- Lemma
Arbitrary intersection of closed sets is closed -- WIP, to do.
-/
lemma is_closed_inter_of_closed (X : β → set ℝ ) ( hj : ∀ j, is_closed (X j) )
: is_closed (Inter X) :=
begin
sorry,
end
end xena -- hide
|
81bc3664c442040ab82722ac603d3dca1f7fb267 | 618003631150032a5676f229d13a079ac875ff77 | /src/algebra/group/type_tags.lean | f4ea6ecc501bc606b10827443174bc32320d7434 | [
"Apache-2.0"
] | permissive | awainverse/mathlib | 939b68c8486df66cfda64d327ad3d9165248c777 | ea76bd8f3ca0a8bf0a166a06a475b10663dec44a | refs/heads/master | 1,659,592,962,036 | 1,590,987,592,000 | 1,590,987,592,000 | 268,436,019 | 1 | 0 | Apache-2.0 | 1,590,990,500,000 | 1,590,990,500,000 | null | UTF-8 | Lean | false | false | 6,813 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import algebra.group.hom
/-!
# Type tags that turn additive structures into multiplicative, and vice versa
We define two type tags:
* `additive α`: turns any multiplicative structure on `α` into the corresponding
additive structure on `additive α`;
* `multiplicative α`: turns any additive structure on `α` into the corresponding
multiplicative structure on `multiplicative α`.
We also define instances `additive.*` and `multiplicative.*` that actually transfer the structures.
-/
universes u v
variables {α : Type u} {β : Type v}
/-- If `α` carries some multiplicative structure, then `additive α` carries the corresponding
additive structure. -/
def additive (α : Type*) := α
/-- If `α` carries some additive structure, then `multiplicative α` carries the corresponding
multiplicative structure. -/
def multiplicative (α : Type*) := α
/-- Reinterpret `x : α` as an element of `additive α`. -/
def additive.of_mul (x : α) : additive α := x
/-- Reinterpret `x : additive α` as an element of `α`. -/
def additive.to_mul (x : additive α) : α := x
lemma of_mul_inj : function.injective (@additive.of_mul α) := λ _ _, id
lemma to_mul_inj : function.injective (@additive.to_mul α) := λ _ _, id
/-- Reinterpret `x : α` as an element of `multiplicative α`. -/
def multiplicative.of_add (x : α) : multiplicative α := x
/-- Reinterpret `x : multiplicative α` as an element of `α`. -/
def multiplicative.to_add (x : multiplicative α) : α := x
lemma of_add_inj : function.injective (@multiplicative.of_add α) := λ _ _, id
lemma to_add_inj : function.injective (@multiplicative.to_add α) := λ _ _, id
@[simp] lemma to_add_of_add (x : α) : (multiplicative.of_add x).to_add = x := rfl
@[simp] lemma of_add_to_add (x : multiplicative α) : multiplicative.of_add x.to_add = x := rfl
@[simp] lemma to_mul_of_mul (x : α) : (additive.of_mul x).to_mul = x := rfl
@[simp] lemma of_mul_to_mul (x : additive α) : additive.of_mul x.to_mul = x := rfl
instance [inhabited α] : inhabited (additive α) := ⟨additive.of_mul (default α)⟩
instance [inhabited α] : inhabited (multiplicative α) := ⟨multiplicative.of_add (default α)⟩
instance additive.has_add [has_mul α] : has_add (additive α) :=
{ add := λ x y, additive.of_mul (x.to_mul * y.to_mul) }
instance [has_add α] : has_mul (multiplicative α) :=
{ mul := λ x y, multiplicative.of_add (x.to_add + y.to_add) }
@[simp] lemma of_add_add [has_add α] (x y : α) :
multiplicative.of_add (x + y) = multiplicative.of_add x * multiplicative.of_add y :=
rfl
@[simp] lemma to_add_mul [has_add α] (x y : multiplicative α) :
(x * y).to_add = x.to_add + y.to_add :=
rfl
@[simp] lemma of_mul_mul [has_mul α] (x y : α) :
additive.of_mul (x * y) = additive.of_mul x + additive.of_mul y :=
rfl
@[simp] lemma to_mul_add [has_mul α] (x y : additive α) :
(x + y).to_mul = x.to_mul * y.to_mul :=
rfl
instance [semigroup α] : add_semigroup (additive α) :=
{ add_assoc := @mul_assoc α _,
..additive.has_add }
instance [add_semigroup α] : semigroup (multiplicative α) :=
{ mul_assoc := @add_assoc α _,
..multiplicative.has_mul }
instance [comm_semigroup α] : add_comm_semigroup (additive α) :=
{ add_comm := @mul_comm _ _,
..additive.add_semigroup }
instance [add_comm_semigroup α] : comm_semigroup (multiplicative α) :=
{ mul_comm := @add_comm _ _,
..multiplicative.semigroup }
instance [left_cancel_semigroup α] : add_left_cancel_semigroup (additive α) :=
{ add_left_cancel := @mul_left_cancel _ _,
..additive.add_semigroup }
instance [add_left_cancel_semigroup α] : left_cancel_semigroup (multiplicative α) :=
{ mul_left_cancel := @add_left_cancel _ _,
..multiplicative.semigroup }
instance [right_cancel_semigroup α] : add_right_cancel_semigroup (additive α) :=
{ add_right_cancel := @mul_right_cancel _ _,
..additive.add_semigroup }
instance [add_right_cancel_semigroup α] : right_cancel_semigroup (multiplicative α) :=
{ mul_right_cancel := @add_right_cancel _ _,
..multiplicative.semigroup }
instance [has_one α] : has_zero (additive α) := ⟨additive.of_mul 1⟩
@[simp] lemma of_mul_one [has_one α] : @additive.of_mul α 1 = 0 := rfl
@[simp] lemma to_mul_zero [has_one α] : (0 : additive α).to_mul = 1 := rfl
instance [has_zero α] : has_one (multiplicative α) := ⟨multiplicative.of_add 0⟩
@[simp] lemma of_add_zero [has_zero α] : @multiplicative.of_add α 0 = 1 := rfl
@[simp] lemma to_add_one [has_zero α] : (1 : multiplicative α).to_add = 0 := rfl
instance [monoid α] : add_monoid (additive α) :=
{ zero := 0,
zero_add := @one_mul _ _,
add_zero := @mul_one _ _,
..additive.add_semigroup }
instance [add_monoid α] : monoid (multiplicative α) :=
{ one := 1,
one_mul := @zero_add _ _,
mul_one := @add_zero _ _,
..multiplicative.semigroup }
instance [comm_monoid α] : add_comm_monoid (additive α) :=
{ .. additive.add_monoid, .. additive.add_comm_semigroup }
instance [add_comm_monoid α] : comm_monoid (multiplicative α) :=
{ ..multiplicative.monoid, .. multiplicative.comm_semigroup }
instance [has_inv α] : has_neg (additive α) := ⟨λ x, multiplicative.of_add x.to_mul⁻¹⟩
@[simp] lemma of_mul_inv [has_inv α] (x : α) : additive.of_mul x⁻¹ = -(additive.of_mul x) := rfl
@[simp] lemma to_mul_neg [has_inv α] (x : additive α) : (-x).to_mul = x.to_mul⁻¹ := rfl
instance [has_neg α] : has_inv (multiplicative α) := ⟨λ x, additive.of_mul (-x.to_add)⟩
@[simp] lemma of_add_neg [has_neg α] (x : α) :
multiplicative.of_add (-x) = (multiplicative.of_add x)⁻¹ := rfl
@[simp] lemma to_add_inv [has_neg α] (x : multiplicative α) :
(x⁻¹).to_add = -x.to_add := rfl
instance [group α] : add_group (additive α) :=
{ add_left_neg := @mul_left_inv α _,
.. additive.has_neg, .. additive.add_monoid }
instance [add_group α] : group (multiplicative α) :=
{ mul_left_inv := @add_left_neg α _,
.. multiplicative.has_inv, ..multiplicative.monoid }
instance [comm_group α] : add_comm_group (additive α) :=
{ .. additive.add_group, .. additive.add_comm_monoid }
instance [add_comm_group α] : comm_group (multiplicative α) :=
{ .. multiplicative.group, .. multiplicative.comm_monoid }
/-- Reinterpret `f : α →+ β` as `multiplicative α →* multiplicative β`. -/
def add_monoid_hom.to_multiplicative [add_monoid α] [add_monoid β] (f : α →+ β) :
multiplicative α →* multiplicative β :=
⟨f.1, f.2, f.3⟩
/-- Reinterpret `f : α →* β` as `additive α →+ additive β`. -/
def monoid_hom.to_additive [monoid α] [monoid β] (f : α →* β) : additive α →+ additive β :=
⟨f.1, f.2, f.3⟩
|
314a24c19652fc1684c4d338f0aaa5c0c67a5225 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Data/NameTrie.lean | 3fb95ee45df0d3d6310b2f7c54f9c9d353089716 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 2,120 | 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.Data.PrefixTree
namespace Lean
inductive NamePart
| str (s : String)
| num (n : Nat)
instance : ToString NamePart where
toString
| NamePart.str s => s
| NamePart.num n => toString n
def NamePart.cmp : NamePart → NamePart → Ordering
| NamePart.str a, NamePart.str b => compare a b
| NamePart.num a, NamePart.num b => compare a b
| NamePart.num _, NamePart.str _ => Ordering.lt
| _, _ => Ordering.gt
def NamePart.lt : NamePart → NamePart → Bool
| NamePart.str a, NamePart.str b => a < b
| NamePart.num a, NamePart.num b => a < b
| NamePart.num _, NamePart.str _ => true
| _, _ => false
def NameTrie (β : Type u) := PrefixTree NamePart β NamePart.cmp
private def toKey (n : Name) : List NamePart :=
loop n []
where
loop
| Name.str p s, parts => loop p (NamePart.str s :: parts)
| Name.num p n, parts => loop p (NamePart.num n :: parts)
| Name.anonymous, parts => parts
def NameTrie.insert (t : NameTrie β) (n : Name) (b : β) : NameTrie β :=
PrefixTree.insert t (toKey n) b
def NameTrie.empty : NameTrie β :=
PrefixTree.empty
instance : Inhabited (NameTrie β) where
default := NameTrie.empty
instance : EmptyCollection (NameTrie β) where
emptyCollection := NameTrie.empty
def NameTrie.find? (t : NameTrie β) (k : Name) : Option β :=
PrefixTree.find? t (toKey k)
@[inline]
def NameTrie.foldMatchingM [Monad m] (t : NameTrie β) (k : Name) (init : σ) (f : β → σ → m σ) : m σ :=
PrefixTree.foldMatchingM t (toKey k) init f
@[inline]
def NameTrie.foldM [Monad m] (t : NameTrie β) (init : σ) (f : β → σ → m σ) : m σ :=
t.foldMatchingM Name.anonymous init f
@[inline]
def NameTrie.forMatchingM [Monad m] (t : NameTrie β) (k : Name) (f : β → m Unit) : m Unit :=
PrefixTree.forMatchingM t (toKey k) f
@[inline]
def NameTrie.forM [Monad m] (t : NameTrie β) (f : β → m Unit) : m Unit :=
t.forMatchingM Name.anonymous f
end Lean
|
efc17b9c8de7a45afd2a769331f72f595916a0c9 | 82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7 | /tests/lean/run/stateRef.lean | 30d6e9d10597479d8c610f1a240fc51908204648 | [
"Apache-2.0"
] | permissive | banksonian/lean4 | 3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc | 78da6b3aa2840693eea354a41e89fc5b212a5011 | refs/heads/master | 1,673,703,624,165 | 1,605,123,551,000 | 1,605,123,551,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,566 | lean | def f (v : Nat) : StateRefT Nat IO Nat := do
IO.println "hello"
modify fun s => s - v
get
def g : IO Nat :=
f 5 $.run' 20
#eval (f 5).run' 20
#eval (do set 100; f 5 : StateRefT Nat IO Nat).run' 0
def f2 : ReaderT Nat (StateRefT Nat IO) Nat := do
let v ← read
IO.println $ "context " ++ toString v
modify fun s => s + v
get
#eval (f2.run 10).run' 20
def f3 : StateT String (StateRefT Nat IO) Nat := do
let s ← get
let n ← getThe Nat
set $ s ++ ", " ++ toString n
let s ← get
IO.println s
set (n+1)
getThe Nat
#eval (f3.run' "test").run' 10
structure Label {β : Type} (v : β) (α : Type) :=
(val : α)
class HasGetAt {β : Type} (v : β) (α : outParam Type) (m : Type → Type) :=
(getAt : m α)
instance monadState.hasGetAt (β : Type) (v : β) (α : Type) (m : Type → Type) [Monad m] [MonadStateOf (Label v α) m] : HasGetAt v α m :=
{ getAt := do let a ← getThe (Label v α); pure a.val }
export HasGetAt (getAt)
abbrev M := StateRefT (Label 0 Nat) $ StateRefT (Label 1 Nat) $ StateRefT (Label 2 Nat) IO
def f4 : M Nat := do
let a0 : Nat ← getAt 0
let a1 ← getAt 1
let a2 ← getAt 2
IO.println $ "state0 " ++ toString a0
IO.println $ "state1 " ++ toString a1
IO.println $ "state1 " ++ toString a2
pure (a0 + a1 + a2)
#eval f4.run' ⟨10⟩ $.run' ⟨20⟩ $.run' ⟨30⟩
abbrev S (ω : Type) := StateRefT Nat $ StateRefT String $ ST ω
def f5 {ω} : S ω Unit := do
let s ← getThe String
modify fun n => n + s.length
pure ()
def f5Pure (n : Nat) (s : String) :=
runST fun _ => f5.run n $.run s
#eval f5Pure 10 "hello world"
|
9f57020803ac179ef5e848376294b330add36a27 | 9dd3f3912f7321eb58ee9aa8f21778ad6221f87c | /library/tools/mini_crush/nano_crush.lean | 4b30be17d1dee7a4c00fb0dd9941b4e3bf51f2a2 | [
"Apache-2.0"
] | permissive | bre7k30/lean | de893411bcfa7b3c5572e61b9e1c52951b310aa4 | 5a924699d076dab1bd5af23a8f910b433e598d7a | refs/heads/master | 1,610,900,145,817 | 1,488,006,845,000 | 1,488,006,845,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,881 | 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
We implement a crush-like strategy using simplifier,
SMT gadgets, and robust simplifier.
This is just a demo.
-/
namespace nano_crush
open tactic
meta def size (e : expr) : nat :=
e^.fold 1 (λ e _ n, n+1)
/- Collect relevant functions -/
meta def is_auto_construction : name → bool
| (name.mk_string "brec_on" p) := tt
| (name.mk_string "cases_on" p) := tt
| (name.mk_string "rec_on" p) := tt
| (name.mk_string "no_confusion" p) := tt
| (name.mk_string "below" p) := tt
| _ := ff
meta def is_relevant_fn (n : name) : tactic bool :=
do env ← get_env,
if ¬env^.is_definition n ∨ is_auto_construction n then return ff
else if env^.in_current_file n then return tt
else in_open_namespaces n
meta def collect_revelant_fns_aux : name_set → expr → tactic name_set
| s e :=
e^.mfold s $ λ t _ s,
match t with
| expr.const c _ :=
if s^.contains c then return s
else mcond (is_relevant_fn c)
(do new_s ← return $ if c^.is_internal then s else s^.insert c,
d ← get_decl c,
collect_revelant_fns_aux new_s d^.value)
(return s)
| _ := return s
end
meta def collect_revelant_fns : tactic name_set :=
do ctx ← local_context,
s₁ ← mfoldl (λ s e, infer_type e >>= collect_revelant_fns_aux s) mk_name_set ctx,
target >>= collect_revelant_fns_aux s₁
meta def add_relevant_eqns (hs : hinst_lemmas) : tactic hinst_lemmas :=
do fns ← collect_revelant_fns,
fns^.mfold hs (λ fn hs, get_eqn_lemmas_for tt fn >>= mfoldl (λ hs d, hs^.add <$> hinst_lemma.mk_from_decl d) hs)
/- Collect terms that are inductive datatypes -/
meta def is_inductive (e : expr) : tactic bool :=
do type ← infer_type e,
C ← return type^.get_app_fn,
env ← get_env,
return $ C^.is_constant && env^.is_inductive C^.const_name
open expr
meta def collect_inductive_aux : expr_set → expr → tactic expr_set
| S e :=
if S^.contains e then return S
else do
new_S ← mcond (is_inductive e) (return $ S^.insert e) (return S),
match e with
| app _ _ := fold_explicit_args e new_S collect_inductive_aux
| pi _ _ d b := if e^.is_arrow then collect_inductive_aux S d >>= flip collect_inductive_aux b else return new_S
| _ := return new_S
end
meta def collect_inductive : expr → tactic expr_set :=
collect_inductive_aux mk_expr_set
open list
meta def collect_inductive_from_target : tactic (list expr) :=
do S ← target >>= collect_inductive,
return $ qsort ((<) on size) S^.to_list
meta def collect_inductive_hyps : tactic (list expr) :=
local_context >>= mfoldl (λ r h, mcond (is_inductive h) (return $ h::r) (return r)) []
/- Induction -/
meta def try_list_aux {α} (s : tactic_state) (tac : α → tactic unit) : list α → tactic unit
| [] := failed
| (e::es) := (write s >> tac e >> now) <|> try_list_aux es
meta def try_list {α} (tac : α → tactic unit) (es : list α) : tactic unit :=
do s ← read, try_list_aux s tac es
meta def induct (tac : tactic unit) : tactic unit :=
collect_inductive_hyps >>= try_list (λ e, induction' e; tac)
meta def split (tac : tactic unit) : tactic unit :=
collect_inductive_from_target >>= try_list (λ e, cases e; tac)
meta def search (tac : tactic unit) : nat → tactic unit
| 0 := all_goals tac >> now
| (d+1) := all_goals (try tac) >> (now <|> split (search d))
meta def rsimp' (hs : hinst_lemmas) : tactic unit :=
rsimp {} hs
meta def mk_relevant_lemmas : tactic hinst_lemmas :=
add_relevant_eqns hinst_lemmas.mk
end nano_crush
open tactic nano_crush
meta def nano_crush (depth : nat := 1) :=
do hs ← mk_relevant_lemmas,
induct $ search (rsimp' hs) depth
|
dcac45c7f215692403f76c316dc86d294cd6cc70 | 8930e38ac0fae2e5e55c28d0577a8e44e2639a6d | /data/finset.lean | 48dde72f4a7450343d1c19cc6fa81499aa1be56c | [
"Apache-2.0"
] | permissive | SG4316/mathlib | 3d64035d02a97f8556ad9ff249a81a0a51a3321a | a7846022507b531a8ab53b8af8a91953fceafd3a | refs/heads/master | 1,584,869,960,527 | 1,530,718,645,000 | 1,530,724,110,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 53,584 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro
Finite sets.
-/
import data.multiset order.boolean_algebra algebra.order_functions
data.sigma.basic logic.embedding
open multiset subtype nat lattice
variables {α : Type*} {β : Type*} {γ : Type*}
/-- `finset α` is the type of finite sets of elements of `α`. It is implemented
as a multiset (a list up to permutation) which has no duplicate elements. -/
structure finset (α : Type*) :=
(val : multiset α)
(nodup : nodup val)
namespace finset
theorem eq_of_veq : ∀ {s t : finset α}, s.1 = t.1 → s = t
| ⟨s, _⟩ ⟨t, _⟩ h := by congr; assumption
@[simp] theorem val_inj {s t : finset α} : s.1 = t.1 ↔ s = t :=
⟨eq_of_veq, congr_arg _⟩
@[simp] theorem erase_dup_eq_self [decidable_eq α] (s : finset α) : erase_dup s.1 = s.1 :=
erase_dup_eq_self.2 s.2
end finset
namespace finset
instance has_decidable_eq [decidable_eq α] : decidable_eq (finset α)
| s₁ s₂ := decidable_of_iff _ val_inj
/- membership -/
instance : has_mem α (finset α) := ⟨λ a s, a ∈ s.1⟩
theorem mem_def {a : α} {s : finset α} : a ∈ s ↔ a ∈ s.1 := iff.rfl
@[simp] theorem mem_mk {a : α} {s nd} : a ∈ @finset.mk α s nd ↔ a ∈ s := iff.rfl
instance decidable_mem [h : decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ s) :=
multiset.decidable_mem _ _
/- set coercion -/
/-- Convert a finset to a set in the natural way. -/
def to_set (s : finset α) : set α := {x | x ∈ s}
instance : has_lift (finset α) (set α) := ⟨to_set⟩
@[simp] lemma mem_coe {a : α} {s : finset α} : a ∈ (↑s : set α) ↔ a ∈ s := iff.rfl
/- extensionality -/
theorem ext {s₁ s₂ : finset α} : s₁ = s₂ ↔ ∀ a, a ∈ s₁ ↔ a ∈ s₂ :=
val_inj.symm.trans $ nodup_ext s₁.2 s₂.2
@[extensionality]
theorem ext' {s₁ s₂ : finset α} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ :=
ext.2
@[simp] theorem coe_inj {s₁ s₂ : finset α} : (↑s₁ : set α) = ↑s₂ ↔ s₁ = s₂ :=
(set.set_eq_def _ _).trans ext.symm
/- subset -/
instance : has_subset (finset α) := ⟨λ s₁ s₂, ∀ ⦃a⦄, a ∈ s₁ → a ∈ s₂⟩
theorem subset_def {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ s₁.1 ⊆ s₂.1 := iff.rfl
@[simp] theorem subset.refl (s : finset α) : s ⊆ s := subset.refl _
theorem subset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := subset.trans
theorem mem_of_subset {s₁ s₂ : finset α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := mem_of_subset
theorem subset.antisymm {s₁ s₂ : finset α} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ :=
ext.2 $ λ a, ⟨@H₁ a, @H₂ a⟩
theorem subset_iff {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ ∀ ⦃x⦄, x ∈ s₁ → x ∈ s₂ := iff.rfl
@[simp] theorem coe_subset {s₁ s₂ : finset α} :
(↑s₁ : set α) ⊆ ↑s₂ ↔ s₁ ⊆ s₂ := iff.rfl
@[simp] theorem val_le_iff {s₁ s₂ : finset α} : s₁.1 ≤ s₂.1 ↔ s₁ ⊆ s₂ := le_iff_subset s₁.2
instance : has_ssubset (finset α) := ⟨λa b, a ⊆ b ∧ ¬ b ⊆ a⟩
instance : partial_order (finset α) :=
{ le := (⊆),
lt := (⊂),
le_refl := subset.refl,
le_trans := @subset.trans _,
le_antisymm := @subset.antisymm _ }
@[simp] theorem le_iff_subset {s₁ s₂ : finset α} : s₁ ≤ s₂ ↔ s₁ ⊆ s₂ := iff.rfl
@[simp] theorem lt_iff_ssubset {s₁ s₂ : finset α} : s₁ < s₂ ↔ s₁ ⊂ s₂ := iff.rfl
@[simp] theorem val_lt_iff {s₁ s₂ : finset α} : s₁.1 < s₂.1 ↔ s₁ ⊂ s₂ :=
and_congr val_le_iff $ not_congr val_le_iff
/- empty -/
protected def empty : finset α := ⟨0, nodup_zero⟩
instance : has_emptyc (finset α) := ⟨finset.empty⟩
instance : inhabited (finset α) := ⟨∅⟩
@[simp] theorem empty_val : (∅ : finset α).1 = 0 := rfl
@[simp] theorem not_mem_empty (a : α) : a ∉ (∅ : finset α) := id
@[simp] theorem ne_empty_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ≠ ∅
| e := not_mem_empty a $ e ▸ h
@[simp] theorem empty_subset (s : finset α) : ∅ ⊆ s := zero_subset _
theorem eq_empty_of_forall_not_mem {s : finset α} (H : ∀x, x ∉ s) : s = ∅ :=
eq_of_veq (eq_zero_of_forall_not_mem H)
@[simp] theorem val_eq_zero {s : finset α} : s.1 = 0 ↔ s = ∅ := @val_inj _ s ∅
theorem subset_empty {s : finset α} : s ⊆ ∅ ↔ s = ∅ := subset_zero.trans val_eq_zero
theorem exists_mem_of_ne_empty {s : finset α} (h : s ≠ ∅) : ∃ a : α, a ∈ s :=
exists_mem_of_ne_zero (mt val_eq_zero.1 h)
@[simp] lemma coe_empty : ↑(∅ : finset α) = (∅ : set α) :=
by simp [set.set_eq_def]
/-- `singleton a` is the set `{a}` containing `a` and nothing else. -/
def singleton (a : α) : finset α := ⟨_, nodup_singleton a⟩
local prefix `ι`:90 := singleton
@[simp] theorem singleton_val (a : α) : (ι a).1 = a :: 0 := rfl
@[simp] theorem mem_singleton {a b : α} : b ∈ ι a ↔ b = a :=
by simp [singleton]
theorem not_mem_singleton {a b : α} : a ∉ ι b ↔ a ≠ b := by simp
theorem mem_singleton_self (a : α) : a ∈ ι a := by simp
theorem singleton_inj {a b : α} : ι a = ι b ↔ a = b :=
⟨λ h, mem_singleton.1 (h ▸ mem_singleton_self _), congr_arg _⟩
@[simp] theorem singleton_ne_empty (a : α) : ι a ≠ ∅ := ne_empty_of_mem (mem_singleton_self _)
@[simp] lemma coe_singleton (a : α) : ↑(ι a) = ({a} : set α) :=
by simp [set.set_eq_def]
/- insert -/
section decidable_eq
variables [decidable_eq α]
/-- `insert a s` is the set `{a} ∪ s` containing `a` and the elements of `s`. -/
instance : has_insert α (finset α) := ⟨λ a s, ⟨_, nodup_ndinsert a s.2⟩⟩
@[simp] theorem has_insert_eq_insert (a : α) (s : finset α) : has_insert.insert a s = insert a s := rfl
theorem insert_def (a : α) (s : finset α) : insert a s = ⟨_, nodup_ndinsert a s.2⟩ := rfl
@[simp] theorem insert_val (a : α) (s : finset α) : (insert a s).1 = ndinsert a s.1 := rfl
theorem insert_val' (a : α) (s : finset α) : (insert a s).1 = erase_dup (a :: s.1) :=
by simp [erase_dup_cons]
theorem insert_val_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : (insert a s).1 = a :: s.1 :=
by rw [insert_val, ndinsert_of_not_mem h]
@[simp] theorem mem_insert {a b : α} {s : finset α} : a ∈ insert b s ↔ a = b ∨ a ∈ s := mem_ndinsert
theorem mem_insert_self (a : α) (s : finset α) : a ∈ insert a s := by simp
theorem mem_insert_of_mem {a b : α} {s : finset α} (h : a ∈ s) : a ∈ insert b s := by simp *
theorem mem_of_mem_insert_of_ne {a b : α} {s : finset α} (h : b ∈ insert a s) : b ≠ a → b ∈ s :=
(mem_insert.1 h).resolve_left
@[simp] lemma coe_insert (a : α) (s : finset α) : ↑(insert a s) = (insert a ↑s : set α) :=
by simp [set.set_eq_def]
@[simp] theorem insert_eq_of_mem {a : α} {s : finset α} (h : a ∈ s) : insert a s = s :=
eq_of_veq $ ndinsert_of_mem h
@[simp] theorem insert.comm (a b : α) (s : finset α) : insert a (insert b s) = insert b (insert a s) :=
ext.2 $ by simp [or.left_comm]
@[simp] theorem insert_idem (a : α) (s : finset α) : insert a (insert a s) = insert a s :=
ext.2 $ by simp
@[simp] theorem insert_ne_empty (a : α) (s : finset α) : insert a s ≠ ∅ :=
ne_empty_of_mem (mem_insert_self a s)
theorem insert_subset {a : α} {s t : finset α} : insert a s ⊆ t ↔ a ∈ t ∧ s ⊆ t :=
by simp [subset_iff, or_imp_distrib, forall_and_distrib]
theorem subset_insert [h : decidable_eq α] (a : α) (s : finset α) : s ⊆ insert a s :=
λ b, mem_insert_of_mem
theorem insert_subset_insert (a : α) {s t : finset α} (h : s ⊆ t) : insert a s ⊆ insert a t :=
insert_subset.2 ⟨mem_insert_self _ _, subset.trans h (subset_insert _ _)⟩
lemma ssubset_iff {s t : finset α} : s ⊂ t ↔ (∃a, a ∉ s ∧ insert a s ⊆ t) :=
iff.intro
(assume ⟨h₁, h₂⟩,
have ∃a, a ∈ t ∧ a ∉ s, by simpa [finset.subset_iff, classical.not_forall] using h₂,
let ⟨a, hat, has⟩ := this in ⟨a, has, insert_subset.mpr ⟨hat, h₁⟩⟩)
(assume ⟨a, hat, has⟩,
let ⟨h₁, h₂⟩ := insert_subset.mp has in
⟨h₂, assume h, hat $ h h₁⟩)
lemma ssubset_insert {s : finset α} {a : α} (h : a ∉ s) : s ⊂ insert a s :=
ssubset_iff.mpr ⟨a, h, subset.refl _⟩
@[recursor 6] protected theorem induction {α : Type*} {p : finset α → Prop} [decidable_eq α]
(h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : ∀ s, p s
| ⟨s, nd⟩ := multiset.induction_on s (λ _, h₁) (λ a s IH nd, begin
cases nodup_cons.1 nd with m nd',
rw [← (eq_of_veq _ : insert a (finset.mk s _) = ⟨a::s, nd⟩)],
{ exact h₂ (by exact m) (IH nd') },
{ rw [insert_val, ndinsert_of_not_mem m] }
end) nd
@[elab_as_eliminator] protected theorem induction_on {α : Type*} {p : finset α → Prop} [decidable_eq α]
(s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : p s :=
finset.induction h₁ h₂ s
@[simp] theorem singleton_eq_singleton (a : α) : _root_.singleton a = singleton a := rfl
@[simp] theorem insert_empty_eq_singleton (a : α) : {a} = singleton a := rfl
@[simp] theorem insert_singleton_self_eq (a : α) : ({a, a} : finset α) = ι a :=
by simp [singleton]
/- union -/
/-- `s ∪ t` is the set such that `a ∈ s ∪ t` iff `a ∈ s` or `a ∈ t`. -/
instance : has_union (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndunion s₁.1 s₂.2⟩⟩
theorem union_val_nd (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = ndunion s₁.1 s₂.1 := rfl
@[simp] theorem union_val (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = s₁.1 ∪ s₂.1 :=
ndunion_eq_union s₁.2
@[simp] theorem mem_union {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := mem_ndunion
theorem mem_union_left {a : α} {s₁ : finset α} (s₂ : finset α) (h : a ∈ s₁) : a ∈ s₁ ∪ s₂ := by simp *
theorem mem_union_right {a : α} {s₂ : finset α} (s₁ : finset α) (h : a ∈ s₂) : a ∈ s₁ ∪ s₂ := by simp *
theorem not_mem_union {a : α} {s₁ s₂ : finset α} : a ∉ s₁ ∪ s₂ ↔ a ∉ s₁ ∧ a ∉ s₂ :=
by simp [not_or_distrib]
@[simp] lemma coe_union (s₁ s₂ : finset α) : ↑(s₁ ∪ s₂) = (↑s₁ ∪ ↑s₂ : set α) := by simp [set.set_eq_def]
theorem union_subset {s₁ s₂ s₃ : finset α} (h₁ : s₁ ⊆ s₃) (h₂ : s₂ ⊆ s₃) : s₁ ∪ s₂ ⊆ s₃ :=
val_le_iff.1 (ndunion_le.2 ⟨h₁, val_le_iff.2 h₂⟩)
theorem subset_union_left {s₁ s₂ : finset α} : s₁ ⊆ s₁ ∪ s₂ := λ x, mem_union_left _
theorem subset_union_right {s₁ s₂ : finset α} : s₂ ⊆ s₁ ∪ s₂ := λ x, mem_union_right _
@[simp] theorem union_comm (s₁ s₂ : finset α) : s₁ ∪ s₂ = s₂ ∪ s₁ := by simp [ext, or_comm]
instance : is_commutative (finset α) (∪) := ⟨union_comm⟩
@[simp] theorem union_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) :=
by simp [ext, or_comm, or.left_comm]
instance : is_associative (finset α) (∪) := ⟨union_assoc⟩
@[simp] theorem union_idempotent (s : finset α) : s ∪ s = s := ext.2 $ by simp
instance : is_idempotent (finset α) (∪) := ⟨union_idempotent⟩
theorem union_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) :=
ext.2 $ by simp [or_comm, or.left_comm]
theorem union_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := by simp
@[simp] theorem union_self (s : finset α) : s ∪ s = s := by simp
@[simp] theorem union_empty (s : finset α) : s ∪ ∅ = s := by simp [ext]
@[simp] theorem empty_union (s : finset α) : ∅ ∪ s = s := by simp [ext]
theorem insert_eq (a : α) (s : finset α) : insert a s = {a} ∪ s := by simp [ext, or_comm, or.left_comm]
@[simp] theorem insert_union (a : α) (s t : finset α) : insert a s ∪ t = insert a (s ∪ t) :=
by simp [ext, or_comm, or.left_comm]
@[simp] theorem union_insert (a : α) (s t : finset α) : s ∪ insert a t = insert a (s ∪ t) :=
by simp [ext, or.left_comm]
theorem insert_union_distrib (a : α) (s t : finset α) : insert a (s ∪ t) = insert a s ∪ insert a t :=
by simp [ext]
/- inter -/
/-- `s ∩ t` is the set such that `a ∈ s ∩ t` iff `a ∈ s` and `a ∈ t`. -/
instance : has_inter (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndinter s₂.1 s₁.2⟩⟩
theorem inter_val_nd (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = ndinter s₁.1 s₂.1 := rfl
@[simp] theorem inter_val (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = s₁.1 ∩ s₂.1 :=
ndinter_eq_inter s₁.2
@[simp] theorem mem_inter {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := mem_ndinter
theorem mem_of_mem_inter_left {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₁ := (mem_inter.1 h).1
theorem mem_of_mem_inter_right {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₂ := (mem_inter.1 h).2
theorem mem_inter_of_mem {a : α} {s₁ s₂ : finset α} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ :=
and_imp.1 mem_inter.2
theorem inter_subset_left {s₁ s₂ : finset α} : s₁ ∩ s₂ ⊆ s₁ := λ a, mem_of_mem_inter_left
theorem inter_subset_right {s₁ s₂ : finset α} : s₁ ∩ s₂ ⊆ s₂ := λ a, mem_of_mem_inter_right
theorem subset_inter {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₁ ⊆ s₃ → s₁ ⊆ s₂ ∩ s₃ :=
by simp [subset_iff] {contextual:=tt}; finish
@[simp] lemma coe_inter (s₁ s₂ : finset α) : ↑(s₁ ∩ s₂) = (↑s₁ ∩ ↑s₂ : set α) := by simp [set.set_eq_def]
@[simp] theorem inter_comm (s₁ s₂ : finset α) : s₁ ∩ s₂ = s₂ ∩ s₁ := ext.2 $ by simp [and_comm]
@[simp] theorem inter_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := ext.2 $ by simp [and_comm, and.left_comm]
@[simp] theorem inter_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := ext.2 $ by simp [and.left_comm]
@[simp] theorem inter_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := ext.2 $ by simp [and.left_comm]
@[simp] theorem inter_self (s : finset α) : s ∩ s = s := ext.2 $ by simp
@[simp] theorem inter_empty (s : finset α) : s ∩ ∅ = ∅ := ext.2 $ by simp
@[simp] theorem empty_inter (s : finset α) : ∅ ∩ s = ∅ := ext.2 $ by simp
theorem inter_eq_empty_iff_disjoint {s₁ s₂ : finset α} : s₁ ∩ s₂ = ∅ ↔ s₁.1.disjoint s₂.1 :=
by rw ← val_eq_zero; simp [inter_eq_zero_iff_disjoint]
@[simp] theorem insert_inter_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₂) :
insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) :=
ext.2 $ by simp; intro x; constructor; finish
@[simp] theorem inter_insert_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₁) :
s₁ ∩ insert a s₂ = insert a (s₁ ∩ s₂) :=
by rw [inter_comm, insert_inter_of_mem h, inter_comm]
@[simp] theorem insert_inter_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₂) :
insert a s₁ ∩ s₂ = s₁ ∩ s₂ :=
ext.2 $ assume a', by by_cases h' : a' = a; simp [mem_inter, mem_insert, h, h', and_comm]
@[simp] theorem inter_insert_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₁) :
s₁ ∩ insert a s₂ = s₁ ∩ s₂ :=
by rw [inter_comm, insert_inter_of_not_mem h, inter_comm]
@[simp] theorem singleton_inter_of_mem {a : α} {s : finset α} : a ∈ s → ι a ∩ s = ι a :=
show a ∈ s → insert a ∅ ∩ s = insert a ∅, by simp {contextual := tt}
@[simp] theorem singleton_inter_of_not_mem {a : α} {s : finset α} : a ∉ s → ι a ∩ s = ∅ :=
show a ∉ s → insert a ∅ ∩ s = ∅, by simp {contextual := tt}
@[simp] theorem inter_singleton_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ∩ ι a = ι a :=
by rw [inter_comm, singleton_inter_of_mem h]
@[simp] theorem inter_singleton_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : s ∩ ι a = ∅ :=
by rw [inter_comm, singleton_inter_of_not_mem h]
/- lattice laws -/
instance : lattice (finset α) :=
{ sup := (∪),
sup_le := assume a b c, union_subset,
le_sup_left := assume a b, subset_union_left,
le_sup_right := assume a b, subset_union_right,
inf := (∩),
le_inf := assume a b c, subset_inter,
inf_le_left := assume a b, inter_subset_left,
inf_le_right := assume a b, inter_subset_right,
..finset.partial_order }
instance : semilattice_inf_bot (finset α) :=
{ bot := ∅, bot_le := empty_subset, ..finset.lattice.lattice }
instance : distrib_lattice (finset α) :=
{ le_sup_inf := assume a b c, show (a ∪ b) ∩ (a ∪ c) ⊆ a ∪ b ∩ c,
by simp [subset_iff, and_imp, or_imp_distrib] {contextual:=tt},
..finset.lattice.lattice }
theorem inter_distrib_left (s t u : finset α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) :=
ext.2 $ by simp [mem_inter, mem_union]; intro; split; finish
theorem inter_distrib_right (s t u : finset α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) :=
ext.2 $ by simp [mem_inter, mem_union]; intro; split; finish
theorem union_distrib_left (s t u : finset α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) :=
ext.2 $ by simp [mem_inter, mem_union]; intro; split; finish
theorem union_distrib_right (s t u : finset α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) :=
ext.2 $ by simp [mem_inter, mem_union]; intro; split; finish
/- erase -/
/-- `erase s a` is the set `s - {a}`, that is, the elements of `s` which are
not equal to `a`. -/
def erase (s : finset α) (a : α) : finset α := ⟨_, nodup_erase_of_nodup a s.2⟩
@[simp] theorem erase_val (s : finset α) (a : α) : (erase s a).1 = s.1.erase a := rfl
@[simp] theorem mem_erase {a b : α} {s : finset α} : a ∈ erase s b ↔ a ≠ b ∧ a ∈ s :=
mem_erase_iff_of_nodup s.2
theorem not_mem_erase (a : α) (s : finset α) : a ∉ erase s a := by simp
@[simp] theorem erase_empty (a : α) : erase ∅ a = ∅ := rfl
theorem ne_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ≠ a := by simp {contextual:=tt}
theorem mem_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ∈ s := mem_of_mem_erase
theorem mem_erase_of_ne_of_mem {a b : α} {s : finset α} : a ≠ b → a ∈ s → a ∈ erase s b := by simp {contextual:=tt}
theorem erase_insert {a : α} {s : finset α} (h : a ∉ s) : erase (insert a s) a = s :=
ext.2 $ assume x, by simp; constructor; finish
theorem insert_erase {a : α} {s : finset α} (h : a ∈ s) : insert a (erase s a) = s :=
ext.2 $ assume x, by simp; constructor; finish
theorem erase_subset_erase (a : α) {s t : finset α} (h : s ⊆ t) : erase s a ⊆ erase t a :=
val_le_iff.1 $ erase_le_erase _ $ val_le_iff.2 h
theorem erase_subset (a : α) (s : finset α) : erase s a ⊆ s := erase_subset _ _
@[simp] lemma coe_erase (a : α) (s : finset α) : ↑(erase s a) = (↑s \ {a} : set α) :=
by simp [set.set_eq_def, and_comm]
lemma erase_ssubset {a : α} {s : finset α} (h : a ∈ s) : s.erase a ⊂ s :=
calc s.erase a ⊂ insert a (s.erase a) : ssubset_insert $ not_mem_erase _ _
... = _ : insert_erase h
theorem erase_eq_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : erase s a = s :=
eq_of_veq $ erase_of_not_mem h
theorem subset_insert_iff {a : α} {s t : finset α} : s ⊆ insert a t ↔ erase s a ⊆ t :=
by simp [subset_iff, or_iff_not_imp_left]; exact forall_congr (λ x, forall_swap)
theorem erase_insert_subset (a : α) (s : finset α) : erase (insert a s) a ⊆ s :=
subset_insert_iff.1 $ subset.refl _
theorem insert_erase_subset (a : α) (s : finset α) : s ⊆ insert a (erase s a) :=
subset_insert_iff.2 $ subset.refl _
/- sdiff -/
/-- `s \ t` is the set consisting of the elements of `s` that are not in `t`. -/
instance : has_sdiff (finset α) := ⟨λs₁ s₂, ⟨s₁.1 - s₂.1, nodup_of_le (sub_le_self _ _) s₁.2⟩⟩
@[simp] theorem mem_sdiff {a : α} {s₁ s₂ : finset α} :
a ∈ s₁ \ s₂ ↔ a ∈ s₁ ∧ a ∉ s₂ := mem_sub_of_nodup s₁.2
@[simp] theorem sdiff_union_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : (s₂ \ s₁) ∪ s₁ = s₂ :=
ext.2 $ λ a, by simpa [or_and_distrib_left, dec_em] using or_iff_right_of_imp (@h a)
@[simp] theorem union_sdiff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ∪ (s₂ \ s₁) = s₂ :=
(union_comm _ _).trans (sdiff_union_of_subset h)
@[simp] theorem inter_sdiff_self (s₁ s₂ : finset α) : s₁ ∩ (s₂ \ s₁) = ∅ :=
ext.2 $ by simp {contextual := tt}
@[simp] theorem sdiff_inter_self (s₁ s₂ : finset α) : (s₂ \ s₁) ∩ s₁ = ∅ :=
by simp
theorem sdiff_subset_sdiff {s₁ s₂ t₁ t₂ : finset α} (h₁ : t₁ ⊆ t₂) (h₂ : s₂ ⊆ s₁) : t₁ \ s₁ ⊆ t₂ \ s₂ :=
by simpa [subset_iff] using λ a m₁ m₂, and.intro (h₁ m₁) (mt (@h₂ _) m₂)
@[simp] lemma coe_sdiff (s₁ s₂ : finset α) : ↑(s₁ \ s₂) = (↑s₁ \ ↑s₂ : set α) :=
by simp [set.set_eq_def]
end decidable_eq
/- attach -/
/-- `attach s` takes the elements of `s` and forms a new set of elements of the
subtype `{x // x ∈ s}`. -/
def attach (s : finset α) : finset {x // x ∈ s} := ⟨attach s.1, nodup_attach.2 s.2⟩
@[simp] theorem attach_val (s : finset α) : s.attach.1 = s.1.attach := rfl
@[simp] theorem mem_attach (s : finset α) : ∀ x, x ∈ s.attach := mem_attach _
@[simp] theorem attach_empty : attach (∅ : finset α) = ∅ := rfl
/- filter -/
section filter
variables {p q : α → Prop} [decidable_pred p] [decidable_pred q]
/-- `filter p s` is the set of elements of `s` that satisfy `p`. -/
def filter (p : α → Prop) [decidable_pred p] (s : finset α) : finset α :=
⟨_, nodup_filter p s.2⟩
@[simp] theorem filter_val (s : finset α) : (filter p s).1 = s.1.filter p := rfl
@[simp] theorem mem_filter {s : finset α} {a : α} : a ∈ s.filter p ↔ a ∈ s ∧ p a := mem_filter
@[simp] theorem filter_subset (s : finset α) : s.filter p ⊆ s := filter_subset _
theorem filter_filter (s : finset α) :
(s.filter p).filter q = s.filter (λa, p a ∧ q a) :=
ext.2 $ assume a, by simp [and_comm, and.left_comm]
@[simp] theorem filter_false {h} (s : finset α) : @filter α (λa, false) h s = ∅ :=
ext.2 $ assume a, by simp
variable [decidable_eq α]
theorem filter_union (s₁ s₂ : finset α) :
(s₁ ∪ s₂).filter p = s₁.filter p ∪ s₂.filter p :=
ext.2 $ by simp [or_and_distrib_right]
theorem filter_or (s : finset α) : s.filter (λ a, p a ∨ q a) = s.filter p ∪ s.filter q :=
ext.2 $ by simp [and_or_distrib_left]
theorem filter_and (s : finset α) : s.filter (λ a, p a ∧ q a) = s.filter p ∩ s.filter q :=
ext.2 $ by simp [and_comm, and.left_comm]
theorem filter_not (s : finset α) : s.filter (λ a, ¬ p a) = s \ s.filter p :=
ext.2 $ by simpa [and_comm] using λ a, and_congr_right $
λ h : a ∈ s, (imp_iff_right h).symm.trans imp_not_comm
theorem sdiff_eq_filter (s₁ s₂ : finset α) :
s₁ \ s₂ = filter (∉ s₂) s₁ := ext.2 $ by simp
theorem filter_union_filter_neg_eq (s : finset α) : s.filter p ∪ s.filter (λa, ¬ p a) = s :=
by simp [filter_not]
theorem filter_inter_filter_neg_eq (s : finset α) : s.filter p ∩ s.filter (λa, ¬ p a) = ∅ :=
by simp [filter_not]
@[simp] lemma coe_filter (s : finset α) : ↑(s.filter p) = ({x ∈ ↑s | p x} : set α) :=
by simp [set.set_eq_def]
end filter
/- range -/
section range
variables {n m l : ℕ}
/-- `range n` is the set of integers less than `n`. -/
def range (n : ℕ) : finset ℕ := ⟨_, nodup_range n⟩
@[simp] theorem range_val (n : ℕ) : (range n).1 = multiset.range n := rfl
@[simp] theorem mem_range : m ∈ range n ↔ m < n := mem_range
@[simp] theorem range_zero : range 0 = ∅ := rfl
@[simp] theorem range_succ : range (succ n) = insert n (range n) := eq_of_veq $ by simp
@[simp] theorem not_mem_range_self : n ∉ range n := not_mem_range_self
@[simp] theorem range_subset {n m} : range n ⊆ range m ↔ n ≤ m := range_subset
theorem exists_nat_subset_range (s : finset ℕ) : ∃n : ℕ, s ⊆ range n :=
finset.induction_on s ⟨0, by simp⟩ $ λ a s ha ⟨n, hn⟩,
⟨max (a + 1) n, insert_subset.2
⟨by simpa using le_max_left (a+1) n, subset.trans hn (by simp [le_max_right])⟩⟩
end range
/- useful rules for calculations with quantifiers -/
theorem exists_mem_empty_iff (p : α → Prop) : (∃ x, x ∈ (∅ : finset α) ∧ p x) ↔ false :=
by simp
theorem exists_mem_insert [d : decidable_eq α]
(a : α) (s : finset α) (p : α → Prop) :
(∃ x, x ∈ insert a s ∧ p x) ↔ p a ∨ (∃ x, x ∈ s ∧ p x) :=
by simp [or_and_distrib_right, exists_or_distrib]
theorem forall_mem_empty_iff (p : α → Prop) : (∀ x, x ∈ (∅ : finset α) → p x) ↔ true :=
by simp
theorem forall_mem_insert [d : decidable_eq α]
(a : α) (s : finset α) (p : α → Prop) :
(∀ x, x ∈ insert a s → p x) ↔ p a ∧ (∀ x, x ∈ s → p x) :=
by simp [or_imp_distrib, forall_and_distrib]
end finset
/- erase_dup on list and multiset -/
namespace multiset
variable [decidable_eq α]
/-- `to_finset s` removes duplicates from the multiset `s` to produce a finset. -/
def to_finset (s : multiset α) : finset α := ⟨_, nodup_erase_dup s⟩
@[simp] theorem to_finset_val (s : multiset α) : s.to_finset.1 = s.erase_dup := rfl
theorem to_finset_eq {s : multiset α} (n : nodup s) : finset.mk s n = s.to_finset :=
finset.val_inj.1 (erase_dup_eq_self.2 n).symm
@[simp] theorem mem_to_finset {a : α} {s : multiset α} : a ∈ s.to_finset ↔ a ∈ s :=
mem_erase_dup
@[simp] lemma to_finset_cons (a : α) (s : multiset α) :
to_finset (a :: s) = insert a (to_finset s) :=
finset.eq_of_veq erase_dup_cons
end multiset
namespace list
variable [decidable_eq α]
/-- `to_finset l` removes duplicates from the list `l` to produce a finset. -/
def to_finset (l : list α) : finset α := multiset.to_finset l
@[simp] theorem to_finset_val (l : list α) : l.to_finset.1 = (l.erase_dup : multiset α) := rfl
theorem to_finset_eq {l : list α} (n : nodup l) : @finset.mk α l n = l.to_finset :=
multiset.to_finset_eq n
@[simp] theorem mem_to_finset {a : α} {l : list α} : a ∈ l.to_finset ↔ a ∈ l :=
mem_erase_dup
@[simp] theorem to_finset_nil : to_finset (@nil α) = ∅ :=
rfl
@[simp] theorem to_finset_cons {a : α} {l : list α} : to_finset (a :: l) = insert a (to_finset l) :=
finset.eq_of_veq $ by by_cases h : a ∈ l; simp [finset.insert_val', multiset.erase_dup_cons, h]
end list
namespace finset
section map
open function
def map (f : α ↪ β) (s : finset α) : finset β :=
⟨s.1.map f, nodup_map f.2 s.2⟩
@[simp] theorem map_val (f : α ↪ β) (s : finset α) : (map f s).1 = s.1.map f := rfl
@[simp] theorem map_empty (f : α ↪ β) (s : finset α) : (∅ : finset α).map f = ∅ := rfl
variables {f : α ↪ β} {s : finset α}
@[simp] theorem mem_map {b : β} : b ∈ s.map f ↔ ∃ a ∈ s, f a = b := by simp [mem_def]
@[simp] theorem mem_map_of_mem (f : α ↪ β) {a} {s : finset α} (h : a ∈ s) : f a ∈ s.map f :=
mem_map.2 ⟨_, h, rfl⟩
theorem map_to_finset [decidable_eq α] [decidable_eq β] {s : multiset α} :
s.to_finset.map f = (s.map f).to_finset := ext.2 $ by simp
theorem map_refl : s.map (embedding.refl _) = s := ext.2 $ by simp [embedding.refl]
theorem map_map {g : β ↪ γ} : (s.map f).map g = s.map (f.trans g) :=
eq_of_veq $ by simp [erase_dup_map_erase_dup_eq]
theorem map_subset_map {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁.map f ⊆ s₂.map f :=
by simp [subset_def, map_subset_map h]
theorem map_filter {p : β → Prop} [decidable_pred p] :
(s.map f).filter p = (s.filter (p ∘ f)).map f :=
ext.2 $ λ b, by simp; rw ← exists_and_distrib_right;
refine exists_congr (λ a, (and_congr_right $ λ e, _).trans and.right_comm);
simp [e.2.symm]
theorem map_union [decidable_eq α] [decidable_eq β]
{f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).map f = s₁.map f ∪ s₂.map f :=
ext.2 $ by simp [mem_map, or_and_distrib_right, exists_or_distrib]
theorem map_inter [decidable_eq α] [decidable_eq β]
{f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∩ s₂).map f = s₁.map f ∩ s₂.map f :=
ext.2 $ by simp [mem_map]; exact λ b,
⟨λ ⟨a, ⟨m₁, m₂⟩, e⟩, ⟨⟨a, m₁, e⟩, ⟨a, m₂, e⟩⟩,
λ ⟨⟨a, m₁, e₁⟩, ⟨a', m₂, e₂⟩⟩, ⟨a, ⟨m₁, f.2 (e₂.trans e₁.symm) ▸ m₂⟩, e₁⟩⟩.
@[simp] theorem map_singleton (f : α ↪ β) (a : α) : (singleton a).map f = singleton (f a) :=
ext.2 $ by simp [mem_map, eq_comm]
@[simp] theorem map_insert [decidable_eq α] [decidable_eq β]
(f : α ↪ β) (a : α) (s : finset α) :
(insert a s).map f = insert (f a) (s.map f) :=
by simp [insert_eq, map_union]
@[simp] theorem map_eq_empty : s.map f = ∅ ↔ s = ∅ :=
⟨λ h, eq_empty_of_forall_not_mem $
λ a m, ne_empty_of_mem (mem_map_of_mem _ m) h, λ e, e.symm ▸ rfl⟩
lemma attach_map_val {s : finset α} : s.attach.map (embedding.subtype _) = s :=
eq_of_veq $ by simp [embedding.subtype]; rw attach_val; simp [multiset.attach_map_val]
end map
section image
variables [decidable_eq β]
/-- `image f s` is the forward image of `s` under `f`. -/
def image (f : α → β) (s : finset α) : finset β := (s.1.map f).to_finset
@[simp] theorem image_val (f : α → β) (s : finset α) : (image f s).1 = (s.1.map f).erase_dup := rfl
@[simp] theorem image_empty (f : α → β) : (∅ : finset α).image f = ∅ := rfl
variables {f : α → β} {s : finset α}
@[simp] theorem mem_image {b : β} : b ∈ s.image f ↔ ∃ a ∈ s, f a = b := by simp [mem_def]
@[simp] theorem mem_image_of_mem (f : α → β) {a} {s : finset α} (h : a ∈ s) : f a ∈ s.image f :=
mem_image.2 ⟨_, h, rfl⟩
@[simp] lemma coe_image {f : α → β} : ↑(s.image f) = f '' ↑s := by simp [set.set_eq_def]
theorem image_to_finset [decidable_eq α] {s : multiset α} : s.to_finset.image f = (s.map f).to_finset := ext.2 $ by simp
@[simp] theorem image_val_of_inj_on (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : (image f s).1 = s.1.map f :=
multiset.erase_dup_eq_self.2 (nodup_map_on H s.2)
theorem image_id [decidable_eq α] : s.image id = s := ext.2 $ by simp
theorem image_image [decidable_eq γ] {g : β → γ} : (s.image f).image g = s.image (g ∘ f) :=
eq_of_veq $ by simp [erase_dup_map_erase_dup_eq]
theorem image_subset_image {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁.image f ⊆ s₂.image f :=
by simp [subset_def, multiset.map_subset_map h]
theorem image_filter {p : β → Prop} [decidable_pred p] :
(s.image f).filter p = (s.filter (p ∘ f)).image f :=
ext.2 $ λ b, by simp [and_comm]; rw ← exists_and_distrib_left; exact
exists_congr (λ a, and.left_comm.trans $ and_congr_right $ λ e, by simp [e.symm])
theorem image_union [decidable_eq α] {f : α → β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).image f = s₁.image f ∪ s₂.image f :=
ext.2 $ by simp [mem_image, or_and_distrib_right, exists_or_distrib]
theorem image_inter [decidable_eq α] (s₁ s₂ : finset α) (hf : ∀x y, f x = f y → x = y) : (s₁ ∩ s₂).image f = s₁.image f ∩ s₂.image f :=
ext.2 $ by simp [mem_image]; exact λ b,
⟨λ ⟨a, ⟨m₁, m₂⟩, e⟩, ⟨⟨a, m₁, e⟩, ⟨a, m₂, e⟩⟩,
λ ⟨⟨a, m₁, e₁⟩, ⟨a', m₂, e₂⟩⟩, ⟨a, ⟨m₁, hf _ _ (e₂.trans e₁.symm) ▸ m₂⟩, e₁⟩⟩.
@[simp] theorem image_singleton [decidable_eq α] (f : α → β) (a : α) : (singleton a).image f = singleton (f a) :=
ext.2 $ by simp [mem_image, eq_comm]
@[simp] theorem image_insert [decidable_eq α] (f : α → β) (a : α) (s : finset α) :
(insert a s).image f = insert (f a) (s.image f) :=
by simp [insert_eq, image_union]
@[simp] theorem image_eq_empty : s.image f = ∅ ↔ s = ∅ :=
⟨λ h, eq_empty_of_forall_not_mem $
λ a m, ne_empty_of_mem (mem_image_of_mem _ m) h, λ e, e.symm ▸ rfl⟩
lemma attach_image_val [decidable_eq α] {s : finset α} : s.attach.image subtype.val = s :=
eq_of_veq $ by simp [multiset.attach_map_val]
@[simp] lemma attach_insert [decidable_eq α] {a : α} {s : finset α} :
attach (insert a s) = insert (⟨a, mem_insert_self a s⟩ : {x // x ∈ insert a s})
((attach s).image (λx, ⟨x.1, mem_insert_of_mem x.2⟩)) :=
begin
apply eq_of_veq,
dsimp,
rw [attach_ndinsert, multiset.erase_dup_eq_self.2],
{ refl },
apply nodup_map_on,
exact assume ⟨a', _⟩ _ ⟨b', _⟩ _ h, by simp at h; simp [h],
exact multiset.nodup_attach.2 s.2
end
theorem map_eq_image (f : α ↪ β) (s : finset α) : s.map f = s.image f :=
eq_of_veq $ (multiset.erase_dup_eq_self.2 (s.map f).2).symm
end image
/- card -/
section card
/-- `card s` is the cardinality (number of elements) of `s`. -/
def card (s : finset α) : nat := s.1.card
theorem card_def (s : finset α) : s.card = s.1.card := rfl
@[simp] theorem card_empty : card (∅ : finset α) = 0 := rfl
@[simp] theorem card_eq_zero {s : finset α} : card s = 0 ↔ s = ∅ :=
card_eq_zero.trans val_eq_zero
theorem card_pos {s : finset α} : 0 < card s ↔ s ≠ ∅ :=
pos_iff_ne_zero.trans $ not_congr card_eq_zero
@[simp] theorem card_insert_of_not_mem [decidable_eq α] {a : α} {s : finset α} (h : a ∉ s) : card (insert a s) = card s + 1 :=
by simpa [card] using congr_arg multiset.card (ndinsert_of_not_mem h)
theorem card_insert_le [decidable_eq α] (a : α) (s : finset α) : card (insert a s) ≤ card s + 1 :=
by by_cases a ∈ s; simp [h, nat.le_add_right]
theorem card_erase_of_mem [decidable_eq α] {a : α} {s : finset α} : a ∈ s → card (erase s a) = pred (card s) := card_erase_of_mem
theorem card_range (n : ℕ) : card (range n) = n := card_range n
theorem card_attach {s : finset α} : card (attach s) = card s := multiset.card_attach
theorem card_image_of_inj_on [decidable_eq β] {f : α → β} {s : finset α}
(H : ∀x∈s, ∀y∈s, f x = f y → x = y) : card (image f s) = card s :=
by simp [card, image_val_of_inj_on H]
theorem card_image_of_injective [decidable_eq β] {f : α → β} (s : finset α)
(H : function.injective f) : card (image f s) = card s :=
card_image_of_inj_on $ λ x _ y _ h, H h
lemma card_eq_of_bijective [decidable_eq α] {s : finset α} {n : ℕ}
(f : ∀i, i < n → α)
(hf : ∀a∈s, ∃i, ∃h:i<n, f i h = a) (hf' : ∀i (h : i < n), f i h ∈ s)
(f_inj : ∀i j (hi : i < n) (hj : j < n), f i hi = f j hj → i = j) :
card s = n :=
have ∀ (a : α), a ∈ s ↔ ∃i (hi : i ∈ range n), f i (mem_range.1 hi) = a,
from assume a, ⟨assume ha, let ⟨i, hi, eq⟩ := hf a ha in ⟨i, mem_range.2 hi, eq⟩,
assume ⟨i, hi, eq⟩, eq ▸ hf' i (mem_range.1 hi)⟩,
have s = ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)),
by simpa [ext],
calc card s = card ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)) :
by rw [this]
... = card ((range n).attach) :
card_image_of_injective _ $ assume ⟨i, hi⟩ ⟨j, hj⟩ eq,
subtype.eq $ f_inj i j (mem_range.1 hi) (mem_range.1 hj) eq
... = card (range n) : card_attach
... = n : card_range n
lemma card_eq_succ [decidable_eq α] {s : finset α} {a : α} {n : ℕ} :
s.card = n + 1 ↔ (∃a t, a ∉ t ∧ insert a t = s ∧ card t = n) :=
iff.intro
(assume eq,
have card s > 0, from eq.symm ▸ nat.zero_lt_succ _,
let ⟨a, has⟩ := finset.exists_mem_of_ne_empty $ card_pos.mp this in
⟨a, s.erase a, s.not_mem_erase a, insert_erase has, by simp [eq, card_erase_of_mem has]⟩)
(assume ⟨a, t, hat, s_eq, n_eq⟩, s_eq ▸ n_eq ▸ card_insert_of_not_mem hat)
theorem card_le_of_subset {s t : finset α} : s ⊆ t → card s ≤ card t :=
multiset.card_le_of_le ∘ val_le_iff.mpr
theorem eq_of_subset_of_card_le {s t : finset α} (h : s ⊆ t) (h₂ : card t ≤ card s) : s = t :=
eq_of_veq $ multiset.eq_of_le_of_card_le (val_le_iff.mpr h) h₂
lemma card_lt_card [decidable_eq α] {s t : finset α} (h : s ⊂ t) : s.card < t.card :=
card_lt_of_lt (val_lt_iff.2 h)
lemma card_le_card_of_inj_on [decidable_eq α] [decidable_eq β] {s : finset α} {t : finset β}
(f : α → β) (hf : ∀a∈s, f a ∈ t) (f_inj : ∀a₁∈s, ∀a₂∈s, f a₁ = f a₂ → a₁ = a₂) :
card s ≤ card t :=
calc card s = card (s.image f) : by rw [card_image_of_inj_on f_inj]
... ≤ card t : card_le_of_subset $
assume x hx, match x, finset.mem_image.1 hx with _, ⟨a, ha, rfl⟩ := hf a ha end
lemma card_le_of_inj_on [decidable_eq α] {n} {s : finset α}
(f : ℕ → α) (hf : ∀i<n, f i ∈ s) (f_inj : ∀i j, i<n → j<n → f i = f j → i = j) : n ≤ card s :=
calc n = card (range n) : (card_range n).symm
... ≤ card s : card_le_card_of_inj_on f
(by simp; assumption)
(by simp; exact assume a₁ h₁ a₂ h₂, f_inj a₁ a₂ h₁ h₂)
@[elab_as_eliminator] lemma strong_induction_on {p : finset α → Sort*} :
∀ (s : finset α), (∀s, (∀t ⊂ s, p t) → p s) → p s
| ⟨s, nd⟩ ih := multiset.strong_induction_on s
(λ s IH nd, ih ⟨s, nd⟩ (λ ⟨t, nd'⟩ ss, IH t (val_lt_iff.2 ss) nd')) nd
@[elab_as_eliminator] lemma case_strong_induction_on [decidable_eq α] {p : finset α → Prop}
(s : finset α) (h₀ : p ∅) (h₁ : ∀ a s, a ∉ s → (∀t ⊆ s, p t) → p (insert a s)) : p s :=
finset.strong_induction_on s $ λ s,
finset.induction_on s (λ _, h₀) $ λ a s n _ ih, h₁ a s n $
λ t ss, ih _ (lt_of_le_of_lt ss (ssubset_insert n) : t < _)
end card
section bind
variables [decidable_eq β] {s : finset α} {t : α → finset β}
/-- `bind s t` is the union of `t x` over `x ∈ s` -/
protected def bind (s : finset α) (t : α → finset β) : finset β := (s.1.bind (λ a, (t a).1)).to_finset
@[simp] theorem bind_val (s : finset α) (t : α → finset β) :
(s.bind t).1 = (s.1.bind (λ a, (t a).1)).erase_dup := rfl
@[simp] theorem bind_empty : finset.bind ∅ t = ∅ := rfl
@[simp] theorem mem_bind {b : β} : b ∈ s.bind t ↔ ∃a∈s, b ∈ t a :=
by simp [mem_def]
@[simp] theorem bind_insert [decidable_eq α] {a : α} : (insert a s).bind t = t a ∪ s.bind t :=
ext.2 $ by simp [or_and_distrib_right, exists_or_distrib]
@[simp] lemma singleton_bind [decidable_eq α] {a : α} : (singleton a).bind t = t a :=
show (insert a ∅ : finset α).bind t = t a, by simp
theorem image_bind [decidable_eq γ] {f : α → β} {s : finset α} {t : β → finset γ} :
(s.image f).bind t = s.bind (λa, t (f a)) :=
by haveI := classical.dec_eq α; exact
finset.induction_on s (by simp) (by simp {contextual := tt})
theorem bind_image [decidable_eq γ] {s : finset α} {t : α → finset β} {f : β → γ} :
(s.bind t).image f = s.bind (λa, (t a).image f) :=
by haveI := classical.dec_eq α; exact
finset.induction_on s (by simp) (by simp [image_union] {contextual := tt})
theorem bind_to_finset [decidable_eq α] (s : multiset α) (t : α → multiset β) :
(s.bind t).to_finset = s.to_finset.bind (λa, (t a).to_finset) :=
ext.2 $ by simp
lemma bind_mono {t₁ t₂ : α → finset β} (h : ∀a∈s, t₁ a ⊆ t₂ a) : s.bind t₁ ⊆ s.bind t₂ :=
have ∀b a, a ∈ s → b ∈ t₁ a → (∃ (a : α), a ∈ s ∧ b ∈ t₂ a),
from assume b a ha hb, ⟨a, ha, finset.mem_of_subset (h a ha) hb⟩,
by simpa [finset.subset_iff]
lemma bind_singleton {f : α → β} : s.bind (λa, {f a}) = s.image f :=
finset.ext.mpr $ by simp [eq_comm]
end bind
section prod
variables {s : finset α} {t : finset β}
/-- `product s t` is the set of pairs `(a, b)` such that `a ∈ s` and `b ∈ t`. -/
protected def product (s : finset α) (t : finset β) : finset (α × β) := ⟨_, nodup_product s.2 t.2⟩
@[simp] theorem product_val : (s.product t).1 = s.1.product t.1 := rfl
@[simp] theorem mem_product {p : α × β} : p ∈ s.product t ↔ p.1 ∈ s ∧ p.2 ∈ t := mem_product
theorem product_eq_bind [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) :
s.product t = s.bind (λa, t.image $ λb, (a, b)) :=
ext.2 $ by simp [and.left_comm]
@[simp] theorem card_product (s : finset α) (t : finset β) : card (s.product t) = card s * card t :=
multiset.card_product _ _
end prod
section sigma
variables {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)}
/-- `sigma s t` is the set of dependent pairs `⟨a, b⟩` such that `a ∈ s` and `b ∈ t a`. -/
protected def sigma (s : finset α) (t : Πa, finset (σ a)) : finset (Σa, σ a) :=
⟨_, nodup_sigma s.2 (λ a, (t a).2)⟩
@[simp] theorem mem_sigma {p : sigma σ} : p ∈ s.sigma t ↔ p.1 ∈ s ∧ p.2 ∈ t (p.1) := mem_sigma
theorem sigma_mono {s₁ s₂ : finset α} {t₁ t₂ : Πa, finset (σ a)} :
s₁ ⊆ s₂ → (∀a, t₁ a ⊆ t₂ a) → s₁.sigma t₁ ⊆ s₂.sigma t₂ :=
by simp [subset_iff, mem_sigma] {contextual := tt}
theorem sigma_eq_bind [decidable_eq α] [∀a, decidable_eq (σ a)] (s : finset α) (t : Πa, finset (σ a)) :
s.sigma t = s.bind (λa, (t a).image $ λb, ⟨a, b⟩) :=
ext.2 $ by simp [and.left_comm]
end sigma
section pi
variables {δ : α → Type*} [decidable_eq α]
def pi (s : finset α) (t : Πa, finset (δ a)) : finset (Πa∈s, δ a) :=
⟨s.1.pi (λ a, (t a).1), nodup_pi s.2 (λ a _, (t a).2)⟩
@[simp] lemma pi_val (s : finset α) (t : Πa, finset (δ a)) :
(s.pi t).1 = s.1.pi (λ a, (t a).1) := rfl
@[simp] lemma mem_pi {s : finset α} {t : Πa, finset (δ a)} {f : Πa∈s, δ a} :
f ∈ s.pi t ↔ (∀a (h : a ∈ s), f a h ∈ t a) :=
mem_pi _ _ _
def pi.empty (β : α → Sort*) [decidable_eq α] (a : α) (h : a ∈ (∅ : finset α)) : β a :=
multiset.pi.empty β a h
def pi.cons (s : finset α) (a : α) (b : δ a) (f : Πa, a ∈ s → δ a) (a' : α) (h : a' ∈ insert a s) : δ a' :=
multiset.pi.cons s.1 a b f _ (multiset.mem_cons.2 $ mem_insert.symm.2 h)
@[simp] lemma pi.cons_same (s : finset α) (a : α) (b : δ a) (f : Πa, a ∈ s → δ a) (h : a ∈ insert a s) :
pi.cons s a b f a h = b :=
multiset.pi.cons_same _
lemma pi.cons_ne {s : finset α} {a a' : α} {b : δ a} {f : Πa, a ∈ s → δ a} {h : a' ∈ insert a s} (ha : a ≠ a') :
pi.cons s a b f a' h = f a' ((mem_insert.1 h).resolve_left ha.symm) :=
multiset.pi.cons_ne _ _
lemma injective_pi_cons {a : α} {b : δ a} {s : finset α} (hs : a ∉ s) :
function.injective (pi.cons s a b) :=
assume e₁ e₂ eq,
@multiset.injective_pi_cons α _ δ a b s.1 hs _ _ $
funext $ assume e, funext $ assume h,
have pi.cons s a b e₁ e (by simpa using h) = pi.cons s a b e₂ e (by simpa using h),
by rw [eq],
this
@[simp] lemma pi_empty {t : Πa:α, finset (δ a)} : pi (∅ : finset α) t = singleton (pi.empty δ) :=
rfl
@[simp] lemma pi_insert [∀a, decidable_eq (δ a)]
{s : finset α} {t : Πa:α, finset (δ a)} {a : α} (ha : a ∉ s) :
pi (insert a s) t = (t a).bind (λb, (pi s t).image (pi.cons s a b)) :=
begin
apply eq_of_veq,
rw ← multiset.erase_dup_eq_self.2 (pi (insert a s) t).2,
refine (λ s' (h : s' = a :: s.1), (_ : erase_dup (multiset.pi s' (λ a, (t a).1)) =
erase_dup ((t a).1.bind $ λ b,
erase_dup $ (multiset.pi s.1 (λ (a : α), (t a).val)).map $
λ f a' h', multiset.pi.cons s.1 a b f a' (h ▸ h')))) _ (insert_val_of_not_mem ha),
subst s', rw pi_cons,
congr, funext b,
rw multiset.erase_dup_eq_self.2,
exact multiset.nodup_map (multiset.injective_pi_cons ha) (pi s t).2,
end
end pi
section powerset
def powerset (s : finset α) : finset (finset α) :=
⟨s.1.powerset.pmap finset.mk
(λ t h, nodup_of_le (mem_powerset.1 h) s.2),
nodup_pmap (λ a ha b hb, congr_arg finset.val)
(nodup_powerset.2 s.2)⟩
@[simp] theorem mem_powerset {s t : finset α} : s ∈ powerset t ↔ s ⊆ t :=
by cases s; simp [powerset]; rw ← val_le_iff
@[simp] theorem empty_mem_powerset (s : finset α) : ∅ ∈ powerset s :=
mem_powerset.2 (empty_subset _)
@[simp] theorem mem_powerset_self (s : finset α) : s ∈ powerset s :=
mem_powerset.2 (subset.refl _)
@[simp] theorem powerset_mono {s t : finset α} : powerset s ⊆ powerset t ↔ s ⊆ t :=
⟨λ h, (mem_powerset.1 $ h $ mem_powerset_self _),
λ st u h, mem_powerset.2 $ subset.trans (mem_powerset.1 h) st⟩
@[simp] theorem card_powerset (s : finset α) :
card (powerset s) = 2 ^ card s :=
(card_pmap _ _ _).trans (card_powerset s.1)
end powerset
section fold
variables (op : β → β → β) [hc : is_commutative β op] [ha : is_associative β op]
local notation a * b := op a b
include hc ha
/-- `fold op b f s` folds the commutative associative operation `op` over the
`f`-image of `s`, i.e. `fold (+) b f {1,2,3} = `f 1 + f 2 + f 3 + b`. -/
def fold (b : β) (f : α → β) (s : finset α) : β := (s.1.map f).fold op b
variables {op} {f : α → β} {b : β} {s : finset α} {a : α}
@[simp] theorem fold_empty : (∅ : finset α).fold op b f = b := rfl
@[simp] theorem fold_insert [decidable_eq α] (h : a ∉ s) : (insert a s).fold op b f = f a * s.fold op b f :=
by simp [fold, ndinsert_of_not_mem h]
@[simp] theorem fold_singleton : (singleton a).fold op b f = f a * b :=
by simp [fold]
@[simp] theorem fold_image [decidable_eq α] [decidable_eq γ] {g : γ → α} {s : finset γ}
(H : ∀ (x ∈ s) (y ∈ s), g x = g y → x = y) : (s.image g).fold op b f = s.fold op b (f ∘ g) :=
by simp [fold, image_val_of_inj_on H, map_map]
@[congr] theorem fold_congr {g : α → β} (H : ∀ x ∈ s, f x = g x) : s.fold op b f = s.fold op b g :=
by rw [fold, fold, map_congr H]
theorem fold_op_distrib {f g : α → β} {b₁ b₂ : β} :
s.fold op (b₁ * b₂) (λx, f x * g x) = s.fold op b₁ f * s.fold op b₂ g :=
by simp [fold, fold_distrib]
theorem fold_hom {op' : γ → γ → γ} [is_commutative γ op'] [is_associative γ op']
{m : β → γ} (hm : ∀x y, m (op x y) = op' (m x) (m y)) :
s.fold op' (m b) (λx, m (f x)) = m (s.fold op b f) :=
by rw [fold, fold, ← fold_hom op hm, multiset.map_map]
theorem fold_union_inter [decidable_eq α] {s₁ s₂ : finset α} {b₁ b₂ : β} :
(s₁ ∪ s₂).fold op b₁ f * (s₁ ∩ s₂).fold op b₂ f = s₁.fold op b₂ f * s₂.fold op b₁ f :=
by unfold fold; rw [← fold_add op, ← map_add, union_val,
inter_val, union_add_inter, map_add, hc.comm, fold_add]
@[simp] theorem fold_insert_idem [decidable_eq α] [hi : is_idempotent β op] :
(insert a s).fold op b f = f a * s.fold op b f :=
by haveI := classical.prop_decidable;
rw [fold, insert_val', ← fold_erase_dup_idem op, erase_dup_map_erase_dup_eq,
fold_erase_dup_idem op]; simp [fold]
end fold
section sup
variables [semilattice_sup_bot α] [decidable_eq α] [decidable_eq β]
/-- Supremum of a finite set: `sup {a, b, c} f = f a ⊔ f b ⊔ f c` -/
def sup (s : finset β) (f : β → α) : α := s.fold (⊔) ⊥ f
variables {s s₁ s₂ : finset β} {f : β → α}
@[simp] lemma sup_empty : (∅ : finset β).sup f = ⊥ :=
fold_empty
@[simp] lemma sup_insert {b : β} : (insert b s : finset β).sup f = f b ⊔ s.sup f :=
fold_insert_idem
@[simp] lemma sup_singleton {b : β} : ({b} : finset β).sup f = f b :=
calc _ = f b ⊔ (∅:finset β).sup f : sup_insert
... = f b : by simp
lemma sup_union : (s₁ ∪ s₂).sup f = s₁.sup f ⊔ s₂.sup f :=
finset.induction_on s₁ (by simp) (by simp {contextual := tt}; cc)
lemma sup_mono_fun {g : β → α} : (∀b∈s, f b ≤ g b) → s.sup f ≤ s.sup g :=
finset.induction_on s (by simp) (by simp [-sup_le_iff, sup_le_sup] {contextual := tt})
lemma le_sup {b : β} (hb : b ∈ s) : f b ≤ s.sup f :=
calc f b ≤ f b ⊔ s.sup f : le_sup_left
... = (insert b s).sup f : by simp
... = s.sup f : by simp [hb]
lemma sup_le {a : α} : (∀b ∈ s, f b ≤ a) → s.sup f ≤ a :=
finset.induction_on s (by simp) (by simp {contextual := tt})
lemma sup_mono (h : s₁ ⊆ s₂) : s₁.sup f ≤ s₂.sup f :=
sup_le $ assume b hb, le_sup (h hb)
end sup
section inf
variables [semilattice_inf_top α] [decidable_eq α] [decidable_eq β]
/-- Infimum of a finite set: `inf {a, b, c} f = f a ⊓ f b ⊓ f c` -/
def inf (s : finset β) (f : β → α) : α := s.fold (⊓) ⊤ f
variables {s s₁ s₂ : finset β} {f : β → α}
@[simp] lemma inf_empty : (∅ : finset β).inf f = ⊤ :=
fold_empty
@[simp] lemma inf_insert {b : β} : (insert b s : finset β).inf f = f b ⊓ s.inf f :=
fold_insert_idem
@[simp] lemma inf_singleton {b : β} : ({b} : finset β).inf f = f b :=
calc _ = f b ⊓ (∅:finset β).inf f : inf_insert
... = f b : by simp
lemma inf_union : (s₁ ∪ s₂).inf f = s₁.inf f ⊓ s₂.inf f :=
finset.induction_on s₁ (by simp) (by simp {contextual := tt}; cc)
lemma inf_mono_fun {g : β → α} : (∀b∈s, f b ≤ g b) → s.inf f ≤ s.inf g :=
finset.induction_on s (by simp) (by simp [inf_le_inf] {contextual := tt})
lemma inf_le {b : β} (hb : b ∈ s) : s.inf f ≤ f b :=
calc f b ≥ f b ⊓ s.inf f : inf_le_left
... = (insert b s).inf f : by simp
... = s.inf f : by simp [hb]
lemma le_inf {a : α} : (∀b ∈ s, a ≤ f b) → a ≤ s.inf f :=
finset.induction_on s (by simp) (by simp {contextual := tt})
lemma inf_mono (h : s₁ ⊆ s₂) : s₂.inf f ≤ s₁.inf f :=
le_inf $ assume b hb, inf_le (h hb)
end inf
/- max and min of finite sets -/
section max_min
variables [decidable_linear_order α]
protected def max : finset α → option α :=
fold (option.lift_or_get max) none some
theorem max_eq_sup_with_bot (s : finset α) :
s.max = @sup (with_bot α) α _ _ _ s some := rfl
@[simp] theorem max_empty : (∅ : finset α).max = none :=
by simp [finset.max]
@[simp] theorem max_insert {a : α} {s : finset α} :
(insert a s).max = option.lift_or_get max (some a) s.max :=
by simp [finset.max, fold_insert_idem]
@[simp] theorem max_singleton {a : α} : finset.max {a} = some a :=
by simp [finset.max, option.lift_or_get]
theorem max_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.max :=
(@le_sup (with_bot α) _ _ _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst
theorem mem_of_max {s : finset α} : ∀ {a : α}, a ∈ s.max → a ∈ s :=
finset.induction_on s (by simp) $
λ b s _ (ih : ∀ {a}, a ∈ s.max → a ∈ s) a (h : a ∈ (insert b s).max),
begin
by_cases p : b = a,
{ induction p, exact mem_insert_self b s },
{ cases option.lift_or_get_choice max_choice (some b) s.max with q q; simp [q] at h,
{ exact absurd h p },
{ exact mem_insert_of_mem (ih h) } }
end
theorem le_max_of_mem {s : finset α} {a b : α} (h₁ : a ∈ s) (h₂ : b ∈ s.max) : a ≤ b :=
by rcases @le_sup (with_bot α) _ _ _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩;
cases h₂.symm.trans hb; assumption
protected def min : finset α → option α :=
fold (option.lift_or_get min) none some
theorem min_eq_inf_with_top (s : finset α) :
s.min = @inf (with_top α) α _ _ _ s some := rfl
@[simp] theorem min_empty : (∅ : finset α).min = none :=
by simp [finset.min]
@[simp] theorem min_insert {a : α} {s : finset α} :
(insert a s).min = option.lift_or_get min (some a) s.min :=
by simp [finset.min, fold_insert_idem]
@[simp] theorem min_singleton {a : α} : finset.min {a} = some a :=
by simp [finset.min, option.lift_or_get]
theorem min_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.min :=
(@inf_le (with_top α) _ _ _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst
theorem mem_of_min {s : finset α} : ∀ {a : α}, a ∈ s.min → a ∈ s :=
finset.induction_on s (by simp) $
λ b s _ (ih : ∀ {a}, a ∈ s.min → a ∈ s) a (h : a ∈ (insert b s).min),
begin
by_cases p : b = a,
{ induction p, exact mem_insert_self b s },
{ cases option.lift_or_get_choice min_choice (some b) s.min with q q; simp [q] at h,
{ exact absurd h p },
{ exact mem_insert_of_mem (ih h) } }
end
theorem le_min_of_mem {s : finset α} {a b : α} (h₁ : b ∈ s) (h₂ : a ∈ s.min) : a ≤ b :=
by rcases @inf_le (with_top α) _ _ _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩;
cases h₂.symm.trans hb; assumption
end max_min
section sort
variables (r : α → α → Prop) [decidable_rel r]
[is_trans α r] [is_antisymm α r] [is_total α r]
/-- `sort s` constructs a sorted list from the unordered set `s`.
(Uses merge sort algorithm.) -/
def sort (s : finset α) : list α := sort r s.1
@[simp] theorem sort_sorted (s : finset α) : list.sorted r (sort r s) :=
sort_sorted _ _
@[simp] theorem sort_eq (s : finset α) : ↑(sort r s) = s.1 :=
sort_eq _ _
@[simp] theorem sort_nodup (s : finset α) : (sort r s).nodup :=
(by rw sort_eq; exact s.2 : @multiset.nodup α (sort r s))
@[simp] theorem sort_to_finset [decidable_eq α] (s : finset α) : (sort r s).to_finset = s :=
list.to_finset_eq (sort_nodup r s) ▸ eq_of_veq (sort_eq r s)
end sort
theorem sort_sorted_lt [decidable_linear_order α] (s : finset α) :
list.sorted (<) (sort (≤) s) :=
(sort_sorted _ _).imp₂ (@lt_of_le_of_ne _ _) (sort_nodup _ _)
instance [has_repr α] : has_repr (finset α) := ⟨λ s, repr s.1⟩
end finset
namespace list
variable [decidable_eq α]
theorem to_finset_card_of_nodup {l : list α} : l.nodup → l.to_finset.card = l.length :=
begin
induction l,
case list.nil { simp },
case list.cons : _ _ ih {
intros nd,
simp at nd,
simp [finset.card_insert_of_not_mem ((not_iff_not_of_iff mem_to_finset).mpr nd.1),
ih nd.2]
}
end
end list
|
1bb6444c44bb3511c5c738099eb5b9ad15a34ed3 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/padics/default.lean | b7700d6a479b9e3fde3b368f00cef50f5c0c1526 | [] | 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 | 146 | lean | import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.padics.padic_integers
import Mathlib.PostPort
namespace Mathlib
|
2fa32075de39b372cc0ea5bef3b12ae21d53ba2d | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/algebra/group/commute_auto.lean | cc14141cf0e2ec097b5d34cc3c0832052034ff2d | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,541 | lean | /-
Copyright (c) 2019 Neil Strickland. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Neil Strickland, Yury Kudryashov
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.group.semiconj
import Mathlib.PostPort
universes u_1
namespace Mathlib
/-!
# Commuting pairs of elements in monoids
We define the predicate `commute a b := a * b = b * a` and provide some operations on terms `(h :
commute a b)`. E.g., if `a`, `b`, and c are elements of a semiring, and that `hb : commute a b` and
`hc : commute a c`. Then `hb.pow_left 5` proves `commute (a ^ 5) b` and `(hb.pow_right 2).add_right
(hb.mul_right hc)` proves `commute a (b ^ 2 + b * c)`.
Lean does not immediately recognise these terms as equations, so for rewriting we need syntax like
`rw [(hb.pow_left 5).eq]` rather than just `rw [hb.pow_left 5]`.
This file defines only a few operations (`mul_left`, `inv_right`, etc). Other operations
(`pow_right`, field inverse etc) are in the files that define corresponding notions.
## Implementation details
Most of the proofs come from the properties of `semiconj_by`.
-/
/-- Two elements commute if `a * b = b * a`. -/
def commute {S : Type u_1} [Mul S] (a : S) (b : S) := semiconj_by a b b
namespace commute
/-- Equality behind `commute a b`; useful for rewriting. -/
protected theorem Mathlib.add_commute.eq {S : Type u_1} [Add S] {a : S} {b : S}
(h : add_commute a b) : a + b = b + a :=
h
/-- Any element commutes with itself. -/
@[simp] protected theorem refl {S : Type u_1} [Mul S] (a : S) : commute a a := Eq.refl (a * a)
/-- If `a` commutes with `b`, then `b` commutes with `a`. -/
protected theorem Mathlib.add_commute.symm {S : Type u_1} [Add S] {a : S} {b : S}
(h : add_commute a b) : add_commute b a :=
Eq.symm h
protected theorem Mathlib.add_commute.symm_iff {S : Type u_1} [Add S] {a : S} {b : S} :
add_commute a b ↔ add_commute b a :=
{ mp := add_commute.symm, mpr := add_commute.symm }
/-- If `a` commutes with both `b` and `c`, then it commutes with their product. -/
@[simp] theorem mul_right {S : Type u_1} [semigroup S] {a : S} {b : S} {c : S} (hab : commute a b)
(hac : commute a c) : commute a (b * c) :=
semiconj_by.mul_right hab hac
/-- If both `a` and `b` commute with `c`, then their product commutes with `c`. -/
@[simp] theorem Mathlib.add_commute.add_left {S : Type u_1} [add_semigroup S] {a : S} {b : S}
{c : S} (hac : add_commute a c) (hbc : add_commute b c) : add_commute (a + b) c :=
add_semiconj_by.add_left hac hbc
protected theorem Mathlib.add_commute.right_comm {S : Type u_1} [add_semigroup S] {b : S} {c : S}
(h : add_commute b c) (a : S) : a + b + c = a + c + b :=
sorry
protected theorem left_comm {S : Type u_1} [semigroup S] {a : S} {b : S} (h : commute a b) (c : S) :
a * (b * c) = b * (a * c) :=
sorry
protected theorem Mathlib.add_commute.all {S : Type u_1} [add_comm_semigroup S] (a : S) (b : S) :
add_commute a b :=
add_comm a b
@[simp] theorem one_right {M : Type u_1} [monoid M] (a : M) : commute a 1 := semiconj_by.one_right a
@[simp] theorem Mathlib.add_commute.zero_left {M : Type u_1} [add_monoid M] (a : M) :
add_commute 0 a :=
add_semiconj_by.zero_left a
theorem Mathlib.add_commute.units_neg_right {M : Type u_1} [add_monoid M] {a : M}
{u : add_units M} : add_commute a ↑u → add_commute a ↑(-u) :=
add_semiconj_by.units_neg_right
@[simp] theorem Mathlib.add_commute.units_neg_right_iff {M : Type u_1} [add_monoid M] {a : M}
{u : add_units M} : add_commute a ↑(-u) ↔ add_commute a ↑u :=
add_semiconj_by.units_neg_right_iff
theorem Mathlib.add_commute.units_neg_left {M : Type u_1} [add_monoid M] {u : add_units M} {a : M} :
add_commute (↑u) a → add_commute (↑(-u)) a :=
add_semiconj_by.units_neg_symm_left
@[simp] theorem Mathlib.add_commute.units_neg_left_iff {M : Type u_1} [add_monoid M]
{u : add_units M} {a : M} : add_commute (↑(-u)) a ↔ add_commute (↑u) a :=
add_semiconj_by.units_neg_symm_left_iff
theorem Mathlib.add_commute.units_coe {M : Type u_1} [add_monoid M] {u₁ : add_units M}
{u₂ : add_units M} : add_commute u₁ u₂ → add_commute ↑u₁ ↑u₂ :=
add_semiconj_by.units_coe
theorem Mathlib.add_commute.units_of_coe {M : Type u_1} [add_monoid M] {u₁ : add_units M}
{u₂ : add_units M} : add_commute ↑u₁ ↑u₂ → add_commute u₁ u₂ :=
add_semiconj_by.units_of_coe
@[simp] theorem units_coe_iff {M : Type u_1} [monoid M] {u₁ : units M} {u₂ : units M} :
commute ↑u₁ ↑u₂ ↔ commute u₁ u₂ :=
semiconj_by.units_coe_iff
theorem Mathlib.add_commute.neg_right {G : Type u_1} [add_group G] {a : G} {b : G} :
add_commute a b → add_commute a (-b) :=
add_semiconj_by.neg_right
@[simp] theorem Mathlib.add_commute.neg_right_iff {G : Type u_1} [add_group G] {a : G} {b : G} :
add_commute a (-b) ↔ add_commute a b :=
add_semiconj_by.neg_right_iff
theorem inv_left {G : Type u_1} [group G] {a : G} {b : G} : commute a b → commute (a⁻¹) b :=
semiconj_by.inv_symm_left
@[simp] theorem inv_left_iff {G : Type u_1} [group G] {a : G} {b : G} :
commute (a⁻¹) b ↔ commute a b :=
semiconj_by.inv_symm_left_iff
theorem Mathlib.add_commute.neg_neg {G : Type u_1} [add_group G] {a : G} {b : G} :
add_commute a b → add_commute (-a) (-b) :=
add_semiconj_by.neg_neg_symm
@[simp] theorem inv_inv_iff {G : Type u_1} [group G] {a : G} {b : G} :
commute (a⁻¹) (b⁻¹) ↔ commute a b :=
semiconj_by.inv_inv_symm_iff
protected theorem Mathlib.add_commute.neg_add_cancel {G : Type u_1} [add_group G] {a : G} {b : G}
(h : add_commute a b) : -a + b + a = b :=
eq.mpr (id (Eq._oldrec (Eq.refl (-a + b + a = b)) (add_commute.eq (add_commute.neg_left h))))
(eq.mpr (id (Eq._oldrec (Eq.refl (b + -a + a = b)) (neg_add_cancel_right b a))) (Eq.refl b))
theorem inv_mul_cancel_assoc {G : Type u_1} [group G] {a : G} {b : G} (h : commute a b) :
a⁻¹ * (b * a) = b :=
eq.mpr (id (Eq._oldrec (Eq.refl (a⁻¹ * (b * a) = b)) (Eq.symm (mul_assoc (a⁻¹) b a))))
(eq.mpr (id (Eq._oldrec (Eq.refl (a⁻¹ * b * a = b)) (commute.inv_mul_cancel h))) (Eq.refl b))
protected theorem mul_inv_cancel {G : Type u_1} [group G] {a : G} {b : G} (h : commute a b) :
a * b * (a⁻¹) = b :=
eq.mpr (id (Eq._oldrec (Eq.refl (a * b * (a⁻¹) = b)) (commute.eq h)))
(eq.mpr (id (Eq._oldrec (Eq.refl (b * a * (a⁻¹) = b)) (mul_inv_cancel_right b a))) (Eq.refl b))
theorem mul_inv_cancel_assoc {G : Type u_1} [group G] {a : G} {b : G} (h : commute a b) :
a * (b * (a⁻¹)) = b :=
eq.mpr (id (Eq._oldrec (Eq.refl (a * (b * (a⁻¹)) = b)) (Eq.symm (mul_assoc a b (a⁻¹)))))
(eq.mpr (id (Eq._oldrec (Eq.refl (a * b * (a⁻¹) = b)) (commute.mul_inv_cancel h))) (Eq.refl b))
end commute
@[simp] theorem mul_inv_cancel_comm {G : Type u_1} [comm_group G] (a : G) (b : G) :
a * b * (a⁻¹) = b :=
commute.mul_inv_cancel (commute.all a b)
@[simp] theorem add_neg_cancel_comm_assoc {G : Type u_1} [add_comm_group G] (a : G) (b : G) :
a + (b + -a) = b :=
add_commute.add_neg_cancel_assoc (add_commute.all a b)
@[simp] theorem inv_mul_cancel_comm {G : Type u_1} [comm_group G] (a : G) (b : G) :
a⁻¹ * b * a = b :=
commute.inv_mul_cancel (commute.all a b)
@[simp] theorem inv_mul_cancel_comm_assoc {G : Type u_1} [comm_group G] (a : G) (b : G) :
a⁻¹ * (b * a) = b :=
commute.inv_mul_cancel_assoc (commute.all a b)
end Mathlib |
340c4a9a5e6bc0881c802295764b77bff40477d8 | 3dd1b66af77106badae6edb1c4dea91a146ead30 | /tests/lean/run/t9.lean | bcda06dc32127473f950a3de870bedc2593e83d4 | [
"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 | 607 | lean | definition bool [inline] : Type.{1} := Type.{0}
definition and (p q : bool) : bool
:= ∀ c : bool, (p → q → c) → c
infixl `∧`:25 := and
theorem and_intro (p q : bool) (H1 : p) (H2 : q) : p ∧ q
:= λ (c : bool) (H : p → q → c), H H1 H2
theorem and_elim_left (p q : bool) (H : p ∧ q) : p
:= H p (λ (H1 : p) (H2 : q), H1)
theorem and_elim_right (p q : bool) (H : p ∧ q) : q
:= H q (λ (H1 : p) (H2 : q), H2)
theorem and_comm (p q : bool) (H : p ∧ q) : q ∧ p
:= have H1 : p, from and_elim_left p q H,
have H2 : q, from and_elim_right p q H,
show q ∧ p, from and_intro q p H2 H1
|
645fdd78f1d2a90427c8ac9b48dd11fc44e35049 | 4fa161becb8ce7378a709f5992a594764699e268 | /src/number_theory/quadratic_reciprocity.lean | b5bb1b28820aff9a031dbca7c2fcb71b27f1002b | [
"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 | 25,011 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import field_theory.finite
import data.zmod.basic
import data.nat.parity
/-!
# Quadratic reciprocity.
This file contains results about quadratic residues modulo a prime number.
The main results are the law of quadratic reciprocity, `quadratic_reciprocity`, as well as the
interpretations in terms of existence of square roots depending on the congruence mod 4,
`exists_pow_two_eq_prime_iff_of_mod_four_eq_one`, and
`exists_pow_two_eq_prime_iff_of_mod_four_eq_three`.
Also proven are conditions for `-1` and `2` to be a square modulo a prime,
`exists_pow_two_eq_neg_one_iff_mod_four_ne_three` and
`exists_pow_two_eq_two_iff`
## Implementation notes
The proof of quadratic reciprocity implemented uses Gauss' lemma and Eisenstein's lemma
-/
open function finset nat finite_field zmod
open_locale big_operators
namespace zmod
variables (p q : ℕ) [fact p.prime] [fact q.prime]
@[simp] lemma card_units : fintype.card (units (zmod p)) = p - 1 :=
by rw [card_units, card]
/-- Fermat's Little Theorem: for every unit `a` of `zmod p`, we have `a ^ (p - 1) = 1`. -/
theorem fermat_little_units {p : ℕ} [fact p.prime] (a : units (zmod p)) :
a ^ (p - 1) = 1 :=
by rw [← card_units p, pow_card_eq_one]
/-- Fermat's Little Theorem: for all nonzero `a : zmod p`, we have `a ^ (p - 1) = 1`. -/
theorem fermat_little {a : zmod p} (ha : a ≠ 0) : a ^ (p - 1) = 1 :=
begin
have := fermat_little_units (units.mk0 a ha),
apply_fun (coe : units (zmod p) → zmod p) at this,
simpa,
end
/-- Euler's Criterion: A unit `x` of `zmod p` is a square if and only if `x ^ (p / 2) = 1`. -/
lemma euler_criterion_units (x : units (zmod p)) :
(∃ y : units (zmod p), y ^ 2 = x) ↔ x ^ (p / 2) = 1 :=
begin
cases nat.prime.eq_two_or_odd ‹p.prime› with hp2 hp_odd,
{ resetI, subst p, refine iff_of_true ⟨1, _⟩ _; apply subsingleton.elim },
obtain ⟨g, hg⟩ := is_cyclic.exists_generator (units (zmod p)),
obtain ⟨n, hn⟩ : x ∈ powers g, { rw powers_eq_gpowers, apply hg },
split,
{ rintro ⟨y, rfl⟩, rw [← pow_mul, two_mul_odd_div_two hp_odd, fermat_little_units], },
{ subst x, assume h,
have key : 2 * (p / 2) ∣ n * (p / 2),
{ rw [← pow_mul] at h,
rw [two_mul_odd_div_two hp_odd, ← card_units, ← order_of_eq_card_of_forall_mem_gpowers hg],
apply order_of_dvd_of_pow_eq_one h },
have : 0 < p / 2 := nat.div_pos (show fact (1 < p), by apply_instance) dec_trivial,
obtain ⟨m, rfl⟩ := dvd_of_mul_dvd_mul_right this key,
refine ⟨g ^ m, _⟩,
rw [mul_comm, pow_mul], },
end
/-- Euler's Criterion: a nonzero `a : zmod p` is a square if and only if `x ^ (p / 2) = 1`. -/
lemma euler_criterion {a : zmod p} (ha : a ≠ 0) :
(∃ y : zmod p, y ^ 2 = a) ↔ a ^ (p / 2) = 1 :=
begin
apply (iff_congr _ (by simp [units.ext_iff])).mp (euler_criterion_units p (units.mk0 a ha)),
simp only [units.ext_iff, _root_.pow_two, units.coe_mk0, units.coe_mul],
split, { rintro ⟨y, hy⟩, exact ⟨y, hy⟩ },
{ rintro ⟨y, rfl⟩,
have hy : y ≠ 0, { rintro rfl, simpa [_root_.zero_pow] using ha, },
refine ⟨units.mk0 y hy, _⟩, simp, }
end
lemma exists_pow_two_eq_neg_one_iff_mod_four_ne_three :
(∃ y : zmod p, y ^ 2 = -1) ↔ p % 4 ≠ 3 :=
begin
cases nat.prime.eq_two_or_odd ‹p.prime› with hp2 hp_odd,
{ resetI, subst p, exact dec_trivial },
change fact (p % 2 = 1) at hp_odd, resetI,
have neg_one_ne_zero : (-1 : zmod p) ≠ 0, from mt neg_eq_zero.1 one_ne_zero,
rw [euler_criterion p neg_one_ne_zero, neg_one_pow_eq_pow_mod_two],
cases mod_two_eq_zero_or_one (p / 2) with p_half_even p_half_odd,
{ rw [p_half_even, _root_.pow_zero, eq_self_iff_true, true_iff],
contrapose! p_half_even with hp,
rw [← nat.mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp],
exact dec_trivial },
{ rw [p_half_odd, _root_.pow_one,
iff_false_intro (ne_neg_self p one_ne_zero).symm, false_iff, not_not],
rw [← nat.mod_mul_right_div_self, show 2 * 2 = 4, from rfl] at p_half_odd,
rw [_root_.fact, ← nat.mod_mul_left_mod _ 2, show 2 * 2 = 4, from rfl] at hp_odd,
have hp : p % 4 < 4, from nat.mod_lt _ dec_trivial,
revert hp hp_odd p_half_odd,
generalize : p % 4 = k, revert k, exact dec_trivial }
end
lemma pow_div_two_eq_neg_one_or_one {a : zmod p} (ha : a ≠ 0) :
a ^ (p / 2) = 1 ∨ a ^ (p / 2) = -1 :=
begin
cases nat.prime.eq_two_or_odd ‹p.prime› with hp2 hp_odd,
{ resetI, subst p, revert a ha, exact dec_trivial },
rw [← mul_self_eq_one_iff, ← _root_.pow_add, ← two_mul, two_mul_odd_div_two hp_odd],
exact fermat_little p ha
end
/-- Wilson's Lemma: the product of `1`, ..., `p-1` is `-1` modulo `p`. -/
@[simp] lemma wilsons_lemma : (nat.fact (p - 1) : zmod p) = -1 :=
begin
refine
calc (nat.fact (p - 1) : zmod p) = (∏ x in Ico 1 (succ (p - 1)), x) :
by rw [← finset.prod_Ico_id_eq_fact, prod_nat_cast]
... = (∏ x : units (zmod p), x) : _
... = -1 :
by rw [prod_hom _ (coe : units (zmod p) → zmod p),
prod_univ_units_id_eq_neg_one, units.coe_neg, units.coe_one],
have hp : 0 < p := nat.prime.pos ‹p.prime›,
symmetry,
refine prod_bij (λ a _, (a : zmod p).val) _ _ _ _,
{ intros a ha,
rw [Ico.mem, ← nat.succ_sub hp, nat.succ_sub_one],
split,
{ apply nat.pos_of_ne_zero, rw ← @val_zero p,
assume h, apply units.coe_ne_zero a (val_injective p h) },
{ exact val_lt _ } },
{ intros a ha, simp only [cast_id, nat_cast_val], },
{ intros _ _ _ _ h, rw units.ext_iff, exact val_injective p h },
{ intros b hb,
rw [Ico.mem, nat.succ_le_iff, ← succ_sub hp, succ_sub_one, nat.pos_iff_ne_zero] at hb,
refine ⟨units.mk0 b _, finset.mem_univ _, _⟩,
{ assume h, apply hb.1, apply_fun val at h,
simpa only [val_cast_of_lt hb.right, val_zero] using h },
{ simp only [val_cast_of_lt hb.right, units.coe_mk0], } }
end
@[simp] lemma prod_Ico_one_prime : (∏ x in Ico 1 p, (x : zmod p)) = -1 :=
begin
conv in (Ico 1 p) { rw [← succ_sub_one p, succ_sub (nat.prime.pos ‹p.prime›)] },
rw [← prod_nat_cast, finset.prod_Ico_id_eq_fact, wilsons_lemma]
end
end zmod
/-- The image of the map sending a non zero natural number `x ≤ p / 2` to the absolute value
of the element of interger in the interval `(-p/2, p/2]` congruent to `a * x` mod p is the set
of non zero natural numbers `x` such that `x ≤ p / 2` -/
lemma Ico_map_val_min_abs_nat_abs_eq_Ico_map_id
(p : ℕ) [hp : fact p.prime] (a : zmod p) (hap : a ≠ 0) :
(Ico 1 (p / 2).succ).1.map (λ x, (a * x).val_min_abs.nat_abs) =
(Ico 1 (p / 2).succ).1.map (λ a, a) :=
begin
have he : ∀ {x}, x ∈ Ico 1 (p / 2).succ → x ≠ 0 ∧ x ≤ p / 2,
by simp [nat.lt_succ_iff, nat.succ_le_iff, nat.pos_iff_ne_zero] {contextual := tt},
have hep : ∀ {x}, x ∈ Ico 1 (p / 2).succ → x < p,
from λ x hx, lt_of_le_of_lt (he hx).2 (nat.div_lt_self hp.pos dec_trivial),
have hpe : ∀ {x}, x ∈ Ico 1 (p / 2).succ → ¬ p ∣ x,
from λ x hx hpx, not_lt_of_ge (le_of_dvd (nat.pos_of_ne_zero (he hx).1) hpx) (hep hx),
have hmem : ∀ (x : ℕ) (hx : x ∈ Ico 1 (p / 2).succ),
(a * x : zmod p).val_min_abs.nat_abs ∈ Ico 1 (p / 2).succ,
{ assume x hx,
simp [hap, char_p.cast_eq_zero_iff (zmod p) p, hpe hx, lt_succ_iff, succ_le_iff,
nat.pos_iff_ne_zero, nat_abs_val_min_abs_le _], },
have hsurj : ∀ (b : ℕ) (hb : b ∈ Ico 1 (p / 2).succ),
∃ x ∈ Ico 1 (p / 2).succ, b = (a * x : zmod p).val_min_abs.nat_abs,
{ assume b hb,
refine ⟨(b / a : zmod p).val_min_abs.nat_abs, Ico.mem.mpr ⟨_, _⟩, _⟩,
{ apply nat.pos_of_ne_zero,
simp only [div_eq_mul_inv, hap, char_p.cast_eq_zero_iff (zmod p) p, hpe hb, not_false_iff,
val_min_abs_eq_zero, inv_eq_zero, int.nat_abs_eq_zero, ne.def, mul_eq_zero_iff', or_self] },
{ apply lt_succ_of_le, apply nat_abs_val_min_abs_le },
{ rw cast_nat_abs_val_min_abs,
split_ifs,
{ erw [mul_div_cancel' _ hap, val_min_abs_def_pos, val_cast_of_lt (hep hb),
if_pos (le_of_lt_succ (Ico.mem.1 hb).2), int.nat_abs_of_nat], },
{ erw [mul_neg_eq_neg_mul_symm, mul_div_cancel' _ hap, nat_abs_val_min_abs_neg,
val_min_abs_def_pos, val_cast_of_lt (hep hb), if_pos (le_of_lt_succ (Ico.mem.1 hb).2),
int.nat_abs_of_nat] } } },
exact multiset.map_eq_map_of_bij_of_nodup _ _ (finset.nodup _) (finset.nodup _)
(λ x _, (a * x : zmod p).val_min_abs.nat_abs) hmem (λ _ _, rfl)
(inj_on_of_surj_on_of_card_le _ hmem hsurj (le_refl _)) hsurj
end
private lemma gauss_lemma_aux₁ (p : ℕ) [hp : fact p.prime] [hp2 : fact (p % 2 = 1)]
{a : ℕ} (hap : (a : zmod p) ≠ 0) :
(a^(p / 2) * (p / 2).fact : zmod p) =
(-1)^((Ico 1 (p / 2).succ).filter
(λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card * (p / 2).fact :=
calc (a ^ (p / 2) * (p / 2).fact : zmod p) =
(∏ x in Ico 1 (p / 2).succ, a * x) :
by rw [prod_mul_distrib, ← prod_nat_cast, ← prod_nat_cast, prod_Ico_id_eq_fact,
prod_const, Ico.card, succ_sub_one]; simp
... = (∏ x in Ico 1 (p / 2).succ, (a * x : zmod p).val) : by simp
... = (∏ x in Ico 1 (p / 2).succ,
(if (a * x : zmod p).val ≤ p / 2 then 1 else -1) *
(a * x : zmod p).val_min_abs.nat_abs) :
prod_congr rfl $ λ _ _, begin
simp only [cast_nat_abs_val_min_abs],
split_ifs; simp
end
... = (-1)^((Ico 1 (p / 2).succ).filter
(λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card *
(∏ x in Ico 1 (p / 2).succ, (a * x : zmod p).val_min_abs.nat_abs) :
have (∏ x in Ico 1 (p / 2).succ,
if (a * x : zmod p).val ≤ p / 2 then (1 : zmod p) else -1) =
(∏ x in (Ico 1 (p / 2).succ).filter
(λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2), -1),
from prod_bij_ne_one (λ x _ _, x)
(λ x, by split_ifs; simp * at * {contextual := tt})
(λ _ _ _ _ _ _, id)
(λ b h _, ⟨b, by simp [-not_le, *] at *⟩)
(by intros; split_ifs at *; simp * at *),
by rw [prod_mul_distrib, this]; simp
... = (-1)^((Ico 1 (p / 2).succ).filter
(λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card * (p / 2).fact :
by rw [← prod_nat_cast, finset.prod_eq_multiset_prod,
Ico_map_val_min_abs_nat_abs_eq_Ico_map_id p a hap,
← finset.prod_eq_multiset_prod, prod_Ico_id_eq_fact]
private lemma gauss_lemma_aux₂ (p : ℕ) [hp : fact p.prime] [hp2 : fact (p % 2 = 1)]
{a : ℕ} (hap : (a : zmod p) ≠ 0) :
(a^(p / 2) : zmod p) = (-1)^((Ico 1 (p / 2).succ).filter
(λ x : ℕ, p / 2 < (a * x : zmod p).val)).card :=
(domain.mul_left_inj
(show ((p / 2).fact : zmod p) ≠ 0,
by rw [ne.def, char_p.cast_eq_zero_iff (zmod p) p, hp.dvd_fact, not_le];
exact nat.div_lt_self hp.pos dec_trivial)).1 $
by simpa using gauss_lemma_aux₁ p hap
private lemma eisenstein_lemma_aux₁ (p : ℕ) [hp : fact p.prime] [hp2 : fact (p % 2 = 1)]
{a : ℕ} (hap : (a : zmod p) ≠ 0) :
((∑ x in Ico 1 (p / 2).succ, a * x : ℕ) : zmod 2) =
((Ico 1 (p / 2).succ).filter
((λ x : ℕ, p / 2 < (a * x : zmod p).val))).card +
∑ x in Ico 1 (p / 2).succ, x
+ (∑ x in Ico 1 (p / 2).succ, (a * x) / p : ℕ) :=
have hp2 : (p : zmod 2) = (1 : ℕ), from (eq_iff_modeq_nat _).2 hp2,
calc ((∑ x in Ico 1 (p / 2).succ, a * x : ℕ) : zmod 2)
= ((∑ x in Ico 1 (p / 2).succ, ((a * x) % p + p * ((a * x) / p)) : ℕ) : zmod 2) :
by simp only [mod_add_div]
... = (∑ x in Ico 1 (p / 2).succ, ((a * x : ℕ) : zmod p).val : ℕ) +
(∑ x in Ico 1 (p / 2).succ, (a * x) / p : ℕ) :
by simp only [val_cast_nat];
simp [sum_add_distrib, mul_sum.symm, nat.cast_add, nat.cast_mul, sum_nat_cast, hp2]
... = _ : congr_arg2 (+)
(calc ((∑ x in Ico 1 (p / 2).succ, ((a * x : ℕ) : zmod p).val : ℕ) : zmod 2)
= ∑ x in Ico 1 (p / 2).succ,
((((a * x : zmod p).val_min_abs +
(if (a * x : zmod p).val ≤ p / 2 then 0 else p)) : ℤ) : zmod 2) :
by simp only [(val_eq_ite_val_min_abs _).symm]; simp [sum_nat_cast]
... = ((Ico 1 (p / 2).succ).filter
(λ x : ℕ, p / 2 < (a * x : zmod p).val)).card +
((∑ x in Ico 1 (p / 2).succ, (a * x : zmod p).val_min_abs.nat_abs) : ℕ) :
by { simp [ite_cast, add_comm, sum_add_distrib, finset.sum_ite, hp2, sum_nat_cast], }
... = _ : by rw [finset.sum_eq_multiset_sum,
Ico_map_val_min_abs_nat_abs_eq_Ico_map_id p a hap,
← finset.sum_eq_multiset_sum];
simp [sum_nat_cast]) rfl
private lemma eisenstein_lemma_aux₂ (p : ℕ) [hp : fact p.prime] [hp2 : fact (p % 2 = 1)]
{a : ℕ} (ha2 : a % 2 = 1) (hap : (a : zmod p) ≠ 0) :
((Ico 1 (p / 2).succ).filter
((λ x : ℕ, p / 2 < (a * x : zmod p).val))).card
≡ ∑ x in Ico 1 (p / 2).succ, (x * a) / p [MOD 2] :=
have ha2 : (a : zmod 2) = (1 : ℕ), from (eq_iff_modeq_nat _).2 ha2,
(eq_iff_modeq_nat 2).1 $ sub_eq_zero.1 $
by simpa [add_left_comm, sub_eq_add_neg, finset.mul_sum.symm, mul_comm, ha2, sum_nat_cast,
add_neg_eq_iff_eq_add.symm, neg_eq_self_mod_two, add_assoc]
using eq.symm (eisenstein_lemma_aux₁ p hap)
lemma div_eq_filter_card {a b c : ℕ} (hb0 : 0 < b) (hc : a / b ≤ c) : a / b =
((Ico 1 c.succ).filter (λ x, x * b ≤ a)).card :=
calc a / b = (Ico 1 (a / b).succ).card : by simp
... = ((Ico 1 c.succ).filter (λ x, x * b ≤ a)).card :
congr_arg _ $ finset.ext $ λ x,
have x * b ≤ a → x ≤ c,
from λ h, le_trans (by rwa [le_div_iff_mul_le _ _ hb0]) hc,
by simp [lt_succ_iff, le_div_iff_mul_le _ _ hb0]; tauto
/-- The given sum is the number of integer points in the triangle formed by the diagonal of the
rectangle `(0, p/2) × (0, q/2)` -/
private lemma sum_Ico_eq_card_lt {p q : ℕ} :
∑ a in Ico 1 (p / 2).succ, (a * q) / p =
(((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter
(λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q)).card :=
if hp0 : p = 0 then by simp [hp0, finset.ext_iff]
else
calc ∑ a in Ico 1 (p / 2).succ, (a * q) / p =
∑ a in Ico 1 (p / 2).succ,
((Ico 1 (q / 2).succ).filter (λ x, x * p ≤ a * q)).card :
finset.sum_congr rfl $ λ x hx,
div_eq_filter_card (nat.pos_of_ne_zero hp0)
(calc x * q / p ≤ (p / 2) * q / p :
nat.div_le_div_right (mul_le_mul_of_nonneg_right
(le_of_lt_succ $ by finish)
(nat.zero_le _))
... ≤ _ : nat.div_mul_div_le_div _ _ _)
... = _ : by rw [← card_sigma];
exact card_congr (λ a _, ⟨a.1, a.2⟩)
(by simp {contextual := tt})
(λ ⟨_, _⟩ ⟨_, _⟩, by simp {contextual := tt})
(λ ⟨b₁, b₂⟩ h, ⟨⟨b₁, b₂⟩,
by revert h; simp {contextual := tt}⟩)
/-- Each of the sums in this lemma is the cardinality of the set integer points in each of the
two triangles formed by the diagonal of the rectangle `(0, p/2) × (0, q/2)`. Adding them
gives the number of points in the rectangle. -/
private lemma sum_mul_div_add_sum_mul_div_eq_mul (p q : ℕ) [hp : fact p.prime]
(hq0 : (q : zmod p) ≠ 0) :
∑ a in Ico 1 (p / 2).succ, (a * q) / p +
∑ a in Ico 1 (q / 2).succ, (a * p) / q =
(p / 2) * (q / 2) :=
have hswap : (((Ico 1 (q / 2).succ).product (Ico 1 (p / 2).succ)).filter
(λ x : ℕ × ℕ, x.2 * q ≤ x.1 * p)).card =
(((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter
(λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p)).card :=
card_congr (λ x _, prod.swap x)
(λ ⟨_, _⟩, by simp {contextual := tt})
(λ ⟨_, _⟩ ⟨_, _⟩, by simp {contextual := tt})
(λ ⟨x₁, x₂⟩ h, ⟨⟨x₂, x₁⟩, by revert h; simp {contextual := tt}⟩),
have hdisj : disjoint
(((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter
(λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q))
(((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter
(λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p)),
from disjoint_filter.2 $ λ x hx hpq hqp,
have hxp : x.1 < p, from lt_of_le_of_lt
(show x.1 ≤ p / 2, by simp [*, nat.lt_succ_iff] at *; tauto)
(nat.div_lt_self hp.pos dec_trivial),
begin
have : (x.1 : zmod p) = 0,
{ simpa [hq0] using congr_arg (coe : ℕ → zmod p) (le_antisymm hpq hqp) },
apply_fun zmod.val at this,
rw [val_cast_of_lt hxp, val_zero] at this,
simp * at *
end,
have hunion : ((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter
(λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q) ∪
((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter
(λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p) =
((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)),
from finset.ext $ λ x, by have := le_total (x.2 * p) (x.1 * q); simp; tauto,
by rw [sum_Ico_eq_card_lt, sum_Ico_eq_card_lt, hswap, ← card_disjoint_union hdisj, hunion,
card_product];
simp
variables (p q : ℕ) [fact p.prime] [fact q.prime]
namespace zmod
/-- The Legendre symbol of `a` and `p` is an integer defined as
* `0` if `a` is `0` modulo `p`;
* `1` if `a ^ (p / 2)` is `1` modulo `p`
(by `euler_criterion` this is equivalent to “`a` is a square modulo `p`”);
* `-1` otherwise.
-/
def legendre_sym (a p : ℕ) : ℤ :=
if (a : zmod p) = 0 then 0
else if (a : zmod p) ^ (p / 2) = 1 then 1
else -1
lemma legendre_sym_eq_pow (a p : ℕ) [hp : fact p.prime] :
(legendre_sym a p : zmod p) = (a ^ (p / 2)) :=
begin
rw legendre_sym,
by_cases ha : (a : zmod p) = 0,
{ simp only [if_pos, ha, _root_.zero_pow (nat.div_pos (hp.two_le) (succ_pos 1)), int.cast_zero] },
cases hp.eq_two_or_odd with hp2 hp_odd,
{ resetI, subst p,
have : ∀ (a : zmod 2),
((if a = 0 then 0 else if a ^ (2 / 2) = 1 then 1 else -1 : ℤ) : zmod 2) = a ^ (2 / 2),
by exact dec_trivial,
exact this a },
{ change fact (p % 2 = 1) at hp_odd, resetI,
rw if_neg ha,
have : (-1 : zmod p) ≠ 1, from (ne_neg_self p one_ne_zero).symm,
cases pow_div_two_eq_neg_one_or_one p ha with h h,
{ rw [if_pos h, h, int.cast_one], },
{ rw [h, if_neg this, int.cast_neg, int.cast_one], } }
end
lemma legendre_sym_eq_one_or_neg_one (a p : ℕ) (ha : (a : zmod p) ≠ 0) :
legendre_sym a p = -1 ∨ legendre_sym a p = 1 :=
by unfold legendre_sym; split_ifs; simp only [*, eq_self_iff_true, or_true, true_or] at *
lemma legendre_sym_eq_zero_iff (a p : ℕ) :
legendre_sym a p = 0 ↔ (a : zmod p) = 0 :=
begin
split,
{ classical, contrapose,
assume ha, cases legendre_sym_eq_one_or_neg_one a p ha with h h,
all_goals { rw h, norm_num } },
{ assume ha, rw [legendre_sym, if_pos ha] }
end
/-- Gauss' lemma. The legendre symbol can be computed by considering the number of naturals less
than `p/2` such that `(a * x) % p > p / 2` -/
lemma gauss_lemma {a : ℕ} [hp1 : fact (p % 2 = 1)] (ha0 : (a : zmod p) ≠ 0) :
legendre_sym a p = (-1) ^ ((Ico 1 (p / 2).succ).filter
(λ x : ℕ, p / 2 < (a * x : zmod p).val)).card :=
have (legendre_sym a p : zmod p) = (((-1)^((Ico 1 (p / 2).succ).filter
(λ x : ℕ, p / 2 < (a * x : zmod p).val)).card : ℤ) : zmod p),
by rw [legendre_sym_eq_pow, gauss_lemma_aux₂ p ha0]; simp,
begin
cases legendre_sym_eq_one_or_neg_one a p ha0;
cases @neg_one_pow_eq_or ℤ _ ((Ico 1 (p / 2).succ).filter
(λ x : ℕ, p / 2 < (a * x : zmod p).val)).card;
simp [*, ne_neg_self p one_ne_zero, (ne_neg_self p one_ne_zero).symm] at *
end
lemma legendre_sym_eq_one_iff {a : ℕ} (ha0 : (a : zmod p) ≠ 0) :
legendre_sym a p = 1 ↔ (∃ b : zmod p, b ^ 2 = a) :=
begin
rw [euler_criterion p ha0, legendre_sym, if_neg ha0],
split_ifs,
{ simp only [h, eq_self_iff_true] },
finish -- this is quite slow. I'm actually surprised that it can close the goal at all!
end
lemma eisenstein_lemma [hp1 : fact (p % 2 = 1)] {a : ℕ} (ha1 : a % 2 = 1) (ha0 : (a : zmod p) ≠ 0) :
legendre_sym a p = (-1)^∑ x in Ico 1 (p / 2).succ, (x * a) / p :=
by rw [neg_one_pow_eq_pow_mod_two, gauss_lemma p ha0, neg_one_pow_eq_pow_mod_two,
show _ = _, from eisenstein_lemma_aux₂ p ha1 ha0]
theorem quadratic_reciprocity [hp1 : fact (p % 2 = 1)] [hq1 : fact (q % 2 = 1)] (hpq : p ≠ q) :
legendre_sym p q * legendre_sym q p = (-1) ^ ((p / 2) * (q / 2)) :=
have hpq0 : (p : zmod q) ≠ 0, from prime_ne_zero q p hpq.symm,
have hqp0 : (q : zmod p) ≠ 0, from prime_ne_zero p q hpq,
by rw [eisenstein_lemma q hp1 hpq0, eisenstein_lemma p hq1 hqp0,
← _root_.pow_add, sum_mul_div_add_sum_mul_div_eq_mul q p hpq0, mul_comm]
-- move this
instance fact_prime_two : fact (nat.prime 2) := nat.prime_two
lemma legendre_sym_two [hp1 : fact (p % 2 = 1)] : legendre_sym 2 p = (-1) ^ (p / 4 + p / 2) :=
have hp2 : p ≠ 2, from mt (congr_arg (% 2)) (by simpa using hp1),
have hp22 : p / 2 / 2 = _ := div_eq_filter_card (show 0 < 2, from dec_trivial)
(nat.div_le_self (p / 2) 2),
have hcard : (Ico 1 (p / 2).succ).card = p / 2, by simp,
have hx2 : ∀ x ∈ Ico 1 (p / 2).succ, (2 * x : zmod p).val = 2 * x,
from λ x hx, have h2xp : 2 * x < p,
from calc 2 * x ≤ 2 * (p / 2) : mul_le_mul_of_nonneg_left
(le_of_lt_succ $ by finish) dec_trivial
... < _ : by conv_rhs {rw [← mod_add_div p 2, add_comm, show p % 2 = 1, from hp1]}; exact lt_succ_self _,
by rw [← nat.cast_two, ← nat.cast_mul, val_cast_of_lt h2xp],
have hdisj : disjoint
((Ico 1 (p / 2).succ).filter (λ x, p / 2 < ((2 : ℕ) * x : zmod p).val))
((Ico 1 (p / 2).succ).filter (λ x, x * 2 ≤ p / 2)),
from disjoint_filter.2 (λ x hx, by simp [hx2 _ hx, mul_comm]),
have hunion :
((Ico 1 (p / 2).succ).filter (λ x, p / 2 < ((2 : ℕ) * x : zmod p).val)) ∪
((Ico 1 (p / 2).succ).filter (λ x, x * 2 ≤ p / 2)) =
Ico 1 (p / 2).succ,
begin
rw [filter_union_right],
conv_rhs {rw [← @filter_true _ (Ico 1 (p / 2).succ)]},
exact filter_congr (λ x hx, by simp [hx2 _ hx, lt_or_le, mul_comm])
end,
begin
rw [gauss_lemma p (prime_ne_zero p 2 hp2),
neg_one_pow_eq_pow_mod_two, @neg_one_pow_eq_pow_mod_two _ _ (p / 4 + p / 2)],
refine congr_arg2 _ rfl ((eq_iff_modeq_nat 2).1 _),
rw [show 4 = 2 * 2, from rfl, ← nat.div_div_eq_div_mul, hp22, nat.cast_add,
← sub_eq_iff_eq_add', sub_eq_add_neg, neg_eq_self_mod_two,
← nat.cast_add, ← card_disjoint_union hdisj, hunion, hcard]
end
lemma exists_pow_two_eq_two_iff [hp1 : fact (p % 2 = 1)] :
(∃ a : zmod p, a ^ 2 = 2) ↔ p % 8 = 1 ∨ p % 8 = 7 :=
have hp2 : ((2 : ℕ) : zmod p) ≠ 0,
from prime_ne_zero p 2 (λ h, by simpa [h] using hp1),
have hpm4 : p % 4 = p % 8 % 4, from (nat.mod_mul_left_mod p 2 4).symm,
have hpm2 : p % 2 = p % 8 % 2, from (nat.mod_mul_left_mod p 4 2).symm,
begin
rw [show (2 : zmod p) = (2 : ℕ), by simp, ← legendre_sym_eq_one_iff p hp2,
legendre_sym_two p, neg_one_pow_eq_one_iff_even (show (-1 : ℤ) ≠ 1, from dec_trivial),
even_add, even_div, even_div],
have := nat.mod_lt p (show 0 < 8, from dec_trivial),
resetI, rw _root_.fact at hp1,
revert this hp1,
erw [hpm4, hpm2],
generalize hm : p % 8 = m,
clear hm,
revert m,
exact dec_trivial
end
lemma exists_pow_two_eq_prime_iff_of_mod_four_eq_one (hp1 : p % 4 = 1) [hq1 : fact (q % 2 = 1)] :
(∃ a : zmod p, a ^ 2 = q) ↔ ∃ b : zmod q, b ^ 2 = p :=
if hpq : p = q then by resetI; subst hpq else
have h1 : ((p / 2) * (q / 2)) % 2 = 0,
from (dvd_iff_mod_eq_zero _ _).1
(dvd_mul_of_dvd_left ((dvd_iff_mod_eq_zero _ _).2 $
by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp1]; refl) _),
begin
haveI hp_odd : fact (p % 2 = 1) := odd_of_mod_four_eq_one hp1,
have hpq0 : (p : zmod q) ≠ 0 := prime_ne_zero q p (ne.symm hpq),
have hqp0 : (q : zmod p) ≠ 0 := prime_ne_zero p q hpq,
have := quadratic_reciprocity p q hpq,
rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym,
if_neg hqp0, if_neg hpq0] at this,
rw [euler_criterion q hpq0, euler_criterion p hqp0],
split_ifs at this; simp *; contradiction,
end
lemma exists_pow_two_eq_prime_iff_of_mod_four_eq_three (hp3 : p % 4 = 3)
(hq3 : q % 4 = 3) (hpq : p ≠ q) : (∃ a : zmod p, a ^ 2 = q) ↔ ¬∃ b : zmod q, b ^ 2 = p :=
have h1 : ((p / 2) * (q / 2)) % 2 = 1,
from nat.odd_mul_odd
(by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp3]; refl)
(by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hq3]; refl),
begin
haveI hp_odd : fact (p % 2 = 1) := odd_of_mod_four_eq_three hp3,
haveI hq_odd : fact (q % 2 = 1) := odd_of_mod_four_eq_three hq3,
have hpq0 : (p : zmod q) ≠ 0 := prime_ne_zero q p (ne.symm hpq),
have hqp0 : (q : zmod p) ≠ 0 := prime_ne_zero p q hpq,
have := quadratic_reciprocity p q hpq,
rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym,
if_neg hpq0, if_neg hqp0] at this,
rw [euler_criterion q hpq0, euler_criterion p hqp0],
split_ifs at this; simp *; contradiction
end
end zmod
|
e2410b530e0eeba6cbc7f2c9489d168a5f283bad | fcf3ffa92a3847189ca669cb18b34ef6b2ec2859 | /src/custom/prime.lean | 932334b59db2f666ae0012ed281d9407523a805d | [
"Apache-2.0"
] | permissive | nomoid/lean-proofs | 4a80a97888699dee42b092b7b959b22d9aa0c066 | b9f03a24623d1a1d111d6c2bbf53c617e2596d6a | refs/heads/master | 1,674,955,317,080 | 1,607,475,706,000 | 1,607,475,706,000 | 314,104,281 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,156 | lean | import data.nat.prime
import polyfill.factorial
import polyfill.mod
import logic.basic
import custom.util
/-
The following code contains a theorem that proves that
there are infinitely many prime numbers. Specifically,
the statement of the theorem is that:
If `n` is a natural number greater than or equal to
`2`, there exists some prime number `p` that is
greater than `n`.
Given that `2` is a natural number, we can iteratively
apply the above theorem to show that there are
infinitely many primes.
The proof of infinitely many primes will be explained
in detail. However, before the theorem statement, there
are also several lemmas presented here that are used in
the proof of the theorem, in addition to those that are
imported from the Lean standard library `mathlib`.
-/
namespace nat
/- Lemma: Given naturals `n` and `m` where `n` divides `m`
and `m > 0`, we have that `n > 0`. -/
lemma dvd_gt_zero (n m : ℕ) (h : 0 < m) : n ∣ m → 0 < n :=
begin
intro h2,
rw dvd_iff_mod_eq_zero at h2,
by_contra h3,
rw ← ne_zero_iff_gt_zero at h3,
rw ne.def at h3,
rw not_not at h3,
rw h3 at h2,
have h4 := mod_zero m,
rw h4 at h2,
rw ← ne_zero_iff_gt_zero at h,
rw h2 at h,
apply ne_self_imp_false 0,
exact h,
end
/- Lemma: `2` is a prime number, where prime is defined as
being `≥ 2` and having exactly `1` and itself as
factors. -/
lemma two_is_prime : prime 2 :=
begin
split,
{
apply le_of_eq,
refl,
},
{
intro m,
intro h,
apply one_or_two,
split,
{
apply dvd_gt_zero m 2,
apply zero_lt_one_add,
exact h,
},
{
apply le_of_dvd,
apply zero_lt_one_add,
exact h,
},
}
end
/- Lemma: Given a factor of a natural number `≥ 2`, if that
factor is not `1`, it must be also `≥ 2` -/
lemma ge_two_of_factor_not_one (a b : ℕ) (h : a ≠ 1) (h2 : 2 ≤ b) : b % a = 0 → 2 ≤ a :=
begin
intro hd,
apply le_of_not_gt,
rw gt_from_lt,
rw ← zero_or_one,
apply not_or,
{
by_contra haz,
have hmz := mod_zero b,
rw haz at hd,
rw hmz at hd,
have hzo := @or.inl (b = 0) (b = 1) hd,
rw zero_or_one at hzo,
have h2n := not_le_of_gt hzo,
apply absurd h2 h2n,
},
{
rw ← ne.def,
exact h,
},
end
/- Lemma: Given a natural number `≥ 2`, that number has at
least one factor that is prime. -/
lemma exists_prime_factor : ∀ (n : ℕ), 2 ≤ n → ∃ (p : ℕ), prime p ∧ n % p = 0 :=
begin
intro n,
intro h,
have hnge2 := le.dest h,
cases hnge2 with m hm,
rw ← hm,
clear hm,
induction m using nat.case_strong_induction_on with d hd,
{
use 2,
split,
{
exact two_is_prime,
},
{
rw add_zero,
exact mod_self 2,
}
},
{
have h2 := @classical.or_not (prime (2 + succ d)),
cases h2,
{
use (2 + succ d),
split,
{
exact h2,
},
{
apply mod_self,
}
},
{
rw prime_def_lt at h2,
rw not_and at h2,
have h2lsd := @le_add_right 2 (succ d),
have h3 := h2 h2lsd,
have hnf1 := classical.not_forall.1,
have h4 := hnf1 h3,
cases h4 with x hx,
have h5 := not_imp.1 hx,
have h6 := not_imp.1 (h5.right),
have hxne1 := h6.right,
rw ← ne.def at hxne1,
have hxdvd := h6.left,
have hmodx := mod_eq_zero_of_dvd hxdvd,
have hxge2 := ge_two_of_factor_not_one x (2 + succ d) hxne1 h2lsd hmodx,
cases (le.dest hxge2) with y hy,
have hlt := h5.left,
rw ← hy at hlt,
have hyltsd := lt_of_add_lt_add_left hlt,
have hyled := le_of_lt_succ hyltsd,
have hdy := hd y hyled,
cases hdy with p hp,
use p,
split,
{
apply hp.left,
},
{
apply mod_eq_zero_of_dvd,
apply dvd_trans,
{
rw dvd_iff_mod_eq_zero,
apply hp.right,
},
{
rw hy,
exact hxdvd,
},
},
},
},
end
/- Lemma: Given a natural number `n`, every natural number
between `1` and `n` inclusive divides `n` factorial. -/
lemma factorial_mod_zero (n d : ℕ) (h : d ≤ n) (h2 : 1 ≤ d) : (factorial n) % d = 0 :=
begin
apply mod_eq_zero_of_dvd,
apply dvd_factorial,
{
exact h2,
},
{
exact h,
},
end
/- Lemma: Given `d ≥ 2` and `n`, where `n mod d` is `0`,
`(n + 1) mod d` is `1`. -/
lemma mod_zero_add_one_is_one (n d : ℕ) (h: 2 ≤ d) : n % d = 0 → (n + 1) % d = 1 :=
begin
intro hmz,
rw add_comm,
rw ← @add_mod_mod 1 n d,
rw hmz,
rw add_zero,
have hle := le.dest h,
cases hle with c hc,
rw ← hc,
rw add_comm,
apply one_mod,
end
/-
Theorem: Given a natural number `n ≥ 2`, there exists a
prime `p` where `p > n`.
This proof is inspired by Euclid's proof of existence
of infinitely many primes. The proof will be written
inline accompanying the corresponding Lean code.
-/
-- Let `n` be a natural number such that `n ≥ 2`.
theorem infinite_primes (n : ℕ) (h : 2 ≤ n) : ∃ (p : ℕ), prime p ∧ p > n :=
begin
-- We have that `n! ≥ n` as a property of factorials.
have hnlnf := self_le_factorial n,
-- Since `n ≥ 2`, it must be the case that `n! ≥ 2`.
have hfng2 := le_trans h hnlnf,
-- Thus, `n! + 1 ≥ 2`.
have hfnp1g2 := le_trans hfng2 (le_add_right (factorial n) 1),
-- From an above lemma, we have shown that any `x ≥ 2`
-- has a prime factor.
-- Therefore, `n! + 1` has a prime factor.
have h1 := exists_prime_factor (factorial n + 1) hfnp1g2,
-- Let `p` be a prime factor of `n! + 1`.
cases h1 with p hp,
-- We want to show that `p` is a prime greater than `n`.
use p,
-- `p` is prime because it is a prime factor of
-- `n! + 1`.
have hprime := hp.left,
split,
-- We will start by showing that `p` is prime.
{
-- We have already shown just now that `p` is
-- prime, so we are done.
exact hprime,
},
-- Now we have to show that `p > n`.
{
-- By contradiction, assume that it is not the case
-- that `p > n`.
by_contra hnpgn,
-- At this point, we will work backwards to show
-- that a contradiction occurs. This backwards
-- solving style may be a bit unintuitive for
-- reading a regular proof in, but it is the style
-- that is preferred by Lean.
-- Since we have shown that `n! + 1` has `p` as a
-- factor, we can create a contradiction by showing
-- that `n! + 1` does not have `p` has a factor.
apply absurd hp.right,
-- To do this, we want to show that
-- `(n! + 1) mod p ≠ 0`.
rw ← ne_from_not_eq ((factorial n + 1) % p) 0,
-- This can be achieved by showing that
-- `(n! + 1) mod p > 0`.
apply ne_of_gt,
-- This can be achieved by showing that
-- `(n! + 1) mod p = 1`.
apply gt_zero_of_eq_one,
-- If we know that `n! mod p = 0`, along with
-- `p ≥ 2`, we can use one
-- of our above lemmas to show that
-- `(n! + 1) mod p = 1`.
apply mod_zero_add_one_is_one,
-- First we need to show that `p ≥ 2`.
{
-- We know that all primes `p` satisfy `p ≥ 2`,
-- so we just need to show that `p` is prime.
apply prime.two_le,
-- However, we have already shown that `p` is
-- prime, so we can conclude `p ≥ 2`.
apply hprime,
},
-- Now we need to show that `n! mod p = 0`.
{
-- We can rewrite this as `p divides n!`.
rw ← dvd_iff_mod_eq_zero,
-- We can use the basic property of factorials
-- where for all `0 < p ≤ n`, `p divides n!`.
apply dvd_factorial,
-- First we need to show that `p > 0`.
{
-- This is equivalent to `p ≥ 1`.
apply lt_of_succ_le,
-- We know that `p ≥ 1` when `p ≥ 2`.
apply le_of_succ_le,
-- Which is true if `p` is a prime.
apply prime.two_le,
-- And we already know that `p` is a prime,
-- so we can conclude that `p > 0`.
apply hprime,
},
-- Lastly, we need to show that `p ≤ n`.
{
-- This is equivalent to showing the
-- inverse of `p > n`.
apply le_of_not_gt,
-- We assumed in our contradiction that it
-- is not the case that `p > n`. Thus,
-- `p ≤ n`.
exact hnpgn,
},
-- We are now done with the proof!
-- As a recap of the backwards logic,
-- by contradiction, we assumed that `p ≤ n`.
-- Therefore, since `p ≥ 0`, we have that
-- `p divides n!`.
},
-- Therefore, `n! mod p = 0`.
-- Therefore, since `p ≥ 2`, `(n! + 1) mod p = 1`.
-- However, we defined `p` as being a prime factor
-- of `(n! + 1)`, so `(n! + 1) mod p = 0`.
-- This is a contradiction, so it must be the case
-- that `p > n`.
-- Since we have already shown that `p` is prime,
-- we can conclude that for all natural numbers
-- `n`, there exists a prime `p` such that `p > n`.
},
end
end nat |
0ce4f26f57e4593ea859b394e8946672d363e19c | 0533ebfa09b11cf8a29da118dd1b86b94949511e | /src/riemann_hypothesis.lean | b1058c055eccf32c30d1a049fa89136e550b83f4 | [
"MIT"
] | permissive | wudcscheme/Lean-RH | 89e9055aac68703876e750c23fb5327979a09822 | 870f78cc7c0715d03466d1211b0f032b425ec984 | refs/heads/main | 1,679,188,429,923 | 1,602,701,790,000 | 1,602,701,790,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,410 | lean | /- ------------------------------------------------------------------------- -|
| @project: riemann_hypothesis |
| @file: riemann_hypothesis.lean |
| @author: Brandon H. Gomes and Alex Kontorovich |
| @affil: Rutgers University |
|- ------------------------------------------------------------------------- -/
import .dirichlet_eta
/-!
-/
namespace riemann_hypothesis --——————————————————————————————————————————————————————————--
variables {ℂ : Type*} {ℝ : Type*}
[has_lift_t nat ℝ] [has_lift_t ℝ ℂ] [preorder ℝ] [Algebra ℝ] [Algebra ℂ]
(ℭ : Complex ℂ ℝ)
open algebra
/--
-/
def form.dirichlet_eta
[has_lift_zero_same nat ℝ]
[has_lift_lt_comm nat ℝ]
(s) (σpos : 0 < ℭ.real_part s)
(σ_le_one : ℭ.real_part s < 1)
:= is_convergent ℭ.abs (dirichlet_eta.partial_pairs ℭ s) 0 → ℭ.real_part s = 2⁻¹
end riemann_hypothesis --————————————————————————————————————————————————————————————————--
|
284663c4701b6a9a35541b605494fce569816e2e | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/category_theory/sites/grothendieck.lean | 658de4af3c30f417ebfb18a0b08266b1ba362b18 | [
"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 | 22,611 | lean | /-
Copyright (c) 2020 Bhavik Mehta, E. W. Ayers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta, E. W. Ayers
-/
import category_theory.sites.sieves
import category_theory.limits.shapes.pullbacks
import category_theory.limits.shapes.multiequalizer
import category_theory.category.preorder
import order.copy
/-!
# Grothendieck topologies
Definition and lemmas about Grothendieck topologies.
A Grothendieck topology for a category `C` is a set of sieves on each object `X` satisfying
certain closure conditions.
Alternate versions of the axioms (in arrow form) are also described.
Two explicit examples of Grothendieck topologies are given:
* The dense topology
* The atomic topology
as well as the complete lattice structure on Grothendieck topologies (which gives two additional
explicit topologies: the discrete and trivial topologies.)
A pretopology, or a basis for a topology is defined in `pretopology.lean`. The topology associated
to a topological space is defined in `spaces.lean`.
## Tags
Grothendieck topology, coverage, pretopology, site
## References
* [nLab, *Grothendieck topology*](https://ncatlab.org/nlab/show/Grothendieck+topology)
* [S. MacLane, I. Moerdijk, *Sheaves in Geometry and Logic*][MM92]
## Implementation notes
We use the definition of [nlab] and [MM92][] (Chapter III, Section 2), where Grothendieck topologies
are saturated collections of morphisms, rather than the notions of the Stacks project (00VG) and
the Elephant, in which topologies are allowed to be unsaturated, and are then completed.
TODO (BM): Add the definition from Stacks, as a pretopology, and complete to a topology.
This is so that we can produce a bijective correspondence between Grothendieck topologies on a
small category and Lawvere-Tierney topologies on its presheaf topos, as well as the equivalence
between Grothendieck topoi and left exact reflective subcategories of presheaf toposes.
-/
universes w v u
namespace category_theory
open category_theory category
variables (C : Type u) [category.{v} C]
/--
The definition of a Grothendieck topology: a set of sieves `J X` on each object `X` satisfying
three axioms:
1. For every object `X`, the maximal sieve is in `J X`.
2. If `S ∈ J X` then its pullback along any `h : Y ⟶ X` is in `J Y`.
3. If `S ∈ J X` and `R` is a sieve on `X`, then provided that the pullback of `R` along any arrow
`f : Y ⟶ X` in `S` is in `J Y`, we have that `R` itself is in `J X`.
A sieve `S` on `X` is referred to as `J`-covering, (or just covering), if `S ∈ J X`.
See <https://stacks.math.columbia.edu/tag/00Z4>, or [nlab], or [MM92][] Chapter III, Section 2,
Definition 1.
-/
structure grothendieck_topology :=
(sieves : Π (X : C), set (sieve X))
(top_mem' : ∀ X, ⊤ ∈ sieves X)
(pullback_stable' : ∀ ⦃X Y : C⦄ ⦃S : sieve X⦄ (f : Y ⟶ X), S ∈ sieves X → S.pullback f ∈ sieves Y)
(transitive' : ∀ ⦃X⦄ ⦃S : sieve X⦄ (hS : S ∈ sieves X) (R : sieve X),
(∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄, S f → R.pullback f ∈ sieves Y) → R ∈ sieves X)
namespace grothendieck_topology
instance : has_coe_to_fun (grothendieck_topology C) (λ _, Π X : C, set (sieve X)) := ⟨sieves⟩
variables {C} {X Y : C} {S R : sieve X}
variables (J : grothendieck_topology C)
/--
An extensionality lemma in terms of the coercion to a pi-type.
We prove this explicitly rather than deriving it so that it is in terms of the coercion rather than
the projection `.sieves`.
-/
@[ext]
lemma ext {J₁ J₂ : grothendieck_topology C} (h : (J₁ : Π (X : C), set (sieve X)) = J₂) : J₁ = J₂ :=
by { cases J₁, cases J₂, congr, apply h }
@[simp] lemma mem_sieves_iff_coe : S ∈ J.sieves X ↔ S ∈ J X := iff.rfl
-- Also known as the maximality axiom.
@[simp] lemma top_mem (X : C) : ⊤ ∈ J X := J.top_mem' X
-- Also known as the stability axiom.
@[simp] lemma pullback_stable (f : Y ⟶ X) (hS : S ∈ J X) : S.pullback f ∈ J Y :=
J.pullback_stable' f hS
lemma transitive (hS : S ∈ J X) (R : sieve X)
(h : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄, S f → R.pullback f ∈ J Y) :
R ∈ J X :=
J.transitive' hS R h
lemma covering_of_eq_top : S = ⊤ → S ∈ J X := λ h, h.symm ▸ J.top_mem X
/--
If `S` is a subset of `R`, and `S` is covering, then `R` is covering as well.
See <https://stacks.math.columbia.edu/tag/00Z5> (2), or discussion after [MM92] Chapter III,
Section 2, Definition 1.
-/
lemma superset_covering (Hss : S ≤ R) (sjx : S ∈ J X) : R ∈ J X :=
begin
apply J.transitive sjx R (λ Y f hf, _),
apply covering_of_eq_top,
rw [← top_le_iff, ← S.pullback_eq_top_of_mem hf],
apply sieve.pullback_monotone _ Hss,
end
/--
The intersection of two covering sieves is covering.
See <https://stacks.math.columbia.edu/tag/00Z5> (1), or [MM92] Chapter III,
Section 2, Definition 1 (iv).
-/
lemma intersection_covering (rj : R ∈ J X) (sj : S ∈ J X) : R ⊓ S ∈ J X :=
begin
apply J.transitive rj _ (λ Y f Hf, _),
rw [sieve.pullback_inter, R.pullback_eq_top_of_mem Hf],
simp [sj],
end
@[simp]
lemma intersection_covering_iff : R ⊓ S ∈ J X ↔ R ∈ J X ∧ S ∈ J X :=
⟨λ h, ⟨J.superset_covering inf_le_left h, J.superset_covering inf_le_right h⟩,
λ t, intersection_covering _ t.1 t.2⟩
lemma bind_covering {S : sieve X} {R : Π ⦃Y : C⦄ ⦃f : Y ⟶ X⦄, S f → sieve Y} (hS : S ∈ J X)
(hR : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄ (H : S f), R H ∈ J Y) :
sieve.bind S R ∈ J X :=
J.transitive hS _ (λ Y f hf, superset_covering J (sieve.le_pullback_bind S R f hf) (hR hf))
/--
The sieve `S` on `X` `J`-covers an arrow `f` to `X` if `S.pullback f ∈ J Y`.
This definition is an alternate way of presenting a Grothendieck topology.
-/
def covers (S : sieve X) (f : Y ⟶ X) : Prop := S.pullback f ∈ J Y
lemma covers_iff (S : sieve X) (f : Y ⟶ X) : J.covers S f ↔ S.pullback f ∈ J Y :=
iff.rfl
lemma covering_iff_covers_id (S : sieve X) : S ∈ J X ↔ J.covers S (𝟙 X) :=
by simp [covers_iff]
/-- The maximality axiom in 'arrow' form: Any arrow `f` in `S` is covered by `S`. -/
lemma arrow_max (f : Y ⟶ X) (S : sieve X) (hf : S f) : J.covers S f :=
begin
rw [covers, (sieve.pullback_eq_top_iff_mem f).1 hf],
apply J.top_mem,
end
/-- The stability axiom in 'arrow' form: If `S` covers `f` then `S` covers `g ≫ f` for any `g`. -/
lemma arrow_stable (f : Y ⟶ X) (S : sieve X) (h : J.covers S f) {Z : C} (g : Z ⟶ Y) :
J.covers S (g ≫ f) :=
begin
rw covers_iff at h ⊢,
simp [h, sieve.pullback_comp],
end
/--
The transitivity axiom in 'arrow' form: If `S` covers `f` and every arrow in `S` is covered by
`R`, then `R` covers `f`.
-/
lemma arrow_trans (f : Y ⟶ X) (S R : sieve X) (h : J.covers S f) :
(∀ {Z : C} (g : Z ⟶ X), S g → J.covers R g) → J.covers R f :=
begin
intro k,
apply J.transitive h,
intros Z g hg,
rw ← sieve.pullback_comp,
apply k (g ≫ f) hg,
end
lemma arrow_intersect (f : Y ⟶ X) (S R : sieve X) (hS : J.covers S f) (hR : J.covers R f) :
J.covers (S ⊓ R) f :=
by simpa [covers_iff] using and.intro hS hR
variable (C)
/--
The trivial Grothendieck topology, in which only the maximal sieve is covering. This topology is
also known as the indiscrete, coarse, or chaotic topology.
See [MM92] Chapter III, Section 2, example (a), or
https://en.wikipedia.org/wiki/Grothendieck_topology#The_discrete_and_indiscrete_topologies
-/
def trivial : grothendieck_topology C :=
{ sieves := λ X, {⊤},
top_mem' := λ X, rfl,
pullback_stable' := λ X Y S f hf,
begin
rw set.mem_singleton_iff at ⊢ hf,
simp [hf],
end,
transitive' := λ X S hS R hR,
begin
rw [set.mem_singleton_iff, ← sieve.id_mem_iff_eq_top] at hS,
simpa using hR hS,
end }
/--
The discrete Grothendieck topology, in which every sieve is covering.
See https://en.wikipedia.org/wiki/Grothendieck_topology#The_discrete_and_indiscrete_topologies.
-/
def discrete : grothendieck_topology C :=
{ sieves := λ X, set.univ,
top_mem' := by simp,
pullback_stable' := λ X Y f, by simp,
transitive' := by simp }
variable {C}
lemma trivial_covering : S ∈ trivial C X ↔ S = ⊤ := set.mem_singleton_iff
/-- See <https://stacks.math.columbia.edu/tag/00Z6> -/
instance : has_le (grothendieck_topology C) :=
{ le := λ J₁ J₂, (J₁ : Π (X : C), set (sieve X)) ≤ (J₂ : Π (X : C), set (sieve X)) }
lemma le_def {J₁ J₂ : grothendieck_topology C} :
J₁ ≤ J₂ ↔ (J₁ : Π (X : C), set (sieve X)) ≤ J₂ := iff.rfl
/-- See <https://stacks.math.columbia.edu/tag/00Z6> -/
instance : partial_order (grothendieck_topology C) :=
{ le_refl := λ J₁, le_def.mpr le_rfl,
le_trans := λ J₁ J₂ J₃ h₁₂ h₂₃, le_def.mpr (le_trans h₁₂ h₂₃),
le_antisymm := λ J₁ J₂ h₁₂ h₂₁, grothendieck_topology.ext (le_antisymm h₁₂ h₂₁),
..grothendieck_topology.has_le }
/-- See <https://stacks.math.columbia.edu/tag/00Z7> -/
instance : has_Inf (grothendieck_topology C) :=
{ Inf := λ T,
{ sieves := Inf (sieves '' T),
top_mem' :=
begin
rintro X S ⟨⟨_, J, hJ, rfl⟩, rfl⟩,
simp,
end,
pullback_stable' :=
begin
rintro X Y S hS f _ ⟨⟨_, J, hJ, rfl⟩, rfl⟩,
apply J.pullback_stable _ (f _ ⟨⟨_, _, hJ, rfl⟩, rfl⟩),
end,
transitive' :=
begin
rintro X S hS R h _ ⟨⟨_, J, hJ, rfl⟩, rfl⟩,
apply J.transitive (hS _ ⟨⟨_, _, hJ, rfl⟩, rfl⟩) _ (λ Y f hf, h hf _ ⟨⟨_, _, hJ, rfl⟩, rfl⟩),
end } }
/-- See <https://stacks.math.columbia.edu/tag/00Z7> -/
lemma is_glb_Inf (s : set (grothendieck_topology C)) : is_glb s (Inf s) :=
begin
refine @is_glb.of_image _ _ _ _ sieves _ _ _ _,
{ intros, refl },
{ exact is_glb_Inf _ },
end
/--
Construct a complete lattice from the `Inf`, but make the trivial and discrete topologies
definitionally equal to the bottom and top respectively.
-/
instance : complete_lattice (grothendieck_topology C) :=
complete_lattice.copy
(complete_lattice_of_Inf _ is_glb_Inf)
_ rfl
(discrete C)
(begin
apply le_antisymm,
{ exact @complete_lattice.le_top _ (complete_lattice_of_Inf _ is_glb_Inf) (discrete C) },
{ intros X S hS,
apply set.mem_univ },
end)
(trivial C)
(begin
apply le_antisymm,
{ intros X S hS,
rw trivial_covering at hS,
apply covering_of_eq_top _ hS },
{ refine @complete_lattice.bot_le _ (complete_lattice_of_Inf _ is_glb_Inf) (trivial C) },
end)
_ rfl
_ rfl
_ rfl
Inf rfl
instance : inhabited (grothendieck_topology C) := ⟨⊤⟩
@[simp] lemma trivial_eq_bot : trivial C = ⊥ := rfl
@[simp] lemma discrete_eq_top : discrete C = ⊤ := rfl
@[simp] lemma bot_covering : S ∈ (⊥ : grothendieck_topology C) X ↔ S = ⊤ := trivial_covering
@[simp] lemma top_covering : S ∈ (⊤ : grothendieck_topology C) X := ⟨⟩
lemma bot_covers (S : sieve X) (f : Y ⟶ X) :
(⊥ : grothendieck_topology C).covers S f ↔ S f :=
by rw [covers_iff, bot_covering, ← sieve.pullback_eq_top_iff_mem]
@[simp] lemma top_covers (S : sieve X) (f : Y ⟶ X) : (⊤ : grothendieck_topology C).covers S f :=
by simp [covers_iff]
/--
The dense Grothendieck topology.
See https://ncatlab.org/nlab/show/dense+topology, or [MM92] Chapter III, Section 2, example (e).
-/
def dense : grothendieck_topology C :=
{ sieves := λ X S, ∀ {Y : C} (f : Y ⟶ X), ∃ Z (g : Z ⟶ Y), S (g ≫ f),
top_mem' := λ X Y f, ⟨Y, 𝟙 Y, ⟨⟩⟩,
pullback_stable' :=
begin
intros X Y S h H Z f,
rcases H (f ≫ h) with ⟨W, g, H'⟩,
exact ⟨W, g, by simpa⟩,
end,
transitive' :=
begin
intros X S H₁ R H₂ Y f,
rcases H₁ f with ⟨Z, g, H₃⟩,
rcases H₂ H₃ (𝟙 Z) with ⟨W, h, H₄⟩,
exact ⟨W, (h ≫ g), by simpa using H₄⟩,
end }
lemma dense_covering : S ∈ dense X ↔ ∀ {Y} (f : Y ⟶ X), ∃ Z (g : Z ⟶ Y), S (g ≫ f) :=
iff.rfl
/--
A category satisfies the right Ore condition if any span can be completed to a commutative square.
NB. Any category with pullbacks obviously satisfies the right Ore condition, see
`right_ore_of_pullbacks`.
-/
def right_ore_condition (C : Type u) [category.{v} C] : Prop :=
∀ {X Y Z : C} (yx : Y ⟶ X) (zx : Z ⟶ X), ∃ W (wy : W ⟶ Y) (wz : W ⟶ Z), wy ≫ yx = wz ≫ zx
lemma right_ore_of_pullbacks [limits.has_pullbacks C] : right_ore_condition C :=
λ X Y Z yx zx, ⟨_, _, _, limits.pullback.condition⟩
/--
The atomic Grothendieck topology: a sieve is covering iff it is nonempty.
For the pullback stability condition, we need the right Ore condition to hold.
See https://ncatlab.org/nlab/show/atomic+site, or [MM92] Chapter III, Section 2, example (f).
-/
def atomic (hro : right_ore_condition C) : grothendieck_topology C :=
{ sieves := λ X S, ∃ Y (f : Y ⟶ X), S f,
top_mem' := λ X, ⟨_, 𝟙 _, ⟨⟩⟩,
pullback_stable' :=
begin
rintros X Y S h ⟨Z, f, hf⟩,
rcases hro h f with ⟨W, g, k, comm⟩,
refine ⟨_, g, _⟩,
simp [comm, hf],
end,
transitive' :=
begin
rintros X S ⟨Y, f, hf⟩ R h,
rcases h hf with ⟨Z, g, hg⟩,
exact ⟨_, _, hg⟩,
end }
/-- `J.cover X` denotes the poset of covers of `X` with respect to the
Grothendieck topology `J`. -/
@[derive preorder]
def cover (X : C) := { S : sieve X // S ∈ J X }
namespace cover
variables {J}
instance : has_coe (J.cover X) (sieve X) := ⟨λ S, S.1⟩
instance : has_coe_to_fun (J.cover X) (λ S, Π ⦃Y⦄ (f : Y ⟶ X), Prop) :=
⟨λ S Y f, (S : sieve X) f⟩
@[simp]
lemma coe_fun_coe (S : J.cover X) (f : Y ⟶ X) : (S : sieve X) f = S f := rfl
lemma condition (S : J.cover X) : (S : sieve X) ∈ J X := S.2
@[ext]
lemma ext (S T : J.cover X) (h : ∀ ⦃Y⦄ (f : Y ⟶ X), S f ↔ T f) : S = T :=
subtype.ext $ sieve.ext h
instance : order_top (J.cover X) :=
{ top := ⟨⊤, J.top_mem _⟩,
le_top := λ S Y f h, by tauto,
..(infer_instance : preorder _) }
instance : semilattice_inf (J.cover X) :=
{ inf := λ S T, ⟨S ⊓ T, J.intersection_covering S.condition T.condition⟩,
le_antisymm := λ S T h1 h2, ext _ _ $ λ Y f, ⟨h1 _, h2 _⟩,
inf_le_left := λ S T Y f hf, hf.1,
inf_le_right := λ S T Y f hf, hf.2,
le_inf := λ S T W h1 h2 Y f h, ⟨h1 _ h, h2 _ h⟩,
..(infer_instance : preorder _) }
instance : inhabited (J.cover X) := ⟨⊤⟩
/-- An auxiliary structure, used to define `S.index` in `plus.lean`. -/
@[nolint has_nonempty_instance, ext]
structure arrow (S : J.cover X) :=
(Y : C)
(f : Y ⟶ X)
(hf : S f)
/-- An auxiliary structure, used to define `S.index` in `plus.lean`. -/
@[nolint has_nonempty_instance, ext]
structure relation (S : J.cover X) :=
(Y₁ Y₂ Z : C)
(g₁ : Z ⟶ Y₁)
(g₂ : Z ⟶ Y₂)
(f₁ : Y₁ ⟶ X)
(f₂ : Y₂ ⟶ X)
(h₁ : S f₁)
(h₂ : S f₂)
(w : g₁ ≫ f₁ = g₂ ≫ f₂)
/-- Map a `arrow` along a refinement `S ⟶ T`. -/
@[simps]
def arrow.map {S T : J.cover X} (I : S.arrow) (f : S ⟶ T) : T.arrow :=
⟨I.Y, I.f, f.le _ I.hf⟩
/-- Map a `relation` along a refinement `S ⟶ T`. -/
@[simps]
def relation.map {S T : J.cover X} (I : S.relation) (f : S ⟶ T) : T.relation :=
⟨_, _, _, I.g₁, I.g₂, I.f₁, I.f₂, f.le _ I.h₁, f.le _ I.h₂, I.w⟩
/-- The first `arrow` associated to a `relation`.
Used in defining `index` in `plus.lean`. -/
@[simps]
def relation.fst {S : J.cover X} (I : S.relation) : S.arrow :=
⟨I.Y₁, I.f₁, I.h₁⟩
/-- The second `arrow` associated to a `relation`.
Used in defining `index` in `plus.lean`. -/
@[simps]
def relation.snd {S : J.cover X} (I : S.relation) : S.arrow :=
⟨I.Y₂, I.f₂, I.h₂⟩
@[simp]
lemma relation.map_fst {S T : J.cover X} (I : S.relation) (f : S ⟶ T) :
I.fst.map f = (I.map f).fst := rfl
@[simp]
lemma relation.map_snd {S T : J.cover X} (I : S.relation) (f : S ⟶ T) :
I.snd.map f = (I.map f).snd := rfl
/-- Pull back a cover along a morphism. -/
def pullback (S : J.cover X) (f : Y ⟶ X) : J.cover Y :=
⟨sieve.pullback f S, J.pullback_stable _ S.condition⟩
/-- An arrow of `S.pullback f` gives rise to an arrow of `S`. -/
@[simps]
def arrow.base {f : Y ⟶ X} {S : J.cover X} (I : (S.pullback f).arrow) : S.arrow :=
⟨I.Y, I.f ≫ f, I.hf⟩
/-- A relation of `S.pullback f` gives rise to a relation of `S`. -/
@[simps]
def relation.base {f : Y ⟶ X} {S : J.cover X} (I : (S.pullback f).relation) : S.relation :=
⟨_, _, _, I.g₁, I.g₂, I.f₁ ≫ f, I.f₂≫ f, I.h₁, I.h₂, by simp [reassoc_of I.w]⟩
@[simp]
lemma relation.base_fst {f : Y ⟶ X} {S : J.cover X} (I : (S.pullback f).relation) :
I.fst.base = I.base.fst := rfl
@[simp]
lemma relation.base_snd {f : Y ⟶ X} {S : J.cover X} (I : (S.pullback f).relation) :
I.snd.base = I.base.snd := rfl
@[simp]
lemma coe_pullback {Z : C} (f : Y ⟶ X) (g : Z ⟶ Y) (S : J.cover X) :
(S.pullback f) g ↔ S (g ≫ f) := iff.rfl
/-- The isomorphism between `S` and the pullback of `S` w.r.t. the identity. -/
def pullback_id (S : J.cover X) : S.pullback (𝟙 X) ≅ S :=
eq_to_iso $ cover.ext _ _ $ λ Y f, by simp
/-- Pulling back with respect to a composition is the composition of the pullbacks. -/
def pullback_comp {X Y Z : C} (S : J.cover X) (f : Z ⟶ Y) (g : Y ⟶ X) :
S.pullback (f ≫ g) ≅ (S.pullback g).pullback f :=
eq_to_iso $ cover.ext _ _ $ λ Y f, by simp
/-- Combine a family of covers over a cover. -/
def bind {X : C} (S : J.cover X) (T : Π (I : S.arrow), J.cover I.Y) : J.cover X :=
⟨sieve.bind S (λ Y f hf, T ⟨Y, f, hf⟩), J.bind_covering S.condition (λ _ _ _, (T _).condition)⟩
/-- The canonical moprhism from `S.bind T` to `T`. -/
def bind_to_base {X : C} (S : J.cover X) (T : Π (I : S.arrow), J.cover I.Y) : S.bind T ⟶ S :=
hom_of_le $ by { rintro Y f ⟨Z,e1,e2,h1,h2,h3⟩, rw ← h3, apply sieve.downward_closed, exact h1 }
/-- An arrow in bind has the form `A ⟶ B ⟶ X` where `A ⟶ B` is an arrow in `T I` for some `I`.
and `B ⟶ X` is an arrow of `S`. This is the object `B`. -/
noncomputable def arrow.middle {X : C} {S : J.cover X} {T : Π (I : S.arrow), J.cover I.Y}
(I : (S.bind T).arrow) : C :=
I.hf.some
/-- An arrow in bind has the form `A ⟶ B ⟶ X` where `A ⟶ B` is an arrow in `T I` for some `I`.
and `B ⟶ X` is an arrow of `S`. This is the hom `A ⟶ B`. -/
noncomputable def arrow.to_middle_hom {X : C} {S : J.cover X} {T : Π (I : S.arrow), J.cover I.Y}
(I : (S.bind T).arrow) : I.Y ⟶ I.middle :=
I.hf.some_spec.some
/-- An arrow in bind has the form `A ⟶ B ⟶ X` where `A ⟶ B` is an arrow in `T I` for some `I`.
and `B ⟶ X` is an arrow of `S`. This is the hom `B ⟶ X`. -/
noncomputable def arrow.from_middle_hom {X : C} {S : J.cover X} {T : Π (I : S.arrow), J.cover I.Y}
(I : (S.bind T).arrow) : I.middle ⟶ X :=
I.hf.some_spec.some_spec.some
lemma arrow.from_middle_condition {X : C} {S : J.cover X} {T : Π (I : S.arrow), J.cover I.Y}
(I : (S.bind T).arrow) : S I.from_middle_hom :=
I.hf.some_spec.some_spec.some_spec.some
/-- An arrow in bind has the form `A ⟶ B ⟶ X` where `A ⟶ B` is an arrow in `T I` for some `I`.
and `B ⟶ X` is an arrow of `S`. This is the hom `B ⟶ X`, as an arrow. -/
noncomputable
def arrow.from_middle {X : C} {S : J.cover X} {T : Π (I : S.arrow), J.cover I.Y}
(I : (S.bind T).arrow) : S.arrow := ⟨_, I.from_middle_hom, I.from_middle_condition⟩
lemma arrow.to_middle_condition {X : C} {S : J.cover X} {T : Π (I : S.arrow), J.cover I.Y}
(I : (S.bind T).arrow) : (T I.from_middle) I.to_middle_hom :=
I.hf.some_spec.some_spec.some_spec.some_spec.1
/-- An arrow in bind has the form `A ⟶ B ⟶ X` where `A ⟶ B` is an arrow in `T I` for some `I`.
and `B ⟶ X` is an arrow of `S`. This is the hom `A ⟶ B`, as an arrow. -/
noncomputable
def arrow.to_middle {X : C} {S : J.cover X} {T : Π (I : S.arrow), J.cover I.Y}
(I : (S.bind T).arrow) : (T I.from_middle).arrow := ⟨_, I.to_middle_hom, I.to_middle_condition⟩
lemma arrow.middle_spec {X : C} {S : J.cover X} {T : Π (I : S.arrow), J.cover I.Y}
(I : (S.bind T).arrow) : I.to_middle_hom ≫ I.from_middle_hom = I.f :=
I.hf.some_spec.some_spec.some_spec.some_spec.2
-- This is used extensively in `plus.lean`, etc.
-- We place this definition here as it will be used in `sheaf.lean` as well.
/-- To every `S : J.cover X` and presheaf `P`, associate a `multicospan_index`. -/
def index {D : Type w} [category.{max v u} D] (S : J.cover X) (P : Cᵒᵖ ⥤ D) :
limits.multicospan_index D :=
{ L := S.arrow,
R := S.relation,
fst_to := λ I, I.fst,
snd_to := λ I, I.snd,
left := λ I, P.obj (opposite.op I.Y),
right := λ I, P.obj (opposite.op I.Z),
fst := λ I, P.map I.g₁.op,
snd := λ I, P.map I.g₂.op }
/-- The natural multifork associated to `S : J.cover X` for a presheaf `P`.
Saying that this multifork is a limit is essentially equivalent to the sheaf condition at the
given object for the given covering sieve. See `sheaf.lean` for an equivalent sheaf condition
using this.
-/
abbreviation multifork {D : Type w} [category.{max v u} D] (S : J.cover X) (P : Cᵒᵖ ⥤ D) :
limits.multifork (S.index P) :=
limits.multifork.of_ι _ (P.obj (opposite.op X)) (λ I, P.map I.f.op) begin
intros I,
dsimp [index],
simp only [← P.map_comp, ← op_comp, I.w]
end
/-- The canonical map from `P.obj (op X)` to the multiequalizer associated to a covering sieve,
assuming such a multiequalizer exists. This will be used in `sheaf.lean` to provide an equivalent
sheaf condition in terms of multiequalizers. -/
noncomputable
abbreviation to_multiequalizer {D : Type w} [category.{max v u} D] (S : J.cover X) (P : Cᵒᵖ ⥤ D)
[limits.has_multiequalizer (S.index P)] :
P.obj (opposite.op X) ⟶ limits.multiequalizer (S.index P) :=
limits.multiequalizer.lift _ _ (λ I, P.map I.f.op) begin
intros I,
dsimp only [index, relation.fst, relation.snd],
simp only [← P.map_comp, ← op_comp, I.w],
end
end cover
/-- Pull back a cover along a morphism. -/
@[simps obj]
def pullback (f : Y ⟶ X) : J.cover X ⥤ J.cover Y :=
{ obj := λ S, S.pullback f,
map := λ S T f, (sieve.pullback_monotone _ f.le).hom }
/-- Pulling back along the identity is naturally isomorphic to the identity functor. -/
def pullback_id (X : C) : J.pullback (𝟙 X) ≅ 𝟭 _ :=
nat_iso.of_components (λ S, S.pullback_id) $ by tidy
/-- Pulling back along a composition is naturally isomorphic to
the composition of the pullbacks. -/
def pullback_comp {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) :
J.pullback (f ≫ g) ≅ J.pullback g ⋙ J.pullback f :=
nat_iso.of_components (λ S, S.pullback_comp f g) $ by tidy
end grothendieck_topology
end category_theory
|
81adedbf18e11e5b221ba93b7b5f7493b0df5855 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/order/rel_iso/group.lean | 5a1851128a2c55dfe2c3fa6d190df8963e2aa1cf | [
"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 | 1,202 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import algebra.group.defs
import order.rel_iso.basic
/-!
# Relation isomorphisms form a group
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> https://github.com/leanprover-community/mathlib4/pull/813
> Any changes to this file require a corresponding PR to mathlib4.
-/
variables {α: Type*}
{r : α → α → Prop}
namespace rel_iso
instance : group (r ≃r r) :=
{ one := rel_iso.refl r,
mul := λ f₁ f₂, f₂.trans f₁,
inv := rel_iso.symm,
mul_assoc := λ f₁ f₂ f₃, rfl,
one_mul := λ f, ext $ λ _, rfl,
mul_one := λ f, ext $ λ _, rfl,
mul_left_inv := λ f, ext f.symm_apply_apply }
@[simp] lemma coe_one : ⇑(1 : r ≃r r) = id := rfl
@[simp] lemma coe_mul (e₁ e₂ : r ≃r r) : ⇑(e₁ * e₂) = e₁ ∘ e₂ := rfl
lemma mul_apply (e₁ e₂ : r ≃r r) (x : α) : (e₁ * e₂) x = e₁ (e₂ x) := rfl
@[simp] lemma inv_apply_self (e : r ≃r r) (x) : e⁻¹ (e x) = x := e.symm_apply_apply x
@[simp] lemma apply_inv_self (e : r ≃r r) (x) : e (e⁻¹ x) = x := e.apply_symm_apply x
end rel_iso
|
6493221717ea3c3f54623c7d6de608a5ab2de950 | 4d3f29a7b2eff44af8fd0d3176232e039acb9ee3 | /Mathlib/Mathlib/Data/Nat/Basic.lean | be0d4be1a18cfaeef04cccfcb83a85c7b6ace19f | [] | no_license | marijnheule/lamr | 5fc5d69d326ff92e321242cfd7f72e78d7f99d7e | 28cc4114c7361059bb54f407fa312bf38b48728b | refs/heads/main | 1,689,338,013,620 | 1,630,359,632,000 | 1,630,359,632,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 28,314 | lean | import Mathlib.Tactic.Basic
import Mathlib.Logic.Basic
notation "ℕ" => Nat
namespace Nat
lemma succ_ne_self : ∀ n : ℕ, succ n ≠ n
| 0, h => absurd h (Nat.succ_ne_zero 0)
| n+1, h => succ_ne_self n (Nat.noConfusion h id)
lemma eq_zero_of_add_eq_zero_right : ∀ {n m : ℕ}, n + m = 0 → n = 0
| 0, m => by simp [Nat.zero_add]
| n+1, m => fun h => by
exfalso
rw [add_one, succ_add] at h
apply succ_ne_zero _ h
lemma eq_zero_of_add_eq_zero_left {n m : ℕ} (h : n + m = 0) : m = 0 :=
@eq_zero_of_add_eq_zero_right m n (Nat.add_comm n m ▸ h)
@[simp] lemma pred_zero : pred 0 = 0 := rfl
@[simp] lemma pred_succ (n : ℕ) : pred (succ n) = n := rfl
protected lemma pos_of_ne_zero {n : ℕ} : n ≠ 0 → 0 < n :=
Or.resolve_left (eq_zero_or_pos n)
-- TODO: in mathlib, this is done for ordered monoids
protected lemma pos_iff_ne_zero {n : ℕ} : 0 < n ↔ n ≠ 0 := by
refine ⟨?_, Nat.pos_of_ne_zero⟩
cases n with
| zero => intro h; contradiction
| succ n => intro _; apply succ_ne_zero
protected lemma not_lt_of_le {n m : ℕ} (h₁ : m ≤ n) : ¬ n < m
| h₂ => Nat.not_le_of_gt h₂ h₁
protected lemma not_le_of_lt {n m : ℕ} : m < n → ¬ n ≤ m := Nat.not_le_of_gt
protected lemma lt_of_not_le {a b : ℕ} : ¬ a ≤ b → b < a := (Nat.lt_or_ge b a).resolve_right
protected lemma le_of_not_lt {a b : ℕ} : ¬ a < b → b ≤ a := (Nat.lt_or_ge a b).resolve_left
protected lemma le_or_le (a b : ℕ) : a ≤ b ∨ b ≤ a := (Nat.lt_or_ge _ _).imp_left Nat.le_of_lt
protected lemma le_of_not_le {a b : ℕ} : ¬ a ≤ b → b ≤ a := (Nat.le_or_le _ _).resolve_left
@[simp] protected lemma not_lt {n m : ℕ} : ¬ n < m ↔ m ≤ n :=
⟨Nat.le_of_not_lt, Nat.not_lt_of_le⟩
@[simp] protected lemma not_le {n m : ℕ} : ¬ n ≤ m ↔ m < n :=
⟨Nat.lt_of_not_le, Nat.not_le_of_lt⟩
protected lemma lt_or_eq_of_le {n m : ℕ} (h : n ≤ m) : n < m ∨ n = m :=
(Nat.lt_or_ge _ _).imp_right (Nat.le_antisymm h)
protected lemma lt_iff_le_not_le {m n : ℕ} : m < n ↔ m ≤ n ∧ ¬ n ≤ m :=
⟨fun h => ⟨Nat.le_of_lt h, Nat.not_le_of_gt h⟩, fun h => Nat.gt_of_not_le h.2⟩
lemma pred_lt_pred : ∀ {n m : ℕ}, n ≠ 0 → n < m → pred n < pred m
| 0, _, h, _ => (h rfl).elim
| n+1, m+1, _, h => lt_of_succ_lt_succ h
protected lemma add_left_cancel_iff {n m k : ℕ} : n + m = n + k ↔ m = k :=
⟨Nat.add_left_cancel, fun | rfl => rfl⟩
protected lemma le_of_add_le_add_left {k n m : ℕ} (h : k + n ≤ k + m) : n ≤ m := by
let ⟨w, hw⟩ := le.dest h
rw [Nat.add_assoc, Nat.add_left_cancel_iff] at hw
exact Nat.le.intro hw
protected lemma le_of_add_le_add_right {k n m : ℕ} : n + k ≤ m + k → n ≤ m := by
rw [Nat.add_comm _ k, Nat.add_comm _ k]
apply Nat.le_of_add_le_add_left
protected lemma add_le_add_iff_le_right (k n m : ℕ) : n + k ≤ m + k ↔ n ≤ m :=
⟨Nat.le_of_add_le_add_right, fun h => Nat.add_le_add_right h _⟩
protected lemma lt_of_add_lt_add_left {k n m : ℕ} (h : k + n < k + m) : n < m :=
Nat.lt_of_le_of_ne (Nat.le_of_add_le_add_left (Nat.le_of_lt h)) fun heq =>
Nat.lt_irrefl (k + m) $ by rwa [heq] at h
protected lemma lt_add_of_pos_right {n k : ℕ} (h : 0 < k) : n < n + k :=
Nat.add_lt_add_left h n
protected lemma lt_add_of_pos_left {n k : ℕ} (h : 0 < k) : n < k + n :=
by rw [Nat.add_comm]; exact Nat.lt_add_of_pos_right h
protected lemma le_of_mul_le_mul_left {a b c : ℕ} (h : c * a ≤ c * b) (hc : 0 < c) : a ≤ b :=
Nat.not_lt.1 fun h1 => Nat.not_le.2 (Nat.mul_lt_mul_of_pos_left h1 hc) h
lemma eq_of_mul_eq_mul_left {m k n : ℕ} (Hn : 0 < n) (H : n * m = n * k) : m = k :=
Nat.le_antisymm (Nat.le_of_mul_le_mul_left (Nat.le_of_eq H) Hn)
(Nat.le_of_mul_le_mul_left (Nat.le_of_eq H.symm) Hn)
lemma eq_of_mul_eq_mul_right {n m k : ℕ} (Hm : 0 < m) (H : n * m = k * m) : n = k :=
by rw [Nat.mul_comm n m, Nat.mul_comm k m] at H
exact Nat.eq_of_mul_eq_mul_left Hm H
protected lemma add_self_ne_one : ∀ (n : ℕ), n + n ≠ 1
| n+1, h =>
have h1 : succ (succ (n + n)) = 1 := succ_add n n ▸ h
Nat.noConfusion h1 fun.
/- sub properties -/
@[simp] protected lemma zero_sub : ∀ a : ℕ, 0 - a = 0
| 0 => rfl
| (a+1) => congr_arg pred (Nat.zero_sub a)
lemma sub_lt_succ (a b : ℕ) : a - b < succ a :=
lt_succ_of_le (sub_le a b)
protected lemma sub_le_sub_right {n m : ℕ} (h : n ≤ m) : ∀ k, n - k ≤ m - k
| 0 => h
| z+1 => pred_le_pred (Nat.sub_le_sub_right h z)
protected lemma add_sub_add_right : ∀ (n k m : ℕ), (n + k) - (m + k) = n - m
| n, 0, m => by rw [Nat.add_zero, Nat.add_zero]
| n, k+1, m => by rw [add_succ, add_succ, succ_sub_succ, Nat.add_sub_add_right n k m]
protected lemma add_sub_add_left (k n m : ℕ) : (k + n) - (k + m) = n - m :=
by rw [Nat.add_comm k n, Nat.add_comm k m, Nat.add_sub_add_right]
protected lemma add_sub_cancel (n m : ℕ) : n + m - m = n :=
suffices n + m - (0 + m) = n by rwa [Nat.zero_add] at this
by rw [Nat.add_sub_add_right, Nat.sub_zero]
protected lemma add_sub_cancel_left (n m : ℕ) : n + m - n = m :=
show n + m - (n + 0) = m by rw [Nat.add_sub_add_left, Nat.sub_zero]
protected lemma sub_sub : ∀ (n m k : ℕ), n - m - k = n - (m + k)
| n, m, 0 => by rw [Nat.add_zero, Nat.sub_zero]
| n, m, (succ k) => by rw [add_succ, sub_succ, sub_succ, Nat.sub_sub n m k]
lemma sub_self_add (n m : ℕ) : n - (n + m) = 0 :=
show (n + 0) - (n + m) = 0 by rw [Nat.add_sub_add_left, Nat.zero_sub]
lemma sub_lt_self {a b : ℕ} (h₀ : 0 < a) (h₁ : a ≤ b) : b - a < b := by
apply sub_lt _ h₀
apply Nat.lt_of_lt_of_le h₀ h₁
lemma sub_one (n : ℕ) : n - 1 = pred n := rfl
lemma succ_sub_one (n : ℕ) : succ n - 1 = n := rfl
lemma succ_pred_eq_of_pos : ∀ {n : ℕ}, 0 < n → succ (pred n) = n
| n+1, _ => rfl
lemma succ_sub (h : n ≤ m) : succ m - n = succ (m - n) :=
let ⟨k, hk⟩ := Nat.le.dest h
by rw [← hk, Nat.add_sub_cancel_left, ← add_succ, Nat.add_sub_cancel_left]
lemma sub_eq_zero_of_le (h : n ≤ m) : n - m = 0 :=
let ⟨k, hk⟩ := Nat.le.dest h; by rw [← hk, sub_self_add]
protected lemma le_of_sub_eq_zero : {n m : ℕ} → n - m = 0 → n ≤ m
| n, 0, H => by rw [Nat.sub_zero] at H; simp [H]
| 0, m+1, H => zero_le _
| n+1, m+1, H => Nat.add_le_add_right
(Nat.le_of_sub_eq_zero $ by simp [Nat.add_sub_add_right] at H; exact H) _
protected lemma sub_eq_zero_iff_le : n - m = 0 ↔ n ≤ m :=
⟨Nat.le_of_sub_eq_zero, Nat.sub_eq_zero_of_le⟩
lemma add_sub_of_le {n m : ℕ} (h : n ≤ m) : n + (m - n) = m :=
let ⟨k, hk⟩ := Nat.le.dest h; by rw [← hk, Nat.add_sub_cancel_left]
protected lemma sub_add_cancel {a b : ℕ} (h: a ≤ b) : b - a + a = b :=
by rw [Nat.add_comm, Nat.add_sub_of_le h]
protected lemma add_sub_cancel' {n m : ℕ} (h : m ≤ n) : m + (n - m) = n :=
by rw [Nat.add_comm, Nat.sub_add_cancel h]
protected lemma add_sub_assoc {m k : ℕ} (h : k ≤ m) (n : ℕ) : n + m - k = n + (m - k) :=
let ⟨l, hl⟩ := Nat.le.dest h
by rw [← hl, Nat.add_sub_cancel_left, Nat.add_comm k, ← Nat.add_assoc, Nat.add_sub_cancel]
protected lemma sub_eq_iff_eq_add {a b c : ℕ} (ab : b ≤ a) : a - b = c ↔ a = c + b :=
⟨fun c_eq => by rw [c_eq.symm, Nat.sub_add_cancel ab],
fun a_eq => by rw [a_eq, Nat.add_sub_cancel]⟩
protected lemma lt_of_sub_eq_succ (H : m - n = succ l) : n < m :=
Nat.not_le.1 fun H' => by simp [Nat.sub_eq_zero_of_le H'] at H
protected lemma lt_of_add_lt_add_right {a b c : ℕ} (h : a + b < c + b) : a < c :=
Nat.lt_of_not_le fun h' => Nat.not_le_of_gt h (Nat.add_le_add_right h' _)
protected lemma sub_pos_of_lt (h : m < n) : 0 < n - m := by
apply Nat.lt_of_add_lt_add_right (b := m)
rw [Nat.zero_add, Nat.sub_add_cancel (Nat.le_of_lt h)]; exact h
protected lemma sub_lt_sub_left : ∀ {k m n : ℕ} (H : k < m) (h : k < n), m - n < m - k
| 0, m+1, n+1, _, _ => by rw [Nat.add_sub_add_right]; exact lt_succ_of_le (Nat.sub_le _ _)
| k+1, m+1, n+1, h1, h2 => by
rw [Nat.add_sub_add_right, Nat.add_sub_add_right]
exact Nat.sub_lt_sub_left (Nat.lt_of_succ_lt_succ h1) (Nat.lt_of_succ_lt_succ h2)
protected lemma sub_lt_left_of_lt_add {n k m : ℕ} (H : n ≤ k) (h : k < n + m) : k - n < m := by
have := Nat.sub_le_sub_right (succ_le_of_lt h) n
rwa [Nat.add_sub_cancel_left, Nat.succ_sub H] at this
protected lemma add_le_of_le_sub_left {n k m : ℕ} (H : m ≤ k) (h : n ≤ k - m) : m + n ≤ k :=
Nat.not_lt.1 fun h' => Nat.not_lt.2 h (Nat.sub_lt_left_of_lt_add H h')
lemma le_of_le_of_sub_le_sub_right {n m k : ℕ} (h₀ : k ≤ m) (h₁ : n - k ≤ m - k) : n ≤ m :=
Nat.not_lt.1 fun h' => by
have := Nat.add_le_of_le_sub_left h₀ h₁
rw [Nat.add_sub_cancel'] at this; exact Nat.not_le.2 h' this
exact Nat.le_trans h₀ (Nat.le_of_lt h')
protected lemma sub_le_sub_right_iff {n m k : ℕ} (h : k ≤ m) : n - k ≤ m - k ↔ n ≤ m :=
⟨le_of_le_of_sub_le_sub_right h, fun h => Nat.sub_le_sub_right h k⟩
lemma le_sub_iff_add_le {x y k : ℕ} (h : k ≤ y) : x ≤ y - k ↔ x + k ≤ y :=
by rw [← Nat.add_sub_cancel x k, Nat.sub_le_sub_right_iff h, Nat.add_sub_cancel]
protected lemma min_comm (a b : ℕ) : Nat.min a b = Nat.min b a := by
simp [Nat.min]
by_cases h₁ : a ≤ b <;> by_cases h₂ : b ≤ a <;> simp [h₁, h₂]
- (exact Nat.le_antisymm h₁ h₂)
- cases not_or_intro h₁ h₂ (Nat.le_or_le _ _)
protected lemma min_le_left (a b : ℕ) : Nat.min a b ≤ a := by
simp [Nat.min]; by_cases a ≤ b <;> simp [h]
- (exact Nat.le_refl _)
- exact Nat.le_of_not_le h
protected lemma min_eq_left (h : a ≤ b) : Nat.min a b = a :=
by simp [Nat.min, h]
protected lemma min_eq_right (h : b ≤ a) : Nat.min a b = b :=
by rw [Nat.min_comm a b]; exact Nat.min_eq_left h
protected lemma zero_min (a : ℕ) : Nat.min 0 a = 0 :=
Nat.min_eq_left (zero_le a)
protected lemma min_zero (a : ℕ) : Nat.min a 0 = 0 :=
Nat.min_eq_right (zero_le a)
lemma sub_eq_sub_min (n m : ℕ) : n - m = n - Nat.min n m :=
if h : n ≥ m then by rw [Nat.min_eq_right h] else by
rw [sub_eq_zero_of_le (Nat.le_of_not_le h),
Nat.min_eq_left (Nat.le_of_not_le h), Nat.sub_self]
@[simp] lemma sub_add_min_cancel (n m : ℕ) : n - m + Nat.min n m = n :=
by rw [sub_eq_sub_min, Nat.sub_add_cancel (Nat.min_le_left n m)]
protected def lt_wf := @Nat.ltWf
protected def strong_rec_on {p : ℕ → Sort u}
(n : ℕ) (H : ∀ n, (∀ m, m < n → p m) → p n) : p n :=
Nat.lt_wf.fix' H n
protected def case_strong_rec_on {p : ℕ → Sort u} (a : ℕ)
(hz : p 0) (hi : ∀ n, (∀ m, m ≤ n → p m) → p (succ n)) : p a :=
Nat.strong_rec_on a fun | 0, _ => hz | n+1, ih => hi n (λ m w => ih m (lt_succ_of_le w))
lemma mod_add_div (m k : ℕ) : m % k + k * (m / k) = m := by
induction m, k using mod.inductionOn with rw [div_eq, mod_eq]
| base x y h => simp [h]
| ind x y h IH => simp [h]; rw [Nat.mul_succ, ← Nat.add_assoc, IH, Nat.sub_add_cancel h.2]
/- div -/
@[simp] protected lemma div_one (n : ℕ) : n / 1 = n :=
have this : n % 1 + 1 * (n / 1) = n := mod_add_div _ _
by rwa [mod_one, Nat.zero_add, Nat.one_mul] at this
@[simp] protected lemma div_zero (n : ℕ) : n / 0 = 0 :=
by rw [div_eq]; simp [Nat.lt_irrefl]
@[simp] protected lemma zero_div (b : ℕ) : 0 / b = 0 :=
(div_eq 0 b).trans $ if_neg $ And.rec Nat.not_le_of_gt
lemma le_div_iff_mul_le (k0 : 0 < k) : x ≤ y / k ↔ x * k ≤ y := by
induction y, k using mod.inductionOn generalizing x with
(rw [div_eq]; simp [h]; cases x with simp [zero_le] | succ x => ?_)
| base y k h =>
simp [eq_false (not_succ_le_zero x), succ_mul, Nat.add_comm]
refine Nat.lt_of_lt_of_le ?_ (Nat.le_add_right _ _)
exact Nat.lt_of_not_le fun h' => h ⟨k0, h'⟩
| ind y k h IH =>
rw [← add_one, Nat.add_le_add_iff_le_right, IH k0, succ_mul, le_sub_iff_add_le h.2]
lemma div_lt_iff_lt_mul (Hk : 0 < k) : x / k < y ↔ x < y * k := by
rw [← Nat.not_le, ← Nat.not_le]; apply not_congr; apply le_div_iff_mul_le Hk
lemma mul_div_le (m n : ℕ) : n * (m / n) ≤ m := by
match n, Nat.eq_zero_or_pos n with
| _, Or.inl rfl => rw [Nat.zero_mul]; exact m.zero_le
| n, Or.inr h => rw [Nat.mul_comm, ← Nat.le_div_iff_mul_le h]; exact Nat.le_refl _
protected lemma div_le_of_le_mul : ∀ {k : ℕ}, m ≤ k * n → m / k ≤ n
| 0, h => by simp [Nat.div_zero]; apply zero_le
| k+1, h => Nat.le_of_mul_le_mul_left (Nat.le_trans (mul_div_le _ _) h) (zero_lt_succ _)
protected lemma div_le_self : ∀ (m n : ℕ), m / n ≤ m
| m, 0 => by simp [Nat.div_zero]; apply zero_le
| m, n+1 => Nat.div_le_of_le_mul $ by
have := Nat.mul_le_mul_right m (succ_pos n)
rwa [Nat.one_mul] at this
lemma div_eq_sub_div (h₁ : 0 < b) (h₂ : b ≤ a) : a / b = (a - b) / b + 1 := by
rw [div_eq a, if_pos]; split <;> assumption
lemma div_eq_of_lt (h₀ : a < b) : a / b = 0 := by
rw [div_eq a, if_neg]
intro h₁
apply Nat.not_le_of_gt h₀ h₁.right
/- successor and predecessor -/
lemma add_one_ne_zero (n : ℕ) : n + 1 ≠ 0 := succ_ne_zero _
lemma eq_zero_or_eq_succ_pred (n : ℕ) : n = 0 ∨ n = succ (pred n) :=
by cases n <;> simp
lemma exists_eq_succ_of_ne_zero (H : n ≠ 0) : ∃k : ℕ, n = succ k :=
⟨_, (eq_zero_or_eq_succ_pred _).resolve_left H⟩
def discriminate (H1: n = 0 → α) (H2 : ∀m, n = succ m → α) : α :=
match e: n with
| 0 => H1 e
| succ m => H2 m e
lemma one_succ_zero : 1 = succ 0 := rfl
def two_step_induction {P : ℕ → Sort u} (H1 : P 0) (H2 : P 1)
(H3 : ∀ (n : ℕ) (IH1 : P n) (IH2 : P (succ n)), P (succ (succ n))) : (a : ℕ) → P a
| 0 => H1
| 1 => H2
| n+2 => H3 _ (two_step_induction H1 H2 H3 _) (two_step_induction H1 H2 H3 _)
def sub_induction {P : ℕ → ℕ → Sort u} (H1 : ∀m, P 0 m)
(H2 : ∀n, P (succ n) 0) (H3 : ∀n m, P n m → P (succ n) (succ m)) : (n m : ℕ) → P n m
| 0, m => H1 _
| n+1, 0 => H2 _
| n+1, m+1 => H3 _ _ (sub_induction H1 H2 H3 n m)
/- addition -/
lemma succ_add_eq_succ_add (n m : ℕ) : succ n + m = n + succ m :=
by simp [succ_add, add_succ]
lemma one_add (n : ℕ) : 1 + n = succ n := by simp [Nat.add_comm]
lemma eq_zero_of_add_eq_zero (H : n + m = 0) : n = 0 ∧ m = 0 :=
⟨Nat.eq_zero_of_add_eq_zero_right H, Nat.eq_zero_of_add_eq_zero_left H⟩
lemma eq_zero_of_mul_eq_zero : ∀ {n m : ℕ}, n * m = 0 → n = 0 ∨ m = 0
| 0, m, _ => Or.inl rfl
| n+1, m, h => by rw [succ_mul] at h; exact Or.inr (eq_zero_of_add_eq_zero_left h)
/- properties of inequality -/
lemma le_succ_of_pred_le : pred n ≤ m → n ≤ succ m :=
match n with | 0 => fun _ => zero_le _ | a+1 => succ_le_succ
lemma le_lt_antisymm {n m : ℕ} (h₁ : n ≤ m) (h₂ : m < n) : False :=
Nat.lt_irrefl n (Nat.lt_of_le_of_lt h₁ h₂)
lemma lt_le_antisymm {n m : ℕ} (h₁ : n < m) (h₂ : m ≤ n) : False :=
le_lt_antisymm h₂ h₁
protected lemma lt_asymm {n m : ℕ} (h₁ : n < m) : ¬ m < n :=
le_lt_antisymm (Nat.le_of_lt h₁)
protected def lt_ge_by_cases {a b : ℕ} {C : Sort u} (h₁ : a < b → C) (h₂ : b ≤ a → C) : C :=
if h : a < b then h₁ h else h₂ (Nat.not_lt.1 h)
protected def lt_by_cases {a b : ℕ} {C : Sort u} (h₁ : a < b → C) (h₂ : a = b → C)
(h₃ : b < a → C) : C :=
Nat.lt_ge_by_cases h₁ fun h₁ =>
Nat.lt_ge_by_cases h₃ fun h => h₂ (Nat.le_antisymm h h₁)
protected lemma lt_trichotomy (a b : ℕ) : a < b ∨ a = b ∨ b < a :=
Nat.lt_by_cases Or.inl (Or.inr ∘ Or.inl) (Or.inr ∘ Or.inr)
protected lemma eq_or_lt_of_not_lt {a b : ℕ} (hnlt : ¬ a < b) : a = b ∨ b < a :=
(Nat.lt_trichotomy a b).resolve_left hnlt
lemma lt_succ_of_lt (h : a < b) : a < succ b := le_succ_of_le h
lemma one_pos : 0 < 1 := Nat.zero_lt_one
/- subtraction -/
protected lemma sub_le_sub_left (k : ℕ) (h : n ≤ m) : k - m ≤ k - n :=
match m, le.dest h with
| _, ⟨a, rfl⟩ => by rw [← Nat.sub_sub]; apply sub_le
protected lemma sub.right_comm (m n k : ℕ) : m - n - k = m - k - n :=
by rw [Nat.sub_sub, Nat.sub_sub, Nat.add_comm]
lemma succ_sub_sub_succ (n m k : ℕ) : succ n - m - succ k = n - m - k :=
by rw [sub.right_comm, succ_sub_succ, sub.right_comm]
lemma mul_pred_left : ∀ (n m : ℕ), pred n * m = n * m - m
| 0, m => by simp [Nat.zero_sub, pred_zero, Nat.zero_mul]
| n+1, m => by rw [pred_succ, succ_mul, Nat.add_sub_cancel]
lemma mul_pred_right (n m : ℕ) : n * pred m = n * m - n :=
by rw [Nat.mul_comm, mul_pred_left, Nat.mul_comm]
protected lemma mul_sub_right_distrib (n) : ∀ (m k : ℕ), (n - m) * k = n * k - m * k
| 0, k => by simp [Nat.sub_zero, Nat.zero_mul]
| m+1, k => by rw [Nat.sub_succ, mul_pred_left, Nat.mul_sub_right_distrib, succ_mul, Nat.sub_sub]
protected lemma mul_sub_left_distrib (n m k : ℕ) : n * (m - k) = n * m - n * k :=
by rw [Nat.mul_comm, Nat.mul_sub_right_distrib, Nat.mul_comm m n, Nat.mul_comm n k]
protected lemma mul_self_sub_mul_self_eq (a b : Nat) : a * a - b * b = (a + b) * (a - b) :=
by rw [Nat.mul_sub_left_distrib, Nat.right_distrib, Nat.right_distrib, Nat.mul_comm b a, Nat.add_comm (a*a) (a*b),
Nat.add_sub_add_left]
lemma succ_mul_succ_eq (a b : Nat) : succ a * succ b = a*b + a + b + 1 := by
rw [mul_succ, succ_mul, Nat.add_right_comm _ a]; rfl
protected lemma sub_sub_self {n m : ℕ} (h : m ≤ n) : n - (n - m) = m :=
(Nat.sub_eq_iff_eq_add (Nat.sub_le _ _)).2 (add_sub_of_le h).symm
protected lemma sub_add_comm {n m k : ℕ} (h : k ≤ n) : n + m - k = n - k + m :=
(Nat.sub_eq_iff_eq_add (Nat.le_trans h (Nat.le_add_right _ _))).2
(by rwa [Nat.add_right_comm, Nat.sub_add_cancel])
lemma sub_one_sub_lt (h : i < n) : n - 1 - i < n := by
rw [Nat.sub_sub]
apply Nat.sub_lt
apply Nat.lt_of_lt_of_le (Nat.zero_lt_succ _) h
rw [Nat.add_comm]
apply Nat.zero_lt_succ
lemma pred_inj : ∀ {a b : ℕ}, 0 < a → 0 < b → Nat.pred a = Nat.pred b → a = b
| a+1, b+1, ha, hb, h => by rw [show a = b from h]
| a+1, 0, ha, hb, h => absurd hb (Nat.lt_irrefl _)
| 0, b+1, ha, hb, h => absurd ha (Nat.lt_irrefl _)
| 0, 0, ha, hb, h => rfl
/- find -/
section find
variable (p : ℕ → Prop)
private def lbp (m n : ℕ) : Prop := m = n + 1 ∧ ∀ k, k ≤ n → ¬p k
variable [DecidablePred p] (H : ∃ n, p n)
private def wf_lbp : WellFounded (lbp p) := by
refine ⟨let ⟨n, pn⟩ := H; ?_⟩
suffices ∀ m k, n ≤ k + m → Acc (lbp p) k from fun a => this _ _ (Nat.le_add_left _ _)
intro m
induction m with refine fun k kn => ⟨_, fun | _, ⟨rfl, a⟩ => ?_⟩
| zero => exact absurd pn (a _ kn)
| succ m IH => exact IH _ (by rw [Nat.add_right_comm]; exact kn)
protected def find_x : {n // p n ∧ ∀ m, m < n → ¬p m} :=
(wf_lbp p H).fix' (C := fun k => (∀n, n < k → ¬p n) → {n // p n ∧ ∀ m, m < n → ¬p m})
(fun m IH al => if pm : p m then ⟨m, pm, al⟩ else
have this : ∀ n, n ≤ m → ¬p n := fun n h =>
(Nat.lt_or_eq_of_le h).elim (al n) fun e => by rw [e]; exact pm
IH _ ⟨rfl, this⟩ fun n h => this n $ Nat.le_of_succ_le_succ h)
0 fun n h => absurd h (Nat.not_lt_zero _)
/--
If `p` is a (decidable) predicate on `ℕ` and `hp : ∃ (n : ℕ), p n` is a proof that
there exists some natural number satisfying `p`, then `nat.find hp` is the
smallest natural number satisfying `p`. Note that `nat.find` is protected,
meaning that you can't just write `find`, even if the `nat` namespace is open.
The API for `nat.find` is:
* `nat.find_spec` is the proof that `nat.find hp` satisfies `p`.
* `nat.find_min` is the proof that if `m < nat.find hp` then `m` does not satisfy `p`.
* `nat.find_min'` is the proof that if `m` does satisfy `p` then `nat.find hp ≤ m`.
-/
protected def find : ℕ := (Nat.find_x p H).1
protected lemma find_spec : p (Nat.find p H) := (Nat.find_x p H).2.1
protected lemma find_min : ∀ {m : ℕ}, m < Nat.find p H → ¬p m := @(Nat.find_x p H).2.2
protected lemma find_min' {m : ℕ} (h : p m) : Nat.find p H ≤ m :=
Nat.not_lt.1 fun l => Nat.find_min p H l h
end find
/- Up -/
/-- A well-ordered relation for "upwards" induction on the ℕural numbers up to some bound `ub`. -/
def Up (ub a i : ℕ) := i < a ∧ i < ub
lemma Up.next {ub i} (h : i < ub) : Up ub (i+1) i := ⟨Nat.lt_succ_self _, h⟩
lemma Up.WF (ub) : WellFounded (Up ub) :=
Subrelation.wf (h₂ := measureWf (ub - .)) @fun a i ⟨ia, iu⟩ => Nat.sub_lt_sub_left iu ia
/- mod -/
@[simp] lemma add_mod_right (x z : ℕ) : (x + z) % z = x % z :=
by rw [mod_eq_sub_mod (Nat.le_add_left _ _), Nat.add_sub_cancel]
@[simp] lemma add_mod_left (x z : ℕ) : (x + z) % x = z % x :=
by rw [Nat.add_comm, add_mod_right]
@[simp] lemma add_mul_mod_self_left (x y z : ℕ) : (x + y * z) % y = x % y := by
induction z with
| zero => rw [Nat.mul_zero, Nat.add_zero]
| succ z ih => rw [mul_succ, ← Nat.add_assoc, add_mod_right, ih]
@[simp] lemma add_mul_mod_self_right (x y z : ℕ) : (x + y * z) % z = x % z :=
by rw [Nat.mul_comm, add_mul_mod_self_left]
@[simp] lemma mul_mod_right (m n : ℕ) : (m * n) % m = 0 :=
by rw [← Nat.zero_add (m*n), add_mul_mod_self_left, zero_mod]
@[simp] lemma mul_mod_left (m n : ℕ) : (m * n) % n = 0 :=
by rw [Nat.mul_comm, mul_mod_right]
lemma mul_mod_mul_left (z x y : ℕ) : (z * x) % (z * y) = z * (x % y) :=
if y0 : y = 0 then
by rw [y0, Nat.mul_zero, mod_zero, mod_zero]
else if z0 : z = 0 then
by rw [z0, Nat.zero_mul, Nat.zero_mul, Nat.zero_mul, mod_zero]
else by
induction x using Nat.strong_rec_on with
| _ n IH =>
have y0 : y > 0 := Nat.pos_of_ne_zero y0
have z0 : z > 0 := Nat.pos_of_ne_zero z0
cases Nat.lt_or_ge n y with
| inl yn => rw [mod_eq_of_lt yn, mod_eq_of_lt (Nat.mul_lt_mul_of_pos_left yn z0)]
| inr yn =>
rw [mod_eq_sub_mod yn, mod_eq_sub_mod (Nat.mul_le_mul_left z yn),
← Nat.mul_sub_left_distrib]
exact IH _ (sub_lt (Nat.lt_of_lt_of_le y0 yn) y0)
lemma mul_mod_mul_right (z x y : ℕ) : (x * z) % (y * z) = (x % y) * z :=
by rw [Nat.mul_comm x z, Nat.mul_comm y z, Nat.mul_comm (x % y) z]; apply mul_mod_mul_left
lemma sub_mul_mod (x k n : ℕ) (h₁ : n*k ≤ x) : (x - n*k) % n = x % n := by
induction k with
| zero => rw [Nat.mul_zero, Nat.sub_zero]
| succ k IH =>
have h₂ : n * k ≤ x := by
rw [mul_succ] at h₁
apply Nat.le_trans _ h₁
apply le_add_right _ n
have h₄ : x - n * k ≥ n := by
apply Nat.le_of_add_le_add_right (k := n*k)
rw [Nat.sub_add_cancel h₂]
simp [mul_succ, Nat.add_comm] at h₁; simp [h₁]
rw [mul_succ, ← Nat.sub_sub, ← mod_eq_sub_mod h₄, IH h₂]
/- div -/
lemma sub_mul_div (x n p : ℕ) (h₁ : n*p ≤ x) : (x - n*p) / n = x / n - p := by
cases eq_zero_or_pos n with
| inl h₀ => rw [h₀, Nat.div_zero, Nat.div_zero, Nat.zero_sub]
| inr h₀ => induction p with
| zero => rw [Nat.mul_zero, Nat.sub_zero, Nat.sub_zero]
| succ p IH =>
have h₂ : n*p ≤ x := by
transitivity
- (apply Nat.mul_le_mul_left; apply le_succ)
- apply h₁
have h₃ : x - n * p ≥ n := by
apply Nat.le_of_add_le_add_right
rw [Nat.sub_add_cancel h₂, Nat.add_comm]
rw [mul_succ] at h₁
apply h₁
rw [sub_succ, ← IH h₂]
rw [div_eq_sub_div h₀ h₃]
simp [add_one, pred_succ, mul_succ, Nat.sub_sub]
lemma div_mul_le_self : ∀ (m n : ℕ), m / n * n ≤ m
| m, 0 => by simp; apply zero_le
| m, n+1 => (le_div_iff_mul_le (Nat.succ_pos _)).1 (Nat.le_refl _)
@[simp] lemma add_div_right (x : ℕ) {z : ℕ} (H : 0 < z) : (x + z) / z = succ (x / z) :=
by rw [div_eq_sub_div H (Nat.le_add_left _ _), Nat.add_sub_cancel]
@[simp] lemma add_div_left (x : ℕ) {z : ℕ} (H : 0 < z) : (z + x) / z = succ (x / z) :=
by rw [Nat.add_comm, add_div_right x H]
@[simp] lemma mul_div_right (n : ℕ) {m : ℕ} (H : 0 < m) : m * n / m = n :=
by induction n <;> simp_all [mul_succ]
@[simp] lemma mul_div_left (m : ℕ) {n : ℕ} (H : 0 < n) : m * n / n = m :=
by rw [Nat.mul_comm, mul_div_right _ H]
protected lemma div_self (H : 0 < n) : n / n = 1 :=
let t := add_div_right 0 H; by rwa [Nat.zero_add, Nat.zero_div] at t
lemma add_mul_div_left (x z : ℕ) {y : ℕ} (H : 0 < y) : (x + y * z) / y = x / y + z := by
induction z with
| zero => rw [Nat.mul_zero, Nat.add_zero, Nat.add_zero]
| succ z ih => rw [mul_succ, ← Nat.add_assoc, add_div_right _ H, ih]; rfl
lemma add_mul_div_right (x y : ℕ) {z : ℕ} (H : 0 < z) : (x + y * z) / z = x / z + y :=
by rw [Nat.mul_comm, add_mul_div_left _ _ H]
protected lemma mul_div_cancel (m : ℕ) {n : ℕ} (H : 0 < n) : m * n / n = m :=
let t := add_mul_div_right 0 m H; by rwa [Nat.zero_add, Nat.zero_div, Nat.zero_add] at t
protected lemma mul_div_cancel_left (m : ℕ) {n : ℕ} (H : 0 < n) : n * m / n = m :=
by rw [Nat.mul_comm, Nat.mul_div_cancel _ H]
protected lemma div_eq_of_eq_mul_left (H1 : 0 < n) (H2 : m = k * n) : m / n = k :=
by rw [H2, Nat.mul_div_cancel _ H1]
protected lemma div_eq_of_eq_mul_right (H1 : 0 < n) (H2 : m = n * k) : m / n = k :=
by rw [H2, Nat.mul_div_cancel_left _ H1]
protected lemma div_eq_of_lt_le
(lo : k * n ≤ m) (hi : m < succ k * n) : m / n = k :=
have npos : 0 < n := (eq_zero_or_pos _).resolve_left fun hn => by
rw [hn, Nat.mul_zero] at hi lo; exact absurd lo (Nat.not_le_of_gt hi)
Nat.le_antisymm
(le_of_lt_succ ((Nat.div_lt_iff_lt_mul npos).2 hi))
((Nat.le_div_iff_mul_le npos).2 lo)
lemma mul_sub_div (x n p : ℕ) (h₁ : x < n*p) : (n * p - succ x) / n = p - succ (x / n) := by
have npos : 0 < n := (eq_zero_or_pos _).resolve_left fun n0 => by
rw [n0, Nat.zero_mul] at h₁; exact not_lt_zero _ h₁
(apply Nat.div_eq_of_lt_le)
- rw [Nat.mul_sub_right_distrib, Nat.mul_comm]
apply Nat.sub_le_sub_left
(exact (div_lt_iff_lt_mul npos).1 (lt_succ_self _))
- change succ (pred (n * p - x)) ≤ (succ (pred (p - x / n))) * n
rw [succ_pred_eq_of_pos (Nat.sub_pos_of_lt h₁),
fun h => succ_pred_eq_of_pos (Nat.sub_pos_of_lt h)] -- TODO: why is the function needed?
- rw [Nat.mul_sub_right_distrib, Nat.mul_comm]
(apply Nat.sub_le_sub_left; apply div_mul_le_self)
- apply (div_lt_iff_lt_mul npos).2; rwa [Nat.mul_comm]
protected lemma div_div_eq_div_mul (m n k : ℕ) : m / n / k = m / (n * k) := by
cases eq_zero_or_pos k with
| inl k0 => rw [k0, Nat.mul_zero, Nat.div_zero, Nat.div_zero] | inr kpos => ?_
cases eq_zero_or_pos n with
| inl n0 => rw [n0, Nat.zero_mul, Nat.div_zero, Nat.zero_div] | inr npos => ?_
(apply Nat.le_antisymm)
- apply (le_div_iff_mul_le (Nat.mul_pos npos kpos)).2
rw [Nat.mul_comm n k, ← Nat.mul_assoc]
apply (le_div_iff_mul_le npos).1
apply (le_div_iff_mul_le kpos).1
(apply Nat.le_refl)
- apply (le_div_iff_mul_le kpos).2
apply (le_div_iff_mul_le npos).2
rw [Nat.mul_assoc, Nat.mul_comm n k]
apply (le_div_iff_mul_le (Nat.mul_pos kpos npos)).1
apply Nat.le_refl
protected lemma mul_div_mul {m : ℕ} (n k : ℕ) (H : 0 < m) : m * n / (m * k) = n / k :=
by rw [← Nat.div_div_eq_div_mul, Nat.mul_div_cancel_left _ H]
protected lemma mul_le_mul_of_nonneg_left {a b c : ℕ} (h₁ : a ≤ b) : c * a ≤ c * b := by
by_cases hba: b ≤ a; { simp [Nat.le_antisymm hba h₁]; apply Nat.le_refl }
by_cases hc0 : c ≤ 0; { simp [Nat.le_antisymm hc0 (zero_le c), Nat.zero_mul] }
exact Nat.le_of_lt (Nat.mul_lt_mul_of_pos_left (Nat.not_le.1 hba) (Nat.not_le.1 hc0))
protected lemma mul_le_mul_of_nonneg_right {a b c : ℕ} (h₁ : a ≤ b) : a * c ≤ b * c := by
by_cases hba : b ≤ a; { simp [Nat.le_antisymm hba h₁]; apply Nat.le_refl }
by_cases hc0 : c ≤ 0; { simp [Nat.le_antisymm hc0 (zero_le c), Nat.mul_zero] }
exact Nat.le_of_lt (Nat.mul_lt_mul_of_pos_right (Nat.not_le.1 hba) (Nat.not_le.1 hc0))
protected lemma mul_lt_mul (hac : a < c) (hbd : b ≤ d) (pos_b : 0 < b) : a * b < c * d :=
Nat.lt_of_lt_of_le (Nat.mul_lt_mul_of_pos_right hac pos_b) (Nat.mul_le_mul_of_nonneg_left hbd)
protected lemma mul_lt_mul' (h1 : a ≤ c) (h2 : b < d) (h3 : 0 < c) : a * b < c * d :=
Nat.lt_of_le_of_lt (Nat.mul_le_mul_of_nonneg_right h1) (Nat.mul_lt_mul_of_pos_left h2 h3)
lemma div_lt_self (h₁ : 0 < n) (h₂ : 1 < m) : n / m < n := by
have m_pos : 0 < m := Nat.lt_trans Nat.zero_lt_one h₂
suffices 1 * n < m * n by
rw [Nat.one_mul, Nat.mul_comm] at this
exact (Nat.div_lt_iff_lt_mul m_pos).2 this
exact Nat.mul_lt_mul h₂ (Nat.le_refl _) h₁
end Nat
|
15a0e614e71588b979ac3494dd85633793cd9e3a | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/list/perm.lean | 8c1667485d02cc3a1fdcd1a06a2526c3b32f1a3d | [
"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 | 55,701 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro
-/
import data.list.dedup
import data.list.permutation
import data.list.range
import data.nat.factorial.basic
/-!
# List Permutations
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file introduces the `list.perm` relation, which is true if two lists are permutations of one
another.
## Notation
The notation `~` is used for permutation equivalence.
-/
open_locale nat
universes uu vv
namespace list
variables {α : Type uu} {β : Type vv} {l₁ l₂ : list α}
/-- `perm l₁ l₂` or `l₁ ~ l₂` asserts that `l₁` and `l₂` are permutations
of each other. This is defined by induction using pairwise swaps. -/
inductive perm : list α → list α → Prop
| nil : perm [] []
| cons : Π (x : α) {l₁ l₂ : list α}, perm l₁ l₂ → perm (x::l₁) (x::l₂)
| swap : Π (x y : α) (l : list α), perm (y::x::l) (x::y::l)
| trans : Π {l₁ l₂ l₃ : list α}, perm l₁ l₂ → perm l₂ l₃ → perm l₁ l₃
open perm (swap)
infix (name := list.perm) ` ~ `:50 := perm
@[refl] protected theorem perm.refl : ∀ (l : list α), l ~ l
| [] := perm.nil
| (x::xs) := (perm.refl xs).cons x
@[symm] protected theorem perm.symm {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₂ ~ l₁ :=
perm.rec_on p
perm.nil
(λ x l₁ l₂ p₁ r₁, r₁.cons x)
(λ x y l, swap y x l)
(λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, r₂.trans r₁)
theorem perm_comm {l₁ l₂ : list α} : l₁ ~ l₂ ↔ l₂ ~ l₁ := ⟨perm.symm, perm.symm⟩
theorem perm.swap'
(x y : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) : y::x::l₁ ~ x::y::l₂ :=
(swap _ _ _).trans ((p.cons _).cons _)
attribute [trans] perm.trans
theorem perm.eqv (α) : equivalence (@perm α) :=
mk_equivalence (@perm α) (@perm.refl α) (@perm.symm α) (@perm.trans α)
instance is_setoid (α) : setoid (list α) :=
setoid.mk (@perm α) (perm.eqv α)
theorem perm.subset {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁ ⊆ l₂ :=
λ a, perm.rec_on p
(λ h, h)
(λ x l₁ l₂ p₁ r₁ i, or.elim i
(λ ax, by simp [ax])
(λ al₁, or.inr (r₁ al₁)))
(λ x y l ayxl, or.elim ayxl
(λ ay, by simp [ay])
(λ axl, or.elim axl
(λ ax, by simp [ax])
(λ al, or.inr (or.inr al))))
(λ l₁ l₂ l₃ p₁ p₂ r₁ r₂ ainl₁, r₂ (r₁ ainl₁))
theorem perm.mem_iff {a : α} {l₁ l₂ : list α} (h : l₁ ~ l₂) : a ∈ l₁ ↔ a ∈ l₂ :=
iff.intro (λ m, h.subset m) (λ m, h.symm.subset m)
lemma perm.subset_congr_left {l₁ l₂ l₃ : list α} (h : l₁ ~ l₂) : l₁ ⊆ l₃ ↔ l₂ ⊆ l₃ :=
⟨h.symm.subset.trans, h.subset.trans⟩
lemma perm.subset_congr_right {l₁ l₂ l₃ : list α} (h : l₁ ~ l₂) : l₃ ⊆ l₁ ↔ l₃ ⊆ l₂ :=
⟨λ h', h'.trans h.subset, λ h', h'.trans h.symm.subset⟩
theorem perm.append_right {l₁ l₂ : list α} (t₁ : list α) (p : l₁ ~ l₂) : l₁++t₁ ~ l₂++t₁ :=
perm.rec_on p
(perm.refl ([] ++ t₁))
(λ x l₁ l₂ p₁ r₁, r₁.cons x)
(λ x y l, swap x y _)
(λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, r₁.trans r₂)
theorem perm.append_left {t₁ t₂ : list α} : ∀ (l : list α), t₁ ~ t₂ → l++t₁ ~ l++t₂
| [] p := p
| (x::xs) p := (perm.append_left xs p).cons x
theorem perm.append {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁++t₁ ~ l₂++t₂ :=
(p₁.append_right t₁).trans (p₂.append_left l₂)
theorem perm.append_cons (a : α) {h₁ h₂ t₁ t₂ : list α}
(p₁ : h₁ ~ h₂) (p₂ : t₁ ~ t₂) : h₁ ++ a::t₁ ~ h₂ ++ a::t₂ :=
p₁.append (p₂.cons a)
@[simp] theorem perm_middle {a : α} : ∀ {l₁ l₂ : list α}, l₁++a::l₂ ~ a::(l₁++l₂)
| [] l₂ := perm.refl _
| (b::l₁) l₂ := ((@perm_middle l₁ l₂).cons _).trans (swap a b _)
@[simp] theorem perm_append_singleton (a : α) (l : list α) : l ++ [a] ~ a::l :=
perm_middle.trans $ by rw [append_nil]
theorem perm_append_comm : ∀ {l₁ l₂ : list α}, (l₁++l₂) ~ (l₂++l₁)
| [] l₂ := by simp
| (a::t) l₂ := (perm_append_comm.cons _).trans perm_middle.symm
theorem concat_perm (l : list α) (a : α) : concat l a ~ a :: l :=
by simp
theorem perm.length_eq {l₁ l₂ : list α} (p : l₁ ~ l₂) : length l₁ = length l₂ :=
perm.rec_on p
rfl
(λ x l₁ l₂ p r, by simp[r])
(λ x y l, by simp)
(λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, eq.trans r₁ r₂)
theorem perm.eq_nil {l : list α} (p : l ~ []) : l = [] :=
eq_nil_of_length_eq_zero p.length_eq
theorem perm.nil_eq {l : list α} (p : [] ~ l) : [] = l :=
p.symm.eq_nil.symm
@[simp]
theorem perm_nil {l₁ : list α} : l₁ ~ [] ↔ l₁ = [] :=
⟨λ p, p.eq_nil, λ e, e ▸ perm.refl _⟩
@[simp]
theorem nil_perm {l₁ : list α} : [] ~ l₁ ↔ l₁ = [] :=
perm_comm.trans perm_nil
theorem not_perm_nil_cons (x : α) (l : list α) : ¬ [] ~ x::l
| p := by injection p.symm.eq_nil
@[simp] theorem reverse_perm : ∀ (l : list α), reverse l ~ l
| [] := perm.nil
| (a::l) := by { rw reverse_cons,
exact (perm_append_singleton _ _).trans ((reverse_perm l).cons a) }
theorem perm_cons_append_cons {l l₁ l₂ : list α} (a : α) (p : l ~ l₁++l₂) :
a::l ~ l₁++(a::l₂) :=
(p.cons a).trans perm_middle.symm
@[simp] theorem perm_replicate {n : ℕ} {a : α} {l : list α} :
l ~ replicate n a ↔ l = replicate n a :=
⟨λ p, eq_replicate.2
⟨p.length_eq.trans $ length_replicate _ _, λ b m, eq_of_mem_replicate $ p.subset m⟩,
λ h, h ▸ perm.refl _⟩
@[simp] theorem replicate_perm {n : ℕ} {a : α} {l : list α} :
replicate n a ~ l ↔ replicate n a = l :=
(perm_comm.trans perm_replicate).trans eq_comm
@[simp] theorem perm_singleton {a : α} {l : list α} : l ~ [a] ↔ l = [a] :=
@perm_replicate α 1 a l
@[simp] theorem singleton_perm {a : α} {l : list α} : [a] ~ l ↔ [a] = l :=
@replicate_perm α 1 a l
alias perm_singleton ↔ perm.eq_singleton _
alias singleton_perm ↔ perm.singleton_eq _
theorem singleton_perm_singleton {a b : α} : [a] ~ [b] ↔ a = b :=
by simp
theorem perm_cons_erase [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) :
l ~ a :: l.erase a :=
let ⟨l₁, l₂, _, e₁, e₂⟩ := exists_erase_eq h in
e₂.symm ▸ e₁.symm ▸ perm_middle
@[elab_as_eliminator] theorem perm_induction_on
{P : list α → list α → Prop} {l₁ l₂ : list α} (p : l₁ ~ l₂)
(h₁ : P [] [])
(h₂ : ∀ x l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (x::l₁) (x::l₂))
(h₃ : ∀ x y l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (y::x::l₁) (x::y::l₂))
(h₄ : ∀ l₁ l₂ l₃, l₁ ~ l₂ → l₂ ~ l₃ → P l₁ l₂ → P l₂ l₃ → P l₁ l₃) :
P l₁ l₂ :=
have P_refl : ∀ l, P l l, from
assume l,
list.rec_on l h₁ (λ x xs ih, h₂ x xs xs (perm.refl xs) ih),
perm.rec_on p h₁ h₂ (λ x y l, h₃ x y l l (perm.refl l) (P_refl l)) h₄
@[congr] theorem perm.filter_map (f : α → option β) {l₁ l₂ : list α} (p : l₁ ~ l₂) :
filter_map f l₁ ~ filter_map f l₂ :=
begin
induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂,
{ simp },
{ simp only [filter_map], cases f x with a; simp [filter_map, IH, perm.cons] },
{ simp only [filter_map], cases f x with a; cases f y with b; simp [filter_map, swap] },
{ exact IH₁.trans IH₂ }
end
@[congr] theorem perm.map (f : α → β) {l₁ l₂ : list α} (p : l₁ ~ l₂) :
map f l₁ ~ map f l₂ :=
filter_map_eq_map f ▸ p.filter_map _
theorem perm.pmap {p : α → Prop} (f : Π a, p a → β)
{l₁ l₂ : list α} (p : l₁ ~ l₂) {H₁ H₂} : pmap f l₁ H₁ ~ pmap f l₂ H₂ :=
begin
induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂,
{ simp },
{ simp [IH, perm.cons] },
{ simp [swap] },
{ refine IH₁.trans IH₂,
exact λ a m, H₂ a (p₂.subset m) }
end
theorem perm.filter (p : α → Prop) [decidable_pred p]
{l₁ l₂ : list α} (s : l₁ ~ l₂) : filter p l₁ ~ filter p l₂ :=
by rw ← filter_map_eq_filter; apply s.filter_map _
theorem filter_append_perm (p : α → Prop) [decidable_pred p]
(l : list α) : filter p l ++ filter (λ x, ¬ p x) l ~ l :=
begin
induction l with x l ih,
{ refl },
{ by_cases h : p x,
{ simp only [h, filter_cons_of_pos, filter_cons_of_neg, not_true, not_false_iff, cons_append],
exact ih.cons x },
{ simp only [h, filter_cons_of_neg, not_false_iff, filter_cons_of_pos],
refine perm.trans _ (ih.cons x),
exact perm_append_comm.trans (perm_append_comm.cons _), } }
end
theorem exists_perm_sublist {l₁ l₂ l₂' : list α}
(s : l₁ <+ l₂) (p : l₂ ~ l₂') : ∃ l₁' ~ l₁, l₁' <+ l₂' :=
begin
induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂ generalizing l₁ s,
{ exact ⟨[], eq_nil_of_sublist_nil s ▸ perm.refl _, nil_sublist _⟩ },
{ cases s with _ _ _ s l₁ _ _ s,
{ exact let ⟨l₁', p', s'⟩ := IH s in ⟨l₁', p', s'.cons _ _ _⟩ },
{ exact let ⟨l₁', p', s'⟩ := IH s in ⟨x::l₁', p'.cons x, s'.cons2 _ _ _⟩ } },
{ cases s with _ _ _ s l₁ _ _ s; cases s with _ _ _ s l₁ _ _ s,
{ exact ⟨l₁, perm.refl _, (s.cons _ _ _).cons _ _ _⟩ },
{ exact ⟨x::l₁, perm.refl _, (s.cons _ _ _).cons2 _ _ _⟩ },
{ exact ⟨y::l₁, perm.refl _, (s.cons2 _ _ _).cons _ _ _⟩ },
{ exact ⟨x::y::l₁, perm.swap _ _ _, (s.cons2 _ _ _).cons2 _ _ _⟩ } },
{ exact let ⟨m₁, pm, sm⟩ := IH₁ s, ⟨r₁, pr, sr⟩ := IH₂ sm in
⟨r₁, pr.trans pm, sr⟩ }
end
theorem perm.sizeof_eq_sizeof [has_sizeof α] {l₁ l₂ : list α} (h : l₁ ~ l₂) :
l₁.sizeof = l₂.sizeof :=
begin
induction h with hd l₁ l₂ h₁₂ h_sz₁₂ a b l l₁ l₂ l₃ h₁₂ h₂₃ h_sz₁₂ h_sz₂₃,
{ refl },
{ simp only [list.sizeof, h_sz₁₂] },
{ simp only [list.sizeof, add_left_comm] },
{ simp only [h_sz₁₂, h_sz₂₃] }
end
section rel
open relator
variables {γ : Type*} {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop}
local infixr ` ∘r ` : 80 := relation.comp
lemma perm_comp_perm : (perm ∘r perm : list α → list α → Prop) = perm :=
begin
funext a c, apply propext,
split,
{ exact assume ⟨b, hab, hba⟩, perm.trans hab hba },
{ exact assume h, ⟨a, perm.refl a, h⟩ }
end
lemma perm_comp_forall₂ {l u v} (hlu : perm l u) (huv : forall₂ r u v) : (forall₂ r ∘r perm) l v :=
begin
induction hlu generalizing v,
case perm.nil { cases huv, exact ⟨[], forall₂.nil, perm.nil⟩ },
case perm.cons : a l u hlu ih
{ cases huv with _ b _ v hab huv',
rcases ih huv' with ⟨l₂, h₁₂, h₂₃⟩,
exact ⟨b::l₂, forall₂.cons hab h₁₂, h₂₃.cons _⟩ },
case perm.swap : a₁ a₂ l₁ l₂ h₂₃
{ cases h₂₃ with _ b₁ _ l₂ h₁ hr_₂₃,
cases hr_₂₃ with _ b₂ _ l₂ h₂ h₁₂,
exact ⟨b₂::b₁::l₂, forall₂.cons h₂ (forall₂.cons h₁ h₁₂), perm.swap _ _ _⟩ },
case perm.trans : la₁ la₂ la₃ _ _ ih₁ ih₂
{ rcases ih₂ huv with ⟨lb₂, hab₂, h₂₃⟩,
rcases ih₁ hab₂ with ⟨lb₁, hab₁, h₁₂⟩,
exact ⟨lb₁, hab₁, perm.trans h₁₂ h₂₃⟩ }
end
lemma forall₂_comp_perm_eq_perm_comp_forall₂ : forall₂ r ∘r perm = perm ∘r forall₂ r :=
begin
funext l₁ l₃, apply propext,
split,
{ assume h, rcases h with ⟨l₂, h₁₂, h₂₃⟩,
have : forall₂ (flip r) l₂ l₁, from h₁₂.flip ,
rcases perm_comp_forall₂ h₂₃.symm this with ⟨l', h₁, h₂⟩,
exact ⟨l', h₂.symm, h₁.flip⟩ },
{ exact assume ⟨l₂, h₁₂, h₂₃⟩, perm_comp_forall₂ h₁₂ h₂₃ }
end
lemma rel_perm_imp (hr : right_unique r) : (forall₂ r ⇒ forall₂ r ⇒ implies) perm perm :=
assume a b h₁ c d h₂ h,
have (flip (forall₂ r) ∘r (perm ∘r forall₂ r)) b d, from ⟨a, h₁, c, h, h₂⟩,
have ((flip (forall₂ r) ∘r forall₂ r) ∘r perm) b d,
by rwa [← forall₂_comp_perm_eq_perm_comp_forall₂, ← relation.comp_assoc] at this,
let ⟨b', ⟨c', hbc, hcb⟩, hbd⟩ := this in
have b' = b, from right_unique_forall₂' hr hcb hbc,
this ▸ hbd
lemma rel_perm (hr : bi_unique r) : (forall₂ r ⇒ forall₂ r ⇒ (↔)) perm perm :=
assume a b hab c d hcd, iff.intro
(rel_perm_imp hr.2 hab hcd)
(rel_perm_imp hr.left.flip hab.flip hcd.flip)
end rel
section subperm
/-- `subperm l₁ l₂`, denoted `l₁ <+~ l₂`, means that `l₁` is a sublist of
a permutation of `l₂`. This is an analogue of `l₁ ⊆ l₂` which respects
multiplicities of elements, and is used for the `≤` relation on multisets. -/
def subperm (l₁ l₂ : list α) : Prop := ∃ l ~ l₁, l <+ l₂
infix ` <+~ `:50 := subperm
theorem nil_subperm {l : list α} : [] <+~ l :=
⟨[], perm.nil, by simp⟩
theorem perm.subperm_left {l l₁ l₂ : list α} (p : l₁ ~ l₂) : l <+~ l₁ ↔ l <+~ l₂ :=
suffices ∀ {l₁ l₂ : list α}, l₁ ~ l₂ → l <+~ l₁ → l <+~ l₂,
from ⟨this p, this p.symm⟩,
λ l₁ l₂ p ⟨u, pu, su⟩,
let ⟨v, pv, sv⟩ := exists_perm_sublist su p in
⟨v, pv.trans pu, sv⟩
theorem perm.subperm_right {l₁ l₂ l : list α} (p : l₁ ~ l₂) : l₁ <+~ l ↔ l₂ <+~ l :=
⟨λ ⟨u, pu, su⟩, ⟨u, pu.trans p, su⟩,
λ ⟨u, pu, su⟩, ⟨u, pu.trans p.symm, su⟩⟩
theorem sublist.subperm {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁ <+~ l₂ :=
⟨l₁, perm.refl _, s⟩
theorem perm.subperm {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁ <+~ l₂ :=
⟨l₂, p.symm, sublist.refl _⟩
@[refl] theorem subperm.refl (l : list α) : l <+~ l := (perm.refl _).subperm
@[trans] theorem subperm.trans {l₁ l₂ l₃ : list α} : l₁ <+~ l₂ → l₂ <+~ l₃ → l₁ <+~ l₃
| s ⟨l₂', p₂, s₂⟩ :=
let ⟨l₁', p₁, s₁⟩ := p₂.subperm_left.2 s in ⟨l₁', p₁, s₁.trans s₂⟩
theorem subperm.length_le {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₁ ≤ length l₂
| ⟨l, p, s⟩ := p.length_eq ▸ s.length_le
theorem subperm.perm_of_length_le {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₂ ≤ length l₁ → l₁ ~ l₂
| ⟨l, p, s⟩ h := (s.eq_of_length_le $ p.symm.length_eq ▸ h) ▸ p.symm
theorem subperm.antisymm {l₁ l₂ : list α} (h₁ : l₁ <+~ l₂) (h₂ : l₂ <+~ l₁) : l₁ ~ l₂ :=
h₁.perm_of_length_le h₂.length_le
theorem subperm.subset {l₁ l₂ : list α} : l₁ <+~ l₂ → l₁ ⊆ l₂
| ⟨l, p, s⟩ := subset.trans p.symm.subset s.subset
lemma subperm.filter (p : α → Prop) [decidable_pred p]
⦃l l' : list α⦄ (h : l <+~ l') : filter p l <+~ filter p l' :=
begin
obtain ⟨xs, hp, h⟩ := h,
exact ⟨_, hp.filter p, h.filter p⟩
end
end subperm
theorem sublist.exists_perm_append : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → ∃ l, l₂ ~ l₁ ++ l
| ._ ._ sublist.slnil := ⟨nil, perm.refl _⟩
| ._ ._ (sublist.cons l₁ l₂ a s) :=
let ⟨l, p⟩ := sublist.exists_perm_append s in
⟨a::l, (p.cons a).trans perm_middle.symm⟩
| ._ ._ (sublist.cons2 l₁ l₂ a s) :=
let ⟨l, p⟩ := sublist.exists_perm_append s in
⟨l, p.cons a⟩
theorem perm.countp_eq (p : α → Prop) [decidable_pred p]
{l₁ l₂ : list α} (s : l₁ ~ l₂) : countp p l₁ = countp p l₂ :=
by rw [countp_eq_length_filter, countp_eq_length_filter];
exact (s.filter _).length_eq
theorem subperm.countp_le (p : α → Prop) [decidable_pred p]
{l₁ l₂ : list α} : l₁ <+~ l₂ → countp p l₁ ≤ countp p l₂
| ⟨l, p', s⟩ := p'.countp_eq p ▸ s.countp_le p
theorem perm.countp_congr (s : l₁ ~ l₂) {p p' : α → Prop} [decidable_pred p] [decidable_pred p']
(hp : ∀ x ∈ l₁, p x = p' x) : l₁.countp p = l₂.countp p' :=
begin
rw ← s.countp_eq p',
clear s,
induction l₁ with y s hs,
{ refl },
{ simp only [mem_cons_iff, forall_eq_or_imp] at hp,
simp only [countp_cons, hs hp.2, hp.1], },
end
theorem countp_eq_countp_filter_add
(l : list α) (p q : α → Prop) [decidable_pred p] [decidable_pred q] :
l.countp p = (l.filter q).countp p + (l.filter (λ a, ¬ q a)).countp p :=
by { rw [← countp_append], exact perm.countp_eq _ (filter_append_perm _ _).symm }
theorem perm.count_eq [decidable_eq α] {l₁ l₂ : list α}
(p : l₁ ~ l₂) (a) : count a l₁ = count a l₂ :=
p.countp_eq _
theorem subperm.count_le [decidable_eq α] {l₁ l₂ : list α}
(s : l₁ <+~ l₂) (a) : count a l₁ ≤ count a l₂ :=
s.countp_le _
theorem perm.foldl_eq' {f : β → α → β} {l₁ l₂ : list α} (p : l₁ ~ l₂) :
(∀ (x ∈ l₁) (y ∈ l₁) z, f (f z x) y = f (f z y) x) → ∀ b, foldl f b l₁ = foldl f b l₂ :=
perm_induction_on p
(λ H b, rfl)
(λ x t₁ t₂ p r H b, r (λ x hx y hy, H _ (or.inr hx) _ (or.inr hy)) _)
(λ x y t₁ t₂ p r H b,
begin
simp only [foldl],
rw [H x (or.inr $ or.inl rfl) y (or.inl rfl)],
exact r (λ x hx y hy, H _ (or.inr $ or.inr hx) _ (or.inr $ or.inr hy)) _
end)
(λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ H b, eq.trans (r₁ H b)
(r₂ (λ x hx y hy, H _ (p₁.symm.subset hx) _ (p₁.symm.subset hy)) b))
theorem perm.foldl_eq {f : β → α → β} {l₁ l₂ : list α} (rcomm : right_commutative f) (p : l₁ ~ l₂) :
∀ b, foldl f b l₁ = foldl f b l₂ :=
p.foldl_eq' $ λ x hx y hy z, rcomm z x y
theorem perm.foldr_eq {f : α → β → β} {l₁ l₂ : list α} (lcomm : left_commutative f) (p : l₁ ~ l₂) :
∀ b, foldr f b l₁ = foldr f b l₂ :=
perm_induction_on p
(λ b, rfl)
(λ x t₁ t₂ p r b, by simp; rw [r b])
(λ x y t₁ t₂ p r b, by simp; rw [lcomm, r b])
(λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ a, eq.trans (r₁ a) (r₂ a))
lemma perm.rec_heq {β : list α → Sort*} {f : Πa l, β l → β (a::l)} {b : β []} {l l' : list α}
(hl : perm l l')
(f_congr : ∀{a l l' b b'}, perm l l' → b == b' → f a l b == f a l' b')
(f_swap : ∀{a a' l b}, f a (a'::l) (f a' l b) == f a' (a::l) (f a l b)) :
@list.rec α β b f l == @list.rec α β b f l' :=
begin
induction hl,
case list.perm.nil { refl },
case list.perm.cons : a l l' h ih { exact f_congr h ih },
case list.perm.swap : a a' l { exact f_swap },
case list.perm.trans : l₁ l₂ l₃ h₁ h₂ ih₁ ih₂ { exact heq.trans ih₁ ih₂ }
end
section
variables {op : α → α → α} [is_associative α op] [is_commutative α op]
local notation (name := op) a ` * ` b := op a b
local notation (name := foldl) l ` <*> ` a := foldl op a l
lemma perm.fold_op_eq {l₁ l₂ : list α} {a : α} (h : l₁ ~ l₂) : l₁ <*> a = l₂ <*> a :=
h.foldl_eq (right_comm _ is_commutative.comm is_associative.assoc) _
end
section comm_monoid
/-- If elements of a list commute with each other, then their product does not
depend on the order of elements. -/
@[to_additive "If elements of a list additively commute with each other, then their sum does not
depend on the order of elements."]
lemma perm.prod_eq' [monoid α] {l₁ l₂ : list α} (h : l₁ ~ l₂) (hc : l₁.pairwise commute) :
l₁.prod = l₂.prod :=
h.foldl_eq' (pairwise.forall_of_forall (λ x y h z, (h z).symm) (λ x hx z, rfl) $
hc.imp $ λ x y h z, by simp only [mul_assoc, h.eq]) _
variable [comm_monoid α]
@[to_additive]
lemma perm.prod_eq {l₁ l₂ : list α} (h : perm l₁ l₂) : prod l₁ = prod l₂ :=
h.fold_op_eq
@[to_additive]
lemma prod_reverse (l : list α) : prod l.reverse = prod l :=
(reverse_perm l).prod_eq
end comm_monoid
theorem perm_inv_core {a : α} {l₁ l₂ r₁ r₂ : list α} : l₁++a::r₁ ~ l₂++a::r₂ → l₁++r₁ ~ l₂++r₂ :=
begin
generalize e₁ : l₁++a::r₁ = s₁, generalize e₂ : l₂++a::r₂ = s₂,
intro p, revert l₁ l₂ r₁ r₂ e₁ e₂,
refine perm_induction_on p _ (λ x t₁ t₂ p IH, _) (λ x y t₁ t₂ p IH, _)
(λ t₁ t₂ t₃ p₁ p₂ IH₁ IH₂, _); intros l₁ l₂ r₁ r₂ e₁ e₂,
{ apply (not_mem_nil a).elim, rw ← e₁, simp },
{ cases l₁ with y l₁; cases l₂ with z l₂;
dsimp at e₁ e₂; injections; subst x,
{ substs t₁ t₂, exact p },
{ substs z t₁ t₂, exact p.trans perm_middle },
{ substs y t₁ t₂, exact perm_middle.symm.trans p },
{ substs z t₁ t₂, exact (IH rfl rfl).cons y } },
{ rcases l₁ with _|⟨y, _|⟨z, l₁⟩⟩; rcases l₂ with _|⟨u, _|⟨v, l₂⟩⟩;
dsimp at e₁ e₂; injections; substs x y,
{ substs r₁ r₂, exact p.cons a },
{ substs r₁ r₂, exact p.cons u },
{ substs r₁ v t₂, exact (p.trans perm_middle).cons u },
{ substs r₁ r₂, exact p.cons y },
{ substs r₁ r₂ y u, exact p.cons a },
{ substs r₁ u v t₂, exact ((p.trans perm_middle).cons y).trans (swap _ _ _) },
{ substs r₂ z t₁, exact (perm_middle.symm.trans p).cons y },
{ substs r₂ y z t₁, exact (swap _ _ _).trans ((perm_middle.symm.trans p).cons u) },
{ substs u v t₁ t₂, exact (IH rfl rfl).swap' _ _ } },
{ substs t₁ t₃,
have : a ∈ t₂ := p₁.subset (by simp),
rcases mem_split this with ⟨l₂, r₂, e₂⟩,
subst t₂, exact (IH₁ rfl rfl).trans (IH₂ rfl rfl) }
end
theorem perm.cons_inv {a : α} {l₁ l₂ : list α} : a::l₁ ~ a::l₂ → l₁ ~ l₂ :=
@perm_inv_core _ _ [] [] _ _
@[simp] theorem perm_cons (a : α) {l₁ l₂ : list α} : a::l₁ ~ a::l₂ ↔ l₁ ~ l₂ :=
⟨perm.cons_inv, perm.cons a⟩
theorem perm_append_left_iff {l₁ l₂ : list α} : ∀ l, l++l₁ ~ l++l₂ ↔ l₁ ~ l₂
| [] := iff.rfl
| (a::l) := (perm_cons a).trans (perm_append_left_iff l)
theorem perm_append_right_iff {l₁ l₂ : list α} (l) : l₁++l ~ l₂++l ↔ l₁ ~ l₂ :=
⟨λ p, (perm_append_left_iff _).1 $ perm_append_comm.trans $ p.trans perm_append_comm,
perm.append_right _⟩
theorem perm_option_to_list {o₁ o₂ : option α} : o₁.to_list ~ o₂.to_list ↔ o₁ = o₂ :=
begin
refine ⟨λ p, _, λ e, e ▸ perm.refl _⟩,
cases o₁ with a; cases o₂ with b, {refl},
{ cases p.length_eq },
{ cases p.length_eq },
{ exact option.mem_to_list.1 (p.symm.subset $ by simp) }
end
theorem subperm_cons (a : α) {l₁ l₂ : list α} : a::l₁ <+~ a::l₂ ↔ l₁ <+~ l₂ :=
⟨λ ⟨l, p, s⟩, begin
cases s with _ _ _ s' u _ _ s',
{ exact (p.subperm_left.2 $ (sublist_cons _ _).subperm).trans s'.subperm },
{ exact ⟨u, p.cons_inv, s'⟩ }
end, λ ⟨l, p, s⟩, ⟨a::l, p.cons a, s.cons2 _ _ _⟩⟩
alias subperm_cons ↔ subperm.of_cons subperm.cons
attribute [protected] subperm.cons
theorem cons_subperm_of_mem {a : α} {l₁ l₂ : list α} (d₁ : nodup l₁) (h₁ : a ∉ l₁) (h₂ : a ∈ l₂)
(s : l₁ <+~ l₂) : a :: l₁ <+~ l₂ :=
begin
rcases s with ⟨l, p, s⟩,
induction s generalizing l₁,
case list.sublist.slnil { cases h₂ },
case list.sublist.cons : r₁ r₂ b s' ih
{ simp at h₂,
cases h₂ with e m,
{ subst b, exact ⟨a::r₁, p.cons a, s'.cons2 _ _ _⟩ },
{ rcases ih m d₁ h₁ p with ⟨t, p', s'⟩, exact ⟨t, p', s'.cons _ _ _⟩ } },
case list.sublist.cons2 : r₁ r₂ b s' ih
{ have bm : b ∈ l₁ := (p.subset $ mem_cons_self _ _),
have am : a ∈ r₂ := h₂.resolve_left (λ e, h₁ $ e.symm ▸ bm),
rcases mem_split bm with ⟨t₁, t₂, rfl⟩,
have st : t₁ ++ t₂ <+ t₁ ++ b :: t₂ := by simp,
rcases ih am (d₁.sublist st)
(mt (λ x, st.subset x) h₁)
(perm.cons_inv $ p.trans perm_middle) with ⟨t, p', s'⟩,
exact ⟨b::t, (p'.cons b).trans $ (swap _ _ _).trans (perm_middle.symm.cons a), s'.cons2 _ _ _⟩ }
end
theorem subperm_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+~ l++l₂ ↔ l₁ <+~ l₂
| [] := iff.rfl
| (a::l) := (subperm_cons a).trans (subperm_append_left l)
theorem subperm_append_right {l₁ l₂ : list α} (l) : l₁++l <+~ l₂++l ↔ l₁ <+~ l₂ :=
(perm_append_comm.subperm_left.trans perm_append_comm.subperm_right).trans (subperm_append_left l)
theorem subperm.exists_of_length_lt {l₁ l₂ : list α} :
l₁ <+~ l₂ → length l₁ < length l₂ → ∃ a, a :: l₁ <+~ l₂
| ⟨l, p, s⟩ h :=
suffices length l < length l₂ → ∃ (a : α), a :: l <+~ l₂, from
(this $ p.symm.length_eq ▸ h).imp (λ a, (p.cons a).subperm_right.1),
begin
clear subperm.exists_of_length_lt p h l₁, rename l₂ u,
induction s with l₁ l₂ a s IH _ _ b s IH; intro h,
{ cases h },
{ cases lt_or_eq_of_le (nat.le_of_lt_succ h : length l₁ ≤ length l₂) with h h,
{ exact (IH h).imp (λ a s, s.trans (sublist_cons _ _).subperm) },
{ exact ⟨a, s.eq_of_length h ▸ subperm.refl _⟩ } },
{ exact (IH $ nat.lt_of_succ_lt_succ h).imp
(λ a s, (swap _ _ _).subperm_right.1 $ (subperm_cons _).2 s) }
end
protected lemma nodup.subperm (d : nodup l₁) (H : l₁ ⊆ l₂) : l₁ <+~ l₂ :=
begin
induction d with a l₁' h d IH,
{ exact ⟨nil, perm.nil, nil_sublist _⟩ },
{ cases forall_mem_cons.1 H with H₁ H₂,
simp at h,
exact cons_subperm_of_mem d h H₁ (IH H₂) }
end
theorem perm_ext {l₁ l₂ : list α} (d₁ : nodup l₁) (d₂ : nodup l₂) :
l₁ ~ l₂ ↔ ∀a, a ∈ l₁ ↔ a ∈ l₂ :=
⟨λ p a, p.mem_iff, λ H, (d₁.subperm $ λ a, (H a).1).antisymm $ d₂.subperm $ λ a, (H a).2⟩
theorem nodup.sublist_ext {l₁ l₂ l : list α} (d : nodup l)
(s₁ : l₁ <+ l) (s₂ : l₂ <+ l) : l₁ ~ l₂ ↔ l₁ = l₂ :=
⟨λ h, begin
induction s₂ with l₂ l a s₂ IH l₂ l a s₂ IH generalizing l₁,
{ exact h.eq_nil },
{ simp at d,
cases s₁ with _ _ _ s₁ l₁ _ _ s₁,
{ exact IH d.2 s₁ h },
{ apply d.1.elim,
exact subperm.subset ⟨_, h.symm, s₂⟩ (mem_cons_self _ _) } },
{ simp at d,
cases s₁ with _ _ _ s₁ l₁ _ _ s₁,
{ apply d.1.elim,
exact subperm.subset ⟨_, h, s₁⟩ (mem_cons_self _ _) },
{ rw IH d.2 s₁ h.cons_inv } }
end, λ h, by rw h⟩
section
variable [decidable_eq α]
-- attribute [congr]
theorem perm.erase (a : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) :
l₁.erase a ~ l₂.erase a :=
if h₁ : a ∈ l₁ then
have h₂ : a ∈ l₂, from p.subset h₁,
perm.cons_inv $ (perm_cons_erase h₁).symm.trans $ p.trans (perm_cons_erase h₂)
else
have h₂ : a ∉ l₂, from mt p.mem_iff.2 h₁,
by rw [erase_of_not_mem h₁, erase_of_not_mem h₂]; exact p
theorem subperm_cons_erase (a : α) (l : list α) : l <+~ a :: l.erase a :=
begin
by_cases h : a ∈ l,
{ exact (perm_cons_erase h).subperm },
{ rw [erase_of_not_mem h],
exact (sublist_cons _ _).subperm }
end
theorem erase_subperm (a : α) (l : list α) : l.erase a <+~ l :=
(erase_sublist _ _).subperm
theorem subperm.erase {l₁ l₂ : list α} (a : α) (h : l₁ <+~ l₂) : l₁.erase a <+~ l₂.erase a :=
let ⟨l, hp, hs⟩ := h in ⟨l.erase a, hp.erase _, hs.erase _⟩
theorem perm.diff_right {l₁ l₂ : list α} (t : list α) (h : l₁ ~ l₂) : l₁.diff t ~ l₂.diff t :=
by induction t generalizing l₁ l₂ h; simp [*, perm.erase]
theorem perm.diff_left (l : list α) {t₁ t₂ : list α} (h : t₁ ~ t₂) : l.diff t₁ = l.diff t₂ :=
by induction h generalizing l; simp [*, perm.erase, erase_comm]
<|> exact (ih_1 _).trans (ih_2 _)
theorem perm.diff {l₁ l₂ t₁ t₂ : list α} (hl : l₁ ~ l₂) (ht : t₁ ~ t₂) :
l₁.diff t₁ ~ l₂.diff t₂ :=
ht.diff_left l₂ ▸ hl.diff_right _
theorem subperm.diff_right {l₁ l₂ : list α} (h : l₁ <+~ l₂) (t : list α) :
l₁.diff t <+~ l₂.diff t :=
by induction t generalizing l₁ l₂ h; simp [*, subperm.erase]
theorem erase_cons_subperm_cons_erase (a b : α) (l : list α) :
(a :: l).erase b <+~ a :: l.erase b :=
begin
by_cases h : a = b,
{ subst b,
rw [erase_cons_head],
apply subperm_cons_erase },
{ rw [erase_cons_tail _ h] }
end
theorem subperm_cons_diff {a : α} : ∀ {l₁ l₂ : list α}, (a :: l₁).diff l₂ <+~ a :: l₁.diff l₂
| l₁ [] := ⟨a::l₁, by simp⟩
| l₁ (b::l₂) :=
begin
simp only [diff_cons],
refine ((erase_cons_subperm_cons_erase a b l₁).diff_right l₂).trans _,
apply subperm_cons_diff
end
theorem subset_cons_diff {a : α} {l₁ l₂ : list α} : (a :: l₁).diff l₂ ⊆ a :: l₁.diff l₂ :=
subperm_cons_diff.subset
theorem perm.bag_inter_right {l₁ l₂ : list α} (t : list α) (h : l₁ ~ l₂) :
l₁.bag_inter t ~ l₂.bag_inter t :=
begin
induction h with x _ _ _ _ x y _ _ _ _ _ _ ih_1 ih_2 generalizing t, {simp},
{ by_cases x ∈ t; simp [*, perm.cons] },
{ by_cases x = y, {simp [h]},
by_cases xt : x ∈ t; by_cases yt : y ∈ t,
{ simp [xt, yt, mem_erase_of_ne h, mem_erase_of_ne (ne.symm h), erase_comm, swap] },
{ simp [xt, yt, mt mem_of_mem_erase, perm.cons] },
{ simp [xt, yt, mt mem_of_mem_erase, perm.cons] },
{ simp [xt, yt] } },
{ exact (ih_1 _).trans (ih_2 _) }
end
theorem perm.bag_inter_left (l : list α) {t₁ t₂ : list α} (p : t₁ ~ t₂) :
l.bag_inter t₁ = l.bag_inter t₂ :=
begin
induction l with a l IH generalizing t₁ t₂ p, {simp},
by_cases a ∈ t₁,
{ simp [h, p.subset h, IH (p.erase _)] },
{ simp [h, mt p.mem_iff.2 h, IH p] }
end
theorem perm.bag_inter {l₁ l₂ t₁ t₂ : list α} (hl : l₁ ~ l₂) (ht : t₁ ~ t₂) :
l₁.bag_inter t₁ ~ l₂.bag_inter t₂ :=
ht.bag_inter_left l₂ ▸ hl.bag_inter_right _
theorem cons_perm_iff_perm_erase {a : α} {l₁ l₂ : list α} : a::l₁ ~ l₂ ↔ a ∈ l₂ ∧ l₁ ~ l₂.erase a :=
⟨λ h, have a ∈ l₂, from h.subset (mem_cons_self a l₁),
⟨this, (h.trans $ perm_cons_erase this).cons_inv⟩,
λ ⟨m, h⟩, (h.cons a).trans (perm_cons_erase m).symm⟩
theorem perm_iff_count {l₁ l₂ : list α} : l₁ ~ l₂ ↔ ∀ a, count a l₁ = count a l₂ :=
⟨perm.count_eq, λ H, begin
induction l₁ with a l₁ IH generalizing l₂,
{ cases l₂ with b l₂, {refl},
specialize H b, simp at H, contradiction },
{ have : a ∈ l₂ := count_pos.1 (by rw ← H; simp; apply nat.succ_pos),
refine ((IH $ λ b, _).cons a).trans (perm_cons_erase this).symm,
specialize H b,
rw (perm_cons_erase this).count_eq at H,
by_cases b = a; simp [h] at H ⊢; assumption }
end⟩
theorem perm_replicate_append_replicate {l : list α} {a b : α} {m n : ℕ} (h : a ≠ b) :
l ~ replicate m a ++ replicate n b ↔ count a l = m ∧ count b l = n ∧ l ⊆ [a, b] :=
begin
rw [perm_iff_count, ← decidable.and_forall_ne a, ← decidable.and_forall_ne b],
suffices : l ⊆ [a, b] ↔ ∀ c, c ≠ b → c ≠ a → c ∉ l,
{ simp [count_replicate, h, h.symm, this] { contextual := tt } },
simp_rw [ne.def, ← and_imp, ← not_or_distrib, decidable.not_imp_not, subset_def, mem_cons_iff,
not_mem_nil, or_false, or_comm],
end
lemma subperm.cons_right {α : Type*} {l l' : list α} (x : α) (h : l <+~ l') : l <+~ x :: l' :=
h.trans (sublist_cons x l').subperm
/-- The list version of `add_tsub_cancel_of_le` for multisets. -/
lemma subperm_append_diff_self_of_count_le {l₁ l₂ : list α}
(h : ∀ x ∈ l₁, count x l₁ ≤ count x l₂) : l₁ ++ l₂.diff l₁ ~ l₂ :=
begin
induction l₁ with hd tl IH generalizing l₂,
{ simp },
{ have : hd ∈ l₂,
{ rw ←count_pos,
exact lt_of_lt_of_le (count_pos.mpr (mem_cons_self _ _)) (h hd (mem_cons_self _ _)) },
replace this : l₂ ~ hd :: l₂.erase hd := perm_cons_erase this,
refine perm.trans _ this.symm,
rw [cons_append, diff_cons, perm_cons],
refine IH (λ x hx, _),
specialize h x (mem_cons_of_mem _ hx),
rw (perm_iff_count.mp this) at h,
by_cases hx : x = hd,
{ subst hd,
simpa [nat.succ_le_succ_iff] using h },
{ simpa [hx] using h } },
end
/-- The list version of `multiset.le_iff_count`. -/
lemma subperm_ext_iff {l₁ l₂ : list α} :
l₁ <+~ l₂ ↔ ∀ x ∈ l₁, count x l₁ ≤ count x l₂ :=
begin
refine ⟨λ h x hx, subperm.count_le h x, λ h, _⟩,
suffices : l₁ <+~ (l₂.diff l₁ ++ l₁),
{ refine this.trans (perm.subperm _),
exact perm_append_comm.trans (subperm_append_diff_self_of_count_le h) },
convert (subperm_append_right _).mpr nil_subperm using 1
end
instance decidable_subperm : decidable_rel ((<+~) : list α → list α → Prop) :=
λ l₁ l₂, decidable_of_iff _ list.subperm_ext_iff.symm
@[simp] lemma subperm_singleton_iff {α} {l : list α} {a : α} : [a] <+~ l ↔ a ∈ l :=
⟨λ ⟨s, hla, h⟩, by rwa [perm_singleton.mp hla, singleton_sublist] at h,
λ h, ⟨[a], perm.refl _, singleton_sublist.mpr h⟩⟩
lemma subperm.cons_left {l₁ l₂ : list α} (h : l₁ <+~ l₂)
(x : α) (hx : count x l₁ < count x l₂) :
x :: l₁ <+~ l₂ :=
begin
rw subperm_ext_iff at h ⊢,
intros y hy,
by_cases hy' : y = x,
{ subst x,
simpa using nat.succ_le_of_lt hx },
{ rw count_cons_of_ne hy',
refine h y _,
simpa [hy'] using hy }
end
instance decidable_perm : ∀ (l₁ l₂ : list α), decidable (l₁ ~ l₂)
| [] [] := is_true $ perm.refl _
| [] (b::l₂) := is_false $ λ h, by have := h.nil_eq; contradiction
| (a::l₁) l₂ := by haveI := decidable_perm l₁ (l₂.erase a);
exact decidable_of_iff' _ cons_perm_iff_perm_erase
-- @[congr]
theorem perm.dedup {l₁ l₂ : list α} (p : l₁ ~ l₂) :
dedup l₁ ~ dedup l₂ :=
perm_iff_count.2 $ λ a,
if h : a ∈ l₁
then by simp [nodup_dedup, h, p.subset h]
else by simp [h, mt p.mem_iff.2 h]
-- attribute [congr]
theorem perm.insert (a : α)
{l₁ l₂ : list α} (p : l₁ ~ l₂) : insert a l₁ ~ insert a l₂ :=
if h : a ∈ l₁
then by simpa [h, p.subset h] using p
else by simpa [h, mt p.mem_iff.2 h] using p.cons a
theorem perm_insert_swap (x y : α) (l : list α) :
insert x (insert y l) ~ insert y (insert x l) :=
begin
by_cases xl : x ∈ l; by_cases yl : y ∈ l; simp [xl, yl],
by_cases xy : x = y, { simp [xy] },
simp [not_mem_cons_of_ne_of_not_mem xy xl,
not_mem_cons_of_ne_of_not_mem (ne.symm xy) yl],
constructor
end
theorem perm_insert_nth {α} (x : α) (l : list α) {n} (h : n ≤ l.length) :
insert_nth n x l ~ x :: l :=
begin
induction l generalizing n,
{ cases n, refl, cases h },
cases n,
{ simp [insert_nth] },
{ simp only [insert_nth, modify_nth_tail],
transitivity,
{ apply perm.cons, apply l_ih,
apply nat.le_of_succ_le_succ h },
{ apply perm.swap } }
end
theorem perm.union_right {l₁ l₂ : list α} (t₁ : list α) (h : l₁ ~ l₂) : l₁ ∪ t₁ ~ l₂ ∪ t₁ :=
begin
induction h with a _ _ _ ih _ _ _ _ _ _ _ _ ih_1 ih_2; try {simp},
{ exact ih.insert a },
{ apply perm_insert_swap },
{ exact ih_1.trans ih_2 }
end
theorem perm.union_left (l : list α) {t₁ t₂ : list α} (h : t₁ ~ t₂) : l ∪ t₁ ~ l ∪ t₂ :=
by induction l; simp [*, perm.insert]
-- @[congr]
theorem perm.union {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁ ∪ t₁ ~ l₂ ∪ t₂ :=
(p₁.union_right t₁).trans (p₂.union_left l₂)
theorem perm.inter_right {l₁ l₂ : list α} (t₁ : list α) : l₁ ~ l₂ → l₁ ∩ t₁ ~ l₂ ∩ t₁ :=
perm.filter _
theorem perm.inter_left (l : list α) {t₁ t₂ : list α} (p : t₁ ~ t₂) : l ∩ t₁ = l ∩ t₂ :=
filter_congr' (λ a _, p.mem_iff)
-- @[congr]
theorem perm.inter {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁ ∩ t₁ ~ l₂ ∩ t₂ :=
p₂.inter_left l₂ ▸ p₁.inter_right t₁
theorem perm.inter_append {l t₁ t₂ : list α} (h : disjoint t₁ t₂) :
l ∩ (t₁ ++ t₂) ~ l ∩ t₁ ++ l ∩ t₂ :=
begin
induction l,
case list.nil
{ simp },
case list.cons : x xs l_ih
{ by_cases h₁ : x ∈ t₁,
{ have h₂ : x ∉ t₂ := h h₁,
simp * },
by_cases h₂ : x ∈ t₂,
{ simp only [*, inter_cons_of_not_mem, false_or, mem_append, inter_cons_of_mem, not_false_iff],
transitivity,
{ apply perm.cons _ l_ih, },
change [x] ++ xs ∩ t₁ ++ xs ∩ t₂ ~ xs ∩ t₁ ++ ([x] ++ xs ∩ t₂),
rw [← list.append_assoc],
solve_by_elim [perm.append_right, perm_append_comm] },
{ simp * } },
end
end
theorem perm.pairwise_iff {R : α → α → Prop} (S : symmetric R) :
∀ {l₁ l₂ : list α} (p : l₁ ~ l₂), pairwise R l₁ ↔ pairwise R l₂ :=
suffices ∀ {l₁ l₂}, l₁ ~ l₂ → pairwise R l₁ → pairwise R l₂, from λ l₁ l₂ p, ⟨this p, this p.symm⟩,
λ l₁ l₂ p d, begin
induction d with a l₁ h d IH generalizing l₂,
{ rw ← p.nil_eq, constructor },
{ have : a ∈ l₂ := p.subset (mem_cons_self _ _),
rcases mem_split this with ⟨s₂, t₂, rfl⟩,
have p' := (p.trans perm_middle).cons_inv,
refine (pairwise_middle S).2 (pairwise_cons.2 ⟨λ b m, _, IH _ p'⟩),
exact h _ (p'.symm.subset m) }
end
lemma pairwise.perm {R : α → α → Prop} {l l' : list α} (hR : l.pairwise R)
(hl : l ~ l') (hsymm : symmetric R) : l'.pairwise R :=
(hl.pairwise_iff hsymm).mp hR
lemma perm.pairwise {R : α → α → Prop} {l l' : list α}
(hl : l ~ l') (hR : l.pairwise R) (hsymm : symmetric R) : l'.pairwise R :=
hR.perm hl hsymm
theorem perm.nodup_iff {l₁ l₂ : list α} : l₁ ~ l₂ → (nodup l₁ ↔ nodup l₂) :=
perm.pairwise_iff $ @ne.symm α
theorem perm.join {l₁ l₂ : list (list α)} (h : l₁ ~ l₂) : l₁.join ~ l₂.join :=
perm.rec_on h
(perm.refl _)
(λ x xs₁ xs₂ hxs ih, ih.append_left x)
(λ x₁ x₂ xs, by simpa only [join, append_assoc] using perm_append_comm.append_right _)
(λ xs₁ xs₂ xs₃ h₁₂ h₂₃, perm.trans)
theorem perm.bind_right {l₁ l₂ : list α} (f : α → list β) (p : l₁ ~ l₂) :
l₁.bind f ~ l₂.bind f :=
(p.map _).join
lemma perm.join_congr :
∀ {l₁ l₂ : list (list α)} (h : list.forall₂ (~) l₁ l₂), l₁.join ~ l₂.join
| _ _ forall₂.nil := perm.refl _
| (a :: as) (b :: bs) (forall₂.cons h₁ h₂) := h₁.append (perm.join_congr h₂)
theorem perm.bind_left (l : list α) {f g : α → list β} (h : ∀ a ∈ l, f a ~ g a) :
l.bind f ~ l.bind g :=
perm.join_congr $
by rwa [list.forall₂_map_right_iff,list.forall₂_map_left_iff, list.forall₂_same]
theorem bind_append_perm (l : list α) (f g : α → list β) :
l.bind f ++ l.bind g ~ l.bind (λ x, f x ++ g x) :=
begin
induction l with a l IH; simp,
refine (perm.trans _ (IH.append_left _)).append_left _,
rw [← append_assoc, ← append_assoc],
exact perm_append_comm.append_right _
end
theorem map_append_bind_perm (l : list α) (f : α → β) (g : α → list β) :
l.map f ++ l.bind g ~ l.bind (λ x, f x :: g x) :=
by simpa [←map_eq_bind] using bind_append_perm l (λ x, [f x]) g
theorem perm.product_right {l₁ l₂ : list α} (t₁ : list β) (p : l₁ ~ l₂) :
product l₁ t₁ ~ product l₂ t₁ :=
p.bind_right _
theorem perm.product_left (l : list α) {t₁ t₂ : list β} (p : t₁ ~ t₂) :
product l t₁ ~ product l t₂ :=
perm.bind_left _ $ λ a ha, p.map _
@[congr] theorem perm.product {l₁ l₂ : list α} {t₁ t₂ : list β}
(p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : product l₁ t₁ ~ product l₂ t₂ :=
(p₁.product_right t₁).trans (p₂.product_left l₂)
theorem perm_lookmap (f : α → option α) {l₁ l₂ : list α}
(H : pairwise (λ a b, ∀ (c ∈ f a) (d ∈ f b), a = b ∧ c = d) l₁)
(p : l₁ ~ l₂) : lookmap f l₁ ~ lookmap f l₂ :=
begin
let F := λ a b, ∀ (c ∈ f a) (d ∈ f b), a = b ∧ c = d,
change pairwise F l₁ at H,
induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp},
{ cases h : f a,
{ simp [h], exact IH (pairwise_cons.1 H).2 },
{ simp [lookmap_cons_some _ _ h, p] } },
{ cases h₁ : f a with c; cases h₂ : f b with d,
{ simp [h₁, h₂], apply swap },
{ simp [h₁, lookmap_cons_some _ _ h₂], apply swap },
{ simp [lookmap_cons_some _ _ h₁, h₂], apply swap },
{ simp [lookmap_cons_some _ _ h₁, lookmap_cons_some _ _ h₂],
rcases (pairwise_cons.1 H).1 _ (or.inl rfl) _ h₂ _ h₁ with ⟨rfl, rfl⟩,
refl } },
{ refine (IH₁ H).trans (IH₂ ((p₁.pairwise_iff _).1 H)),
exact λ a b h c h₁ d h₂, (h d h₂ c h₁).imp eq.symm eq.symm }
end
theorem perm.erasep (f : α → Prop) [decidable_pred f] {l₁ l₂ : list α}
(H : pairwise (λ a b, f a → f b → false) l₁)
(p : l₁ ~ l₂) : erasep f l₁ ~ erasep f l₂ :=
begin
let F := λ a b, f a → f b → false,
change pairwise F l₁ at H,
induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp},
{ by_cases h : f a,
{ simp [h, p] },
{ simp [h], exact IH (pairwise_cons.1 H).2 } },
{ by_cases h₁ : f a; by_cases h₂ : f b; simp [h₁, h₂],
{ cases (pairwise_cons.1 H).1 _ (or.inl rfl) h₂ h₁ },
{ apply swap } },
{ refine (IH₁ H).trans (IH₂ ((p₁.pairwise_iff _).1 H)),
exact λ a b h h₁ h₂, h h₂ h₁ }
end
lemma perm.take_inter {α} [decidable_eq α] {xs ys : list α} (n : ℕ)
(h : xs ~ ys) (h' : ys.nodup) :
xs.take n ~ ys.inter (xs.take n) :=
begin
simp only [list.inter] at *,
induction h generalizing n,
case list.perm.nil : n
{ simp only [not_mem_nil, filter_false, take_nil] },
case list.perm.cons : h_x h_l₁ h_l₂ h_a h_ih n
{ cases n; simp only [mem_cons_iff, true_or, eq_self_iff_true, filter_cons_of_pos,
perm_cons, take, not_mem_nil, filter_false],
cases h' with _ _ h₁ h₂,
convert h_ih h₂ n using 1,
apply filter_congr',
introv h, simp only [(h₁ x h).symm, false_or], },
case list.perm.swap : h_x h_y h_l n
{ cases h' with _ _ h₁ h₂,
cases h₂ with _ _ h₂ h₃,
have := h₁ _ (or.inl rfl),
cases n; simp only [mem_cons_iff, not_mem_nil, filter_false, take],
cases n; simp only [mem_cons_iff, false_or, true_or, filter, *, nat.nat_zero_eq_zero, if_true,
not_mem_nil, eq_self_iff_true, or_false, if_false, perm_cons, take],
{ rw filter_eq_nil.2, intros, solve_by_elim [ne.symm], },
{ convert perm.swap _ _ _, rw @filter_congr' _ _ (∈ take n h_l),
{ clear h₁, induction n generalizing h_l, { simp },
cases h_l; simp only [mem_cons_iff, true_or, eq_self_iff_true, filter_cons_of_pos,
true_and, take, not_mem_nil, filter_false, take_nil],
cases h₃ with _ _ h₃ h₄,
rwa [@filter_congr' _ _ (∈ take n_n h_l_tl), n_ih],
{ introv h, apply h₂ _ (or.inr h), },
{ introv h, simp only [(h₃ x h).symm, false_or], }, },
{ introv h, simp only [(h₂ x h).symm, (h₁ x (or.inr h)).symm, false_or], } } },
case list.perm.trans : h_l₁ h_l₂ h_l₃ h₀ h₁ h_ih₀ h_ih₁ n
{ transitivity,
{ apply h_ih₀, rwa h₁.nodup_iff },
{ apply perm.filter _ h₁, } },
end
lemma perm.drop_inter {α} [decidable_eq α] {xs ys : list α} (n : ℕ)
(h : xs ~ ys) (h' : ys.nodup) :
xs.drop n ~ ys.inter (xs.drop n) :=
begin
by_cases h'' : n ≤ xs.length,
{ let n' := xs.length - n,
have h₀ : n = xs.length - n',
{ dsimp [n'], rwa tsub_tsub_cancel_of_le, } ,
have h₁ : n' ≤ xs.length,
{ apply tsub_le_self },
have h₂ : xs.drop n = (xs.reverse.take n').reverse,
{ rw [reverse_take _ h₁, h₀, reverse_reverse], },
rw [h₂],
apply (reverse_perm _).trans,
rw inter_reverse,
apply perm.take_inter _ _ h',
apply (reverse_perm _).trans; assumption, },
{ have : drop n xs = [],
{ apply eq_nil_of_length_eq_zero,
rw [length_drop, tsub_eq_zero_iff_le],
apply le_of_not_ge h'' },
simp [this, list.inter], }
end
lemma perm.slice_inter {α} [decidable_eq α] {xs ys : list α} (n m : ℕ)
(h : xs ~ ys) (h' : ys.nodup) :
list.slice n m xs ~ ys ∩ (list.slice n m xs) :=
begin
simp only [slice_eq],
have : n ≤ n + m := nat.le_add_right _ _,
have := h.nodup_iff.2 h',
apply perm.trans _ (perm.inter_append _).symm;
solve_by_elim [perm.append, perm.drop_inter, perm.take_inter, disjoint_take_drop, h, h']
{ max_depth := 7 },
end
/- enumerating permutations -/
section permutations
theorem perm_of_mem_permutations_aux :
∀ {ts is l : list α}, l ∈ permutations_aux ts is → l ~ ts ++ is :=
begin
refine permutations_aux.rec (by simp) _,
introv IH1 IH2 m,
rw [permutations_aux_cons, permutations, mem_foldr_permutations_aux2] at m,
rcases m with m | ⟨l₁, l₂, m, _, e⟩,
{ exact (IH1 m).trans perm_middle },
{ subst e,
have p : l₁ ++ l₂ ~ is,
{ simp [permutations] at m,
cases m with e m, {simp [e]},
exact is.append_nil ▸ IH2 m },
exact ((perm_middle.trans (p.cons _)).append_right _).trans (perm_append_comm.cons _) }
end
theorem perm_of_mem_permutations {l₁ l₂ : list α}
(h : l₁ ∈ permutations l₂) : l₁ ~ l₂ :=
(eq_or_mem_of_mem_cons h).elim (λ e, e ▸ perm.refl _)
(λ m, append_nil l₂ ▸ perm_of_mem_permutations_aux m)
theorem length_permutations_aux : ∀ ts is : list α,
length (permutations_aux ts is) + is.length! = (length ts + length is)! :=
begin
refine permutations_aux.rec (by simp) _,
intros t ts is IH1 IH2,
have IH2 : length (permutations_aux is nil) + 1 = is.length!,
{ simpa using IH2 },
simp [-add_comm, nat.factorial, nat.add_succ, mul_comm] at IH1,
rw [permutations_aux_cons,
length_foldr_permutations_aux2' _ _ _ _ _
(λ l m, (perm_of_mem_permutations m).length_eq),
permutations, length, length, IH2,
nat.succ_add, nat.factorial_succ, mul_comm (nat.succ _), ← IH1,
add_comm (_*_), add_assoc, nat.mul_succ, mul_comm]
end
theorem length_permutations (l : list α) : length (permutations l) = (length l)! :=
length_permutations_aux l []
theorem mem_permutations_of_perm_lemma {is l : list α}
(H : l ~ [] ++ is → (∃ ts' ~ [], l = ts' ++ is) ∨ l ∈ permutations_aux is [])
: l ~ is → l ∈ permutations is :=
by simpa [permutations, perm_nil] using H
theorem mem_permutations_aux_of_perm :
∀ {ts is l : list α}, l ~ is ++ ts → (∃ is' ~ is, l = is' ++ ts) ∨ l ∈ permutations_aux ts is :=
begin
refine permutations_aux.rec (by simp) _,
intros t ts is IH1 IH2 l p,
rw [permutations_aux_cons, mem_foldr_permutations_aux2],
rcases IH1 (p.trans perm_middle) with ⟨is', p', e⟩ | m,
{ clear p, subst e,
rcases mem_split (p'.symm.subset (mem_cons_self _ _)) with ⟨l₁, l₂, e⟩,
subst is',
have p := (perm_middle.symm.trans p').cons_inv,
cases l₂ with a l₂',
{ exact or.inl ⟨l₁, by simpa using p⟩ },
{ exact or.inr (or.inr ⟨l₁, a::l₂',
mem_permutations_of_perm_lemma IH2 p, by simp⟩) } },
{ exact or.inr (or.inl m) }
end
@[simp] theorem mem_permutations {s t : list α} : s ∈ permutations t ↔ s ~ t :=
⟨perm_of_mem_permutations, mem_permutations_of_perm_lemma mem_permutations_aux_of_perm⟩
theorem perm_permutations'_aux_comm (a b : α) (l : list α) :
(permutations'_aux a l).bind (permutations'_aux b) ~
(permutations'_aux b l).bind (permutations'_aux a) :=
begin
induction l with c l ih, {simp [swap]},
simp [permutations'_aux], apply perm.swap',
have : ∀ a b,
(map (cons c) (permutations'_aux a l)).bind (permutations'_aux b) ~
map (cons b ∘ cons c) (permutations'_aux a l) ++
map (cons c) ((permutations'_aux a l).bind (permutations'_aux b)),
{ intros,
simp only [map_bind, permutations'_aux],
refine (bind_append_perm _ (λ x, [_]) _).symm.trans _,
rw [← map_eq_bind, ← bind_map] },
refine (((this _ _).append_left _).trans _).trans ((this _ _).append_left _).symm,
rw [← append_assoc, ← append_assoc],
exact perm_append_comm.append (ih.map _),
end
theorem perm.permutations' {s t : list α} (p : s ~ t) :
permutations' s ~ permutations' t :=
begin
induction p with a s t p IH a b l s t u p₁ p₂ IH₁ IH₂, {simp},
{ simp only [permutations'], exact IH.bind_right _ },
{ simp only [permutations'],
rw [bind_assoc, bind_assoc],
apply perm.bind_left,
intros l' hl',
apply perm_permutations'_aux_comm },
{ exact IH₁.trans IH₂ }
end
theorem permutations_perm_permutations' (ts : list α) : ts.permutations ~ ts.permutations' :=
begin
obtain ⟨n, h⟩ : ∃ n, length ts < n := ⟨_, nat.lt_succ_self _⟩,
induction n with n IH generalizing ts, {cases h},
refine list.reverse_rec_on ts (λ h, _) (λ ts t _ h, _) h, {simp [permutations]},
rw [← concat_eq_append, length_concat, nat.succ_lt_succ_iff] at h,
have IH₂ := (IH ts.reverse (by rwa [length_reverse])).trans (reverse_perm _).permutations',
simp only [permutations_append, foldr_permutations_aux2,
permutations_aux_nil, permutations_aux_cons, append_nil],
refine (perm_append_comm.trans ((IH₂.bind_right _).append ((IH _ h).map _))).trans
(perm.trans _ perm_append_comm.permutations'),
rw [map_eq_bind, singleton_append, permutations'],
convert bind_append_perm _ _ _, funext ys,
rw [permutations'_aux_eq_permutations_aux2, permutations_aux2_append]
end
@[simp] theorem mem_permutations' {s t : list α} : s ∈ permutations' t ↔ s ~ t :=
(permutations_perm_permutations' _).symm.mem_iff.trans mem_permutations
theorem perm.permutations {s t : list α} (h : s ~ t) : permutations s ~ permutations t :=
(permutations_perm_permutations' _).trans $ h.permutations'.trans
(permutations_perm_permutations' _).symm
@[simp] theorem perm_permutations_iff {s t : list α} : permutations s ~ permutations t ↔ s ~ t :=
⟨λ h, mem_permutations.1 $ h.mem_iff.1 $ mem_permutations.2 (perm.refl _), perm.permutations⟩
@[simp] theorem perm_permutations'_iff {s t : list α} : permutations' s ~ permutations' t ↔ s ~ t :=
⟨λ h, mem_permutations'.1 $ h.mem_iff.1 $ mem_permutations'.2 (perm.refl _), perm.permutations'⟩
lemma nth_le_permutations'_aux (s : list α) (x : α) (n : ℕ)
(hn : n < length (permutations'_aux x s)) :
(permutations'_aux x s).nth_le n hn = s.insert_nth n x :=
begin
induction s with y s IH generalizing n,
{ simp only [length, permutations'_aux, nat.lt_one_iff] at hn,
simp [hn] },
{ cases n,
{ simp },
{ simpa using IH _ _ } }
end
lemma count_permutations'_aux_self [decidable_eq α] (l : list α) (x : α) :
count (x :: l) (permutations'_aux x l) = length (take_while ((=) x) l) + 1 :=
begin
induction l with y l IH generalizing x,
{ simp [take_while], },
{ rw [permutations'_aux, count_cons_self],
by_cases hx : x = y,
{ subst hx,
simpa [take_while, nat.succ_inj'] using IH _ },
{ rw take_while,
rw if_neg hx,
cases permutations'_aux x l with a as,
{ simp },
{ rw [count_eq_zero_of_not_mem, length, zero_add],
simp [hx, ne.symm hx] } } }
end
@[simp] lemma length_permutations'_aux (s : list α) (x : α) :
length (permutations'_aux x s) = length s + 1 :=
begin
induction s with y s IH,
{ simp },
{ simpa using IH }
end
@[simp] lemma permutations'_aux_nth_le_zero (s : list α) (x : α)
(hn : 0 < length (permutations'_aux x s) := by simp) :
(permutations'_aux x s).nth_le 0 hn = x :: s :=
nth_le_permutations'_aux _ _ _ _
lemma injective_permutations'_aux (x : α) : function.injective (permutations'_aux x) :=
begin
intros s t h,
apply insert_nth_injective s.length x,
have hl : s.length = t.length := by simpa using congr_arg length h,
rw [←nth_le_permutations'_aux s x s.length (by simp),
←nth_le_permutations'_aux t x s.length (by simp [hl])],
simp [h, hl]
end
lemma nodup_permutations'_aux_of_not_mem (s : list α) (x : α) (hx : x ∉ s) :
nodup (permutations'_aux x s) :=
begin
induction s with y s IH,
{ simp },
{ simp only [not_or_distrib, mem_cons_iff] at hx,
simp only [not_and, exists_eq_right_right, mem_map, permutations'_aux, nodup_cons],
refine ⟨λ _, ne.symm hx.left, _⟩,
rw nodup_map_iff,
{ exact IH hx.right },
{ simp } }
end
lemma nodup_permutations'_aux_iff {s : list α} {x : α} :
nodup (permutations'_aux x s) ↔ x ∉ s :=
begin
refine ⟨λ h, _, nodup_permutations'_aux_of_not_mem _ _⟩,
intro H,
obtain ⟨k, hk, hk'⟩ := nth_le_of_mem H,
rw nodup_iff_nth_le_inj at h,
suffices : k = k + 1,
{ simpa using this },
refine h k (k + 1) _ _ _,
{ simpa [nat.lt_succ_iff] using hk.le },
{ simpa using hk },
rw [nth_le_permutations'_aux, nth_le_permutations'_aux],
have hl : length (insert_nth k x s) = length (insert_nth (k + 1) x s),
{ rw [length_insert_nth _ _ hk.le, length_insert_nth _ _ (nat.succ_le_of_lt hk)] },
refine ext_le hl (λ n hn hn', _),
rcases lt_trichotomy n k with H|rfl|H,
{ rw [nth_le_insert_nth_of_lt _ _ _ _ H (H.trans hk),
nth_le_insert_nth_of_lt _ _ _ _ (H.trans (nat.lt_succ_self _))] },
{ rw [nth_le_insert_nth_self _ _ _ hk.le,
nth_le_insert_nth_of_lt _ _ _ _ (nat.lt_succ_self _) hk, hk'] },
{ rcases (nat.succ_le_of_lt H).eq_or_lt with rfl|H',
{ rw [nth_le_insert_nth_self _ _ _ (nat.succ_le_of_lt hk)],
convert hk' using 1,
convert nth_le_insert_nth_add_succ _ _ _ 0 _,
simpa using hk },
{ obtain ⟨m, rfl⟩ := nat.exists_eq_add_of_lt H',
rw [length_insert_nth _ _ hk.le, nat.succ_lt_succ_iff, nat.succ_add] at hn,
rw nth_le_insert_nth_add_succ,
convert nth_le_insert_nth_add_succ s x k m.succ _ using 2,
{ simp [nat.add_succ, nat.succ_add] },
{ simp [add_left_comm, add_comm] },
{ simpa [nat.add_succ] using hn },
{ simpa [nat.succ_add] using hn } } }
end
lemma nodup_permutations (s : list α) (hs : nodup s) :
nodup s.permutations :=
begin
rw (permutations_perm_permutations' s).nodup_iff,
induction hs with x l h h' IH,
{ simp },
{ rw [permutations'],
rw nodup_bind,
split,
{ intros ys hy,
rw mem_permutations' at hy,
rw [nodup_permutations'_aux_iff, hy.mem_iff],
exact λ H, h x H rfl },
{ refine IH.pairwise_of_forall_ne (λ as ha bs hb H, _),
rw disjoint_iff_ne,
rintro a ha' b hb' rfl,
obtain ⟨n, hn, hn'⟩ := nth_le_of_mem ha',
obtain ⟨m, hm, hm'⟩ := nth_le_of_mem hb',
rw mem_permutations' at ha hb,
have hl : as.length = bs.length := (ha.trans hb.symm).length_eq,
simp only [nat.lt_succ_iff, length_permutations'_aux] at hn hm,
rw nth_le_permutations'_aux at hn' hm',
have hx : nth_le (insert_nth n x as) m
(by rwa [length_insert_nth _ _ hn, nat.lt_succ_iff, hl]) = x,
{ simp [hn', ←hm', hm] },
have hx' : nth_le (insert_nth m x bs) n
(by rwa [length_insert_nth _ _ hm, nat.lt_succ_iff, ←hl]) = x,
{ simp [hm', ←hn', hn] },
rcases lt_trichotomy n m with ht|ht|ht,
{ suffices : x ∈ bs,
{ exact h x (hb.subset this) rfl },
rw [←hx', nth_le_insert_nth_of_lt _ _ _ _ ht (ht.trans_le hm)],
exact nth_le_mem _ _ _ },
{ simp only [ht] at hm' hn',
rw ←hm' at hn',
exact H (insert_nth_injective _ _ hn') },
{ suffices : x ∈ as,
{ exact h x (ha.subset this) rfl },
rw [←hx, nth_le_insert_nth_of_lt _ _ _ _ ht (ht.trans_le hn)],
exact nth_le_mem _ _ _ } } }
end
-- TODO: `nodup s.permutations ↔ nodup s`
-- TODO: `count s s.permutations = (zip_with count s s.tails).prod`
end permutations
end list
|
09e444214bf4d286803084c225edf4d0039562ae | 07c76fbd96ea1786cc6392fa834be62643cea420 | /hott/homotopy/sphere2.hlean | 3386d6bea24cfd707cf73a3fda64dac7f1f5e300 | [
"Apache-2.0"
] | permissive | fpvandoorn/lean2 | 5a430a153b570bf70dc8526d06f18fc000a60ad9 | 0889cf65b7b3cebfb8831b8731d89c2453dd1e9f | refs/heads/master | 1,592,036,508,364 | 1,545,093,958,000 | 1,545,093,958,000 | 75,436,854 | 0 | 0 | null | 1,480,718,780,000 | 1,480,718,780,000 | null | UTF-8 | Lean | false | false | 3,554 | hlean | /-
Copyright (c) 2016 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
Calculating homotopy groups of spheres.
In this file we calculate
π₂(S²) = Z
πₙ(S²) = πₙ(S³) for n > 2
πₙ(Sⁿ) = Z for n > 0
π₂(S³) = Z
-/
import .homotopy_group .freudenthal
open eq group algebra is_equiv equiv fin prod chain_complex pointed fiber nat is_trunc trunc_index
sphere.ops trunc is_conn susp bool
namespace sphere
/- Corollaries of the complex hopf fibration combined with the LES of homotopy groups -/
open sphere sphere.ops int circle hopf
definition π2S2 : πg[2] (S 2) ≃g gℤ :=
begin
refine _ ⬝g fundamental_group_of_circle,
refine _ ⬝g homotopy_group_isomorphism_of_pequiv _ pfiber_complex_hopf,
fapply isomorphism_of_equiv,
{ fapply equiv.mk,
{ exact cc_to_fn (LES_of_homotopy_groups complex_hopf) (1, 2)},
{ refine LES_is_equiv_of_trivial complex_hopf 1 2 _ _,
{ have H : 1 ≤[ℕ] 2, from !one_le_succ,
apply trivial_homotopy_group_of_is_conn, exact H, rexact is_conn_sphere 3 },
{ refine tr_rev (λx, is_contr (ptrunctype._trans_of_to_pType x))
(LES_of_homotopy_groups_1 complex_hopf 2) _,
apply trivial_homotopy_group_of_is_conn, apply le.refl, rexact is_conn_sphere 3 }}},
{ exact homomorphism.struct (homomorphism_LES_of_homotopy_groups_fun _ (0, 2))}
end
open circle
definition πnS3_eq_πnS2 (n : ℕ) : πg[n+3] (S 3) ≃g πg[n+3] (S 2) :=
begin
fapply isomorphism_of_equiv,
{ fapply equiv.mk,
{ exact cc_to_fn (LES_of_homotopy_groups complex_hopf) (n+3, 0)},
{ have H : is_trunc 1 (pfiber complex_hopf),
from is_trunc_equiv_closed_rev _ pfiber_complex_hopf is_trunc_circle,
refine LES_is_equiv_of_trivial complex_hopf (n+3) 0 _ _,
{ have H2 : 1 ≤[ℕ] n + 1, from !one_le_succ,
exact @trivial_ghomotopy_group_of_is_trunc _ _ _ H H2 },
{ refine tr_rev (λx, is_contr (ptrunctype._trans_of_to_pType x))
(LES_of_homotopy_groups_2 complex_hopf _) _,
have H2 : 1 ≤[ℕ] n + 2, from !one_le_succ,
apply trivial_ghomotopy_group_of_is_trunc _ _ _ H2 }}},
{ exact homomorphism.struct (homomorphism_LES_of_homotopy_groups_fun _ (n+2, 0))}
end
definition sphere_stability_pequiv (k n : ℕ) (H : k + 2 ≤ 2 * n) :
π[k + 1] (S (n+1)) ≃* π[k] (S n) :=
iterate_susp_stability_pequiv H pbool
definition stability_isomorphism (k n : ℕ) (H : k + 3 ≤ 2 * n)
: πg[k+1 +1] (S (n+1)) ≃g πg[k+1] (S n) :=
iterate_susp_stability_isomorphism H pbool
open int circle hopf
definition πnSn (n : ℕ) [H : is_succ n] : πg[n] (S (n)) ≃g gℤ :=
begin
induction H with n,
cases n with n IH,
{ exact fundamental_group_of_circle },
{ induction n with n IH,
{ exact π2S2 },
{ refine _ ⬝g IH, apply stability_isomorphism,
rexact add_mul_le_mul_add n 1 2 }}
end
theorem not_is_trunc_sphere (n : ℕ) : ¬is_trunc n (S (n+1)) :=
begin
intro H,
note H2 := trivial_ghomotopy_group_of_is_trunc (S (n+1)) n n !le.refl,
have H3 : is_contr ℤ, from is_trunc_equiv_closed _ (equiv_of_isomorphism (πnSn (n+1))) _,
have H4 : (0 : ℤ) ≠ (1 : ℤ), from dec_star,
apply H4,
apply is_prop.elim,
end
definition π3S2 : πg[3] (S 2) ≃g gℤ :=
begin
refine _ ⬝g πnSn 3, symmetry, rexact πnS3_eq_πnS2 0
end
end sphere
|
0d21d3396cab30d877258d9832e4beff054e36ee | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/linear_algebra/affine_space/independent.lean | b181b043a3cc7de4a6589ce817504343f773bb0c | [
"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 | 31,034 | 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.finset.sort
import data.fin.vec_notation
import linear_algebra.affine_space.combination
import linear_algebra.affine_space.affine_equiv
import linear_algebra.basis
/-!
# Affine independence
This file defines affinely independent families of points.
## Main definitions
* `affine_independent` defines affinely independent families of points
as those where no nontrivial weighted subtraction is `0`. This is
proved equivalent to two other formulations: linear independence of
the results of subtracting a base point in the family from the other
points in the family, or any equal affine combinations having the
same weights. A bundled type `simplex` is provided for finite
affinely independent families of points, with an abbreviation
`triangle` for the case of three points.
## References
* https://en.wikipedia.org/wiki/Affine_space
-/
noncomputable theory
open_locale big_operators classical affine
open function
section affine_independent
variables (k : Type*) {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V]
variables [affine_space V P] {ι : Type*}
include V
/-- An indexed family is said to be affinely independent if no
nontrivial weighted subtractions (where the sum of weights is 0) are
0. -/
def affine_independent (p : ι → P) : Prop :=
∀ (s : finset ι) (w : ι → k), ∑ i in s, w i = 0 → s.weighted_vsub p w = (0:V) → ∀ i ∈ s, w i = 0
/-- The definition of `affine_independent`. -/
lemma affine_independent_def (p : ι → P) :
affine_independent k p ↔
∀ (s : finset ι) (w : ι → k),
∑ i in s, w i = 0 → s.weighted_vsub p w = (0 : V) → ∀ i ∈ s, w i = 0 :=
iff.rfl
/-- A family with at most one point is affinely independent. -/
lemma affine_independent_of_subsingleton [subsingleton ι] (p : ι → P) :
affine_independent k p :=
λ s w h hs i hi, fintype.eq_of_subsingleton_of_sum_eq h i hi
/-- A family indexed by a `fintype` is affinely independent if and
only if no nontrivial weighted subtractions over `finset.univ` (where
the sum of the weights is 0) are 0. -/
lemma affine_independent_iff_of_fintype [fintype ι] (p : ι → P) :
affine_independent k p ↔
∀ w : ι → k, ∑ i, w i = 0 → finset.univ.weighted_vsub p w = (0 : V) → ∀ i, w i = 0 :=
begin
split,
{ exact λ h w hw hs i, h finset.univ w hw hs i (finset.mem_univ _) },
{ intros h s w hw hs i hi,
rw finset.weighted_vsub_indicator_subset _ _ (finset.subset_univ s) at hs,
rw set.sum_indicator_subset _ (finset.subset_univ s) at hw,
replace h := h ((↑s : set ι).indicator w) hw hs i,
simpa [hi] using h }
end
/-- A family is affinely independent if and only if the differences
from a base point in that family are linearly independent. -/
lemma affine_independent_iff_linear_independent_vsub (p : ι → P) (i1 : ι) :
affine_independent k p ↔ linear_independent k (λ i : {x // x ≠ i1}, (p i -ᵥ p i1 : V)) :=
begin
split,
{ intro h,
rw linear_independent_iff',
intros s g hg i hi,
set f : ι → k := λ x, if hx : x = i1 then -∑ y in s, g y else g ⟨x, hx⟩ with hfdef,
let s2 : finset ι := insert i1 (s.map (embedding.subtype _)),
have hfg : ∀ x : {x // x ≠ i1}, g x = f x,
{ intro x,
rw hfdef,
dsimp only [],
erw [dif_neg x.property, subtype.coe_eta] },
rw hfg,
have hf : ∑ ι in s2, f ι = 0,
{ rw [finset.sum_insert (finset.not_mem_map_subtype_of_not_property s (not_not.2 rfl)),
finset.sum_subtype_map_embedding (λ x hx, (hfg x).symm)],
rw hfdef,
dsimp only [],
rw dif_pos rfl,
exact neg_add_self _ },
have hs2 : s2.weighted_vsub p f = (0:V),
{ set f2 : ι → V := λ x, f x • (p x -ᵥ p i1) with hf2def,
set g2 : {x // x ≠ i1} → V := λ x, g x • (p x -ᵥ p i1) with hg2def,
have hf2g2 : ∀ x : {x // x ≠ i1}, f2 x = g2 x,
{ simp_rw [hf2def, hg2def, hfg],
exact λ x, rfl },
rw [finset.weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero s2 f p hf (p i1),
finset.weighted_vsub_of_point_insert, finset.weighted_vsub_of_point_apply,
finset.sum_subtype_map_embedding (λ x hx, hf2g2 x)],
exact hg },
exact h s2 f hf hs2 i (finset.mem_insert_of_mem (finset.mem_map.2 ⟨i, hi, rfl⟩)) },
{ intro h,
rw linear_independent_iff' at h,
intros s w hw hs i hi,
rw [finset.weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero s w p hw (p i1),
←s.weighted_vsub_of_point_erase w p i1, finset.weighted_vsub_of_point_apply] at hs,
let f : ι → V := λ i, w i • (p i -ᵥ p i1),
have hs2 : ∑ i in (s.erase i1).subtype (λ i, i ≠ i1), f i = 0,
{ rw [←hs],
convert finset.sum_subtype_of_mem f (λ x, finset.ne_of_mem_erase) },
have h2 := h ((s.erase i1).subtype (λ i, i ≠ i1)) (λ x, w x) hs2,
simp_rw [finset.mem_subtype] at h2,
have h2b : ∀ i ∈ s, i ≠ i1 → w i = 0 :=
λ i his hi, h2 ⟨i, hi⟩ (finset.mem_erase_of_ne_of_mem hi his),
exact finset.eq_zero_of_sum_eq_zero hw h2b i hi }
end
/-- A set is affinely independent if and only if the differences from
a base point in that set are linearly independent. -/
lemma affine_independent_set_iff_linear_independent_vsub {s : set P} {p₁ : P} (hp₁ : p₁ ∈ s) :
affine_independent k (λ p, p : s → P) ↔
linear_independent k (λ v, v : (λ p, (p -ᵥ p₁ : V)) '' (s \ {p₁}) → V) :=
begin
rw affine_independent_iff_linear_independent_vsub k (λ p, p : s → P) ⟨p₁, hp₁⟩,
split,
{ intro h,
have hv : ∀ v : (λ p, (p -ᵥ p₁ : V)) '' (s \ {p₁}), (v : V) +ᵥ p₁ ∈ s \ {p₁} :=
λ v, (vsub_left_injective p₁).mem_set_image.1
((vadd_vsub (v : V) p₁).symm ▸ v.property),
let f : (λ p : P, (p -ᵥ p₁ : V)) '' (s \ {p₁}) → {x : s // x ≠ ⟨p₁, hp₁⟩} :=
λ x, ⟨⟨(x : V) +ᵥ p₁, set.mem_of_mem_diff (hv x)⟩,
λ hx, set.not_mem_of_mem_diff (hv x) (subtype.ext_iff.1 hx)⟩,
convert h.comp f
(λ x1 x2 hx, (subtype.ext (vadd_right_cancel p₁ (subtype.ext_iff.1 (subtype.ext_iff.1 hx))))),
ext v,
exact (vadd_vsub (v : V) p₁).symm },
{ intro h,
let f : {x : s // x ≠ ⟨p₁, hp₁⟩} → (λ p : P, (p -ᵥ p₁ : V)) '' (s \ {p₁}) :=
λ x, ⟨((x : s) : P) -ᵥ p₁, ⟨x, ⟨⟨(x : s).property, λ hx, x.property (subtype.ext hx)⟩, rfl⟩⟩⟩,
convert h.comp f
(λ x1 x2 hx, subtype.ext (subtype.ext (vsub_left_cancel (subtype.ext_iff.1 hx)))) }
end
/-- A set of nonzero vectors is linearly independent if and only if,
given a point `p₁`, the vectors added to `p₁` and `p₁` itself are
affinely independent. -/
lemma linear_independent_set_iff_affine_independent_vadd_union_singleton {s : set V}
(hs : ∀ v ∈ s, v ≠ (0 : V)) (p₁ : P) : linear_independent k (λ v, v : s → V) ↔
affine_independent k (λ p, p : {p₁} ∪ ((λ v, v +ᵥ p₁) '' s) → P) :=
begin
rw affine_independent_set_iff_linear_independent_vsub k
(set.mem_union_left _ (set.mem_singleton p₁)),
have h : (λ p, (p -ᵥ p₁ : V)) '' (({p₁} ∪ (λ v, v +ᵥ p₁) '' s) \ {p₁}) = s,
{ simp_rw [set.union_diff_left, set.image_diff (vsub_left_injective p₁), set.image_image,
set.image_singleton, vsub_self, vadd_vsub, set.image_id'],
exact set.diff_singleton_eq_self (λ h, hs 0 h rfl) },
rw h
end
/-- A family is affinely independent if and only if any affine
combinations (with sum of weights 1) that evaluate to the same point
have equal `set.indicator`. -/
lemma affine_independent_iff_indicator_eq_of_affine_combination_eq (p : ι → P) :
affine_independent k p ↔ ∀ (s1 s2 : finset ι) (w1 w2 : ι → k), ∑ i in s1, w1 i = 1 →
∑ i in s2, w2 i = 1 → s1.affine_combination p w1 = s2.affine_combination p w2 →
set.indicator ↑s1 w1 = set.indicator ↑s2 w2 :=
begin
split,
{ intros ha s1 s2 w1 w2 hw1 hw2 heq,
ext i,
by_cases hi : i ∈ (s1 ∪ s2),
{ rw ←sub_eq_zero,
rw set.sum_indicator_subset _ (finset.subset_union_left s1 s2) at hw1,
rw set.sum_indicator_subset _ (finset.subset_union_right s1 s2) at hw2,
have hws : ∑ i in s1 ∪ s2, (set.indicator ↑s1 w1 - set.indicator ↑s2 w2) i = 0,
{ simp [hw1, hw2] },
rw [finset.affine_combination_indicator_subset _ _ (finset.subset_union_left s1 s2),
finset.affine_combination_indicator_subset _ _ (finset.subset_union_right s1 s2),
←@vsub_eq_zero_iff_eq V, finset.affine_combination_vsub] at heq,
exact ha (s1 ∪ s2) (set.indicator ↑s1 w1 - set.indicator ↑s2 w2) hws heq i hi },
{ rw [←finset.mem_coe, finset.coe_union] at hi,
simp [mt (set.mem_union_left ↑s2) hi, mt (set.mem_union_right ↑s1) hi] } },
{ intros ha s w hw hs i0 hi0,
let w1 : ι → k := function.update (function.const ι 0) i0 1,
have hw1 : ∑ i in s, w1 i = 1,
{ rw [finset.sum_update_of_mem hi0, finset.sum_const_zero, add_zero] },
have hw1s : s.affine_combination p w1 = p i0 :=
s.affine_combination_of_eq_one_of_eq_zero w1 p hi0 (function.update_same _ _ _)
(λ _ _ hne, function.update_noteq hne _ _),
let w2 := w + w1,
have hw2 : ∑ i in s, w2 i = 1,
{ simp [w2, finset.sum_add_distrib, hw, hw1] },
have hw2s : s.affine_combination p w2 = p i0,
{ simp [w2, ←finset.weighted_vsub_vadd_affine_combination, hs, hw1s] },
replace ha := ha s s w2 w1 hw2 hw1 (hw1s.symm ▸ hw2s),
have hws : w2 i0 - w1 i0 = 0,
{ rw ←finset.mem_coe at hi0,
rw [←set.indicator_of_mem hi0 w2, ←set.indicator_of_mem hi0 w1, ha, sub_self] },
simpa [w2] using hws }
end
variables {k}
/-- If we single out one member of an affine-independent family of points and affinely transport
all others along the line joining them to this member, the resulting new family of points is affine-
independent.
This is the affine version of `linear_independent.units_smul`. -/
lemma affine_independent.units_line_map
{p : ι → P} (hp : affine_independent k p) (j : ι) (w : ι → units k) :
affine_independent k (λ i, affine_map.line_map (p j) (p i) (w i : k)) :=
begin
rw affine_independent_iff_linear_independent_vsub k _ j at hp ⊢,
simp only [affine_map.line_map_vsub_left, affine_map.coe_const, affine_map.line_map_same],
exact hp.units_smul (λ i, w i),
end
lemma affine_independent.indicator_eq_of_affine_combination_eq {p : ι → P}
(ha : affine_independent k p) (s₁ s₂ : finset ι) (w₁ w₂ : ι → k) (hw₁ : ∑ i in s₁, w₁ i = 1)
(hw₂ : ∑ i in s₂, w₂ i = 1) (h : s₁.affine_combination p w₁ = s₂.affine_combination p w₂) :
set.indicator ↑s₁ w₁ = set.indicator ↑s₂ w₂ :=
(affine_independent_iff_indicator_eq_of_affine_combination_eq k p).1 ha s₁ s₂ w₁ w₂ hw₁ hw₂ h
/-- An affinely independent family is injective, if the underlying
ring is nontrivial. -/
protected lemma affine_independent.injective [nontrivial k] {p : ι → P}
(ha : affine_independent k p) :
function.injective p :=
begin
intros i j hij,
rw affine_independent_iff_linear_independent_vsub _ _ j at ha,
by_contra hij',
exact ha.ne_zero ⟨i, hij'⟩ (vsub_eq_zero_iff_eq.mpr hij)
end
/-- If a family is affinely independent, so is any subfamily given by
composition of an embedding into index type with the original
family. -/
lemma affine_independent.comp_embedding {ι2 : Type*} (f : ι2 ↪ ι) {p : ι → P}
(ha : affine_independent k p) : affine_independent k (p ∘ f) :=
begin
intros fs w hw hs i0 hi0,
let fs' := fs.map f,
let w' := λ i, if h : ∃ i2, f i2 = i then w h.some else 0,
have hw' : ∀ i2 : ι2, w' (f i2) = w i2,
{ intro i2,
have h : ∃ i : ι2, f i = f i2 := ⟨i2, rfl⟩,
have hs : h.some = i2 := f.injective h.some_spec,
simp_rw [w', dif_pos h, hs] },
have hw's : ∑ i in fs', w' i = 0,
{ rw [←hw, finset.sum_map],
simp [hw'] },
have hs' : fs'.weighted_vsub p w' = (0:V),
{ rw [←hs, finset.weighted_vsub_map],
congr' with i,
simp [hw'] },
rw [←ha fs' w' hw's hs' (f i0) ((finset.mem_map' _).2 hi0), hw']
end
/-- If a family is affinely independent, so is any subfamily indexed
by a subtype of the index type. -/
protected lemma affine_independent.subtype {p : ι → P}
(ha : affine_independent k p) (s : set ι) : affine_independent k (λ i : s, p i) :=
ha.comp_embedding (embedding.subtype _)
/-- If an indexed family of points is affinely independent, so is the
corresponding set of points. -/
protected lemma affine_independent.range {p : ι → P} (ha : affine_independent k p) :
affine_independent k (λ x, x : set.range p → P) :=
begin
let f : set.range p → ι := λ x, x.property.some,
have hf : ∀ x, p (f x) = x := λ x, x.property.some_spec,
let fe : set.range p ↪ ι := ⟨f, λ x₁ x₂ he, subtype.ext (hf x₁ ▸ hf x₂ ▸ he ▸ rfl)⟩,
convert ha.comp_embedding fe,
ext,
simp [hf]
end
lemma affine_independent_equiv {ι' : Type*} (e : ι ≃ ι') {p : ι' → P} :
affine_independent k (p ∘ e) ↔ affine_independent k p :=
begin
refine ⟨_, affine_independent.comp_embedding e.to_embedding⟩,
intros h,
have : p = p ∘ e ∘ e.symm.to_embedding, { ext, simp, },
rw this,
exact h.comp_embedding e.symm.to_embedding,
end
/-- If a set of points is affinely independent, so is any subset. -/
protected lemma affine_independent.mono {s t : set P}
(ha : affine_independent k (λ x, x : t → P)) (hs : s ⊆ t) :
affine_independent k (λ x, x : s → P) :=
ha.comp_embedding (s.embedding_of_subset t hs)
/-- If the range of an injective indexed family of points is affinely
independent, so is that family. -/
lemma affine_independent.of_set_of_injective {p : ι → P}
(ha : affine_independent k (λ x, x : set.range p → P)) (hi : function.injective p) :
affine_independent k p :=
ha.comp_embedding
(⟨λ i, ⟨p i, set.mem_range_self _⟩, λ x y h, hi (subtype.mk_eq_mk.1 h)⟩ : ι ↪ set.range p)
section composition
variables {V₂ P₂ : Type*} [add_comm_group V₂] [module k V₂] [affine_space V₂ P₂]
include V₂
/-- If the image of a family of points in affine space under an affine transformation is affine-
independent, then the original family of points is also affine-independent. -/
lemma affine_independent.of_comp {p : ι → P} (f : P →ᵃ[k] P₂) (hai : affine_independent k (f ∘ p)) :
affine_independent k p :=
begin
cases is_empty_or_nonempty ι with h h, { haveI := h, apply affine_independent_of_subsingleton, },
obtain ⟨i⟩ := h,
rw affine_independent_iff_linear_independent_vsub k p i,
simp_rw [affine_independent_iff_linear_independent_vsub k (f ∘ p) i, function.comp_app,
← f.linear_map_vsub] at hai,
exact linear_independent.of_comp f.linear hai,
end
/-- The image of a family of points in affine space, under an injective affine transformation, is
affine-independent. -/
lemma affine_independent.map'
{p : ι → P} (hai : affine_independent k p) (f : P →ᵃ[k] P₂) (hf : function.injective f) :
affine_independent k (f ∘ p) :=
begin
cases is_empty_or_nonempty ι with h h, { haveI := h, apply affine_independent_of_subsingleton, },
obtain ⟨i⟩ := h,
rw affine_independent_iff_linear_independent_vsub k p i at hai,
simp_rw [affine_independent_iff_linear_independent_vsub k (f ∘ p) i, function.comp_app,
← f.linear_map_vsub],
have hf' : f.linear.ker = ⊥, { rwa [linear_map.ker_eq_bot, f.injective_iff_linear_injective], },
exact linear_independent.map' hai f.linear hf',
end
/-- Injective affine maps preserve affine independence. -/
lemma affine_map.affine_independent_iff {p : ι → P} (f : P →ᵃ[k] P₂) (hf : function.injective f) :
affine_independent k (f ∘ p) ↔ affine_independent k p :=
⟨affine_independent.of_comp f, λ hai, affine_independent.map' hai f hf⟩
/-- Affine equivalences preserve affine independence of families of points. -/
lemma affine_equiv.affine_independent_iff {p : ι → P} (e : P ≃ᵃ[k] P₂) :
affine_independent k (e ∘ p) ↔ affine_independent k p :=
e.to_affine_map.affine_independent_iff e.to_equiv.injective
/-- Affine equivalences preserve affine independence of subsets. -/
lemma affine_equiv.affine_independent_set_of_eq_iff {s : set P} (e : P ≃ᵃ[k] P₂) :
affine_independent k (coe : (e '' s) → P₂) ↔ affine_independent k (coe : s → P) :=
begin
have : e ∘ (coe : s → P) = (coe : e '' s → P₂) ∘ ((e : P ≃ P₂).image s) := rfl,
rw [← e.affine_independent_iff, this, affine_independent_equiv],
end
end composition
/-- If a family is affinely independent, and the spans of points
indexed by two subsets of the index type have a point in common, those
subsets of the index type have an element in common, if the underlying
ring is nontrivial. -/
lemma affine_independent.exists_mem_inter_of_exists_mem_inter_affine_span [nontrivial k]
{p : ι → P} (ha : affine_independent k p) {s1 s2 : set ι} {p0 : P}
(hp0s1 : p0 ∈ affine_span k (p '' s1)) (hp0s2 : p0 ∈ affine_span k (p '' s2)):
∃ (i : ι), i ∈ s1 ∩ s2 :=
begin
rw set.image_eq_range at hp0s1 hp0s2,
rw [mem_affine_span_iff_eq_affine_combination,
←finset.eq_affine_combination_subset_iff_eq_affine_combination_subtype] at hp0s1 hp0s2,
rcases hp0s1 with ⟨fs1, hfs1, w1, hw1, hp0s1⟩,
rcases hp0s2 with ⟨fs2, hfs2, w2, hw2, hp0s2⟩,
rw affine_independent_iff_indicator_eq_of_affine_combination_eq at ha,
replace ha := ha fs1 fs2 w1 w2 hw1 hw2 (hp0s1 ▸ hp0s2),
have hnz : ∑ i in fs1, w1 i ≠ 0 := hw1.symm ▸ one_ne_zero,
rcases finset.exists_ne_zero_of_sum_ne_zero hnz with ⟨i, hifs1, hinz⟩,
simp_rw [←set.indicator_of_mem (finset.mem_coe.2 hifs1) w1, ha] at hinz,
use [i, hfs1 hifs1, hfs2 (set.mem_of_indicator_ne_zero hinz)]
end
/-- If a family is affinely independent, the spans of points indexed
by disjoint subsets of the index type are disjoint, if the underlying
ring is nontrivial. -/
lemma affine_independent.affine_span_disjoint_of_disjoint [nontrivial k] {p : ι → P}
(ha : affine_independent k p) {s1 s2 : set ι} (hd : s1 ∩ s2 = ∅) :
(affine_span k (p '' s1) : set P) ∩ affine_span k (p '' s2) = ∅ :=
begin
by_contradiction hne,
change (affine_span k (p '' s1) : set P) ∩ affine_span k (p '' s2) ≠ ∅ at hne,
rw set.ne_empty_iff_nonempty at hne,
rcases hne with ⟨p0, hp0s1, hp0s2⟩,
cases ha.exists_mem_inter_of_exists_mem_inter_affine_span hp0s1 hp0s2 with i hi,
exact set.not_mem_empty i (hd ▸ hi)
end
/-- If a family is affinely independent, a point in the family is in
the span of some of the points given by a subset of the index type if
and only if that point's index is in the subset, if the underlying
ring is nontrivial. -/
@[simp] protected lemma affine_independent.mem_affine_span_iff [nontrivial k] {p : ι → P}
(ha : affine_independent k p) (i : ι) (s : set ι) :
p i ∈ affine_span k (p '' s) ↔ i ∈ s :=
begin
split,
{ intro hs,
have h := affine_independent.exists_mem_inter_of_exists_mem_inter_affine_span
ha hs (mem_affine_span k (set.mem_image_of_mem _ (set.mem_singleton _))),
rwa [←set.nonempty_def, set.inter_singleton_nonempty] at h },
{ exact λ h, mem_affine_span k (set.mem_image_of_mem p h) }
end
/-- If a family is affinely independent, a point in the family is not
in the affine span of the other points, if the underlying ring is
nontrivial. -/
lemma affine_independent.not_mem_affine_span_diff [nontrivial k] {p : ι → P}
(ha : affine_independent k p) (i : ι) (s : set ι) :
p i ∉ affine_span k (p '' (s \ {i})) :=
by simp [ha]
lemma exists_nontrivial_relation_sum_zero_of_not_affine_ind
{t : finset V} (h : ¬ affine_independent k (coe : t → V)) :
∃ f : V → k, ∑ e in t, f e • e = 0 ∧ ∑ e in t, f e = 0 ∧ ∃ x ∈ t, f x ≠ 0 :=
begin
classical,
rw affine_independent_iff_of_fintype at h,
simp only [exists_prop, not_forall] at h,
obtain ⟨w, hw, hwt, i, hi⟩ := h,
simp only [finset.weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero _ w (coe : t → V) hw 0,
vsub_eq_sub, finset.weighted_vsub_of_point_apply, sub_zero] at hwt,
let f : Π (x : V), x ∈ t → k := λ x hx, w ⟨x, hx⟩,
refine ⟨λ x, if hx : x ∈ t then f x hx else (0 : k), _, _, by { use i, simp [hi, f], }⟩,
suffices : ∑ (e : V) in t, dite (e ∈ t) (λ hx, (f e hx) • e) (λ hx, 0) = 0,
{ convert this, ext, by_cases hx : x ∈ t; simp [hx], },
all_goals
{ simp only [finset.sum_dite_of_true (λx h, h), subtype.val_eq_coe, finset.mk_coe, f, hwt, hw], },
end
end affine_independent
section division_ring
variables {k : Type*} {V : Type*} {P : Type*} [division_ring k] [add_comm_group V] [module k V]
variables [affine_space V P] {ι : Type*}
include V
/-- An affinely independent set of points can be extended to such a
set that spans the whole space. -/
lemma exists_subset_affine_independent_affine_span_eq_top {s : set P}
(h : affine_independent k (λ p, p : s → P)) :
∃ t : set P, s ⊆ t ∧ affine_independent k (λ p, p : t → P) ∧ affine_span k t = ⊤ :=
begin
rcases s.eq_empty_or_nonempty with rfl | ⟨p₁, hp₁⟩,
{ have p₁ : P := add_torsor.nonempty.some,
let hsv := basis.of_vector_space k V,
have hsvi := hsv.linear_independent,
have hsvt := hsv.span_eq,
rw basis.coe_of_vector_space at hsvi hsvt,
have h0 : ∀ v : V, v ∈ (basis.of_vector_space_index _ _) → v ≠ 0,
{ intros v hv, simpa using hsv.ne_zero ⟨v, hv⟩ },
rw linear_independent_set_iff_affine_independent_vadd_union_singleton k h0 p₁ at hsvi,
exact ⟨{p₁} ∪ (λ v, v +ᵥ p₁) '' _, set.empty_subset _, hsvi,
affine_span_singleton_union_vadd_eq_top_of_span_eq_top p₁ hsvt⟩ },
{ rw affine_independent_set_iff_linear_independent_vsub k hp₁ at h,
let bsv := basis.extend h,
have hsvi := bsv.linear_independent,
have hsvt := bsv.span_eq,
rw basis.coe_extend at hsvi hsvt,
have hsv := h.subset_extend (set.subset_univ _),
have h0 : ∀ v : V, v ∈ (h.extend _) → v ≠ 0,
{ intros v hv, simpa using bsv.ne_zero ⟨v, hv⟩ },
rw linear_independent_set_iff_affine_independent_vadd_union_singleton k h0 p₁ at hsvi,
refine ⟨{p₁} ∪ (λ v, v +ᵥ p₁) '' h.extend (set.subset_univ _), _, _⟩,
{ refine set.subset.trans _ (set.union_subset_union_right _ (set.image_subset _ hsv)),
simp [set.image_image] },
{ use [hsvi, affine_span_singleton_union_vadd_eq_top_of_span_eq_top p₁ hsvt] } }
end
variables (k V)
lemma exists_affine_independent (s : set P) :
∃ t ⊆ s, affine_span k t = affine_span k s ∧ affine_independent k (coe : t → P) :=
begin
rcases s.eq_empty_or_nonempty with rfl | ⟨p, hp⟩,
{ exact ⟨∅, set.empty_subset ∅, rfl, affine_independent_of_subsingleton k _⟩, },
obtain ⟨b, hb₁, hb₂, hb₃⟩ := exists_linear_independent k ((equiv.vadd_const p).symm '' s),
have hb₀ : ∀ (v : V), v ∈ b → v ≠ 0, { exact λ v hv, hb₃.ne_zero (⟨v, hv⟩ : b), },
rw linear_independent_set_iff_affine_independent_vadd_union_singleton k hb₀ p at hb₃,
refine ⟨{p} ∪ (equiv.vadd_const p) '' b, _, _, hb₃⟩,
{ apply set.union_subset (set.singleton_subset_iff.mpr hp),
rwa ← (equiv.vadd_const p).subset_image' b s, },
{ rw [equiv.coe_vadd_const_symm, ← vector_span_eq_span_vsub_set_right k hp] at hb₂,
apply affine_subspace.ext_of_direction_eq,
{ have : submodule.span k b = submodule.span k (insert 0 b), { by simp, },
simp only [direction_affine_span, ← hb₂, equiv.coe_vadd_const, set.singleton_union,
vector_span_eq_span_vsub_set_right k (set.mem_insert p _), this],
congr,
change (equiv.vadd_const p).symm '' insert p ((equiv.vadd_const p) '' b) = _,
rw [set.image_insert_eq, ← set.image_comp],
simp, },
{ use p,
simp only [equiv.coe_vadd_const, set.singleton_union, set.mem_inter_eq, coe_affine_span],
exact ⟨mem_span_points k _ _ (set.mem_insert p _), mem_span_points k _ _ hp⟩, }, },
end
variables (k) {V P}
/-- Two different points are affinely independent. -/
lemma affine_independent_of_ne {p₁ p₂ : P} (h : p₁ ≠ p₂) : affine_independent k ![p₁, p₂] :=
begin
rw affine_independent_iff_linear_independent_vsub k ![p₁, p₂] 0,
let i₁ : {x // x ≠ (0 : fin 2)} := ⟨1, by norm_num⟩,
have he' : ∀ i, i = i₁,
{ rintro ⟨i, hi⟩,
ext,
fin_cases i,
{ simpa using hi } },
haveI : unique {x // x ≠ (0 : fin 2)} := ⟨⟨i₁⟩, he'⟩,
have hz : (![p₁, p₂] ↑(default {x // x ≠ (0 : fin 2)}) -ᵥ ![p₁, p₂] 0 : V) ≠ 0,
{ rw he' (default _), simp, cc },
exact linear_independent_unique _ hz
end
end division_ring
namespace affine
variables (k : Type*) {V : Type*} (P : Type*) [ring k] [add_comm_group V] [module k V]
variables [affine_space V P]
include V
/-- A `simplex k P n` is a collection of `n + 1` affinely
independent points. -/
structure simplex (n : ℕ) :=
(points : fin (n + 1) → P)
(independent : affine_independent k points)
/-- A `triangle k P` is a collection of three affinely independent points. -/
abbreviation triangle := simplex k P 2
namespace simplex
variables {P}
/-- Construct a 0-simplex from a point. -/
def mk_of_point (p : P) : simplex k P 0 :=
⟨λ _, p, affine_independent_of_subsingleton k _⟩
/-- The point in a simplex constructed with `mk_of_point`. -/
@[simp] lemma mk_of_point_points (p : P) (i : fin 1) : (mk_of_point k p).points i = p :=
rfl
instance [inhabited P] : inhabited (simplex k P 0) :=
⟨mk_of_point k $ default P⟩
instance nonempty : nonempty (simplex k P 0) :=
⟨mk_of_point k $ add_torsor.nonempty.some⟩
variables {k V}
/-- Two simplices are equal if they have the same points. -/
@[ext] lemma ext {n : ℕ} {s1 s2 : simplex k P n} (h : ∀ i, s1.points i = s2.points i) :
s1 = s2 :=
begin
cases s1,
cases s2,
congr' with i,
exact h i
end
/-- Two simplices are equal if and only if they have the same points. -/
lemma ext_iff {n : ℕ} (s1 s2 : simplex k P n): s1 = s2 ↔ ∀ i, s1.points i = s2.points i :=
⟨λ h _, h ▸ rfl, ext⟩
/-- A face of a simplex is a simplex with the given subset of
points. -/
def face {n : ℕ} (s : simplex k P n) {fs : finset (fin (n + 1))} {m : ℕ} (h : fs.card = m + 1) :
simplex k P m :=
⟨s.points ∘ fs.order_emb_of_fin h,
s.independent.comp_embedding (fs.order_emb_of_fin h).to_embedding⟩
/-- The points of a face of a simplex are given by `mono_of_fin`. -/
lemma face_points {n : ℕ} (s : simplex k P n) {fs : finset (fin (n + 1))} {m : ℕ}
(h : fs.card = m + 1) (i : fin (m + 1)) :
(s.face h).points i = s.points (fs.order_emb_of_fin h i) :=
rfl
/-- The points of a face of a simplex are given by `mono_of_fin`. -/
lemma face_points' {n : ℕ} (s : simplex k P n) {fs : finset (fin (n + 1))} {m : ℕ}
(h : fs.card = m + 1) : (s.face h).points = s.points ∘ (fs.order_emb_of_fin h) :=
rfl
/-- A single-point face equals the 0-simplex constructed with
`mk_of_point`. -/
@[simp] lemma face_eq_mk_of_point {n : ℕ} (s : simplex k P n) (i : fin (n + 1)) :
s.face (finset.card_singleton i) = mk_of_point k (s.points i) :=
by { ext, simp [face_points] }
/-- The set of points of a face. -/
@[simp] lemma range_face_points {n : ℕ} (s : simplex k P n) {fs : finset (fin (n + 1))}
{m : ℕ} (h : fs.card = m + 1) : set.range (s.face h).points = s.points '' ↑fs :=
by rw [face_points', set.range_comp, finset.range_order_emb_of_fin]
end simplex
end affine
namespace affine
namespace simplex
variables {k : Type*} {V : Type*} {P : Type*} [division_ring k]
[add_comm_group V] [module k V] [affine_space V P]
include V
/-- The centroid of a face of a simplex as the centroid of a subset of
the points. -/
@[simp] lemma face_centroid_eq_centroid {n : ℕ} (s : simplex k P n) {fs : finset (fin (n + 1))}
{m : ℕ} (h : fs.card = m + 1) :
finset.univ.centroid k (s.face h).points = fs.centroid k s.points :=
begin
convert (finset.univ.centroid_map k (fs.order_emb_of_fin h).to_embedding s.points).symm,
rw [← finset.coe_inj, finset.coe_map, finset.coe_univ, set.image_univ],
simp
end
/-- Over a characteristic-zero division ring, the centroids given by
two subsets of the points of a simplex are equal if and only if those
faces are given by the same subset of points. -/
@[simp] lemma centroid_eq_iff [char_zero k] {n : ℕ} (s : simplex k P n)
{fs₁ fs₂ : finset (fin (n + 1))} {m₁ m₂ : ℕ} (h₁ : fs₁.card = m₁ + 1) (h₂ : fs₂.card = m₂ + 1) :
fs₁.centroid k s.points = fs₂.centroid k s.points ↔ fs₁ = fs₂ :=
begin
split,
{ intro h,
rw [finset.centroid_eq_affine_combination_fintype,
finset.centroid_eq_affine_combination_fintype] at h,
have ha := (affine_independent_iff_indicator_eq_of_affine_combination_eq k s.points).1
s.independent _ _ _ _ (fs₁.sum_centroid_weights_indicator_eq_one_of_card_eq_add_one k h₁)
(fs₂.sum_centroid_weights_indicator_eq_one_of_card_eq_add_one k h₂) h,
simp_rw [finset.coe_univ, set.indicator_univ, function.funext_iff,
finset.centroid_weights_indicator_def, finset.centroid_weights, h₁, h₂] at ha,
ext i,
replace ha := ha i,
split,
all_goals
{ intro hi,
by_contradiction hni,
simp [hi, hni] at ha,
norm_cast at ha } },
{ intro h,
have hm : m₁ = m₂,
{ subst h,
simpa [h₁] using h₂ },
subst hm,
congr,
exact h }
end
/-- Over a characteristic-zero division ring, the centroids of two
faces of a simplex are equal if and only if those faces are given by
the same subset of points. -/
lemma face_centroid_eq_iff [char_zero k] {n : ℕ} (s : simplex k P n)
{fs₁ fs₂ : finset (fin (n + 1))} {m₁ m₂ : ℕ} (h₁ : fs₁.card = m₁ + 1) (h₂ : fs₂.card = m₂ + 1) :
finset.univ.centroid k (s.face h₁).points = finset.univ.centroid k (s.face h₂).points ↔
fs₁ = fs₂ :=
begin
rw [face_centroid_eq_centroid, face_centroid_eq_centroid],
exact s.centroid_eq_iff h₁ h₂
end
/-- Two simplices with the same points have the same centroid. -/
lemma centroid_eq_of_range_eq {n : ℕ} {s₁ s₂ : simplex k P n}
(h : set.range s₁.points = set.range s₂.points) :
finset.univ.centroid k s₁.points = finset.univ.centroid k s₂.points :=
begin
rw [←set.image_univ, ←set.image_univ, ←finset.coe_univ] at h,
exact finset.univ.centroid_eq_of_inj_on_of_image_eq k _
(λ _ _ _ _ he, affine_independent.injective s₁.independent he)
(λ _ _ _ _ he, affine_independent.injective s₂.independent he) h
end
end simplex
end affine
|
6b677eb588b8933c4b771895675f9f52b179eb77 | 2c096fdfecf64e46ea7bc6ce5521f142b5926864 | /src/Init/Data/Char/Basic.lean | 970af62506f770b68ff2dd13448c31089b7e5702 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | Kha/lean4 | 1005785d2c8797ae266a303968848e5f6ce2fe87 | b99e11346948023cd6c29d248cd8f3e3fb3474cf | refs/heads/master | 1,693,355,498,027 | 1,669,080,461,000 | 1,669,113,138,000 | 184,748,176 | 0 | 0 | Apache-2.0 | 1,665,995,520,000 | 1,556,884,930,000 | Lean | UTF-8 | Lean | false | false | 3,081 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import Init.Data.UInt
/-- Determines if the given integer is a valid [Unicode scalar value](https://www.unicode.org/glossary/#unicode_scalar_value).
Note that values in `[0xd800, 0xdfff]` are reserved for [UTF-16 surrogate pairs](https://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates).
-/
@[inline, reducible] def isValidChar (n : UInt32) : Prop :=
n < 0xd800 ∨ (0xdfff < n ∧ n < 0x110000)
namespace Char
protected def lt (a b : Char) : Prop := a.val < b.val
protected def le (a b : Char) : Prop := a.val ≤ b.val
instance : LT Char := ⟨Char.lt⟩
instance : LE Char := ⟨Char.le⟩
instance (a b : Char) : Decidable (a < b) :=
UInt32.decLt _ _
instance (a b : Char) : Decidable (a ≤ b) :=
UInt32.decLe _ _
/-- Determines if the given nat is a valid [Unicode scalar value](https://www.unicode.org/glossary/#unicode_scalar_value).-/
abbrev isValidCharNat (n : Nat) : Prop :=
n < 0xd800 ∨ (0xdfff < n ∧ n < 0x110000)
theorem isValidUInt32 (n : Nat) (h : isValidCharNat n) : n < UInt32.size := by
match h with
| Or.inl h =>
apply Nat.lt_trans h
decide
| Or.inr ⟨_, h₂⟩ =>
apply Nat.lt_trans h₂
decide
theorem isValidChar_of_isValidChar_Nat (n : Nat) (h : isValidCharNat n) : isValidChar (UInt32.ofNat' n (isValidUInt32 n h)) :=
match h with
| Or.inl h => Or.inl h
| Or.inr ⟨h₁, h₂⟩ => Or.inr ⟨h₁, h₂⟩
theorem isValidChar_zero : isValidChar 0 :=
Or.inl (by decide)
/-- Underlying unicode code point as a `Nat`. -/
@[inline] def toNat (c : Char) : Nat :=
c.val.toNat
instance : Inhabited Char where
default := 'A'
/-- Is the character a space (U+0020) a tab (U+0009), a carriage return (U+000D) or a newline (U+000A)? -/
def isWhitespace (c : Char) : Bool :=
c = ' ' || c = '\t' || c = '\r' || c = '\n'
/-- Is the character in `ABCDEFGHIJKLMNOPQRSTUVWXYZ`? -/
def isUpper (c : Char) : Bool :=
c.val ≥ 65 && c.val ≤ 90
/-- Is the character in `abcdefghijklmnopqrstuvwxyz`? -/
def isLower (c : Char) : Bool :=
c.val ≥ 97 && c.val ≤ 122
/-- Is the character in `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`? -/
def isAlpha (c : Char) : Bool :=
c.isUpper || c.isLower
/-- Is the character in `0123456789`? -/
def isDigit (c : Char) : Bool :=
c.val ≥ 48 && c.val ≤ 57
/-- Is the character in `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`? -/
def isAlphanum (c : Char) : Bool :=
c.isAlpha || c.isDigit
/-- Convert an upper case character to its lower case character.
Only works on basic latin letters.
-/
def toLower (c : Char) : Char :=
let n := toNat c;
if n >= 65 ∧ n <= 90 then ofNat (n + 32) else c
/-- Convert a lower case character to its upper case character.
Only works on basic latin letters.
-/
def toUpper (c : Char) : Char :=
let n := toNat c;
if n >= 97 ∧ n <= 122 then ofNat (n - 32) else c
end Char
|
caaa0514a60832fdb7ff66e3e065c1ea441a1ba8 | 8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3 | /src/data/int/basic.lean | bcc764eacaaad1b95cfedd91ac36bdc41487ed05 | [
"Apache-2.0"
] | permissive | troyjlee/mathlib | e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5 | 45e7eb8447555247246e3fe91c87066506c14875 | refs/heads/master | 1,689,248,035,046 | 1,629,470,528,000 | 1,629,470,528,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 55,392 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
-/
import algebra.order_functions
import data.nat.pow
/-!
# Basic operations on the integers
This file contains:
* instances on `ℤ`. The stronger one is `int.linear_ordered_comm_ring`.
* some basic lemmas about integers
## Recursors
* `int.rec`: Sign disjunction. Something is true/defined on `ℤ` if it's true/defined for nonnegative
and for negative values.
* `int.bit_cases_on`: Parity disjunction. Something is true/defined on `ℤ` if it's true/defined for
even and for odd values.
* `int.induction_on`: Simple growing induction on positive numbers, plus simple decreasing induction
on negative numbers. Note that this recursor is currently only `Prop`-valued.
* `int.induction_on'`: Simple growing induction for numbers greater than `b`, plus simple decreasing
induction on numbers less than `b`.
-/
open nat
namespace int
instance : inhabited ℤ := ⟨int.zero⟩
instance : nontrivial ℤ :=
⟨⟨0, 1, int.zero_ne_one⟩⟩
instance : comm_ring int :=
{ add := int.add,
add_assoc := int.add_assoc,
zero := int.zero,
zero_add := int.zero_add,
add_zero := int.add_zero,
neg := int.neg,
add_left_neg := int.add_left_neg,
add_comm := int.add_comm,
mul := int.mul,
mul_assoc := int.mul_assoc,
one := int.one,
one_mul := int.one_mul,
mul_one := int.mul_one,
sub := int.sub,
left_distrib := int.distrib_left,
right_distrib := int.distrib_right,
mul_comm := int.mul_comm,
gsmul := (*),
gsmul_zero' := int.zero_mul,
gsmul_succ' := λ n x, by rw [succ_eq_one_add, of_nat_add, int.distrib_right, of_nat_one,
int.one_mul],
gsmul_neg' := λ n x, neg_mul_eq_neg_mul_symm (n.succ : ℤ) x }
/-! ### Extra instances to short-circuit type class resolution -/
-- instance : has_sub int := by apply_instance -- This is in core
instance : add_comm_monoid int := by apply_instance
instance : add_monoid int := by apply_instance
instance : monoid int := by apply_instance
instance : comm_monoid int := by apply_instance
instance : comm_semigroup int := by apply_instance
instance : semigroup int := by apply_instance
instance : add_comm_semigroup int := by apply_instance
instance : add_semigroup int := by apply_instance
instance : comm_semiring int := by apply_instance
instance : semiring int := by apply_instance
instance : ring int := by apply_instance
instance : distrib int := by apply_instance
instance : linear_ordered_comm_ring int :=
{ add_le_add_left := @int.add_le_add_left,
mul_pos := @int.mul_pos,
zero_le_one := le_of_lt int.zero_lt_one,
.. int.comm_ring, .. int.linear_order, .. int.nontrivial }
instance : linear_ordered_add_comm_group int :=
by apply_instance
@[simp] lemma add_neg_one (i : ℤ) : i + -1 = i - 1 := rfl
theorem abs_eq_nat_abs : ∀ a : ℤ, abs a = nat_abs a
| (n : ℕ) := abs_of_nonneg $ coe_zero_le _
| -[1+ n] := abs_of_nonpos $ le_of_lt $ neg_succ_lt_zero _
theorem nat_abs_abs (a : ℤ) : nat_abs (abs a) = nat_abs a :=
by rw [abs_eq_nat_abs]; refl
theorem sign_mul_abs (a : ℤ) : sign a * abs a = a :=
by rw [abs_eq_nat_abs, sign_mul_nat_abs]
@[simp] lemma default_eq_zero : default ℤ = 0 := rfl
meta instance : has_to_format ℤ := ⟨λ z, to_string z⟩
meta instance : has_reflect ℤ := by tactic.mk_has_reflect_instance
attribute [simp] int.coe_nat_add int.coe_nat_mul int.coe_nat_zero int.coe_nat_one int.coe_nat_succ
attribute [simp] int.of_nat_eq_coe int.bodd
@[simp] theorem add_def {a b : ℤ} : int.add a b = a + b := rfl
@[simp] theorem mul_def {a b : ℤ} : int.mul a b = a * b := rfl
@[simp] lemma neg_succ_not_nonneg (n : ℕ) : 0 ≤ -[1+ n] ↔ false :=
by { simp only [not_le, iff_false], exact int.neg_succ_lt_zero n, }
@[simp] lemma neg_succ_not_pos (n : ℕ) : 0 < -[1+ n] ↔ false :=
by simp only [not_lt, iff_false]
@[simp] lemma neg_succ_sub_one (n : ℕ) : -[1+ n] - 1 = -[1+ (n+1)] := rfl
@[simp] theorem coe_nat_mul_neg_succ (m n : ℕ) : (m : ℤ) * -[1+ n] = -(m * succ n) := rfl
@[simp] theorem neg_succ_mul_coe_nat (m n : ℕ) : -[1+ m] * n = -(succ m * n) := rfl
@[simp] theorem neg_succ_mul_neg_succ (m n : ℕ) : -[1+ m] * -[1+ n] = succ m * succ n := rfl
@[simp, norm_cast]
theorem coe_nat_le {m n : ℕ} : (↑m : ℤ) ≤ ↑n ↔ m ≤ n := coe_nat_le_coe_nat_iff m n
@[simp, norm_cast]
theorem coe_nat_lt {m n : ℕ} : (↑m : ℤ) < ↑n ↔ m < n := coe_nat_lt_coe_nat_iff m n
@[simp, norm_cast]
theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n := int.coe_nat_eq_coe_nat_iff m n
@[simp] theorem coe_nat_pos {n : ℕ} : (0 : ℤ) < n ↔ 0 < n :=
by rw [← int.coe_nat_zero, coe_nat_lt]
@[simp] theorem coe_nat_eq_zero {n : ℕ} : (n : ℤ) = 0 ↔ n = 0 :=
by rw [← int.coe_nat_zero, coe_nat_inj']
theorem coe_nat_ne_zero {n : ℕ} : (n : ℤ) ≠ 0 ↔ n ≠ 0 :=
not_congr coe_nat_eq_zero
@[simp] lemma coe_nat_nonneg (n : ℕ) : 0 ≤ (n : ℤ) := coe_nat_le.2 (nat.zero_le _)
lemma coe_nat_ne_zero_iff_pos {n : ℕ} : (n : ℤ) ≠ 0 ↔ 0 < n :=
⟨λ h, nat.pos_of_ne_zero (coe_nat_ne_zero.1 h),
λ h, (ne_of_lt (coe_nat_lt.2 h)).symm⟩
lemma coe_nat_succ_pos (n : ℕ) : 0 < (n.succ : ℤ) := int.coe_nat_pos.2 (succ_pos n)
@[simp, norm_cast] theorem coe_nat_abs (n : ℕ) : abs (n : ℤ) = n :=
abs_of_nonneg (coe_nat_nonneg n)
/-! ### succ and pred -/
/-- Immediate successor of an integer: `succ n = n + 1` -/
def succ (a : ℤ) := a + 1
/-- Immediate predecessor of an integer: `pred n = n - 1` -/
def pred (a : ℤ) := a - 1
theorem nat_succ_eq_int_succ (n : ℕ) : (nat.succ n : ℤ) = int.succ n := rfl
theorem pred_succ (a : ℤ) : pred (succ a) = a := add_sub_cancel _ _
theorem succ_pred (a : ℤ) : succ (pred a) = a := sub_add_cancel _ _
theorem neg_succ (a : ℤ) : -succ a = pred (-a) := neg_add _ _
theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a :=
by rw [neg_succ, succ_pred]
theorem neg_pred (a : ℤ) : -pred a = succ (-a) :=
by rw [eq_neg_of_eq_neg (neg_succ (-a)).symm, neg_neg]
theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a :=
by rw [neg_pred, pred_succ]
theorem pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n
theorem neg_nat_succ (n : ℕ) : -(nat.succ n : ℤ) = pred (-n) := neg_succ n
theorem succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := succ_neg_succ n
theorem lt_succ_self (a : ℤ) : a < succ a :=
lt_add_of_pos_right _ zero_lt_one
theorem pred_self_lt (a : ℤ) : pred a < a :=
sub_lt_self _ zero_lt_one
theorem add_one_le_iff {a b : ℤ} : a + 1 ≤ b ↔ a < b := iff.rfl
theorem lt_add_one_iff {a b : ℤ} : a < b + 1 ↔ a ≤ b :=
add_le_add_iff_right _
@[simp] lemma succ_coe_nat_pos (n : ℕ) : 0 < (n : ℤ) + 1 :=
lt_add_one_iff.mpr (by simp)
@[norm_cast] lemma coe_pred_of_pos {n : ℕ} (h : 0 < n) : ((n - 1 : ℕ) : ℤ) = (n : ℤ) - 1 :=
by { cases n, cases h, simp, }
lemma le_add_one {a b : ℤ} (h : a ≤ b) : a ≤ b + 1 :=
le_of_lt (int.lt_add_one_iff.mpr h)
theorem sub_one_lt_iff {a b : ℤ} : a - 1 < b ↔ a ≤ b :=
sub_lt_iff_lt_add.trans lt_add_one_iff
theorem le_sub_one_iff {a b : ℤ} : a ≤ b - 1 ↔ a < b :=
le_sub_iff_add_le
@[simp] lemma eq_zero_iff_abs_lt_one {a : ℤ} : abs a < 1 ↔ a = 0 :=
⟨λ a0, let ⟨hn, hp⟩ := abs_lt.mp a0 in (le_of_lt_add_one (by exact hp)).antisymm hn,
λ a0, (abs_eq_zero.mpr a0).le.trans_lt zero_lt_one⟩
@[elab_as_eliminator] protected lemma induction_on {p : ℤ → Prop}
(i : ℤ) (hz : p 0) (hp : ∀ i : ℕ, p i → p (i + 1)) (hn : ∀ i : ℕ, p (-i) → p (-i - 1)) : p i :=
begin
induction i,
{ induction i,
{ exact hz },
{ exact hp _ i_ih } },
{ have : ∀ n:ℕ, p (- n),
{ intro n, induction n,
{ simp [hz] },
{ convert hn _ n_ih using 1, simp [sub_eq_neg_add] } },
exact this (i + 1) }
end
/-- Inductively define a function on `ℤ` by defining it at `b`, for the `succ` of a number greater
than `b`, and the `pred` of a number less than `b`. -/
protected def induction_on' {C : ℤ → Sort*} (z : ℤ) (b : ℤ) :
C b → (∀ k, b ≤ k → C k → C (k + 1)) → (∀ k ≤ b, C k → C (k - 1)) → C z :=
λ H0 Hs Hp,
begin
rw ←sub_add_cancel z b,
induction (z - b) with n n,
{ induction n with n ih, { rwa [of_nat_zero, zero_add] },
rw [of_nat_succ, add_assoc, add_comm 1 b, ←add_assoc],
exact Hs _ (le_add_of_nonneg_left (of_nat_nonneg _)) ih },
{ induction n with n ih,
{ rw [neg_succ_of_nat_eq, ←of_nat_eq_coe, of_nat_zero, zero_add, neg_add_eq_sub],
exact Hp _ (le_refl _) H0 },
{ rw [neg_succ_of_nat_coe', nat.succ_eq_add_one, ←neg_succ_of_nat_coe, sub_add_eq_add_sub],
exact Hp _ (le_of_lt (add_lt_of_neg_of_le (neg_succ_lt_zero _) (le_refl _))) ih } }
end
/-! ### nat abs -/
attribute [simp] nat_abs nat_abs_of_nat nat_abs_zero nat_abs_one
theorem nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b :=
begin
have : ∀ (a b : ℕ), nat_abs (sub_nat_nat a (nat.succ b)) ≤ nat.succ (a + b),
{ refine (λ a b : ℕ, sub_nat_nat_elim a b.succ
(λ m n i, n = b.succ → nat_abs i ≤ (m + b).succ) _ _ rfl);
intros i n e,
{ subst e, rw [add_comm _ i, add_assoc],
exact nat.le_add_right i (b.succ + b).succ },
{ apply succ_le_succ,
rw [← succ.inj e, ← add_assoc, add_comm],
apply nat.le_add_right } },
cases a; cases b with b b; simp [nat_abs, nat.succ_add];
try {refl}; [skip, rw add_comm a b]; apply this
end
lemma nat_abs_sub_le (a b : ℤ) : nat_abs (a - b) ≤ nat_abs a + nat_abs b :=
by { rw [sub_eq_add_neg, ← int.nat_abs_neg b], apply nat_abs_add_le }
theorem nat_abs_neg_of_nat (n : ℕ) : nat_abs (neg_of_nat n) = n :=
by cases n; refl
theorem nat_abs_mul (a b : ℤ) : nat_abs (a * b) = (nat_abs a) * (nat_abs b) :=
by cases a; cases b;
simp only [← int.mul_def, int.mul, nat_abs_neg_of_nat, eq_self_iff_true, int.nat_abs]
lemma nat_abs_mul_nat_abs_eq {a b : ℤ} {c : ℕ} (h : a * b = (c : ℤ)) :
a.nat_abs * b.nat_abs = c :=
by rw [← nat_abs_mul, h, nat_abs_of_nat]
@[simp] lemma nat_abs_mul_self' (a : ℤ) : (nat_abs a * nat_abs a : ℤ) = a * a :=
by rw [← int.coe_nat_mul, nat_abs_mul_self]
theorem neg_succ_of_nat_eq' (m : ℕ) : -[1+ m] = -m - 1 :=
by simp [neg_succ_of_nat_eq, sub_eq_neg_add]
lemma nat_abs_ne_zero_of_ne_zero {z : ℤ} (hz : z ≠ 0) : z.nat_abs ≠ 0 :=
λ h, hz $ int.eq_zero_of_nat_abs_eq_zero h
@[simp] lemma nat_abs_eq_zero {a : ℤ} : a.nat_abs = 0 ↔ a = 0 :=
⟨int.eq_zero_of_nat_abs_eq_zero, λ h, h.symm ▸ rfl⟩
lemma nat_abs_ne_zero {a : ℤ} : a.nat_abs ≠ 0 ↔ a ≠ 0 := not_congr int.nat_abs_eq_zero
lemma nat_abs_lt_nat_abs_of_nonneg_of_lt {a b : ℤ} (w₁ : 0 ≤ a) (w₂ : a < b) :
a.nat_abs < b.nat_abs :=
begin
lift b to ℕ using le_trans w₁ (le_of_lt w₂),
lift a to ℕ using w₁,
simpa using w₂,
end
lemma nat_abs_eq_nat_abs_iff {a b : ℤ} : a.nat_abs = b.nat_abs ↔ a = b ∨ a = -b :=
begin
split; intro h,
{ cases int.nat_abs_eq a with h₁ h₁; cases int.nat_abs_eq b with h₂ h₂;
rw [h₁, h₂]; simp [h], },
{ cases h; rw h, rw int.nat_abs_neg, },
end
lemma nat_abs_eq_iff {a : ℤ} {n : ℕ} : a.nat_abs = n ↔ a = n ∨ a = -n :=
by rw [←int.nat_abs_eq_nat_abs_iff, int.nat_abs_of_nat]
lemma nat_abs_eq_iff_mul_self_eq {a b : ℤ} : a.nat_abs = b.nat_abs ↔ a * a = b * b :=
begin
rw [← abs_eq_iff_mul_self_eq, abs_eq_nat_abs, abs_eq_nat_abs],
exact int.coe_nat_inj'.symm
end
lemma nat_abs_lt_iff_mul_self_lt {a b : ℤ} : a.nat_abs < b.nat_abs ↔ a * a < b * b :=
begin
rw [← abs_lt_iff_mul_self_lt, abs_eq_nat_abs, abs_eq_nat_abs],
exact int.coe_nat_lt.symm
end
lemma nat_abs_le_iff_mul_self_le {a b : ℤ} : a.nat_abs ≤ b.nat_abs ↔ a * a ≤ b * b :=
begin
rw [← abs_le_iff_mul_self_le, abs_eq_nat_abs, abs_eq_nat_abs],
exact int.coe_nat_le.symm
end
lemma nat_abs_eq_iff_sq_eq {a b : ℤ} : a.nat_abs = b.nat_abs ↔ a ^ 2 = b ^ 2 :=
by { rw [sq, sq], exact nat_abs_eq_iff_mul_self_eq }
lemma nat_abs_lt_iff_sq_lt {a b : ℤ} : a.nat_abs < b.nat_abs ↔ a ^ 2 < b ^ 2 :=
by { rw [sq, sq], exact nat_abs_lt_iff_mul_self_lt }
lemma nat_abs_le_iff_sq_le {a b : ℤ} : a.nat_abs ≤ b.nat_abs ↔ a ^ 2 ≤ b ^ 2 :=
by { rw [sq, sq], exact nat_abs_le_iff_mul_self_le }
/-! ### `/` -/
@[simp] theorem of_nat_div (m n : ℕ) : of_nat (m / n) = (of_nat m) / (of_nat n) := rfl
@[simp, norm_cast] theorem coe_nat_div (m n : ℕ) : ((m / n : ℕ) : ℤ) = m / n := rfl
theorem neg_succ_of_nat_div (m : ℕ) {b : ℤ} (H : 0 < b) :
-[1+m] / b = -(m / b + 1) :=
match b, eq_succ_of_zero_lt H with ._, ⟨n, rfl⟩ := rfl end
-- Will be generalized to Euclidean domains.
local attribute [simp]
protected theorem zero_div : ∀ (b : ℤ), 0 / b = 0
| 0 := show of_nat _ = _, by simp
| (n+1:ℕ) := show of_nat _ = _, by simp
| -[1+ n] := show -of_nat _ = _, by simp
local attribute [simp] -- Will be generalized to Euclidean domains.
protected theorem div_zero : ∀ (a : ℤ), a / 0 = 0
| 0 := show of_nat _ = _, by simp
| (n+1:ℕ) := show of_nat _ = _, by simp
| -[1+ n] := rfl
@[simp] protected theorem div_neg : ∀ (a b : ℤ), a / -b = -(a / b)
| (m : ℕ) 0 := show of_nat (m / 0) = -(m / 0 : ℕ), by rw nat.div_zero; refl
| (m : ℕ) (n+1:ℕ) := rfl
| 0 -[1+ n] := by simp
| (m+1:ℕ) -[1+ n] := (neg_neg _).symm
| -[1+ m] 0 := rfl
| -[1+ m] (n+1:ℕ) := rfl
| -[1+ m] -[1+ n] := rfl
theorem div_of_neg_of_pos {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b = -((-a - 1) / b + 1) :=
match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ :=
by change (- -[1+ m] : ℤ) with (m+1 : ℤ); rw add_sub_cancel; refl
end
protected theorem div_nonneg {a b : ℤ} (Ha : 0 ≤ a) (Hb : 0 ≤ b) : 0 ≤ a / b :=
match a, b, eq_coe_of_zero_le Ha, eq_coe_of_zero_le Hb with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := coe_zero_le _
end
protected theorem div_nonpos {a b : ℤ} (Ha : 0 ≤ a) (Hb : b ≤ 0) : a / b ≤ 0 :=
nonpos_of_neg_nonneg $ by rw [← int.div_neg]; exact int.div_nonneg Ha (neg_nonneg_of_nonpos Hb)
theorem div_neg' {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b < 0 :=
match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := neg_succ_lt_zero _
end
@[simp] protected theorem div_one : ∀ (a : ℤ), a / 1 = a
| 0 := show of_nat _ = _, by simp
| (n+1:ℕ) := congr_arg of_nat (nat.div_one _)
| -[1+ n] := congr_arg neg_succ_of_nat (nat.div_one _)
theorem div_eq_zero_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a / b = 0 :=
match a, b, eq_coe_of_zero_le H1, eq_succ_of_zero_lt (lt_of_le_of_lt H1 H2), H2 with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 :=
congr_arg of_nat $ nat.div_eq_of_lt $ lt_of_coe_nat_lt_coe_nat H2
end
theorem div_eq_zero_of_lt_abs {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < abs b) : a / b = 0 :=
match b, abs b, abs_eq_nat_abs b, H2 with
| (n : ℕ), ._, rfl, H2 := div_eq_zero_of_lt H1 H2
| -[1+ n], ._, rfl, H2 := neg_injective $ by rw [← int.div_neg]; exact div_eq_zero_of_lt H1 H2
end
protected theorem add_mul_div_right (a b : ℤ) {c : ℤ} (H : c ≠ 0) :
(a + b * c) / c = a / c + b :=
have ∀ {k n : ℕ} {a : ℤ}, (a + n * k.succ) / k.succ = a / k.succ + n, from
λ k n a, match a with
| (m : ℕ) := congr_arg of_nat $ nat.add_mul_div_right _ _ k.succ_pos
| -[1+ m] := show ((n * k.succ:ℕ) - m.succ : ℤ) / k.succ =
n - (m / k.succ + 1 : ℕ), begin
cases lt_or_ge m (n*k.succ) with h h,
{ rw [← int.coe_nat_sub h,
← int.coe_nat_sub ((nat.div_lt_iff_lt_mul _ _ k.succ_pos).2 h)],
apply congr_arg of_nat,
rw [mul_comm, nat.mul_sub_div], rwa mul_comm },
{ change (↑(n * nat.succ k) - (m + 1) : ℤ) / ↑(nat.succ k) =
↑n - ((m / nat.succ k : ℕ) + 1),
rw [← sub_sub, ← sub_sub, ← neg_sub (m:ℤ), ← neg_sub _ (n:ℤ),
← int.coe_nat_sub h,
← int.coe_nat_sub ((nat.le_div_iff_mul_le _ _ k.succ_pos).2 h),
← neg_succ_of_nat_coe', ← neg_succ_of_nat_coe'],
{ apply congr_arg neg_succ_of_nat,
rw [mul_comm, nat.sub_mul_div], rwa mul_comm } }
end
end,
have ∀ {a b c : ℤ}, 0 < c → (a + b * c) / c = a / c + b, from
λ a b c H, match c, eq_succ_of_zero_lt H, b with
| ._, ⟨k, rfl⟩, (n : ℕ) := this
| ._, ⟨k, rfl⟩, -[1+ n] :=
show (a - n.succ * k.succ) / k.succ = (a / k.succ) - n.succ, from
eq_sub_of_add_eq $ by rw [← this, sub_add_cancel]
end,
match lt_trichotomy c 0 with
| or.inl hlt := neg_inj.1 $ by rw [← int.div_neg, neg_add, ← int.div_neg, ← neg_mul_neg];
apply this (neg_pos_of_neg hlt)
| or.inr (or.inl heq) := absurd heq H
| or.inr (or.inr hgt) := this hgt
end
protected theorem add_mul_div_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b ≠ 0) :
(a + b * c) / b = a / b + c :=
by rw [mul_comm, int.add_mul_div_right _ _ H]
protected theorem add_div_of_dvd_right {a b c : ℤ} (H : c ∣ b) :
(a + b) / c = a / c + b / c :=
begin
by_cases h1 : c = 0,
{ simp [h1] },
cases H with k hk,
rw hk,
change c ≠ 0 at h1,
rw [mul_comm c k, int.add_mul_div_right _ _ h1, ←zero_add (k * c), int.add_mul_div_right _ _ h1,
int.zero_div, zero_add]
end
protected theorem add_div_of_dvd_left {a b c : ℤ} (H : c ∣ a) :
(a + b) / c = a / c + b / c :=
by rw [add_comm, int.add_div_of_dvd_right H, add_comm]
@[simp] protected theorem mul_div_cancel (a : ℤ) {b : ℤ} (H : b ≠ 0) : a * b / b = a :=
by have := int.add_mul_div_right 0 a H;
rwa [zero_add, int.zero_div, zero_add] at this
@[simp] protected theorem mul_div_cancel_left {a : ℤ} (b : ℤ) (H : a ≠ 0) : a * b / a = b :=
by rw [mul_comm, int.mul_div_cancel _ H]
@[simp] protected theorem div_self {a : ℤ} (H : a ≠ 0) : a / a = 1 :=
by have := int.mul_div_cancel 1 H; rwa one_mul at this
/-! ### mod -/
theorem of_nat_mod (m n : nat) : (m % n : ℤ) = of_nat (m % n) := rfl
@[simp, norm_cast] theorem coe_nat_mod (m n : ℕ) : (↑(m % n) : ℤ) = ↑m % ↑n := rfl
theorem neg_succ_of_nat_mod (m : ℕ) {b : ℤ} (bpos : 0 < b) :
-[1+m] % b = b - 1 - m % b :=
by rw [sub_sub, add_comm]; exact
match b, eq_succ_of_zero_lt bpos with ._, ⟨n, rfl⟩ := rfl end
@[simp] theorem mod_neg : ∀ (a b : ℤ), a % -b = a % b
| (m : ℕ) n := @congr_arg ℕ ℤ _ _ (λ i, ↑(m % i)) (nat_abs_neg _)
| -[1+ m] n := @congr_arg ℕ ℤ _ _ (λ i, sub_nat_nat i (nat.succ (m % i))) (nat_abs_neg _)
@[simp] theorem mod_abs (a b : ℤ) : a % (abs b) = a % b :=
abs_by_cases (λ i, a % i = a % b) rfl (mod_neg _ _)
local attribute [simp] -- Will be generalized to Euclidean domains.
theorem zero_mod (b : ℤ) : 0 % b = 0 := rfl
local attribute [simp] -- Will be generalized to Euclidean domains.
theorem mod_zero : ∀ (a : ℤ), a % 0 = a
| (m : ℕ) := congr_arg of_nat $ nat.mod_zero _
| -[1+ m] := congr_arg neg_succ_of_nat $ nat.mod_zero _
local attribute [simp] -- Will be generalized to Euclidean domains.
theorem mod_one : ∀ (a : ℤ), a % 1 = 0
| (m : ℕ) := congr_arg of_nat $ nat.mod_one _
| -[1+ m] := show (1 - (m % 1).succ : ℤ) = 0, by rw nat.mod_one; refl
theorem mod_eq_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a % b = a :=
match a, b, eq_coe_of_zero_le H1, eq_coe_of_zero_le (le_trans H1 (le_of_lt H2)), H2 with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 :=
congr_arg of_nat $ nat.mod_eq_of_lt (lt_of_coe_nat_lt_coe_nat H2)
end
theorem mod_nonneg : ∀ (a : ℤ) {b : ℤ}, b ≠ 0 → 0 ≤ a % b
| (m : ℕ) n H := coe_zero_le _
| -[1+ m] n H :=
sub_nonneg_of_le $ coe_nat_le_coe_nat_of_le $ nat.mod_lt _ (nat_abs_pos_of_ne_zero H)
theorem mod_lt_of_pos (a : ℤ) {b : ℤ} (H : 0 < b) : a % b < b :=
match a, b, eq_succ_of_zero_lt H with
| (m : ℕ), ._, ⟨n, rfl⟩ := coe_nat_lt_coe_nat_of_lt (nat.mod_lt _ (nat.succ_pos _))
| -[1+ m], ._, ⟨n, rfl⟩ := sub_lt_self _ (coe_nat_lt_coe_nat_of_lt $ nat.succ_pos _)
end
theorem mod_lt (a : ℤ) {b : ℤ} (H : b ≠ 0) : a % b < abs b :=
by rw [← mod_abs]; exact mod_lt_of_pos _ (abs_pos.2 H)
theorem mod_add_div_aux (m n : ℕ) : (n - (m % n + 1) - (n * (m / n) + n) : ℤ) = -[1+ m] :=
begin
rw [← sub_sub, neg_succ_of_nat_coe, sub_sub (n:ℤ)],
apply eq_neg_of_eq_neg,
rw [neg_sub, sub_sub_self, add_right_comm],
exact @congr_arg ℕ ℤ _ _ (λi, (i + 1 : ℤ)) (nat.mod_add_div _ _).symm
end
theorem mod_add_div : ∀ (a b : ℤ), a % b + b * (a / b) = a
| (m : ℕ) 0 := congr_arg of_nat (nat.mod_add_div _ _)
| (m : ℕ) (n+1:ℕ) := congr_arg of_nat (nat.mod_add_div _ _)
| 0 -[1+ n] := by simp
| (m+1:ℕ) -[1+ n] := show (_ + -(n+1) * -((m + 1) / (n + 1) : ℕ) : ℤ) = _,
by rw [neg_mul_neg]; exact congr_arg of_nat (nat.mod_add_div _ _)
| -[1+ m] 0 := by rw [mod_zero, int.div_zero]; refl
| -[1+ m] (n+1:ℕ) := mod_add_div_aux m n.succ
| -[1+ m] -[1+ n] := mod_add_div_aux m n.succ
theorem div_add_mod (a b : ℤ) : b * (a / b) + a % b = a :=
(add_comm _ _).trans (mod_add_div _ _)
lemma mod_add_div' (m k : ℤ) : m % k + (m / k) * k = m :=
by { rw mul_comm, exact mod_add_div _ _ }
lemma div_add_mod' (m k : ℤ) : (m / k) * k + m % k = m :=
by { rw mul_comm, exact div_add_mod _ _ }
theorem mod_def (a b : ℤ) : a % b = a - b * (a / b) :=
eq_sub_of_add_eq (mod_add_div _ _)
@[simp] theorem add_mul_mod_self {a b c : ℤ} : (a + b * c) % c = a % c :=
if cz : c = 0 then by rw [cz, mul_zero, add_zero] else
by rw [mod_def, mod_def, int.add_mul_div_right _ _ cz,
mul_add, mul_comm, add_sub_add_right_eq_sub]
@[simp] theorem add_mul_mod_self_left (a b c : ℤ) : (a + b * c) % b = a % b :=
by rw [mul_comm, add_mul_mod_self]
@[simp] theorem add_mod_self {a b : ℤ} : (a + b) % b = a % b :=
by have := add_mul_mod_self_left a b 1; rwa mul_one at this
@[simp] theorem add_mod_self_left {a b : ℤ} : (a + b) % a = b % a :=
by rw [add_comm, add_mod_self]
@[simp] theorem mod_add_mod (m n k : ℤ) : (m % n + k) % n = (m + k) % n :=
by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm;
rwa [add_right_comm, mod_add_div] at this
@[simp] theorem add_mod_mod (m n k : ℤ) : (m + n % k) % k = (m + n) % k :=
by rw [add_comm, mod_add_mod, add_comm]
lemma add_mod (a b n : ℤ) : (a + b) % n = ((a % n) + (b % n)) % n :=
by rw [add_mod_mod, mod_add_mod]
theorem add_mod_eq_add_mod_right {m n k : ℤ} (i : ℤ) (H : m % n = k % n) :
(m + i) % n = (k + i) % n :=
by rw [← mod_add_mod, ← mod_add_mod k, H]
theorem add_mod_eq_add_mod_left {m n k : ℤ} (i : ℤ) (H : m % n = k % n) :
(i + m) % n = (i + k) % n :=
by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm]
theorem mod_add_cancel_right {m n k : ℤ} (i) : (m + i) % n = (k + i) % n ↔
m % n = k % n :=
⟨λ H, by have := add_mod_eq_add_mod_right (-i) H;
rwa [add_neg_cancel_right, add_neg_cancel_right] at this,
add_mod_eq_add_mod_right _⟩
theorem mod_add_cancel_left {m n k i : ℤ} :
(i + m) % n = (i + k) % n ↔ m % n = k % n :=
by rw [add_comm, add_comm i, mod_add_cancel_right]
theorem mod_sub_cancel_right {m n k : ℤ} (i) : (m - i) % n = (k - i) % n ↔
m % n = k % n :=
mod_add_cancel_right _
theorem mod_eq_mod_iff_mod_sub_eq_zero {m n k : ℤ} : m % n = k % n ↔ (m - k) % n = 0 :=
(mod_sub_cancel_right k).symm.trans $ by simp
@[simp] theorem mul_mod_left (a b : ℤ) : (a * b) % b = 0 :=
by rw [← zero_add (a * b), add_mul_mod_self, zero_mod]
@[simp] theorem mul_mod_right (a b : ℤ) : (a * b) % a = 0 :=
by rw [mul_comm, mul_mod_left]
lemma mul_mod (a b n : ℤ) : (a * b) % n = ((a % n) * (b % n)) % n :=
begin
conv_lhs {
rw [←mod_add_div a n, ←mod_add_div' b n, right_distrib, left_distrib, left_distrib,
mul_assoc, mul_assoc, ←left_distrib n _ _, add_mul_mod_self_left, ← mul_assoc,
add_mul_mod_self] }
end
@[simp] lemma neg_mod_two (i : ℤ) : (-i) % 2 = i % 2 :=
begin
apply int.mod_eq_mod_iff_mod_sub_eq_zero.mpr,
convert int.mul_mod_right 2 (-i),
simp only [two_mul, sub_eq_add_neg]
end
local attribute [simp] -- Will be generalized to Euclidean domains.
theorem mod_self {a : ℤ} : a % a = 0 :=
by have := mul_mod_left 1 a; rwa one_mul at this
@[simp] theorem mod_mod_of_dvd (n : ℤ) {m k : ℤ} (h : m ∣ k) : n % k % m = n % m :=
begin
conv { to_rhs, rw ←mod_add_div n k },
rcases h with ⟨t, rfl⟩, rw [mul_assoc, add_mul_mod_self_left]
end
@[simp] theorem mod_mod (a b : ℤ) : a % b % b = a % b :=
by conv {to_rhs, rw [← mod_add_div a b, add_mul_mod_self_left]}
lemma sub_mod (a b n : ℤ) : (a - b) % n = ((a % n) - (b % n)) % n :=
begin
apply (mod_add_cancel_right b).mp,
rw [sub_add_cancel, ← add_mod_mod, sub_add_cancel, mod_mod]
end
/-! ### properties of `/` and `%` -/
@[simp] theorem mul_div_mul_of_pos {a : ℤ} (b c : ℤ) (H : 0 < a) : a * b / (a * c) = b / c :=
suffices ∀ (m k : ℕ) (b : ℤ), (m.succ * b / (m.succ * k) : ℤ) = b / k, from
match a, eq_succ_of_zero_lt H, c, eq_coe_or_neg c with
| ._, ⟨m, rfl⟩, ._, ⟨k, or.inl rfl⟩ := this _ _ _
| ._, ⟨m, rfl⟩, ._, ⟨k, or.inr rfl⟩ :=
by rw [← neg_mul_eq_mul_neg, int.div_neg, int.div_neg];
apply congr_arg has_neg.neg; apply this
end,
λ m k b, match b, k with
| (n : ℕ), k := congr_arg of_nat (nat.mul_div_mul _ _ m.succ_pos)
| -[1+ n], 0 := by rw [int.coe_nat_zero, mul_zero, int.div_zero, int.div_zero]
| -[1+ n], k+1 := congr_arg neg_succ_of_nat $
show (m.succ * n + m) / (m.succ * k.succ) = n / k.succ, begin
apply nat.div_eq_of_lt_le,
{ refine le_trans _ (nat.le_add_right _ _),
rw [← nat.mul_div_mul _ _ m.succ_pos],
apply nat.div_mul_le_self },
{ change m.succ * n.succ ≤ _,
rw [mul_left_comm],
apply nat.mul_le_mul_left,
apply (nat.div_lt_iff_lt_mul _ _ k.succ_pos).1,
apply nat.lt_succ_self }
end
end
@[simp] theorem mul_div_mul_of_pos_left (a : ℤ) {b : ℤ} (H : 0 < b) (c : ℤ) :
a * b / (c * b) = a / c :=
by rw [mul_comm, mul_comm c, mul_div_mul_of_pos _ _ H]
@[simp] theorem mul_mod_mul_of_pos {a : ℤ} (H : 0 < a) (b c : ℤ) : a * b % (a * c) = a * (b % c) :=
by rw [mod_def, mod_def, mul_div_mul_of_pos _ _ H, mul_sub_left_distrib, mul_assoc]
theorem lt_div_add_one_mul_self (a : ℤ) {b : ℤ} (H : 0 < b) : a < (a / b + 1) * b :=
by { rw [add_mul, one_mul, mul_comm, ← sub_lt_iff_lt_add', ← mod_def],
exact mod_lt_of_pos _ H }
theorem abs_div_le_abs : ∀ (a b : ℤ), abs (a / b) ≤ abs a :=
suffices ∀ (a : ℤ) (n : ℕ), abs (a / n) ≤ abs a, from
λ a b, match b, eq_coe_or_neg b with
| ._, ⟨n, or.inl rfl⟩ := this _ _
| ._, ⟨n, or.inr rfl⟩ := by rw [int.div_neg, abs_neg]; apply this
end,
λ a n, by rw [abs_eq_nat_abs, abs_eq_nat_abs]; exact
coe_nat_le_coe_nat_of_le (match a, n with
| (m : ℕ), n := nat.div_le_self _ _
| -[1+ m], 0 := nat.zero_le _
| -[1+ m], n+1 := nat.succ_le_succ (nat.div_le_self _ _)
end)
theorem div_le_self {a : ℤ} (b : ℤ) (Ha : 0 ≤ a) : a / b ≤ a :=
by have := le_trans (le_abs_self _) (abs_div_le_abs a b);
rwa [abs_of_nonneg Ha] at this
theorem mul_div_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : b * (a / b) = a :=
by have := mod_add_div a b; rwa [H, zero_add] at this
theorem div_mul_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : a / b * b = a :=
by rw [mul_comm, mul_div_cancel_of_mod_eq_zero H]
lemma mod_two_eq_zero_or_one (n : ℤ) : n % 2 = 0 ∨ n % 2 = 1 :=
have h : n % 2 < 2 := abs_of_nonneg (show 0 ≤ (2 : ℤ), from dec_trivial) ▸ int.mod_lt _ dec_trivial,
have h₁ : 0 ≤ n % 2 := int.mod_nonneg _ dec_trivial,
match (n % 2), h, h₁ with
| (0 : ℕ) := λ _ _, or.inl rfl
| (1 : ℕ) := λ _ _, or.inr rfl
| (k + 2 : ℕ) := λ h _, absurd h dec_trivial
| -[1+ a] := λ _ h₁, absurd h₁ dec_trivial
end
/-! ### dvd -/
@[norm_cast] theorem coe_nat_dvd {m n : ℕ} : (↑m : ℤ) ∣ ↑n ↔ m ∣ n :=
⟨λ ⟨a, ae⟩, m.eq_zero_or_pos.elim
(λm0, by simp [m0] at ae; simp [ae, m0])
(λm0l, by {
cases eq_coe_of_zero_le (@nonneg_of_mul_nonneg_left ℤ _ m a
(by simp [ae.symm]) (by simpa using m0l)) with k e,
subst a, exact ⟨k, int.coe_nat_inj ae⟩ }),
λ ⟨k, e⟩, dvd.intro k $ by rw [e, int.coe_nat_mul]⟩
theorem coe_nat_dvd_left {n : ℕ} {z : ℤ} : (↑n : ℤ) ∣ z ↔ n ∣ z.nat_abs :=
by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd]
theorem coe_nat_dvd_right {n : ℕ} {z : ℤ} : z ∣ (↑n : ℤ) ↔ z.nat_abs ∣ n :=
by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd]
theorem dvd_antisymm {a b : ℤ} (H1 : 0 ≤ a) (H2 : 0 ≤ b) : a ∣ b → b ∣ a → a = b :=
begin
rw [← abs_of_nonneg H1, ← abs_of_nonneg H2, abs_eq_nat_abs, abs_eq_nat_abs],
rw [coe_nat_dvd, coe_nat_dvd, coe_nat_inj'],
apply nat.dvd_antisymm
end
theorem dvd_of_mod_eq_zero {a b : ℤ} (H : b % a = 0) : a ∣ b :=
⟨b / a, (mul_div_cancel_of_mod_eq_zero H).symm⟩
theorem mod_eq_zero_of_dvd : ∀ {a b : ℤ}, a ∣ b → b % a = 0
| a ._ ⟨c, rfl⟩ := mul_mod_right _ _
theorem dvd_iff_mod_eq_zero (a b : ℤ) : a ∣ b ↔ b % a = 0 :=
⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩
/-- If `a % b = c` then `b` divides `a - c`. -/
lemma dvd_sub_of_mod_eq {a b c : ℤ} (h : a % b = c) : b ∣ a - c :=
begin
have hx : a % b % b = c % b, { rw h },
rw [mod_mod, ←mod_sub_cancel_right c, sub_self, zero_mod] at hx,
exact dvd_of_mod_eq_zero hx
end
theorem nat_abs_dvd {a b : ℤ} : (a.nat_abs : ℤ) ∣ b ↔ a ∣ b :=
(nat_abs_eq a).elim (λ e, by rw ← e) (λ e, by rw [← neg_dvd, ← e])
theorem dvd_nat_abs {a b : ℤ} : a ∣ b.nat_abs ↔ a ∣ b :=
(nat_abs_eq b).elim (λ e, by rw ← e) (λ e, by rw [← dvd_neg, ← e])
instance decidable_dvd : @decidable_rel ℤ (∣) :=
assume a n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm
protected theorem div_mul_cancel {a b : ℤ} (H : b ∣ a) : a / b * b = a :=
div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H)
protected theorem mul_div_cancel' {a b : ℤ} (H : a ∣ b) : a * (b / a) = b :=
by rw [mul_comm, int.div_mul_cancel H]
protected theorem mul_div_assoc (a : ℤ) : ∀ {b c : ℤ}, c ∣ b → (a * b) / c = a * (b / c)
| ._ c ⟨d, rfl⟩ := if cz : c = 0 then by simp [cz] else
by rw [mul_left_comm, int.mul_div_cancel_left _ cz, int.mul_div_cancel_left _ cz]
protected theorem mul_div_assoc' (b : ℤ) {a c : ℤ} (h : c ∣ a) : a * b / c = a / c * b :=
by rw [mul_comm, int.mul_div_assoc _ h, mul_comm]
theorem div_dvd_div : ∀ {a b c : ℤ} (H1 : a ∣ b) (H2 : b ∣ c), b / a ∣ c / a
| a ._ ._ ⟨b, rfl⟩ ⟨c, rfl⟩ := if az : a = 0 then by simp [az] else
by rw [int.mul_div_cancel_left _ az, mul_assoc, int.mul_div_cancel_left _ az];
apply dvd_mul_right
protected theorem eq_mul_of_div_eq_right {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) :
a = b * c :=
by rw [← H2, int.mul_div_cancel' H1]
protected theorem div_eq_of_eq_mul_right {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = b * c) :
a / b = c :=
by rw [H2, int.mul_div_cancel_left _ H1]
protected theorem eq_div_of_mul_eq_right {a b c : ℤ} (H1 : a ≠ 0) (H2 : a * b = c) :
b = c / a :=
eq.symm $ int.div_eq_of_eq_mul_right H1 H2.symm
protected theorem div_eq_iff_eq_mul_right {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) :
a / b = c ↔ a = b * c :=
⟨int.eq_mul_of_div_eq_right H', int.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 int.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, int.eq_mul_of_div_eq_right H1 H2]
protected theorem div_eq_of_eq_mul_left {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = c * b) :
a / b = c :=
int.div_eq_of_eq_mul_right H1 (by rw [mul_comm, H2])
protected lemma eq_zero_of_div_eq_zero {d n : ℤ} (h : d ∣ n) (H : n / d = 0) : n = 0 :=
by rw [← int.mul_div_cancel' h, H, mul_zero]
theorem neg_div_of_dvd : ∀ {a b : ℤ} (H : b ∣ a), -a / b = -(a / b)
| ._ b ⟨c, rfl⟩ := if bz : b = 0 then by simp [bz] else
by rw [neg_mul_eq_mul_neg, int.mul_div_cancel_left _ bz, int.mul_div_cancel_left _ bz]
lemma sub_div_of_dvd (a : ℤ) {b c : ℤ} (hcb : c ∣ b) : (a - b) / c = a / c - b / c :=
begin
rw [sub_eq_add_neg, sub_eq_add_neg, int.add_div_of_dvd_right ((dvd_neg c b).mpr hcb)],
congr,
exact neg_div_of_dvd hcb,
end
lemma sub_div_of_dvd_sub {a b c : ℤ} (hcab : c ∣ (a - b)) : (a - b) / c = a / c - b / c :=
by rw [eq_sub_iff_add_eq, ← int.add_div_of_dvd_left hcab, sub_add_cancel]
theorem div_sign : ∀ a b, a / sign b = a * sign b
| a (n+1:ℕ) := by unfold sign; simp
| a 0 := by simp [sign]
| a -[1+ n] := by simp [sign]
@[simp] theorem sign_mul : ∀ a b, sign (a * b) = sign a * sign b
| a 0 := by simp
| 0 b := by simp
| (m+1:ℕ) (n+1:ℕ) := rfl
| (m+1:ℕ) -[1+ n] := rfl
| -[1+ m] (n+1:ℕ) := rfl
| -[1+ m] -[1+ n] := rfl
protected theorem sign_eq_div_abs (a : ℤ) : sign a = a / (abs a) :=
if az : a = 0 then by simp [az] else
(int.div_eq_of_eq_mul_left (mt abs_eq_zero.1 az)
(sign_mul_abs _).symm).symm
theorem mul_sign : ∀ (i : ℤ), i * sign i = nat_abs i
| (n+1:ℕ) := mul_one _
| 0 := mul_zero _
| -[1+ n] := mul_neg_one _
@[simp]
theorem sign_pow_bit1 (k : ℕ) : ∀ n : ℤ, n.sign ^ (bit1 k) = n.sign
| (n+1:ℕ) := one_pow (bit1 k)
| 0 := zero_pow (nat.zero_lt_bit1 k)
| -[1+ n] := (neg_pow_bit1 1 k).trans (congr_arg (λ x, -x) (one_pow (bit1 k)))
theorem le_of_dvd {a b : ℤ} (bpos : 0 < b) (H : a ∣ b) : a ≤ b :=
match a, b, eq_succ_of_zero_lt bpos, H with
| (m : ℕ), ._, ⟨n, rfl⟩, H := coe_nat_le_coe_nat_of_le $
nat.le_of_dvd n.succ_pos $ coe_nat_dvd.1 H
| -[1+ m], ._, ⟨n, rfl⟩, _ :=
le_trans (le_of_lt $ neg_succ_lt_zero _) (coe_zero_le _)
end
theorem eq_one_of_dvd_one {a : ℤ} (H : 0 ≤ a) (H' : a ∣ 1) : a = 1 :=
match a, eq_coe_of_zero_le H, H' with
| ._, ⟨n, rfl⟩, H' := congr_arg coe $
nat.eq_one_of_dvd_one $ coe_nat_dvd.1 H'
end
theorem eq_one_of_mul_eq_one_right {a b : ℤ} (H : 0 ≤ a) (H' : a * b = 1) : a = 1 :=
eq_one_of_dvd_one H ⟨b, H'.symm⟩
theorem eq_one_of_mul_eq_one_left {a b : ℤ} (H : 0 ≤ b) (H' : a * b = 1) : b = 1 :=
eq_one_of_mul_eq_one_right H (by rw [mul_comm, H'])
lemma of_nat_dvd_of_dvd_nat_abs {a : ℕ} : ∀ {z : ℤ} (haz : a ∣ z.nat_abs), ↑a ∣ z
| (int.of_nat _) haz := int.coe_nat_dvd.2 haz
| -[1+k] haz :=
begin
change ↑a ∣ -(k+1 : ℤ),
apply dvd_neg_of_dvd,
apply int.coe_nat_dvd.2,
exact haz
end
lemma dvd_nat_abs_of_of_nat_dvd {a : ℕ} : ∀ {z : ℤ} (haz : ↑a ∣ z), a ∣ z.nat_abs
| (int.of_nat _) haz := int.coe_nat_dvd.1 (int.dvd_nat_abs.2 haz)
| -[1+k] haz :=
have haz' : (↑a:ℤ) ∣ (↑(k+1):ℤ), from dvd_of_dvd_neg haz,
int.coe_nat_dvd.1 haz'
lemma pow_dvd_of_le_of_pow_dvd {p m n : ℕ} {k : ℤ} (hmn : m ≤ n) (hdiv : ↑(p ^ n) ∣ k) :
↑(p ^ m) ∣ k :=
begin
induction k,
{ apply int.coe_nat_dvd.2,
apply pow_dvd_of_le_of_pow_dvd hmn,
apply int.coe_nat_dvd.1 hdiv },
change -[1+k] with -(↑(k+1) : ℤ),
apply dvd_neg_of_dvd,
apply int.coe_nat_dvd.2,
apply pow_dvd_of_le_of_pow_dvd hmn,
apply int.coe_nat_dvd.1,
apply dvd_of_dvd_neg,
exact hdiv,
end
lemma dvd_of_pow_dvd {p k : ℕ} {m : ℤ} (hk : 1 ≤ k) (hpk : ↑(p^k) ∣ m) : ↑p ∣ m :=
by rw ←pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk
/-- If `n > 0` then `m` is not divisible by `n` iff it is between `n * k` and `n * (k + 1)`
for some `k`. -/
lemma exists_lt_and_lt_iff_not_dvd (m : ℤ) {n : ℤ} (hn : 0 < n) :
(∃ k, n * k < m ∧ m < n * (k + 1)) ↔ ¬ n ∣ m :=
begin
split,
{ rintro ⟨k, h1k, h2k⟩ ⟨l, rfl⟩, rw [mul_lt_mul_left hn] at h1k h2k,
rw [lt_add_one_iff, ← not_lt] at h2k, exact h2k h1k },
{ intro h, rw [dvd_iff_mod_eq_zero, ← ne.def] at h,
have := (mod_nonneg m hn.ne.symm).lt_of_ne h.symm,
simp only [← mod_add_div m n] {single_pass := tt},
refine ⟨m / n, lt_add_of_pos_left _ this, _⟩,
rw [add_comm _ (1 : ℤ), left_distrib, mul_one], exact add_lt_add_right (mod_lt_of_pos _ hn) _ }
end
/-! ### `/` and ordering -/
protected theorem div_mul_le (a : ℤ) {b : ℤ} (H : b ≠ 0) : a / b * b ≤ a :=
le_of_sub_nonneg $ by rw [mul_comm, ← mod_def]; apply mod_nonneg _ H
protected theorem div_le_of_le_mul {a b c : ℤ} (H : 0 < c) (H' : a ≤ b * c) : a / c ≤ b :=
le_of_mul_le_mul_right (le_trans (int.div_mul_le _ (ne_of_gt H)) H') H
protected theorem mul_lt_of_lt_div {a b c : ℤ} (H : 0 < c) (H3 : a < b / c) : a * c < b :=
lt_of_not_ge $ mt (int.div_le_of_le_mul H) (not_le_of_gt H3)
protected theorem mul_le_of_le_div {a b c : ℤ} (H1 : 0 < c) (H2 : a ≤ b / c) : a * c ≤ b :=
le_trans (decidable.mul_le_mul_of_nonneg_right H2 (le_of_lt H1)) (int.div_mul_le _ (ne_of_gt H1))
protected theorem le_div_of_mul_le {a b c : ℤ} (H1 : 0 < c) (H2 : a * c ≤ b) : a ≤ b / c :=
le_of_lt_add_one $ lt_of_mul_lt_mul_right
(lt_of_le_of_lt H2 (lt_div_add_one_mul_self _ H1)) (le_of_lt H1)
protected theorem le_div_iff_mul_le {a b c : ℤ} (H : 0 < c) : a ≤ b / c ↔ a * c ≤ b :=
⟨int.mul_le_of_le_div H, int.le_div_of_mul_le H⟩
protected theorem div_le_div {a b c : ℤ} (H : 0 < c) (H' : a ≤ b) : a / c ≤ b / c :=
int.le_div_of_mul_le H (le_trans (int.div_mul_le _ (ne_of_gt H)) H')
protected theorem div_lt_of_lt_mul {a b c : ℤ} (H : 0 < c) (H' : a < b * c) : a / c < b :=
lt_of_not_ge $ mt (int.mul_le_of_le_div H) (not_le_of_gt H')
protected theorem lt_mul_of_div_lt {a b c : ℤ} (H1 : 0 < c) (H2 : a / c < b) : a < b * c :=
lt_of_not_ge $ mt (int.le_div_of_mul_le H1) (not_le_of_gt H2)
protected theorem div_lt_iff_lt_mul {a b c : ℤ} (H : 0 < c) : a / c < b ↔ a < b * c :=
⟨int.lt_mul_of_div_lt H, int.div_lt_of_lt_mul H⟩
protected theorem le_mul_of_div_le {a b c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ a) (H3 : a / b ≤ c) :
a ≤ c * b :=
by rw [← int.div_mul_cancel H2]; exact decidable.mul_le_mul_of_nonneg_right H3 H1
protected theorem lt_div_of_mul_lt {a b c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ c) (H3 : a * b < c) :
a < c / b :=
lt_of_not_ge $ mt (int.le_mul_of_div_le H1 H2) (not_le_of_gt H3)
protected theorem lt_div_iff_mul_lt {a b : ℤ} (c : ℤ) (H : 0 < c) (H' : c ∣ b) :
a < b / c ↔ a * c < b :=
⟨int.mul_lt_of_lt_div H, int.lt_div_of_mul_lt (le_of_lt H) H'⟩
theorem div_pos_of_pos_of_dvd {a b : ℤ} (H1 : 0 < a) (H2 : 0 ≤ b) (H3 : b ∣ a) : 0 < a / b :=
int.lt_div_of_mul_lt H2 H3 (by rwa zero_mul)
theorem div_eq_div_of_mul_eq_mul {a b c d : ℤ} (H2 : d ∣ c) (H3 : b ≠ 0)
(H4 : d ≠ 0) (H5 : a * d = b * c) :
a / b = c / d :=
int.div_eq_of_eq_mul_right H3 $
by rw [← int.mul_div_assoc _ H2]; exact
(int.div_eq_of_eq_mul_left H4 H5.symm).symm
theorem eq_mul_div_of_mul_eq_mul_of_dvd_left {a b c d : ℤ} (hb : b ≠ 0) (hbc : b ∣ c)
(h : b * a = c * d) :
a = c / b * d :=
begin
cases hbc with k hk,
subst hk,
rw [int.mul_div_cancel_left _ hb],
rw mul_assoc at h,
apply mul_left_cancel' hb h
end
/-- If an integer with larger absolute value divides an integer, it is
zero. -/
lemma eq_zero_of_dvd_of_nat_abs_lt_nat_abs {a b : ℤ} (w : a ∣ b) (h : nat_abs b < nat_abs a) :
b = 0 :=
begin
rw [←nat_abs_dvd, ←dvd_nat_abs, coe_nat_dvd] at w,
rw ←nat_abs_eq_zero,
exact eq_zero_of_dvd_of_lt w h
end
lemma eq_zero_of_dvd_of_nonneg_of_lt {a b : ℤ} (w₁ : 0 ≤ a) (w₂ : a < b) (h : b ∣ a) : a = 0 :=
eq_zero_of_dvd_of_nat_abs_lt_nat_abs h (nat_abs_lt_nat_abs_of_nonneg_of_lt w₁ w₂)
/-- If two integers are congruent to a sufficiently large modulus,
they are equal. -/
lemma eq_of_mod_eq_of_nat_abs_sub_lt_nat_abs {a b c : ℤ} (h1 : a % b = c)
(h2 : nat_abs (a - c) < nat_abs b) :
a = c :=
eq_of_sub_eq_zero (eq_zero_of_dvd_of_nat_abs_lt_nat_abs (dvd_sub_of_mod_eq h1) h2)
theorem of_nat_add_neg_succ_of_nat_of_lt {m n : ℕ} (h : m < n.succ) :
of_nat m + -[1+n] = -[1+ n - m] :=
begin
change sub_nat_nat _ _ = _,
have h' : n.succ - m = (n - m).succ,
apply succ_sub,
apply le_of_lt_succ h,
simp [*, sub_nat_nat]
end
theorem of_nat_add_neg_succ_of_nat_of_ge {m n : ℕ}
(h : n.succ ≤ m) : of_nat m + -[1+n] = of_nat (m - n.succ) :=
begin
change sub_nat_nat _ _ = _,
have h' : n.succ - m = 0,
apply nat.sub_eq_zero_of_le h,
simp [*, sub_nat_nat]
end
@[simp] theorem neg_add_neg (m n : ℕ) : -[1+m] + -[1+n] = -[1+nat.succ(m+n)] := rfl
/-! ### to_nat -/
theorem to_nat_eq_max : ∀ (a : ℤ), (to_nat a : ℤ) = max a 0
| (n : ℕ) := (max_eq_left (coe_zero_le n)).symm
| -[1+ n] := (max_eq_right (le_of_lt (neg_succ_lt_zero n))).symm
@[simp] lemma to_nat_zero : (0 : ℤ).to_nat = 0 := rfl
@[simp] lemma to_nat_one : (1 : ℤ).to_nat = 1 := rfl
@[simp] theorem to_nat_of_nonneg {a : ℤ} (h : 0 ≤ a) : (to_nat a : ℤ) = a :=
by rw [to_nat_eq_max, max_eq_left h]
@[simp] lemma to_nat_sub_of_le {a b : ℤ} (h : b ≤ a) : (to_nat (a - b) : ℤ) = a - b :=
int.to_nat_of_nonneg (sub_nonneg_of_le h)
@[simp] theorem to_nat_coe_nat (n : ℕ) : to_nat ↑n = n := rfl
@[simp] lemma to_nat_coe_nat_add_one {n : ℕ} : ((n : ℤ) + 1).to_nat = n + 1 := rfl
theorem le_to_nat (a : ℤ) : a ≤ to_nat a :=
by rw [to_nat_eq_max]; apply le_max_left
@[simp] theorem to_nat_le {a : ℤ} {n : ℕ} : to_nat a ≤ n ↔ a ≤ n :=
by rw [(coe_nat_le_coe_nat_iff _ _).symm, to_nat_eq_max, max_le_iff];
exact and_iff_left (coe_zero_le _)
@[simp] theorem lt_to_nat {n : ℕ} {a : ℤ} : n < to_nat a ↔ (n : ℤ) < a :=
le_iff_le_iff_lt_iff_lt.1 to_nat_le
theorem to_nat_le_to_nat {a b : ℤ} (h : a ≤ b) : to_nat a ≤ to_nat b :=
by rw to_nat_le; exact le_trans h (le_to_nat b)
theorem to_nat_lt_to_nat {a b : ℤ} (hb : 0 < b) : to_nat a < to_nat b ↔ a < b :=
⟨λ h, begin cases a, exact lt_to_nat.1 h, exact lt_trans (neg_succ_of_nat_lt_zero a) hb, end,
λ h, begin rw lt_to_nat, cases a, exact h, exact hb end⟩
theorem lt_of_to_nat_lt {a b : ℤ} (h : to_nat a < to_nat b) : a < b :=
(to_nat_lt_to_nat $ lt_to_nat.1 $ lt_of_le_of_lt (nat.zero_le _) h).1 h
lemma to_nat_add {a b : ℤ} (ha : 0 ≤ a) (hb : 0 ≤ b) :
(a + b).to_nat = a.to_nat + b.to_nat :=
begin
lift a to ℕ using ha,
lift b to ℕ using hb,
norm_cast,
end
lemma to_nat_add_nat {a : ℤ} (ha : 0 ≤ a) (n : ℕ) : (a + n).to_nat = a.to_nat + n :=
begin
lift a to ℕ using ha,
norm_cast,
end
@[simp]
lemma pred_to_nat : ∀ (i : ℤ), (i - 1).to_nat = i.to_nat - 1
| (0:ℕ) := rfl
| (n+1:ℕ) := by simp
| -[1+ n] := rfl
@[simp]
lemma to_nat_pred_coe_of_pos {i : ℤ} (h : 0 < i) : ((i.to_nat - 1 : ℕ) : ℤ) = i - 1 :=
by simp [h, le_of_lt h] with push_cast
@[simp] lemma to_nat_sub_to_nat_neg : ∀ (n : ℤ), ↑n.to_nat - ↑((-n).to_nat) = n
| (0 : ℕ) := rfl
| (n+1 : ℕ) := show ↑(n+1) - (0:ℤ) = n+1, from sub_zero _
| -[1+ n] := show 0 - (n+1 : ℤ) = _, from zero_sub _
@[simp] lemma to_nat_add_to_nat_neg_eq_nat_abs : ∀ (n : ℤ), (n.to_nat) + ((-n).to_nat) = n.nat_abs
| (0 : ℕ) := rfl
| (n+1 : ℕ) := show (n+1) + 0 = n+1, from add_zero _
| -[1+ n] := show 0 + (n+1) = n+1, from zero_add _
/-- If `n : ℕ`, then `int.to_nat' n = some n`, if `n : ℤ` is negative, then `int.to_nat' n = none`.
-/
def to_nat' : ℤ → option ℕ
| (n : ℕ) := some n
| -[1+ n] := none
theorem mem_to_nat' : ∀ (a : ℤ) (n : ℕ), n ∈ to_nat' a ↔ a = n
| (m : ℕ) n := option.some_inj.trans coe_nat_inj'.symm
| -[1+ m] n := by split; intro h; cases h
lemma to_nat_of_nonpos : ∀ {z : ℤ}, z ≤ 0 → z.to_nat = 0
| (0 : ℕ) := λ _, rfl
| (n + 1 : ℕ) := λ h, (h.not_lt (by { exact_mod_cast nat.succ_pos n })).elim
| (-[1+ n]) := λ _, rfl
/-! ### units -/
@[simp] theorem units_nat_abs (u : units ℤ) : nat_abs u = 1 :=
units.ext_iff.1 $ nat.units_eq_one ⟨nat_abs u, nat_abs ↑u⁻¹,
by rw [← nat_abs_mul, units.mul_inv]; refl,
by rw [← nat_abs_mul, units.inv_mul]; refl⟩
theorem units_eq_one_or (u : units ℤ) : u = 1 ∨ u = -1 :=
by simpa only [units.ext_iff, units_nat_abs] using nat_abs_eq u
lemma is_unit_eq_one_or {a : ℤ} : is_unit a → a = 1 ∨ a = -1
| ⟨x, hx⟩ := hx ▸ (units_eq_one_or _).imp (congr_arg coe) (congr_arg coe)
lemma is_unit_iff {a : ℤ} : is_unit a ↔ a = 1 ∨ a = -1 :=
begin
refine ⟨λ h, is_unit_eq_one_or h, λ h, _⟩,
rcases h with rfl | rfl,
{ exact is_unit_one },
{ exact is_unit_one.neg }
end
theorem is_unit_iff_nat_abs_eq {n : ℤ} : is_unit n ↔ n.nat_abs = 1 :=
by simp [nat_abs_eq_iff, is_unit_iff]
lemma units_inv_eq_self (u : units ℤ) : u⁻¹ = u :=
(units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl)
@[simp] lemma units_mul_self (u : units ℤ) : u * u = 1 :=
(units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl)
-- `units.coe_mul` is a "wrong turn" for the simplifier, this undoes it and simplifies further
@[simp] lemma units_coe_mul_self (u : units ℤ) : (u * u : ℤ) = 1 :=
by rw [←units.coe_mul, units_mul_self, units.coe_one]
@[simp] lemma neg_one_pow_ne_zero {n : ℕ} : (-1 : ℤ)^n ≠ 0 :=
pow_ne_zero _ (abs_pos.mp trivial)
/-! ### bitwise ops -/
@[simp] lemma bodd_zero : bodd 0 = ff := rfl
@[simp] lemma bodd_one : bodd 1 = tt := rfl
lemma bodd_two : bodd 2 = ff := rfl
@[simp, norm_cast] lemma bodd_coe (n : ℕ) : int.bodd n = nat.bodd n := rfl
@[simp] lemma bodd_sub_nat_nat (m n : ℕ) : bodd (sub_nat_nat m n) = bxor m.bodd n.bodd :=
by apply sub_nat_nat_elim m n (λ m n i, bodd i = bxor m.bodd n.bodd); intros;
simp; cases i.bodd; simp
@[simp] lemma bodd_neg_of_nat (n : ℕ) : bodd (neg_of_nat n) = n.bodd :=
by cases n; simp; refl
@[simp] lemma bodd_neg (n : ℤ) : bodd (-n) = bodd n :=
by cases n; simp [has_neg.neg, int.coe_nat_eq, int.neg, bodd, -of_nat_eq_coe]
@[simp] lemma bodd_add (m n : ℤ) : bodd (m + n) = bxor (bodd m) (bodd n) :=
by cases m with m m; cases n with n n; unfold has_add.add;
simp [int.add, -of_nat_eq_coe, bool.bxor_comm]
@[simp] lemma bodd_mul (m n : ℤ) : bodd (m * n) = bodd m && bodd n :=
by cases m with m m; cases n with n n;
simp [← int.mul_def, int.mul, -of_nat_eq_coe, bool.bxor_comm]
theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n
| (n : ℕ) :=
by rw [show (cond (bodd n) 1 0 : ℤ) = (cond (bodd n) 1 0 : ℕ),
by cases bodd n; refl]; exact congr_arg of_nat n.bodd_add_div2
| -[1+ n] := begin
refine eq.trans _ (congr_arg neg_succ_of_nat n.bodd_add_div2),
dsimp [bodd], cases nat.bodd n; dsimp [cond, bnot, div2, int.mul],
{ change -[1+ 2 * nat.div2 n] = _, rw zero_add },
{ rw [zero_add, add_comm], refl }
end
theorem div2_val : ∀ n, div2 n = n / 2
| (n : ℕ) := congr_arg of_nat n.div2_val
| -[1+ n] := congr_arg neg_succ_of_nat n.div2_val
lemma bit0_val (n : ℤ) : bit0 n = 2 * n := (two_mul _).symm
lemma bit1_val (n : ℤ) : bit1 n = 2 * n + 1 := congr_arg (+(1:ℤ)) (bit0_val _)
lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 :=
by { cases b, apply (bit0_val n).trans (add_zero _).symm, apply bit1_val }
lemma bit_decomp (n : ℤ) : bit (bodd n) (div2 n) = n :=
(bit_val _ _).trans $ (add_comm _ _).trans $ bodd_add_div2 _
/-- Defines a function from `ℤ` conditionally, if it is defined for odd and even integers separately
using `bit`. -/
def {u} bit_cases_on {C : ℤ → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n :=
by rw [← bit_decomp n]; apply h
@[simp] lemma bit_zero : bit ff 0 = 0 := rfl
@[simp] lemma bit_coe_nat (b) (n : ℕ) : bit b n = nat.bit b n :=
by rw [bit_val, nat.bit_val]; cases b; refl
@[simp] lemma bit_neg_succ (b) (n : ℕ) : bit b -[1+ n] = -[1+ nat.bit (bnot b) n] :=
by rw [bit_val, nat.bit_val]; cases b; refl
@[simp] lemma bodd_bit (b n) : bodd (bit b n) = b :=
by rw bit_val; simp; cases b; cases bodd 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_bit (b n) : div2 (bit b n) = n :=
begin
rw [bit_val, div2_val, add_comm, int.add_mul_div_left, (_ : (_/2:ℤ) = 0), zero_add],
cases b,
{ simp },
{ show of_nat _ = _, rw nat.div_eq_zero; simp },
{ cc }
end
lemma bit0_ne_bit1 (m n : ℤ) : bit0 m ≠ bit1 n :=
mt (congr_arg bodd) $ by simp
lemma bit1_ne_bit0 (m n : ℤ) : bit1 m ≠ bit0 n :=
(bit0_ne_bit1 _ _).symm
lemma bit1_ne_zero (m : ℤ) : bit1 m ≠ 0 :=
by simpa only [bit0_zero] using bit1_ne_bit0 m 0
@[simp] lemma test_bit_zero (b) : ∀ n, test_bit (bit b n) 0 = b
| (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_zero
| -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_zero];
clear test_bit_zero; cases b; refl
@[simp] lemma test_bit_succ (m b) : ∀ n, test_bit (bit b n) (nat.succ m) = test_bit n m
| (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_succ
| -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_succ]
private meta def bitwise_tac : tactic unit := `[
funext m,
funext n,
cases m with m m; cases n with n n; try {refl},
all_goals {
apply congr_arg of_nat <|> apply congr_arg neg_succ_of_nat,
try {dsimp [nat.land, nat.ldiff, nat.lor]},
try {rw [
show nat.bitwise (λ a b, a && bnot b) n m =
nat.bitwise (λ a b, b && bnot a) m n, from
congr_fun (congr_fun (@nat.bitwise_swap (λ a b, b && bnot a) rfl) n) m]},
apply congr_arg (λ f, nat.bitwise f m n),
funext a,
funext b,
cases a; cases b; refl
},
all_goals {unfold nat.land nat.ldiff nat.lor}
]
theorem bitwise_or : bitwise bor = lor := by bitwise_tac
theorem bitwise_and : bitwise band = land := by bitwise_tac
theorem bitwise_diff : bitwise (λ a b, a && bnot b) = ldiff := by bitwise_tac
theorem bitwise_xor : bitwise bxor = lxor := by bitwise_tac
@[simp] lemma bitwise_bit (f : bool → bool → bool) (a m b n) :
bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) :=
begin
cases m with m m; cases n with n n;
repeat { rw [← int.coe_nat_eq] <|> rw bit_coe_nat <|> rw bit_neg_succ };
unfold bitwise nat_bitwise bnot;
[ induction h : f ff ff,
induction h : f ff tt,
induction h : f tt ff,
induction h : f tt tt ],
all_goals {
unfold cond, rw nat.bitwise_bit,
repeat { rw bit_coe_nat <|> rw bit_neg_succ <|> rw bnot_bnot } },
all_goals { unfold bnot {fail_if_unchanged := ff}; rw h; refl }
end
@[simp] lemma lor_bit (a m b n) : lor (bit a m) (bit b n) = bit (a || b) (lor m n) :=
by rw [← bitwise_or, bitwise_bit]
@[simp] lemma land_bit (a m b n) : land (bit a m) (bit b n) = bit (a && b) (land m n) :=
by rw [← bitwise_and, bitwise_bit]
@[simp] lemma ldiff_bit (a m b n) : ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) :=
by rw [← bitwise_diff, bitwise_bit]
@[simp] lemma lxor_bit (a m b n) : lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) :=
by rw [← bitwise_xor, bitwise_bit]
@[simp] lemma lnot_bit (b) : ∀ n, lnot (bit b n) = bit (bnot b) (lnot n)
| (n : ℕ) := by simp [lnot]
| -[1+ n] := by simp [lnot]
@[simp] lemma test_bit_bitwise (f : bool → bool → bool) (m n k) :
test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) :=
begin
induction k with k IH generalizing m n;
apply bit_cases_on m; intros a m';
apply bit_cases_on n; intros b n';
rw bitwise_bit,
{ simp [test_bit_zero] },
{ simp [test_bit_succ, IH] }
end
@[simp] lemma test_bit_lor (m n k) : test_bit (lor m n) k = test_bit m k || test_bit n k :=
by rw [← bitwise_or, test_bit_bitwise]
@[simp] lemma test_bit_land (m n k) : test_bit (land m n) k = test_bit m k && test_bit n k :=
by rw [← bitwise_and, test_bit_bitwise]
@[simp]
lemma test_bit_ldiff (m n k) : test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) :=
by rw [← bitwise_diff, test_bit_bitwise]
@[simp] lemma test_bit_lxor (m n k) : test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) :=
by rw [← bitwise_xor, test_bit_bitwise]
@[simp] lemma test_bit_lnot : ∀ n k, test_bit (lnot n) k = bnot (test_bit n k)
| (n : ℕ) k := by simp [lnot, test_bit]
| -[1+ n] k := by simp [lnot, test_bit]
lemma shiftl_add : ∀ (m : ℤ) (n : ℕ) (k : ℤ), shiftl m (n + k) = shiftl (shiftl m n) k
| (m : ℕ) n (k:ℕ) := congr_arg of_nat (nat.shiftl_add _ _ _)
| -[1+ m] n (k:ℕ) := congr_arg neg_succ_of_nat (nat.shiftl'_add _ _ _ _)
| (m : ℕ) n -[1+k] := sub_nat_nat_elim n k.succ
(λ n k i, shiftl ↑m i = nat.shiftr (nat.shiftl m n) k)
(λ i n, congr_arg coe $
by rw [← nat.shiftl_sub, nat.add_sub_cancel_left]; apply nat.le_add_right)
(λ i n, congr_arg coe $
by rw [add_assoc, nat.shiftr_add, ← nat.shiftl_sub, nat.sub_self]; refl)
| -[1+ m] n -[1+k] := sub_nat_nat_elim n k.succ
(λ n k i, shiftl -[1+ m] i = -[1+ nat.shiftr (nat.shiftl' tt m n) k])
(λ i n, congr_arg neg_succ_of_nat $
by rw [← nat.shiftl'_sub, nat.add_sub_cancel_left]; apply nat.le_add_right)
(λ i n, congr_arg neg_succ_of_nat $
by rw [add_assoc, nat.shiftr_add, ← nat.shiftl'_sub, nat.sub_self]; refl)
lemma shiftl_sub (m : ℤ) (n : ℕ) (k : ℤ) : shiftl m (n - k) = shiftr (shiftl m n) k :=
shiftl_add _ _ _
@[simp] lemma shiftl_neg (m n : ℤ) : shiftl m (-n) = shiftr m n := rfl
@[simp] lemma shiftr_neg (m n : ℤ) : shiftr m (-n) = shiftl m n := by rw [← shiftl_neg, neg_neg]
@[simp] lemma shiftl_coe_nat (m n : ℕ) : shiftl m n = nat.shiftl m n := rfl
@[simp] lemma shiftr_coe_nat (m n : ℕ) : shiftr m n = nat.shiftr m n := by cases n; refl
@[simp] lemma shiftl_neg_succ (m n : ℕ) : shiftl -[1+ m] n = -[1+ nat.shiftl' tt m n] := rfl
@[simp]
lemma shiftr_neg_succ (m n : ℕ) : shiftr -[1+ m] n = -[1+ nat.shiftr m n] := by cases n; refl
lemma shiftr_add : ∀ (m : ℤ) (n k : ℕ), shiftr m (n + k) = shiftr (shiftr m n) k
| (m : ℕ) n k := by rw [shiftr_coe_nat, shiftr_coe_nat,
← int.coe_nat_add, shiftr_coe_nat, nat.shiftr_add]
| -[1+ m] n k := by rw [shiftr_neg_succ, shiftr_neg_succ,
← int.coe_nat_add, shiftr_neg_succ, nat.shiftr_add]
lemma shiftl_eq_mul_pow : ∀ (m : ℤ) (n : ℕ), shiftl m n = m * ↑(2 ^ n)
| (m : ℕ) n := congr_arg coe (nat.shiftl_eq_mul_pow _ _)
| -[1+ m] n := @congr_arg ℕ ℤ _ _ (λi, -i) (nat.shiftl'_tt_eq_mul_pow _ _)
lemma shiftr_eq_div_pow : ∀ (m : ℤ) (n : ℕ), shiftr m n = m / ↑(2 ^ n)
| (m : ℕ) n := by rw shiftr_coe_nat; exact congr_arg coe (nat.shiftr_eq_div_pow _ _)
| -[1+ m] n := begin
rw [shiftr_neg_succ, neg_succ_of_nat_div, nat.shiftr_eq_div_pow], refl,
exact coe_nat_lt_coe_nat_of_lt (pow_pos dec_trivial _)
end
lemma one_shiftl (n : ℕ) : shiftl 1 n = (2 ^ n : ℕ) :=
congr_arg coe (nat.one_shiftl _)
@[simp] lemma zero_shiftl : ∀ n : ℤ, shiftl 0 n = 0
| (n : ℕ) := congr_arg coe (nat.zero_shiftl _)
| -[1+ n] := congr_arg coe (nat.zero_shiftr _)
@[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := zero_shiftl _
end int
attribute [irreducible] int.nonneg
|
5f9e9ce4a94b8d634e438818ae241bb2508350c3 | 75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2 | /tests/lean/run/match2.lean | 6569da0d9d05103aee94dd733891bd834acf4633 | [
"Apache-2.0"
] | permissive | jroesch/lean | 30ef0860fa905d35b9ad6f76de1a4f65c9af6871 | 3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2 | refs/heads/master | 1,586,090,835,348 | 1,455,142,203,000 | 1,455,142,277,000 | 51,536,958 | 1 | 0 | null | 1,455,215,811,000 | 1,455,215,811,000 | null | UTF-8 | Lean | false | false | 827 | lean | import data.nat.basic
open nat
definition two1 : nat := 2
definition two2 : nat := succ (succ (zero))
definition f (x : nat) (y : nat) := y
constant g : nat → nat → nat
constants a b : nat
(*
local tc = type_checker_with_hints(get_env())
local plugin = whnf_match_plugin(tc)
function tst_match(p, t)
local r1, r2 = match(p, t, plugin)
assert(r1)
print("--------------")
for i = 1, #r1 do
print(" expr:#" .. i .. " := " .. tostring(r1[i]))
end
for i = 1, #r2 do
print(" lvl:#" .. i .. " := " .. tostring(r2[i]))
end
end
local nat = Const("nat")
local f = Const("f")
local g = Const("g")
local a = Const("a")
local b = Const("b")
local x = mk_idx_metavar(0, nat)
local p = g(x, f(x, a))
local t = g(a, f(b, a))
tst_match(p, t)
tst_match(f(x, x), f(a, b))
*)
|
9809a43e3526d37b33c269855048c874738f07e2 | e30ff3aabdac29f8ea40ad76887544d0f9be9018 | /ircbot/router.lean | b51800a4d6aa7cd287bf585b6254151db56e3cdf | [] | no_license | forked-from-1kasper/leanbot | bdef0efa3e4d0eb75b06c1707fb4e35086bb57fa | c61c8c7fdad7b05877e0d232719ce23d2999557f | refs/heads/master | 1,651,846,081,986 | 1,646,404,009,000 | 1,646,404,009,000 | 127,132,795 | 12 | 1 | null | 1,605,183,650,000 | 1,522,237,998,000 | Lean | UTF-8 | Lean | false | false | 916 | lean | import ircbot.support ircbot.parsing
open types support parser
def Word := many_char1 parsing.WordChar <* many' parsing.Ws
def Words := many_char1 (sat $ function.const char true)
structure speech :=
(object : person) (subject text : string) (type : message)
def router {α : Type} (name desc : string) (syntax : option string)
(p : parser α) (func : speech → α → io (list irc_text))
(wherein : list message) : bot_function :=
let p' := parsing.tok ("\\" ++ name) >> p in
{ name := name,
syntax := syntax,
description := desc,
func := λ input,
match input with
| irc_text.parsed_normal
{ object := some object, type := type,
args := [ subject ], text := text } :=
if subject.front = '#' ∧ type ∈ wherein then
sum.rec_on (run_string p' text) (λ _, pure [])
(func ⟨object, subject, text, type⟩)
else pure []
| _ := pure []
end } |
f91e2c598096f44d5b7aa41a470077f990bef5a0 | 367134ba5a65885e863bdc4507601606690974c1 | /src/data/pequiv.lean | dfd505a4b40fcd8bf7a70c1595a59a679ace647d | [
"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 | 11,180 | lean | /-
Copyright (c) 2019 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import data.set.lattice
universes u v w x
/-- A `pequiv` is a partial equivalence, a representation of a bijection between a subset
of `α` and a subset of `β` -/
structure pequiv (α : Type u) (β : Type v) :=
(to_fun : α → option β)
(inv_fun : β → option α)
(inv : ∀ (a : α) (b : β), a ∈ inv_fun b ↔ b ∈ to_fun a)
infixr ` ≃. `:25 := pequiv
namespace pequiv
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
open function option
instance : has_coe_to_fun (α ≃. β) := ⟨_, to_fun⟩
@[simp] lemma coe_mk_apply (f₁ : α → option β) (f₂ : β → option α) (h) (x : α) :
(pequiv.mk f₁ f₂ h : α → option β) x = f₁ x := rfl
@[ext] lemma ext : ∀ {f g : α ≃. β} (h : ∀ x, f x = g x), f = g
| ⟨f₁, f₂, hf⟩ ⟨g₁, g₂, hg⟩ h :=
have h : f₁ = g₁, from funext h,
have ∀ b, f₂ b = g₂ b,
begin
subst h,
assume b,
have hf := λ a, hf a b,
have hg := λ a, hg a b,
cases h : g₂ b with a,
{ simp only [h, option.not_mem_none, false_iff] at hg,
simp only [hg, iff_false] at hf,
rwa [option.eq_none_iff_forall_not_mem] },
{ rw [← option.mem_def, hf, ← hg, h, option.mem_def] }
end,
by simp [*, funext_iff]
lemma ext_iff {f g : α ≃. β} : f = g ↔ ∀ x, f x = g x :=
⟨congr_fun ∘ congr_arg _, ext⟩
@[refl] protected def refl (α : Type*) : α ≃. α :=
{ to_fun := some,
inv_fun := some,
inv := λ _ _, eq_comm }
@[symm] protected def symm (f : α ≃. β) : β ≃. α :=
{ to_fun := f.2,
inv_fun := f.1,
inv := λ _ _, (f.inv _ _).symm }
lemma mem_iff_mem (f : α ≃. β) : ∀ {a : α} {b : β}, a ∈ f.symm b ↔ b ∈ f a := f.3
lemma eq_some_iff (f : α ≃. β) : ∀ {a : α} {b : β}, f.symm b = some a ↔ f a = some b := f.3
@[trans] protected def trans (f : α ≃. β) (g : β ≃. γ) : pequiv α γ :=
{ to_fun := λ a, (f a).bind g,
inv_fun := λ a, (g.symm a).bind f.symm,
inv := λ a b, by simp [*, and.comm, eq_some_iff f, eq_some_iff g] at * }
@[simp] lemma refl_apply (a : α) : pequiv.refl α a = some a := rfl
@[simp] lemma symm_refl : (pequiv.refl α).symm = pequiv.refl α := rfl
@[simp] lemma symm_symm (f : α ≃. β) : f.symm.symm = f := by cases f; refl
lemma symm_injective : function.injective (@pequiv.symm α β) :=
left_inverse.injective symm_symm
lemma trans_assoc (f : α ≃. β) (g : β ≃. γ) (h : γ ≃. δ) :
(f.trans g).trans h = f.trans (g.trans h) :=
ext (λ _, option.bind_assoc _ _ _)
lemma mem_trans (f : α ≃. β) (g : β ≃. γ) (a : α) (c : γ) :
c ∈ f.trans g a ↔ ∃ b, b ∈ f a ∧ c ∈ g b := option.bind_eq_some'
lemma trans_eq_some (f : α ≃. β) (g : β ≃. γ) (a : α) (c : γ) :
f.trans g a = some c ↔ ∃ b, f a = some b ∧ g b = some c := option.bind_eq_some'
lemma trans_eq_none (f : α ≃. β) (g : β ≃. γ) (a : α) :
f.trans g a = none ↔ (∀ b c, b ∉ f a ∨ c ∉ g b) :=
begin
simp only [eq_none_iff_forall_not_mem, mem_trans, imp_iff_not_or.symm],
push_neg, tauto
end
@[simp] lemma refl_trans (f : α ≃. β) : (pequiv.refl α).trans f = f :=
by ext; dsimp [pequiv.trans]; refl
@[simp] lemma trans_refl (f : α ≃. β) : f.trans (pequiv.refl β) = f :=
by ext; dsimp [pequiv.trans]; simp
protected lemma inj (f : α ≃. β) {a₁ a₂ : α} {b : β} (h₁ : b ∈ f a₁) (h₂ : b ∈ f a₂) : a₁ = a₂ :=
by rw ← mem_iff_mem at *; cases h : f.symm b; simp * at *
lemma injective_of_forall_ne_is_some (f : α ≃. β) (a₂ : α)
(h : ∀ (a₁ : α), a₁ ≠ a₂ → is_some (f a₁)) : injective f :=
has_left_inverse.injective
⟨λ b, option.rec_on b a₂ (λ b', option.rec_on (f.symm b') a₂ id),
λ x, begin
classical,
cases hfx : f x,
{ have : x = a₂, from not_imp_comm.1 (h x) (hfx.symm ▸ by simp), simp [this] },
{ simp only [hfx], rw [(eq_some_iff f).2 hfx], refl }
end⟩
lemma injective_of_forall_is_some {f : α ≃. β}
(h : ∀ (a : α), is_some (f a)) : injective f :=
(classical.em (nonempty α)).elim
(λ hn, injective_of_forall_ne_is_some f (classical.choice hn)
(λ a _, h a))
(λ hn x, (hn ⟨x⟩).elim)
section of_set
variables (s : set α) [decidable_pred s]
def of_set (s : set α) [decidable_pred s] : α ≃. α :=
{ to_fun := λ a, if a ∈ s then some a else none,
inv_fun := λ a, if a ∈ s then some a else none,
inv := λ a b, by split_ifs; finish [eq_comm] }
lemma mem_of_set_self_iff {s : set α} [decidable_pred s] {a : α} : a ∈ of_set s a ↔ a ∈ s :=
by dsimp [of_set]; split_ifs; simp *
lemma mem_of_set_iff {s : set α} [decidable_pred s] {a b : α} : a ∈ of_set s b ↔ a = b ∧ a ∈ s :=
by dsimp [of_set]; split_ifs; split; finish
@[simp] lemma of_set_eq_some_iff {s : set α} {h : decidable_pred s} {a b : α} :
of_set s b = some a ↔ a = b ∧ a ∈ s := mem_of_set_iff
@[simp] lemma of_set_eq_some_self_iff {s : set α} {h : decidable_pred s} {a : α} :
of_set s a = some a ↔ a ∈ s := mem_of_set_self_iff
@[simp] lemma of_set_symm : (of_set s).symm = of_set s := rfl
@[simp] lemma of_set_univ : of_set set.univ = pequiv.refl α := rfl
@[simp] lemma of_set_eq_refl {s : set α} [decidable_pred s] :
of_set s = pequiv.refl α ↔ s = set.univ :=
⟨λ h, begin
rw [set.eq_univ_iff_forall],
intro,
rw [← mem_of_set_self_iff, h],
exact rfl
end, λ h, by simp only [of_set_univ.symm, h]; congr⟩
end of_set
lemma symm_trans_rev (f : α ≃. β) (g : β ≃. γ) : (f.trans g).symm = g.symm.trans f.symm := rfl
lemma trans_symm (f : α ≃. β) : f.trans f.symm = of_set {a | (f a).is_some} :=
begin
ext,
dsimp [pequiv.trans],
simp only [eq_some_iff f, option.is_some_iff_exists, option.mem_def, bind_eq_some',
of_set_eq_some_iff],
split,
{ rintros ⟨b, hb₁, hb₂⟩,
exact ⟨pequiv.inj _ hb₂ hb₁, b, hb₂⟩ },
{ simp {contextual := tt} }
end
lemma symm_trans (f : α ≃. β) : f.symm.trans f = of_set {b | (f.symm b).is_some} :=
symm_injective $ by simp [symm_trans_rev, trans_symm, -symm_symm]
lemma trans_symm_eq_iff_forall_is_some {f : α ≃. β} :
f.trans f.symm = pequiv.refl α ↔ ∀ a, is_some (f a) :=
by rw [trans_symm, of_set_eq_refl, set.eq_univ_iff_forall]; refl
instance : has_bot (α ≃. β) :=
⟨{ to_fun := λ _, none,
inv_fun := λ _, none,
inv := by simp }⟩
@[simp] lemma bot_apply (a : α) : (⊥ : α ≃. β) a = none := rfl
@[simp] lemma symm_bot : (⊥ : α ≃. β).symm = ⊥ := rfl
@[simp] lemma trans_bot (f : α ≃. β) : f.trans (⊥ : β ≃. γ) = ⊥ :=
by ext; dsimp [pequiv.trans]; simp
@[simp] lemma bot_trans (f : β ≃. γ) : (⊥ : α ≃. β).trans f = ⊥ :=
by ext; dsimp [pequiv.trans]; simp
lemma is_some_symm_get (f : α ≃. β) {a : α} (h : is_some (f a)) :
is_some (f.symm (option.get h)) :=
is_some_iff_exists.2 ⟨a, by rw [f.eq_some_iff, some_get]⟩
section single
variables [decidable_eq α] [decidable_eq β] [decidable_eq γ]
def single (a : α) (b : β) : α ≃. β :=
{ to_fun := λ x, if x = a then some b else none,
inv_fun := λ x, if x = b then some a else none,
inv := λ _ _, by simp; split_ifs; cc }
lemma mem_single (a : α) (b : β) : b ∈ single a b a := if_pos rfl
lemma mem_single_iff (a₁ a₂ : α) (b₁ b₂ : β) : b₁ ∈ single a₂ b₂ a₁ ↔ a₁ = a₂ ∧ b₁ = b₂ :=
by dsimp [single]; split_ifs; simp [*, eq_comm]
@[simp] lemma symm_single (a : α) (b : β) : (single a b).symm = single b a := rfl
@[simp] lemma single_apply (a : α) (b : β) : single a b a = some b := if_pos rfl
lemma single_apply_of_ne {a₁ a₂ : α} (h : a₁ ≠ a₂) (b : β) : single a₁ b a₂ = none := if_neg h.symm
lemma single_trans_of_mem (a : α) {b : β} {c : γ} {f : β ≃. γ} (h : c ∈ f b) :
(single a b).trans f = single a c :=
begin
ext,
dsimp [single, pequiv.trans],
split_ifs; simp * at *
end
lemma trans_single_of_mem {a : α} {b : β} (c : γ) {f : α ≃. β} (h : b ∈ f a) :
f.trans (single b c) = single a c :=
symm_injective $ single_trans_of_mem _ ((mem_iff_mem f).2 h)
@[simp]
lemma single_trans_single (a : α) (b : β) (c : γ) : (single a b).trans (single b c) = single a c :=
single_trans_of_mem _ (mem_single _ _)
@[simp] lemma single_subsingleton_eq_refl [subsingleton α] (a b : α) : single a b = pequiv.refl α :=
begin
ext i j,
dsimp [single],
rw [if_pos (subsingleton.elim i a), subsingleton.elim i j, subsingleton.elim b j]
end
lemma trans_single_of_eq_none {b : β} (c : γ) {f : δ ≃. β} (h : f.symm b = none) :
f.trans (single b c) = ⊥ :=
begin
ext,
simp only [eq_none_iff_forall_not_mem, option.mem_def, f.eq_some_iff] at h,
dsimp [pequiv.trans, single],
simp,
intros,
split_ifs;
simp * at *
end
lemma single_trans_of_eq_none (a : α) {b : β} {f : β ≃. δ} (h : f b = none) :
(single a b).trans f = ⊥ :=
symm_injective $ trans_single_of_eq_none _ h
lemma single_trans_single_of_ne {b₁ b₂ : β} (h : b₁ ≠ b₂) (a : α) (c : γ) :
(single a b₁).trans (single b₂ c) = ⊥ :=
single_trans_of_eq_none _ (single_apply_of_ne h.symm _)
end single
section order
instance : partial_order (α ≃. β) :=
{ le := λ f g, ∀ (a : α) (b : β), b ∈ f a → b ∈ g a,
le_refl := λ _ _ _, id,
le_trans := λ f g h fg gh a b, (gh a b) ∘ (fg a b),
le_antisymm := λ f g fg gf, ext begin
assume a,
cases h : g a with b,
{ exact eq_none_iff_forall_not_mem.2
(λ b hb, option.not_mem_none b $ h ▸ fg a b hb) },
{ exact gf _ _ h }
end }
lemma le_def {f g : α ≃. β} : f ≤ g ↔ (∀ (a : α) (b : β), b ∈ f a → b ∈ g a) := iff.rfl
instance : order_bot (α ≃. β) :=
{ bot_le := λ _ _ _ h, (not_mem_none _ h).elim,
..pequiv.partial_order,
..pequiv.has_bot }
instance [decidable_eq α] [decidable_eq β] : semilattice_inf_bot (α ≃. β) :=
{ inf := λ f g,
{ to_fun := λ a, if f a = g a then f a else none,
inv_fun := λ b, if f.symm b = g.symm b then f.symm b else none,
inv := λ a b, begin
have := @mem_iff_mem _ _ f a b,
have := @mem_iff_mem _ _ g a b,
split_ifs; finish
end },
inf_le_left := λ _ _ _ _, by simp; split_ifs; cc,
inf_le_right := λ _ _ _ _, by simp; split_ifs; cc,
le_inf := λ f g h fg gh a b, begin
have := fg a b,
have := gh a b,
simp [le_def],
split_ifs; finish
end,
..pequiv.order_bot }
end order
end pequiv
namespace equiv
variables {α : Type*} {β : Type*} {γ : Type*}
def to_pequiv (f : α ≃ β) : α ≃. β :=
{ to_fun := some ∘ f,
inv_fun := some ∘ f.symm,
inv := by simp [equiv.eq_symm_apply, eq_comm] }
@[simp] lemma to_pequiv_refl : (equiv.refl α).to_pequiv = pequiv.refl α := rfl
lemma to_pequiv_trans (f : α ≃ β) (g : β ≃ γ) : (f.trans g).to_pequiv =
f.to_pequiv.trans g.to_pequiv := rfl
lemma to_pequiv_symm (f : α ≃ β) : f.symm.to_pequiv = f.to_pequiv.symm := rfl
lemma to_pequiv_apply (f : α ≃ β) (x : α) : f.to_pequiv x = some (f x) := rfl
end equiv
|
3659558d29d81245506de8cd7f674b49d0a8aadb | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/linear_algebra/bilinear_form.lean | 010a7ee11c4aeea1614a85297b668c02c728f99e | [
"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 | 69,539 | lean | /-
Copyright (c) 2018 Andreas Swerdlow. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andreas Swerdlow, Kexing Ying
-/
import linear_algebra.dual
import linear_algebra.matrix.basis
import linear_algebra.matrix.nondegenerate
import linear_algebra.matrix.nonsingular_inverse
import linear_algebra.tensor_product
/-!
# Bilinear form
This file defines a bilinear form over a module. Basic ideas
such as orthogonality are also introduced, as well as reflexivive,
symmetric, non-degenerate and alternating bilinear forms. Adjoints of
linear maps with respect to a bilinear form are also introduced.
A bilinear form on an R-(semi)module M, is a function from M x M to R,
that is linear in both arguments. Comments will typically abbreviate
"(semi)module" as just "module", but the definitions should be as general as
possible.
The result that there exists an orthogonal basis with respect to a symmetric,
nondegenerate bilinear form can be found in `quadratic_form.lean` with
`exists_orthogonal_basis`.
## Notations
Given any term B of type bilin_form, due to a coercion, can use
the notation B x y to refer to the function field, ie. B x y = B.bilin x y.
In this file we use the following type variables:
- `M`, `M'`, ... are modules over the semiring `R`,
- `M₁`, `M₁'`, ... are modules over the ring `R₁`,
- `M₂`, `M₂'`, ... are modules over the commutative semiring `R₂`,
- `M₃`, `M₃'`, ... are modules over the commutative ring `R₃`,
- `V`, ... is a vector space over the field `K`.
## References
* <https://en.wikipedia.org/wiki/Bilinear_form>
## Tags
Bilinear form,
-/
open_locale big_operators
universes u v w
/-- `bilin_form R M` is the type of `R`-bilinear functions `M → M → R`. -/
structure bilin_form (R : Type*) (M : Type*) [semiring R] [add_comm_monoid M] [module R M] :=
(bilin : M → M → R)
(bilin_add_left : ∀ (x y z : M), bilin (x + y) z = bilin x z + bilin y z)
(bilin_smul_left : ∀ (a : R) (x y : M), bilin (a • x) y = a * (bilin x y))
(bilin_add_right : ∀ (x y z : M), bilin x (y + z) = bilin x y + bilin x z)
(bilin_smul_right : ∀ (a : R) (x y : M), bilin x (a • y) = a * (bilin x y))
variables {R : Type*} {M : Type*} [semiring R] [add_comm_monoid M] [module R M]
variables {R₁ : Type*} {M₁ : Type*} [ring R₁] [add_comm_group M₁] [module R₁ M₁]
variables {R₂ : Type*} {M₂ : Type*} [comm_semiring R₂] [add_comm_monoid M₂] [module R₂ M₂]
variables {R₃ : Type*} {M₃ : Type*} [comm_ring R₃] [add_comm_group M₃] [module R₃ M₃]
variables {V : Type*} {K : Type*} [field K] [add_comm_group V] [module K V]
variables {B : bilin_form R M} {B₁ : bilin_form R₁ M₁} {B₂ : bilin_form R₂ M₂}
namespace bilin_form
instance : has_coe_to_fun (bilin_form R M) (λ _, M → M → R) := ⟨bilin⟩
initialize_simps_projections bilin_form (bilin -> apply)
@[simp] lemma coe_fn_mk (f : M → M → R) (h₁ h₂ h₃ h₄) :
(bilin_form.mk f h₁ h₂ h₃ h₄ : M → M → R) = f :=
rfl
lemma coe_fn_congr : Π {x x' y y' : M}, x = x' → y = y' → B x y = B x' y'
| _ _ _ _ rfl rfl := rfl
@[simp]
lemma add_left (x y z : M) : B (x + y) z = B x z + B y z := bilin_add_left B x y z
@[simp]
lemma smul_left (a : R) (x y : M) : B (a • x) y = a * (B x y) := bilin_smul_left B a x y
@[simp]
lemma add_right (x y z : M) : B x (y + z) = B x y + B x z := bilin_add_right B x y z
@[simp]
lemma smul_right (a : R) (x y : M) : B x (a • y) = a * (B x y) := bilin_smul_right B a x y
@[simp]
lemma zero_left (x : M) : B 0 x = 0 :=
by { rw [←@zero_smul R _ _ _ _ (0 : M), smul_left, zero_mul] }
@[simp]
lemma zero_right (x : M) : B x 0 = 0 :=
by rw [←@zero_smul _ _ _ _ _ (0 : M), smul_right, zero_mul]
@[simp]
lemma neg_left (x y : M₁) : B₁ (-x) y = -(B₁ x y) :=
by rw [←@neg_one_smul R₁ _ _, smul_left, neg_one_mul]
@[simp]
lemma neg_right (x y : M₁) : B₁ x (-y) = -(B₁ x y) :=
by rw [←@neg_one_smul R₁ _ _, smul_right, neg_one_mul]
@[simp]
lemma sub_left (x y z : M₁) : B₁ (x - y) z = B₁ x z - B₁ y z :=
by rw [sub_eq_add_neg, sub_eq_add_neg, add_left, neg_left]
@[simp]
lemma sub_right (x y z : M₁) : B₁ x (y - z) = B₁ x y - B₁ x z :=
by rw [sub_eq_add_neg, sub_eq_add_neg, add_right, neg_right]
variable {D : bilin_form R M}
@[ext] lemma ext (H : ∀ (x y : M), B x y = D x y) : B = D :=
by { cases B, cases D, congr, funext, exact H _ _ }
lemma congr_fun (h : B = D) (x y : M) : B x y = D x y := h ▸ rfl
lemma ext_iff : B = D ↔ (∀ x y, B x y = D x y) := ⟨congr_fun, ext⟩
instance : add_comm_monoid (bilin_form R M) :=
{ add := λ B D, { bilin := λ x y, B x y + D x y,
bilin_add_left := λ x y z, by { rw add_left, rw add_left, ac_refl },
bilin_smul_left := λ a x y, by { rw [smul_left, smul_left, mul_add] },
bilin_add_right := λ x y z, by { rw add_right, rw add_right, ac_refl },
bilin_smul_right := λ a x y, by { rw [smul_right, smul_right, mul_add] } },
add_assoc := by { intros, ext, unfold bilin coe_fn has_coe_to_fun.coe bilin, rw add_assoc },
zero := { bilin := λ x y, 0,
bilin_add_left := λ x y z, (add_zero 0).symm,
bilin_smul_left := λ a x y, (mul_zero a).symm,
bilin_add_right := λ x y z, (zero_add 0).symm,
bilin_smul_right := λ a x y, (mul_zero a).symm },
zero_add := by { intros, ext, unfold coe_fn has_coe_to_fun.coe bilin, rw zero_add },
add_zero := by { intros, ext, unfold coe_fn has_coe_to_fun.coe bilin, rw add_zero },
add_comm := by { intros, ext, unfold coe_fn has_coe_to_fun.coe bilin, rw add_comm } }
instance : add_comm_group (bilin_form R₁ M₁) :=
{ neg := λ B, { bilin := λ x y, - (B.1 x y),
bilin_add_left := λ x y z, by rw [bilin_add_left, neg_add],
bilin_smul_left := λ a x y, by rw [bilin_smul_left, mul_neg_eq_neg_mul_symm],
bilin_add_right := λ x y z, by rw [bilin_add_right, neg_add],
bilin_smul_right := λ a x y, by rw [bilin_smul_right, mul_neg_eq_neg_mul_symm] },
add_left_neg := by { intros, ext, unfold coe_fn has_coe_to_fun.coe bilin, rw neg_add_self },
.. bilin_form.add_comm_monoid }
@[simp]
lemma add_apply (x y : M) : (B + D) x y = B x y + D x y := rfl
@[simp]
lemma zero_apply (x y : M) : (0 : bilin_form R M) x y = 0 := rfl
@[simp]
lemma neg_apply (x y : M₁) : (-B₁) x y = -(B₁ x y) := rfl
instance : inhabited (bilin_form R M) := ⟨0⟩
section
/-- `bilin_form R M` inherits the scalar action from any commutative subalgebra `R₂` of `R`.
When `R` itself is commutative, this provides an `R`-action via `algebra.id`. -/
instance [algebra R₂ R] : module R₂ (bilin_form R M) :=
{ smul := λ c B,
{ bilin := λ x y, c • B x y,
bilin_add_left := λ x y z,
by { unfold coe_fn has_coe_to_fun.coe bilin, rw [bilin_add_left, smul_add] },
bilin_smul_left := λ a x y, by { unfold coe_fn has_coe_to_fun.coe bilin,
rw [bilin_smul_left, ←algebra.mul_smul_comm] },
bilin_add_right := λ x y z, by { unfold coe_fn has_coe_to_fun.coe bilin,
rw [bilin_add_right, smul_add] },
bilin_smul_right := λ a x y, by { unfold coe_fn has_coe_to_fun.coe bilin,
rw [bilin_smul_right, ←algebra.mul_smul_comm] } },
smul_add := λ c B D, by { ext, unfold coe_fn has_coe_to_fun.coe bilin, rw smul_add },
add_smul := λ c B D, by { ext, unfold coe_fn has_coe_to_fun.coe bilin, rw add_smul },
mul_smul := λ a c D, by { ext, unfold coe_fn has_coe_to_fun.coe bilin, rw ←smul_assoc, refl },
one_smul := λ B, by { ext, unfold coe_fn has_coe_to_fun.coe bilin, rw one_smul },
zero_smul := λ B, by { ext, unfold coe_fn has_coe_to_fun.coe bilin, rw zero_smul },
smul_zero := λ B, by { ext, unfold coe_fn has_coe_to_fun.coe bilin, rw smul_zero } }
@[simp] lemma smul_apply [algebra R₂ R] (B : bilin_form R M) (a : R₂) (x y : M) :
(a • B) x y = a • (B x y) :=
rfl
end
section flip
variables (R₂)
/-- Auxiliary construction for the flip of a bilinear form, obtained by exchanging the left and
right arguments. This version is a `linear_map`; it is later upgraded to a `linear_equiv`
in `flip_hom`. -/
def flip_hom_aux [algebra R₂ R] : bilin_form R M →ₗ[R₂] bilin_form R M :=
{ to_fun := λ A,
{ bilin := λ i j, A j i,
bilin_add_left := λ x y z, A.bilin_add_right z x y,
bilin_smul_left := λ a x y, A.bilin_smul_right a y x,
bilin_add_right := λ x y z, A.bilin_add_left y z x,
bilin_smul_right := λ a x y, A.bilin_smul_left a y x },
map_add' := λ A₁ A₂, by { ext, simp } ,
map_smul' := λ c A, by { ext, simp } }
variables {R₂}
lemma flip_flip_aux [algebra R₂ R] (A : bilin_form R M) :
(flip_hom_aux R₂) (flip_hom_aux R₂ A) = A :=
by { ext A x y, simp [flip_hom_aux] }
variables (R₂)
/-- The flip of a bilinear form, obtained by exchanging the left and right arguments. This is a
less structured version of the equiv which applies to general (noncommutative) rings `R` with a
distinguished commutative subring `R₂`; over a commutative ring use `flip`. -/
def flip_hom [algebra R₂ R] : bilin_form R M ≃ₗ[R₂] bilin_form R M :=
{ inv_fun := flip_hom_aux R₂,
left_inv := flip_flip_aux,
right_inv := flip_flip_aux,
.. flip_hom_aux R₂ }
variables {R₂}
@[simp] lemma flip_apply [algebra R₂ R] (A : bilin_form R M) (x y : M) :
flip_hom R₂ A x y = A y x :=
rfl
lemma flip_flip [algebra R₂ R] :
(flip_hom R₂).trans (flip_hom R₂) = linear_equiv.refl R₂ (bilin_form R M) :=
by { ext A x y, simp }
/-- The flip of a bilinear form over a ring, obtained by exchanging the left and right arguments,
here considered as an `ℕ`-linear equivalence, i.e. an additive equivalence. -/
abbreviation flip' : bilin_form R M ≃ₗ[ℕ] bilin_form R M := flip_hom ℕ
/-- The `flip` of a bilinear form over a commutative ring, obtained by exchanging the left and
right arguments. -/
abbreviation flip : bilin_form R₂ M₂ ≃ₗ[R₂] bilin_form R₂ M₂ := flip_hom R₂
end flip
section to_lin'
variables [algebra R₂ R] [module R₂ M] [is_scalar_tower R₂ R M]
/-- Auxiliary definition to define `to_lin_hom`; see below. -/
def to_lin_hom_aux₁ (A : bilin_form R M) (x : M) : M →ₗ[R] R :=
{ to_fun := λ y, A x y,
map_add' := A.bilin_add_right x,
map_smul' := λ c, A.bilin_smul_right c x }
/-- Auxiliary definition to define `to_lin_hom`; see below. -/
def to_lin_hom_aux₂ (A : bilin_form R M) : M →ₗ[R₂] M →ₗ[R] R :=
{ to_fun := to_lin_hom_aux₁ A,
map_add' := λ x₁ x₂, linear_map.ext $ λ x, by simp only [to_lin_hom_aux₁, linear_map.coe_mk,
linear_map.add_apply, add_left],
map_smul' := λ c x, linear_map.ext $
begin
dsimp [to_lin_hom_aux₁],
intros,
simp only [← algebra_map_smul R c x, algebra.smul_def, linear_map.coe_mk,
linear_map.smul_apply, smul_left]
end }
variables (R₂)
/-- The linear map obtained from a `bilin_form` by fixing the left co-ordinate and evaluating in
the right.
This is the most general version of the construction; it is `R₂`-linear for some distinguished
commutative subsemiring `R₂` of the scalar ring. Over a semiring with no particular distinguished
such subsemiring, use `to_lin'`, which is `ℕ`-linear. Over a commutative semiring, use `to_lin`,
which is linear. -/
def to_lin_hom : bilin_form R M →ₗ[R₂] M →ₗ[R₂] M →ₗ[R] R :=
{ to_fun := to_lin_hom_aux₂,
map_add' := λ A₁ A₂, linear_map.ext $ λ x,
begin
dsimp only [to_lin_hom_aux₁, to_lin_hom_aux₂],
apply linear_map.ext,
intros y,
simp only [to_lin_hom_aux₂, to_lin_hom_aux₁, linear_map.coe_mk,
linear_map.add_apply, add_apply],
end ,
map_smul' := λ c A,
begin
dsimp [to_lin_hom_aux₁, to_lin_hom_aux₂],
apply linear_map.ext,
intros x,
apply linear_map.ext,
intros y,
simp only [to_lin_hom_aux₂, to_lin_hom_aux₁,
linear_map.coe_mk, linear_map.smul_apply, smul_apply],
end }
variables {R₂}
@[simp] lemma to_lin'_apply (A : bilin_form R M) (x : M) :
⇑(to_lin_hom R₂ A x) = A x :=
rfl
/-- The linear map obtained from a `bilin_form` by fixing the left co-ordinate and evaluating in
the right.
Over a commutative semiring, use `to_lin`, which is linear rather than `ℕ`-linear. -/
abbreviation to_lin' : bilin_form R M →ₗ[ℕ] M →ₗ[ℕ] M →ₗ[R] R := to_lin_hom ℕ
@[simp]
lemma sum_left {α} (t : finset α) (g : α → M) (w : M) :
B (∑ i in t, g i) w = ∑ i in t, B (g i) w :=
(bilin_form.to_lin' B).map_sum₂ t g w
@[simp]
lemma sum_right {α} (t : finset α) (w : M) (g : α → M) :
B w (∑ i in t, g i) = ∑ i in t, B w (g i) :=
(bilin_form.to_lin' B w).map_sum
variables (R₂)
/-- The linear map obtained from a `bilin_form` by fixing the right co-ordinate and evaluating in
the left.
This is the most general version of the construction; it is `R₂`-linear for some distinguished
commutative subsemiring `R₂` of the scalar ring. Over semiring with no particular distinguished
such subsemiring, use `to_lin'_flip`, which is `ℕ`-linear. Over a commutative semiring, use
`to_lin_flip`, which is linear. -/
def to_lin_hom_flip : bilin_form R M →ₗ[R₂] M →ₗ[R₂] M →ₗ[R] R :=
(to_lin_hom R₂).comp (flip_hom R₂).to_linear_map
variables {R₂}
@[simp] lemma to_lin'_flip_apply (A : bilin_form R M) (x : M) :
⇑(to_lin_hom_flip R₂ A x) = λ y, A y x :=
rfl
/-- The linear map obtained from a `bilin_form` by fixing the right co-ordinate and evaluating in
the left.
Over a commutative semiring, use `to_lin_flip`, which is linear rather than `ℕ`-linear. -/
abbreviation to_lin'_flip : bilin_form R M →ₗ[ℕ] M →ₗ[ℕ] M →ₗ[R] R := to_lin_hom_flip ℕ
end to_lin'
end bilin_form
section equiv_lin
/-- A map with two arguments that is linear in both is a bilinear form.
This is an auxiliary definition for the full linear equivalence `linear_map.to_bilin`.
-/
def linear_map.to_bilin_aux (f : M₂ →ₗ[R₂] M₂ →ₗ[R₂] R₂) : bilin_form R₂ M₂ :=
{ bilin := λ x y, f x y,
bilin_add_left := λ x y z, (linear_map.map_add f x y).symm ▸ linear_map.add_apply (f x) (f y) z,
bilin_smul_left := λ a x y, by rw [linear_map.map_smul, linear_map.smul_apply, smul_eq_mul],
bilin_add_right := λ x y z, linear_map.map_add (f x) y z,
bilin_smul_right := λ a x y, linear_map.map_smul (f x) a y }
/-- Bilinear forms are linearly equivalent to maps with two arguments that are linear in both. -/
def bilin_form.to_lin : bilin_form R₂ M₂ ≃ₗ[R₂] (M₂ →ₗ[R₂] M₂ →ₗ[R₂] R₂) :=
{ inv_fun := linear_map.to_bilin_aux,
left_inv := λ B, by { ext, simp [linear_map.to_bilin_aux] },
right_inv := λ B, by { ext, simp [linear_map.to_bilin_aux] },
.. bilin_form.to_lin_hom R₂ }
/-- A map with two arguments that is linear in both is linearly equivalent to bilinear form. -/
def linear_map.to_bilin : (M₂ →ₗ[R₂] M₂ →ₗ[R₂] R₂) ≃ₗ[R₂] bilin_form R₂ M₂ :=
bilin_form.to_lin.symm
@[simp] lemma linear_map.to_bilin_aux_eq (f : M₂ →ₗ[R₂] M₂ →ₗ[R₂] R₂) :
linear_map.to_bilin_aux f = linear_map.to_bilin f :=
rfl
@[simp] lemma linear_map.to_bilin_symm :
(linear_map.to_bilin.symm : bilin_form R₂ M₂ ≃ₗ[R₂] _) = bilin_form.to_lin := rfl
@[simp] lemma bilin_form.to_lin_symm :
(bilin_form.to_lin.symm : _ ≃ₗ[R₂] bilin_form R₂ M₂) = linear_map.to_bilin :=
linear_map.to_bilin.symm_symm
@[simp, norm_cast]
lemma bilin_form.to_lin_apply (x : M₂) : ⇑(bilin_form.to_lin B₂ x) = B₂ x := rfl
end equiv_lin
namespace bilin_form
section comp
variables {M' : Type w} [add_comm_monoid M'] [module R M']
/-- Apply a linear map on the left and right argument of a bilinear form. -/
def comp (B : bilin_form R M') (l r : M →ₗ[R] M') : bilin_form R M :=
{ bilin := λ x y, B (l x) (r y),
bilin_add_left := λ x y z, by rw [linear_map.map_add, add_left],
bilin_smul_left := λ x y z, by rw [linear_map.map_smul, smul_left],
bilin_add_right := λ x y z, by rw [linear_map.map_add, add_right],
bilin_smul_right := λ x y z, by rw [linear_map.map_smul, smul_right] }
/-- Apply a linear map to the left argument of a bilinear form. -/
def comp_left (B : bilin_form R M) (f : M →ₗ[R] M) : bilin_form R M :=
B.comp f linear_map.id
/-- Apply a linear map to the right argument of a bilinear form. -/
def comp_right (B : bilin_form R M) (f : M →ₗ[R] M) : bilin_form R M :=
B.comp linear_map.id f
lemma comp_comp {M'' : Type*} [add_comm_monoid M''] [module R M'']
(B : bilin_form R M'') (l r : M →ₗ[R] M') (l' r' : M' →ₗ[R] M'') :
(B.comp l' r').comp l r = B.comp (l'.comp l) (r'.comp r) := rfl
@[simp] lemma comp_left_comp_right (B : bilin_form R M) (l r : M →ₗ[R] M) :
(B.comp_left l).comp_right r = B.comp l r := rfl
@[simp] lemma comp_right_comp_left (B : bilin_form R M) (l r : M →ₗ[R] M) :
(B.comp_right r).comp_left l = B.comp l r := rfl
@[simp] lemma comp_apply (B : bilin_form R M') (l r : M →ₗ[R] M') (v w) :
B.comp l r v w = B (l v) (r w) := rfl
@[simp] lemma comp_left_apply (B : bilin_form R M) (f : M →ₗ[R] M) (v w) :
B.comp_left f v w = B (f v) w := rfl
@[simp] lemma comp_right_apply (B : bilin_form R M) (f : M →ₗ[R] M) (v w) :
B.comp_right f v w = B v (f w) := rfl
@[simp] lemma comp_id_left (B : bilin_form R M) (r : M →ₗ[R] M) :
B.comp linear_map.id r = B.comp_right r :=
by { ext, refl }
@[simp] lemma comp_id_right (B : bilin_form R M) (l : M →ₗ[R] M) :
B.comp l linear_map.id = B.comp_left l :=
by { ext, refl }
@[simp] lemma comp_left_id (B : bilin_form R M) :
B.comp_left linear_map.id = B :=
by { ext, refl }
@[simp] lemma comp_right_id (B : bilin_form R M) :
B.comp_right linear_map.id = B :=
by { ext, refl }
-- Shortcut for `comp_id_{left,right}` followed by `comp_{right,left}_id`,
-- has to be declared after the former two to get the right priority
@[simp] lemma comp_id_id (B : bilin_form R M) :
B.comp linear_map.id linear_map.id = B :=
by { ext, refl }
lemma comp_injective (B₁ B₂ : bilin_form R M') {l r : M →ₗ[R] M'}
(hₗ : function.surjective l) (hᵣ : function.surjective r) :
B₁.comp l r = B₂.comp l r ↔ B₁ = B₂ :=
begin
split; intros h,
{ -- B₁.comp l r = B₂.comp l r → B₁ = B₂
ext,
cases hₗ x with x' hx, subst hx,
cases hᵣ y with y' hy, subst hy,
rw [←comp_apply, ←comp_apply, h], },
{ -- B₁ = B₂ → B₁.comp l r = B₂.comp l r
subst h, },
end
end comp
variables {M₂' : Type*} [add_comm_monoid M₂'] [module R₂ M₂']
section congr
/-- Apply a linear equivalence on the arguments of a bilinear form. -/
def congr (e : M₂ ≃ₗ[R₂] M₂') : bilin_form R₂ M₂ ≃ₗ[R₂] bilin_form R₂ M₂' :=
{ to_fun := λ B, B.comp e.symm e.symm,
inv_fun := λ B, B.comp e e,
left_inv :=
λ B, ext (λ x y, by simp only [comp_apply, linear_equiv.coe_coe, e.symm_apply_apply]),
right_inv :=
λ B, ext (λ x y, by simp only [comp_apply, linear_equiv.coe_coe, e.apply_symm_apply]),
map_add' := λ B B', ext (λ x y, by simp only [comp_apply, add_apply]),
map_smul' := λ B B', ext (λ x y, by simp [comp_apply, smul_apply]) }
@[simp] lemma congr_apply (e : M₂ ≃ₗ[R₂] M₂') (B : bilin_form R₂ M₂) (x y : M₂') :
congr e B x y = B (e.symm x) (e.symm y) := rfl
@[simp] lemma congr_symm (e : M₂ ≃ₗ[R₂] M₂') :
(congr e).symm = congr e.symm :=
by { ext B x y, simp only [congr_apply, linear_equiv.symm_symm], refl }
lemma congr_comp {M₂'' : Type*} [add_comm_monoid M₂''] [module R₂ M₂'']
(e : M₂ ≃ₗ[R₂] M₂') (B : bilin_form R₂ M₂) (l r : M₂'' →ₗ[R₂] M₂') :
(congr e B).comp l r = B.comp
(linear_map.comp (e.symm : M₂' →ₗ[R₂] M₂) l)
(linear_map.comp (e.symm : M₂' →ₗ[R₂] M₂) r) :=
rfl
lemma comp_congr {M₂'' : Type*} [add_comm_monoid M₂''] [module R₂ M₂'']
(e : M₂' ≃ₗ[R₂] M₂'') (B : bilin_form R₂ M₂) (l r : M₂' →ₗ[R₂] M₂) :
congr e (B.comp l r) = B.comp
(l.comp (e.symm : M₂'' →ₗ[R₂] M₂'))
(r.comp (e.symm : M₂'' →ₗ[R₂] M₂')) :=
rfl
end congr
section lin_mul_lin
/-- `lin_mul_lin f g` is the bilinear form mapping `x` and `y` to `f x * g y` -/
def lin_mul_lin (f g : M₂ →ₗ[R₂] R₂) : bilin_form R₂ M₂ :=
{ bilin := λ x y, f x * g y,
bilin_add_left := λ x y z, by rw [linear_map.map_add, add_mul],
bilin_smul_left := λ x y z, by rw [linear_map.map_smul, smul_eq_mul, mul_assoc],
bilin_add_right := λ x y z, by rw [linear_map.map_add, mul_add],
bilin_smul_right := λ x y z, by rw [linear_map.map_smul, smul_eq_mul, mul_left_comm] }
variables {f g : M₂ →ₗ[R₂] R₂}
@[simp] lemma lin_mul_lin_apply (x y) : lin_mul_lin f g x y = f x * g y := rfl
@[simp] lemma lin_mul_lin_comp (l r : M₂' →ₗ[R₂] M₂) :
(lin_mul_lin f g).comp l r = lin_mul_lin (f.comp l) (g.comp r) :=
rfl
@[simp] lemma lin_mul_lin_comp_left (l : M₂ →ₗ[R₂] M₂) :
(lin_mul_lin f g).comp_left l = lin_mul_lin (f.comp l) g :=
rfl
@[simp] lemma lin_mul_lin_comp_right (r : M₂ →ₗ[R₂] M₂) :
(lin_mul_lin f g).comp_right r = lin_mul_lin f (g.comp r) :=
rfl
end lin_mul_lin
/-- The proposition that two elements of a bilinear form space are orthogonal. For orthogonality
of an indexed set of elements, use `bilin_form.is_Ortho`. -/
def is_ortho (B : bilin_form R M) (x y : M) : Prop :=
B x y = 0
lemma is_ortho_def {B : bilin_form R M} {x y : M} :
B.is_ortho x y ↔ B x y = 0 := iff.rfl
lemma is_ortho_zero_left (x : M) : is_ortho B (0 : M) x :=
zero_left x
lemma is_ortho_zero_right (x : M) : is_ortho B x (0 : M) :=
zero_right x
lemma ne_zero_of_not_is_ortho_self {B : bilin_form K V}
(x : V) (hx₁ : ¬ B.is_ortho x x) : x ≠ 0 :=
λ hx₂, hx₁ (hx₂.symm ▸ is_ortho_zero_left _)
/-- A set of vectors `v` is orthogonal with respect to some bilinear form `B` if and only
if for all `i ≠ j`, `B (v i) (v j) = 0`. For orthogonality between two elements, use
`bilin_form.is_ortho` -/
def is_Ortho {n : Type w} (B : bilin_form R M) (v : n → M) : Prop :=
pairwise (B.is_ortho on v)
lemma is_Ortho_def {n : Type w} {B : bilin_form R M} {v : n → M} :
B.is_Ortho v ↔ ∀ i j : n, i ≠ j → B (v i) (v j) = 0 := iff.rfl
section
variables {R₄ M₄ : Type*} [ring R₄] [is_domain R₄]
variables [add_comm_group M₄] [module R₄ M₄] {G : bilin_form R₄ M₄}
@[simp]
theorem is_ortho_smul_left {x y : M₄} {a : R₄} (ha : a ≠ 0) :
is_ortho G (a • x) y ↔ is_ortho G x y :=
begin
dunfold is_ortho,
split; intro H,
{ rw [smul_left, mul_eq_zero] at H,
cases H,
{ trivial },
{ exact H }},
{ rw [smul_left, H, mul_zero] },
end
@[simp]
theorem is_ortho_smul_right {x y : M₄} {a : R₄} (ha : a ≠ 0) :
is_ortho G x (a • y) ↔ is_ortho G x y :=
begin
dunfold is_ortho,
split; intro H,
{ rw [smul_right, mul_eq_zero] at H,
cases H,
{ trivial },
{ exact H }},
{ rw [smul_right, H, mul_zero] },
end
/-- A set of orthogonal vectors `v` with respect to some bilinear form `B` is linearly independent
if for all `i`, `B (v i) (v i) ≠ 0`. -/
lemma linear_independent_of_is_Ortho
{n : Type w} {B : bilin_form K V} {v : n → V}
(hv₁ : B.is_Ortho v) (hv₂ : ∀ i, ¬ B.is_ortho (v i) (v i)) :
linear_independent K v :=
begin
classical,
rw linear_independent_iff',
intros s w hs i hi,
have : B (s.sum $ λ (i : n), w i • v i) (v i) = 0,
{ rw [hs, zero_left] },
have hsum : s.sum (λ (j : n), w j * B (v j) (v i)) = w i * B (v i) (v i),
{ apply finset.sum_eq_single_of_mem i hi,
intros j hj hij,
rw [is_Ortho_def.1 hv₁ _ _ hij, mul_zero], },
simp_rw [sum_left, smul_left, hsum] at this,
exact eq_zero_of_ne_zero_of_mul_right_eq_zero (hv₂ i) this,
end
end
section basis
variables {B₃ F₃ : bilin_form R₃ M₃}
variables {ι : Type*} (b : basis ι R₃ M₃)
/-- Two bilinear forms are equal when they are equal on all basis vectors. -/
lemma ext_basis (h : ∀ i j, B₃ (b i) (b j) = F₃ (b i) (b j)) : B₃ = F₃ :=
to_lin.injective $ b.ext $ λ i, b.ext $ λ j, h i j
/-- Write out `B x y` as a sum over `B (b i) (b j)` if `b` is a basis. -/
lemma sum_repr_mul_repr_mul (x y : M₃) :
(b.repr x).sum (λ i xi, (b.repr y).sum (λ j yj, xi • yj • B₃ (b i) (b j))) = B₃ x y :=
begin
conv_rhs { rw [← b.total_repr x, ← b.total_repr y] },
simp_rw [finsupp.total_apply, finsupp.sum, sum_left, sum_right,
smul_left, smul_right, smul_eq_mul]
end
end basis
end bilin_form
section matrix
variables {n o : Type*}
open bilin_form finset linear_map matrix
open_locale matrix
/-- The map from `matrix n n R` to bilinear forms on `n → R`.
This is an auxiliary definition for the equivalence `matrix.to_bilin_form'`. -/
def matrix.to_bilin'_aux [fintype n] (M : matrix n n R₂) : bilin_form R₂ (n → R₂) :=
{ bilin := λ v w, ∑ i j, v i * M i j * w j,
bilin_add_left := λ x y z, by simp only [pi.add_apply, add_mul, sum_add_distrib],
bilin_smul_left := λ a x y, by simp only [pi.smul_apply, smul_eq_mul, mul_assoc, mul_sum],
bilin_add_right := λ x y z, by simp only [pi.add_apply, mul_add, sum_add_distrib],
bilin_smul_right := λ a x y,
by simp only [pi.smul_apply, smul_eq_mul, mul_assoc, mul_left_comm, mul_sum] }
lemma matrix.to_bilin'_aux_std_basis [fintype n] [decidable_eq n] (M : matrix n n R₂)
(i j : n) : M.to_bilin'_aux (std_basis R₂ (λ _, R₂) i 1) (std_basis R₂ (λ _, R₂) j 1) = M i j :=
begin
rw [matrix.to_bilin'_aux, coe_fn_mk, sum_eq_single i, sum_eq_single j],
{ simp only [std_basis_same, std_basis_same, one_mul, mul_one] },
{ rintros j' - hj',
apply mul_eq_zero_of_right,
exact std_basis_ne R₂ (λ _, R₂) _ _ hj' 1 },
{ intros,
have := finset.mem_univ j,
contradiction },
{ rintros i' - hi',
refine finset.sum_eq_zero (λ j _, _),
apply mul_eq_zero_of_left,
apply mul_eq_zero_of_left,
exact std_basis_ne R₂ (λ _, R₂) _ _ hi' 1 },
{ intros,
have := finset.mem_univ i,
contradiction }
end
/-- The linear map from bilinear forms to `matrix n n R` given an `n`-indexed basis.
This is an auxiliary definition for the equivalence `matrix.to_bilin_form'`. -/
def bilin_form.to_matrix_aux (b : n → M₂) : bilin_form R₂ M₂ →ₗ[R₂] matrix n n R₂ :=
{ to_fun := λ B i j, B (b i) (b j),
map_add' := λ f g, rfl,
map_smul' := λ f g, rfl }
variables [fintype n] [fintype o]
lemma to_bilin'_aux_to_matrix_aux [decidable_eq n] (B₃ : bilin_form R₃ (n → R₃)) :
matrix.to_bilin'_aux (bilin_form.to_matrix_aux (λ j, std_basis R₃ (λ _, R₃) j 1) B₃) = B₃ :=
begin
refine ext_basis (pi.basis_fun R₃ n) (λ i j, _),
rw [bilin_form.to_matrix_aux, linear_map.coe_mk, pi.basis_fun_apply, pi.basis_fun_apply,
matrix.to_bilin'_aux_std_basis]
end
section to_matrix'
/-! ### `to_matrix'` section
This section deals with the conversion between matrices and bilinear forms on `n → R₃`.
-/
variables [decidable_eq n] [decidable_eq o]
/-- The linear equivalence between bilinear forms on `n → R` and `n × n` matrices -/
def bilin_form.to_matrix' : bilin_form R₃ (n → R₃) ≃ₗ[R₃] matrix n n R₃ :=
{ inv_fun := matrix.to_bilin'_aux,
left_inv := by convert to_bilin'_aux_to_matrix_aux,
right_inv := λ M,
by { ext i j, simp only [bilin_form.to_matrix_aux, matrix.to_bilin'_aux_std_basis] },
..bilin_form.to_matrix_aux (λ j, std_basis R₃ (λ _, R₃) j 1) }
@[simp] lemma bilin_form.to_matrix_aux_std_basis (B : bilin_form R₃ (n → R₃)) :
bilin_form.to_matrix_aux (λ j, std_basis R₃ (λ _, R₃) j 1) B =
bilin_form.to_matrix' B :=
rfl
/-- The linear equivalence between `n × n` matrices and bilinear forms on `n → R` -/
def matrix.to_bilin' : matrix n n R₃ ≃ₗ[R₃] bilin_form R₃ (n → R₃) :=
bilin_form.to_matrix'.symm
@[simp] lemma matrix.to_bilin'_aux_eq (M : matrix n n R₃) :
matrix.to_bilin'_aux M = matrix.to_bilin' M :=
rfl
lemma matrix.to_bilin'_apply (M : matrix n n R₃) (x y : n → R₃) :
matrix.to_bilin' M x y = ∑ i j, x i * M i j * y j := rfl
lemma matrix.to_bilin'_apply' (M : matrix n n R₃) (v w : n → R₃) :
matrix.to_bilin' M v w = matrix.dot_product v (M.mul_vec w) :=
begin
simp_rw [matrix.to_bilin'_apply, matrix.dot_product,
matrix.mul_vec, matrix.dot_product],
refine finset.sum_congr rfl (λ _ _, _),
rw finset.mul_sum,
refine finset.sum_congr rfl (λ _ _, _),
rw ← mul_assoc,
end
@[simp] lemma matrix.to_bilin'_std_basis (M : matrix n n R₃) (i j : n) :
matrix.to_bilin' M (std_basis R₃ (λ _, R₃) i 1) (std_basis R₃ (λ _, R₃) j 1) =
M i j :=
matrix.to_bilin'_aux_std_basis M i j
@[simp] lemma bilin_form.to_matrix'_symm :
(bilin_form.to_matrix'.symm : matrix n n R₃ ≃ₗ[R₃] _) = matrix.to_bilin' :=
rfl
@[simp] lemma matrix.to_bilin'_symm :
(matrix.to_bilin'.symm : _ ≃ₗ[R₃] matrix n n R₃) = bilin_form.to_matrix' :=
bilin_form.to_matrix'.symm_symm
@[simp] lemma matrix.to_bilin'_to_matrix' (B : bilin_form R₃ (n → R₃)) :
matrix.to_bilin' (bilin_form.to_matrix' B) = B :=
matrix.to_bilin'.apply_symm_apply B
@[simp] lemma bilin_form.to_matrix'_to_bilin' (M : matrix n n R₃) :
bilin_form.to_matrix' (matrix.to_bilin' M) = M :=
bilin_form.to_matrix'.apply_symm_apply M
@[simp] lemma bilin_form.to_matrix'_apply (B : bilin_form R₃ (n → R₃)) (i j : n) :
bilin_form.to_matrix' B i j =
B (std_basis R₃ (λ _, R₃) i 1) (std_basis R₃ (λ _, R₃) j 1) :=
rfl
@[simp] lemma bilin_form.to_matrix'_comp (B : bilin_form R₃ (n → R₃))
(l r : (o → R₃) →ₗ[R₃] (n → R₃)) :
(B.comp l r).to_matrix' = l.to_matrix'ᵀ ⬝ B.to_matrix' ⬝ r.to_matrix' :=
begin
ext i j,
simp only [bilin_form.to_matrix'_apply, bilin_form.comp_apply, transpose_apply, matrix.mul_apply,
linear_map.to_matrix', linear_equiv.coe_mk, sum_mul],
rw sum_comm,
conv_lhs { rw ← sum_repr_mul_repr_mul (pi.basis_fun R₃ n) (l _) (r _) },
rw finsupp.sum_fintype,
{ apply sum_congr rfl,
rintros i' -,
rw finsupp.sum_fintype,
{ apply sum_congr rfl,
rintros j' -,
simp only [smul_eq_mul, pi.basis_fun_repr, mul_assoc, mul_comm, mul_left_comm,
pi.basis_fun_apply] },
{ intros, simp only [zero_smul, smul_zero] } },
{ intros, simp only [zero_smul, finsupp.sum_zero] }
end
lemma bilin_form.to_matrix'_comp_left (B : bilin_form R₃ (n → R₃))
(f : (n → R₃) →ₗ[R₃] (n → R₃)) : (B.comp_left f).to_matrix' = f.to_matrix'ᵀ ⬝ B.to_matrix' :=
by simp only [bilin_form.comp_left, bilin_form.to_matrix'_comp, to_matrix'_id, matrix.mul_one]
lemma bilin_form.to_matrix'_comp_right (B : bilin_form R₃ (n → R₃))
(f : (n → R₃) →ₗ[R₃] (n → R₃)) : (B.comp_right f).to_matrix' = B.to_matrix' ⬝ f.to_matrix' :=
by simp only [bilin_form.comp_right, bilin_form.to_matrix'_comp, to_matrix'_id,
transpose_one, matrix.one_mul]
lemma bilin_form.mul_to_matrix'_mul (B : bilin_form R₃ (n → R₃))
(M : matrix o n R₃) (N : matrix n o R₃) :
M ⬝ B.to_matrix' ⬝ N = (B.comp Mᵀ.to_lin' N.to_lin').to_matrix' :=
by simp only [B.to_matrix'_comp, transpose_transpose, to_matrix'_to_lin']
lemma bilin_form.mul_to_matrix' (B : bilin_form R₃ (n → R₃)) (M : matrix n n R₃) :
M ⬝ B.to_matrix' = (B.comp_left Mᵀ.to_lin').to_matrix' :=
by simp only [B.to_matrix'_comp_left, transpose_transpose, to_matrix'_to_lin']
lemma bilin_form.to_matrix'_mul (B : bilin_form R₃ (n → R₃)) (M : matrix n n R₃) :
B.to_matrix' ⬝ M = (B.comp_right M.to_lin').to_matrix' :=
by simp only [B.to_matrix'_comp_right, to_matrix'_to_lin']
lemma matrix.to_bilin'_comp (M : matrix n n R₃) (P Q : matrix n o R₃) :
M.to_bilin'.comp P.to_lin' Q.to_lin' = (Pᵀ ⬝ M ⬝ Q).to_bilin' :=
bilin_form.to_matrix'.injective
(by simp only [bilin_form.to_matrix'_comp, bilin_form.to_matrix'_to_bilin', to_matrix'_to_lin'])
end to_matrix'
section to_matrix
/-! ### `to_matrix` section
This section deals with the conversion between matrices and bilinear forms on
a module with a fixed basis.
-/
variables [decidable_eq n] (b : basis n R₃ M₃)
/-- `bilin_form.to_matrix b` is the equivalence between `R`-bilinear forms on `M` and
`n`-by-`n` matrices with entries in `R`, if `b` is an `R`-basis for `M`. -/
noncomputable def bilin_form.to_matrix : bilin_form R₃ M₃ ≃ₗ[R₃] matrix n n R₃ :=
(bilin_form.congr b.equiv_fun).trans bilin_form.to_matrix'
/-- `bilin_form.to_matrix b` is the equivalence between `R`-bilinear forms on `M` and
`n`-by-`n` matrices with entries in `R`, if `b` is an `R`-basis for `M`. -/
noncomputable def matrix.to_bilin : matrix n n R₃ ≃ₗ[R₃] bilin_form R₃ M₃ :=
(bilin_form.to_matrix b).symm
@[simp] lemma basis.equiv_fun_symm_std_basis (i : n) :
b.equiv_fun.symm (std_basis R₃ (λ _, R₃) i 1) = b i :=
begin
rw [b.equiv_fun_symm_apply, finset.sum_eq_single i],
{ rw [std_basis_same, one_smul] },
{ rintros j - hj,
rw [std_basis_ne _ _ _ _ hj, zero_smul] },
{ intro,
have := mem_univ i,
contradiction }
end
@[simp] lemma bilin_form.to_matrix_apply (B : bilin_form R₃ M₃) (i j : n) :
bilin_form.to_matrix b B i j = B (b i) (b j) :=
by rw [bilin_form.to_matrix, linear_equiv.trans_apply, bilin_form.to_matrix'_apply, congr_apply,
b.equiv_fun_symm_std_basis, b.equiv_fun_symm_std_basis]
@[simp] lemma matrix.to_bilin_apply (M : matrix n n R₃) (x y : M₃) :
matrix.to_bilin b M x y = ∑ i j, b.repr x i * M i j * b.repr y j :=
begin
rw [matrix.to_bilin, bilin_form.to_matrix, linear_equiv.symm_trans_apply, ← matrix.to_bilin'],
simp only [congr_symm, congr_apply, linear_equiv.symm_symm, matrix.to_bilin'_apply,
basis.equiv_fun_apply]
end
-- Not a `simp` lemma since `bilin_form.to_matrix` needs an extra argument
lemma bilinear_form.to_matrix_aux_eq (B : bilin_form R₃ M₃) :
bilin_form.to_matrix_aux b B = bilin_form.to_matrix b B :=
ext (λ i j, by rw [bilin_form.to_matrix_apply, bilin_form.to_matrix_aux, linear_map.coe_mk])
@[simp] lemma bilin_form.to_matrix_symm :
(bilin_form.to_matrix b).symm = matrix.to_bilin b :=
rfl
@[simp] lemma matrix.to_bilin_symm :
(matrix.to_bilin b).symm = bilin_form.to_matrix b :=
(bilin_form.to_matrix b).symm_symm
lemma matrix.to_bilin_basis_fun :
matrix.to_bilin (pi.basis_fun R₃ n) = matrix.to_bilin' :=
by { ext M, simp only [matrix.to_bilin_apply, matrix.to_bilin'_apply, pi.basis_fun_repr] }
lemma bilin_form.to_matrix_basis_fun :
bilin_form.to_matrix (pi.basis_fun R₃ n) = bilin_form.to_matrix' :=
by { ext B, rw [bilin_form.to_matrix_apply, bilin_form.to_matrix'_apply,
pi.basis_fun_apply, pi.basis_fun_apply] }
@[simp] lemma matrix.to_bilin_to_matrix (B : bilin_form R₃ M₃) :
matrix.to_bilin b (bilin_form.to_matrix b B) = B :=
(matrix.to_bilin b).apply_symm_apply B
@[simp] lemma bilin_form.to_matrix_to_bilin (M : matrix n n R₃) :
bilin_form.to_matrix b (matrix.to_bilin b M) = M :=
(bilin_form.to_matrix b).apply_symm_apply M
variables {M₃' : Type*} [add_comm_group M₃'] [module R₃ M₃']
variables (c : basis o R₃ M₃')
variables [decidable_eq o]
-- Cannot be a `simp` lemma because `b` must be inferred.
lemma bilin_form.to_matrix_comp
(B : bilin_form R₃ M₃) (l r : M₃' →ₗ[R₃] M₃) :
bilin_form.to_matrix c (B.comp l r) =
(to_matrix c b l)ᵀ ⬝ bilin_form.to_matrix b B ⬝ to_matrix c b r :=
begin
ext i j,
simp only [bilin_form.to_matrix_apply, bilin_form.comp_apply, transpose_apply, matrix.mul_apply,
linear_map.to_matrix', linear_equiv.coe_mk, sum_mul],
rw sum_comm,
conv_lhs { rw ← sum_repr_mul_repr_mul b },
rw finsupp.sum_fintype,
{ apply sum_congr rfl,
rintros i' -,
rw finsupp.sum_fintype,
{ apply sum_congr rfl,
rintros j' -,
simp only [smul_eq_mul, linear_map.to_matrix_apply,
basis.equiv_fun_apply, mul_assoc, mul_comm, mul_left_comm] },
{ intros, simp only [zero_smul, smul_zero] } },
{ intros, simp only [zero_smul, finsupp.sum_zero] }
end
lemma bilin_form.to_matrix_comp_left (B : bilin_form R₃ M₃) (f : M₃ →ₗ[R₃] M₃) :
bilin_form.to_matrix b (B.comp_left f) = (to_matrix b b f)ᵀ ⬝ bilin_form.to_matrix b B :=
by simp only [comp_left, bilin_form.to_matrix_comp b b, to_matrix_id, matrix.mul_one]
lemma bilin_form.to_matrix_comp_right (B : bilin_form R₃ M₃) (f : M₃ →ₗ[R₃] M₃) :
bilin_form.to_matrix b (B.comp_right f) = bilin_form.to_matrix b B ⬝ (to_matrix b b f) :=
by simp only [bilin_form.comp_right, bilin_form.to_matrix_comp b b, to_matrix_id,
transpose_one, matrix.one_mul]
@[simp]
lemma bilin_form.to_matrix_mul_basis_to_matrix (c : basis o R₃ M₃) (B : bilin_form R₃ M₃) :
(b.to_matrix c)ᵀ ⬝ bilin_form.to_matrix b B ⬝ b.to_matrix c = bilin_form.to_matrix c B :=
by rw [← linear_map.to_matrix_id_eq_basis_to_matrix, ← bilin_form.to_matrix_comp,
bilin_form.comp_id_id]
lemma bilin_form.mul_to_matrix_mul (B : bilin_form R₃ M₃)
(M : matrix o n R₃) (N : matrix n o R₃) :
M ⬝ bilin_form.to_matrix b B ⬝ N =
bilin_form.to_matrix c (B.comp (to_lin c b Mᵀ) (to_lin c b N)) :=
by simp only [B.to_matrix_comp b c, to_matrix_to_lin, transpose_transpose]
lemma bilin_form.mul_to_matrix (B : bilin_form R₃ M₃) (M : matrix n n R₃) :
M ⬝ bilin_form.to_matrix b B =
bilin_form.to_matrix b (B.comp_left (to_lin b b Mᵀ)) :=
by rw [B.to_matrix_comp_left b, to_matrix_to_lin, transpose_transpose]
lemma bilin_form.to_matrix_mul (B : bilin_form R₃ M₃) (M : matrix n n R₃) :
bilin_form.to_matrix b B ⬝ M =
bilin_form.to_matrix b (B.comp_right (to_lin b b M)) :=
by rw [B.to_matrix_comp_right b, to_matrix_to_lin]
lemma matrix.to_bilin_comp (M : matrix n n R₃) (P Q : matrix n o R₃) :
(matrix.to_bilin b M).comp (to_lin c b P) (to_lin c b Q) = matrix.to_bilin c (Pᵀ ⬝ M ⬝ Q) :=
(bilin_form.to_matrix c).injective
(by simp only [bilin_form.to_matrix_comp b c, bilin_form.to_matrix_to_bilin, to_matrix_to_lin])
end to_matrix
end matrix
namespace refl_bilin_form
open refl_bilin_form bilin_form
/-- The proposition that a bilinear form is reflexive -/
def is_refl (B : bilin_form R M) : Prop := ∀ (x y : M), B x y = 0 → B y x = 0
variable (H : is_refl B)
lemma eq_zero : ∀ {x y : M}, B x y = 0 → B y x = 0 := λ x y, H x y
lemma ortho_sym {x y : M} :
is_ortho B x y ↔ is_ortho B y x := ⟨eq_zero H, eq_zero H⟩
end refl_bilin_form
namespace sym_bilin_form
open sym_bilin_form bilin_form
/-- The proposition that a bilinear form is symmetric -/
def is_sym (B : bilin_form R M) : Prop := ∀ (x y : M), B x y = B y x
variable (H : is_sym B)
lemma sym (x y : M) : B x y = B y x := H x y
lemma is_refl : refl_bilin_form.is_refl B := λ x y H1, H x y ▸ H1
lemma ortho_sym {x y : M} :
is_ortho B x y ↔ is_ortho B y x := refl_bilin_form.ortho_sym (is_refl H)
lemma is_sym_iff_flip' [algebra R₂ R] : is_sym B ↔ flip_hom R₂ B = B :=
begin
split,
{ intros h,
ext x y,
exact h y x },
{ intros h x y,
conv_lhs { rw ← h },
simp }
end
end sym_bilin_form
namespace alt_bilin_form
open alt_bilin_form bilin_form
/-- The proposition that a bilinear form is alternating -/
def is_alt (B : bilin_form R M) : Prop := ∀ (x : M), B x x = 0
variable (H : is_alt B)
include H
lemma self_eq_zero (x : M) : B x x = 0 := H x
lemma neg (H : is_alt B₁) (x y : M₁) :
- B₁ x y = B₁ y x :=
begin
have H1 : B₁ (x + y) (x + y) = 0,
{ exact self_eq_zero H (x + y) },
rw [add_left, add_right, add_right,
self_eq_zero H, self_eq_zero H, ring.zero_add,
ring.add_zero, add_eq_zero_iff_neg_eq] at H1,
exact H1,
end
end alt_bilin_form
namespace bilin_form
section linear_adjoints
variables (B) (F : bilin_form R M)
variables {M' : Type*} [add_comm_monoid M'] [module R M']
variables (B' : bilin_form R M') (f f' : M →ₗ[R] M') (g g' : M' →ₗ[R] M)
/-- Given a pair of modules equipped with bilinear forms, this is the condition for a pair of
maps between them to be mutually adjoint. -/
def is_adjoint_pair := ∀ ⦃x y⦄, B' (f x) y = B x (g y)
variables {B B' B₂ f f' g g'}
lemma is_adjoint_pair.eq (h : is_adjoint_pair B B' f g) :
∀ {x y}, B' (f x) y = B x (g y) := h
lemma is_adjoint_pair_iff_comp_left_eq_comp_right (f g : module.End R M) :
is_adjoint_pair B F f g ↔ F.comp_left f = B.comp_right g :=
begin
split; intros h,
{ ext x y, rw [comp_left_apply, comp_right_apply], apply h, },
{ intros x y, rw [←comp_left_apply, ←comp_right_apply], rw h, },
end
lemma is_adjoint_pair_zero : is_adjoint_pair B B' 0 0 :=
λ x y, by simp only [bilin_form.zero_left, bilin_form.zero_right, linear_map.zero_apply]
lemma is_adjoint_pair_id : is_adjoint_pair B B 1 1 := λ x y, rfl
lemma is_adjoint_pair.add (h : is_adjoint_pair B B' f g) (h' : is_adjoint_pair B B' f' g') :
is_adjoint_pair B B' (f + f') (g + g') :=
λ x y, by rw [linear_map.add_apply, linear_map.add_apply, add_left, add_right, h, h']
variables {M₁' : Type*} [add_comm_group M₁'] [module R₁ M₁']
variables {B₁' : bilin_form R₁ M₁'} {f₁ f₁' : M₁ →ₗ[R₁] M₁'} {g₁ g₁' : M₁' →ₗ[R₁] M₁}
lemma is_adjoint_pair.sub (h : is_adjoint_pair B₁ B₁' f₁ g₁) (h' : is_adjoint_pair B₁ B₁' f₁' g₁') :
is_adjoint_pair B₁ B₁' (f₁ - f₁') (g₁ - g₁') :=
λ x y, by rw [linear_map.sub_apply, linear_map.sub_apply, sub_left, sub_right, h, h']
variables {M₂' : Type*} [add_comm_monoid M₂'] [module R₂ M₂']
variables {B₂' : bilin_form R₂ M₂'} {f₂ f₂' : M₂ →ₗ[R₂] M₂'} {g₂ g₂' : M₂' →ₗ[R₂] M₂}
lemma is_adjoint_pair.smul (c : R₂) (h : is_adjoint_pair B₂ B₂' f₂ g₂) :
is_adjoint_pair B₂ B₂' (c • f₂) (c • g₂) :=
λ x y, by rw [linear_map.smul_apply, linear_map.smul_apply, smul_left, smul_right, h]
variables {M'' : Type*} [add_comm_monoid M''] [module R M'']
variables (B'' : bilin_form R M'')
lemma is_adjoint_pair.comp {f' : M' →ₗ[R] M''} {g' : M'' →ₗ[R] M'}
(h : is_adjoint_pair B B' f g) (h' : is_adjoint_pair B' B'' f' g') :
is_adjoint_pair B B'' (f'.comp f) (g.comp g') :=
λ x y, by rw [linear_map.comp_apply, linear_map.comp_apply, h', h]
lemma is_adjoint_pair.mul
{f g f' g' : module.End R M} (h : is_adjoint_pair B B f g) (h' : is_adjoint_pair B B f' g') :
is_adjoint_pair B B (f * f') (g' * g) :=
λ x y, by rw [linear_map.mul_apply, linear_map.mul_apply, h, h']
variables (B B' B₁ B₂) (F₂ : bilin_form R₂ M₂)
/-- The condition for an endomorphism to be "self-adjoint" with respect to a pair of bilinear forms
on the underlying module. In the case that these two forms are identical, this is the usual concept
of self adjointness. In the case that one of the forms is the negation of the other, this is the
usual concept of skew adjointness. -/
def is_pair_self_adjoint (f : module.End R M) := is_adjoint_pair B F f f
/-- The set of pair-self-adjoint endomorphisms are a submodule of the type of all endomorphisms. -/
def is_pair_self_adjoint_submodule : submodule R₂ (module.End R₂ M₂) :=
{ carrier := { f | is_pair_self_adjoint B₂ F₂ f },
zero_mem' := is_adjoint_pair_zero,
add_mem' := λ f g hf hg, hf.add hg,
smul_mem' := λ c f h, h.smul c, }
@[simp] lemma mem_is_pair_self_adjoint_submodule (f : module.End R₂ M₂) :
f ∈ is_pair_self_adjoint_submodule B₂ F₂ ↔ is_pair_self_adjoint B₂ F₂ f :=
by refl
variables {M₃' : Type*} [add_comm_group M₃'] [module R₃ M₃']
variables (B₃ F₃ : bilin_form R₃ M₃)
lemma is_pair_self_adjoint_equiv (e : M₃' ≃ₗ[R₃] M₃) (f : module.End R₃ M₃) :
is_pair_self_adjoint B₃ F₃ f ↔
is_pair_self_adjoint (B₃.comp ↑e ↑e) (F₃.comp ↑e ↑e) (e.symm.conj f) :=
begin
have hₗ : (F₃.comp ↑e ↑e).comp_left (e.symm.conj f) = (F₃.comp_left f).comp ↑e ↑e :=
by { ext, simp [linear_equiv.symm_conj_apply], },
have hᵣ : (B₃.comp ↑e ↑e).comp_right (e.symm.conj f) = (B₃.comp_right f).comp ↑e ↑e :=
by { ext, simp [linear_equiv.conj_apply], },
have he : function.surjective (⇑(↑e : M₃' →ₗ[R₃] M₃) : M₃' → M₃) := e.surjective,
show bilin_form.is_adjoint_pair _ _ _ _ ↔ bilin_form.is_adjoint_pair _ _ _ _,
rw [is_adjoint_pair_iff_comp_left_eq_comp_right, is_adjoint_pair_iff_comp_left_eq_comp_right,
hᵣ, hₗ, comp_injective _ _ he he],
end
/-- An endomorphism of a module is self-adjoint with respect to a bilinear form if it serves as an
adjoint for itself. -/
def is_self_adjoint (f : module.End R M) := is_adjoint_pair B B f f
/-- An endomorphism of a module is skew-adjoint with respect to a bilinear form if its negation
serves as an adjoint. -/
def is_skew_adjoint (f : module.End R₁ M₁) := is_adjoint_pair B₁ B₁ f (-f)
lemma is_skew_adjoint_iff_neg_self_adjoint (f : module.End R₁ M₁) :
B₁.is_skew_adjoint f ↔ is_adjoint_pair (-B₁) B₁ f f :=
show (∀ x y, B₁ (f x) y = B₁ x ((-f) y)) ↔ ∀ x y, B₁ (f x) y = (-B₁) x (f y),
by simp only [linear_map.neg_apply, bilin_form.neg_apply, bilin_form.neg_right]
/-- The set of self-adjoint endomorphisms of a module with bilinear form is a submodule. (In fact
it is a Jordan subalgebra.) -/
def self_adjoint_submodule := is_pair_self_adjoint_submodule B₂ B₂
@[simp] lemma mem_self_adjoint_submodule (f : module.End R₂ M₂) :
f ∈ B₂.self_adjoint_submodule ↔ B₂.is_self_adjoint f := iff.rfl
/-- The set of skew-adjoint endomorphisms of a module with bilinear form is a submodule. (In fact
it is a Lie subalgebra.) -/
def skew_adjoint_submodule := is_pair_self_adjoint_submodule (-B₃) B₃
@[simp] lemma mem_skew_adjoint_submodule (f : module.End R₃ M₃) :
f ∈ B₃.skew_adjoint_submodule ↔ B₃.is_skew_adjoint f :=
by { rw is_skew_adjoint_iff_neg_self_adjoint, exact iff.rfl, }
end linear_adjoints
end bilin_form
section matrix_adjoints
open_locale matrix
variables {n : Type w} [fintype n]
variables (b : basis n R₃ M₃)
variables (J J₃ A A' : matrix n n R₃)
/-- The condition for the square matrices `A`, `A'` to be an adjoint pair with respect to the square
matrices `J`, `J₃`. -/
def matrix.is_adjoint_pair := Aᵀ ⬝ J₃ = J ⬝ A'
/-- The condition for a square matrix `A` to be self-adjoint with respect to the square matrix
`J`. -/
def matrix.is_self_adjoint := matrix.is_adjoint_pair J J A A
/-- The condition for a square matrix `A` to be skew-adjoint with respect to the square matrix
`J`. -/
def matrix.is_skew_adjoint := matrix.is_adjoint_pair J J A (-A)
@[simp] lemma is_adjoint_pair_to_bilin' [decidable_eq n] :
bilin_form.is_adjoint_pair (matrix.to_bilin' J) (matrix.to_bilin' J₃)
(matrix.to_lin' A) (matrix.to_lin' A') ↔
matrix.is_adjoint_pair J J₃ A A' :=
begin
rw bilin_form.is_adjoint_pair_iff_comp_left_eq_comp_right,
have h : ∀ (B B' : bilin_form R₃ (n → R₃)), B = B' ↔
(bilin_form.to_matrix' B) = (bilin_form.to_matrix' B'),
{ intros B B',
split; intros h,
{ rw h },
{ exact bilin_form.to_matrix'.injective h } },
rw [h, bilin_form.to_matrix'_comp_left, bilin_form.to_matrix'_comp_right,
linear_map.to_matrix'_to_lin', linear_map.to_matrix'_to_lin',
bilin_form.to_matrix'_to_bilin', bilin_form.to_matrix'_to_bilin'],
refl,
end
@[simp] lemma is_adjoint_pair_to_bilin [decidable_eq n] :
bilin_form.is_adjoint_pair (matrix.to_bilin b J) (matrix.to_bilin b J₃)
(matrix.to_lin b b A) (matrix.to_lin b b A') ↔
matrix.is_adjoint_pair J J₃ A A' :=
begin
rw bilin_form.is_adjoint_pair_iff_comp_left_eq_comp_right,
have h : ∀ (B B' : bilin_form R₃ M₃), B = B' ↔
(bilin_form.to_matrix b B) = (bilin_form.to_matrix b B'),
{ intros B B',
split; intros h,
{ rw h },
{ exact (bilin_form.to_matrix b).injective h } },
rw [h, bilin_form.to_matrix_comp_left, bilin_form.to_matrix_comp_right,
linear_map.to_matrix_to_lin, linear_map.to_matrix_to_lin,
bilin_form.to_matrix_to_bilin, bilin_form.to_matrix_to_bilin],
refl,
end
lemma matrix.is_adjoint_pair_equiv [decidable_eq n] (P : matrix n n R₃) (h : is_unit P) :
(Pᵀ ⬝ J ⬝ P).is_adjoint_pair (Pᵀ ⬝ J ⬝ P) A A' ↔
J.is_adjoint_pair J (P ⬝ A ⬝ P⁻¹) (P ⬝ A' ⬝ P⁻¹) :=
have h' : is_unit P.det := P.is_unit_iff_is_unit_det.mp h,
begin
let u := P.nonsing_inv_unit h',
let v := Pᵀ.nonsing_inv_unit (P.is_unit_det_transpose h'),
let x := Aᵀ * Pᵀ * J,
let y := J * P * A',
suffices : x * ↑u = ↑v * y ↔ ↑v⁻¹ * x = y * ↑u⁻¹,
{ dunfold matrix.is_adjoint_pair,
repeat { rw matrix.transpose_mul, },
simp only [←matrix.mul_eq_mul, ←mul_assoc, P.transpose_nonsing_inv],
conv_lhs { to_rhs, rw [mul_assoc, mul_assoc], congr, skip, rw ←mul_assoc, },
conv_rhs { rw [mul_assoc, mul_assoc], conv { to_lhs, congr, skip, rw ←mul_assoc }, },
exact this, },
rw units.eq_mul_inv_iff_mul_eq, conv_rhs { rw mul_assoc, }, rw v.inv_mul_eq_iff_eq_mul,
end
variables [decidable_eq n]
/-- The submodule of pair-self-adjoint matrices with respect to bilinear forms corresponding to
given matrices `J`, `J₂`. -/
def pair_self_adjoint_matrices_submodule : submodule R₃ (matrix n n R₃) :=
(bilin_form.is_pair_self_adjoint_submodule (matrix.to_bilin' J) (matrix.to_bilin' J₃)).map
((linear_map.to_matrix' : ((n → R₃) →ₗ[R₃] (n → R₃)) ≃ₗ[R₃] matrix n n R₃) :
((n → R₃) →ₗ[R₃] (n → R₃)) →ₗ[R₃] matrix n n R₃)
@[simp] lemma mem_pair_self_adjoint_matrices_submodule :
A ∈ (pair_self_adjoint_matrices_submodule J J₃) ↔ matrix.is_adjoint_pair J J₃ A A :=
begin
simp only [pair_self_adjoint_matrices_submodule, linear_equiv.coe_coe,
linear_map.to_matrix'_apply, submodule.mem_map, bilin_form.mem_is_pair_self_adjoint_submodule],
split,
{ rintros ⟨f, hf, hA⟩,
have hf' : f = A.to_lin' := by rw [←hA, matrix.to_lin'_to_matrix'], rw hf' at hf,
rw ← is_adjoint_pair_to_bilin',
exact hf, },
{ intros h, refine ⟨A.to_lin', _, linear_map.to_matrix'_to_lin' _⟩,
exact (is_adjoint_pair_to_bilin' _ _ _ _).mpr h, },
end
/-- The submodule of self-adjoint matrices with respect to the bilinear form corresponding to
the matrix `J`. -/
def self_adjoint_matrices_submodule : submodule R₃ (matrix n n R₃) :=
pair_self_adjoint_matrices_submodule J J
@[simp] lemma mem_self_adjoint_matrices_submodule :
A ∈ self_adjoint_matrices_submodule J ↔ J.is_self_adjoint A :=
by { erw mem_pair_self_adjoint_matrices_submodule, refl, }
/-- The submodule of skew-adjoint matrices with respect to the bilinear form corresponding to
the matrix `J`. -/
def skew_adjoint_matrices_submodule : submodule R₃ (matrix n n R₃) :=
pair_self_adjoint_matrices_submodule (-J) J
@[simp] lemma mem_skew_adjoint_matrices_submodule :
A ∈ skew_adjoint_matrices_submodule J ↔ J.is_skew_adjoint A :=
begin
erw mem_pair_self_adjoint_matrices_submodule,
simp [matrix.is_skew_adjoint, matrix.is_adjoint_pair],
end
end matrix_adjoints
namespace bilin_form
section orthogonal
/-- The orthogonal complement of a submodule `N` with respect to some bilinear form is the set of
elements `x` which are orthogonal to all elements of `N`; i.e., for all `y` in `N`, `B x y = 0`.
Note that for general (neither symmetric nor antisymmetric) bilinear forms this definition has a
chirality; in addition to this "left" orthogonal complement one could define a "right" orthogonal
complement for which, for all `y` in `N`, `B y x = 0`. This variant definition is not currently
provided in mathlib. -/
def orthogonal (B : bilin_form R M) (N : submodule R M) : submodule R M :=
{ carrier := { m | ∀ n ∈ N, is_ortho B n m },
zero_mem' := λ x _, is_ortho_zero_right x,
add_mem' := λ x y hx hy n hn,
by rw [is_ortho, add_right, show B n x = 0, by exact hx n hn,
show B n y = 0, by exact hy n hn, zero_add],
smul_mem' := λ c x hx n hn,
by rw [is_ortho, smul_right, show B n x = 0, by exact hx n hn, mul_zero] }
variables {N L : submodule R M}
@[simp] lemma mem_orthogonal_iff {N : submodule R M} {m : M} :
m ∈ B.orthogonal N ↔ ∀ n ∈ N, is_ortho B n m := iff.rfl
lemma orthogonal_le (h : N ≤ L) : B.orthogonal L ≤ B.orthogonal N :=
λ _ hn l hl, hn l (h hl)
lemma le_orthogonal_orthogonal (b : refl_bilin_form.is_refl B) :
N ≤ B.orthogonal (B.orthogonal N) :=
λ n hn m hm, b _ _ (hm n hn)
-- ↓ This lemma only applies in fields as we require `a * b = 0 → a = 0 ∨ b = 0`
lemma span_singleton_inf_orthogonal_eq_bot
{B : bilin_form K V} {x : V} (hx : ¬ B.is_ortho x x) :
(K ∙ x) ⊓ B.orthogonal (K ∙ x) = ⊥ :=
begin
rw ← finset.coe_singleton,
refine eq_bot_iff.2 (λ y h, _),
rcases mem_span_finset.1 h.1 with ⟨μ, rfl⟩,
have := h.2 x _,
{ rw finset.sum_singleton at this ⊢,
suffices hμzero : μ x = 0,
{ rw [hμzero, zero_smul, submodule.mem_bot] },
change B x (μ x • x) = 0 at this, rw [smul_right] at this,
exact or.elim (zero_eq_mul.mp this.symm) id (λ hfalse, false.elim $ hx hfalse) },
{ rw submodule.mem_span; exact λ _ hp, hp $ finset.mem_singleton_self _ }
end
-- ↓ This lemma only applies in fields since we use the `mul_eq_zero`
lemma orthogonal_span_singleton_eq_to_lin_ker {B : bilin_form K V} (x : V) :
B.orthogonal (K ∙ x) = (bilin_form.to_lin B x).ker :=
begin
ext y,
simp_rw [mem_orthogonal_iff, linear_map.mem_ker,
submodule.mem_span_singleton ],
split,
{ exact λ h, h x ⟨1, one_smul _ _⟩ },
{ rintro h _ ⟨z, rfl⟩,
rw [is_ortho, smul_left, mul_eq_zero],
exact or.intro_right _ h }
end
lemma span_singleton_sup_orthogonal_eq_top {B : bilin_form K V}
{x : V} (hx : ¬ B.is_ortho x x) :
(K ∙ x) ⊔ B.orthogonal (K ∙ x) = ⊤ :=
begin
rw orthogonal_span_singleton_eq_to_lin_ker,
exact linear_map.span_singleton_sup_ker_eq_top _ hx,
end
/-- Given a bilinear form `B` and some `x` such that `B x x ≠ 0`, the span of the singleton of `x`
is complement to its orthogonal complement. -/
lemma is_compl_span_singleton_orthogonal {B : bilin_form K V}
{x : V} (hx : ¬ B.is_ortho x x) : is_compl (K ∙ x) (B.orthogonal $ K ∙ x) :=
{ inf_le_bot := eq_bot_iff.1 $ span_singleton_inf_orthogonal_eq_bot hx,
top_le_sup := eq_top_iff.1 $ span_singleton_sup_orthogonal_eq_top hx }
end orthogonal
/-- The restriction of a bilinear form on a submodule. -/
@[simps apply]
def restrict (B : bilin_form R M) (W : submodule R M) : bilin_form R W :=
{ bilin := λ a b, B a b,
bilin_add_left := λ _ _ _, add_left _ _ _,
bilin_smul_left := λ _ _ _, smul_left _ _ _,
bilin_add_right := λ _ _ _, add_right _ _ _,
bilin_smul_right := λ _ _ _, smul_right _ _ _}
/-- The restriction of a symmetric bilinear form on a submodule is also symmetric. -/
lemma restrict_sym (B : bilin_form R M) (b : sym_bilin_form.is_sym B)
(W : submodule R M) : sym_bilin_form.is_sym $ B.restrict W :=
λ x y, b x y
/-- A nondegenerate bilinear form is a bilinear form such that the only element that is orthogonal
to every other element is `0`; i.e., for all nonzero `m` in `M`, there exists `n` in `M` with
`B m n ≠ 0`.
Note that for general (neither symmetric nor antisymmetric) bilinear forms this definition has a
chirality; in addition to this "left" nondegeneracy condition one could define a "right"
nondegeneracy condition that in the situation described, `B n m ≠ 0`. This variant definition is
not currently provided in mathlib. In finite dimension either definition implies the other. -/
def nondegenerate (B : bilin_form R M) : Prop :=
∀ m : M, (∀ n : M, B m n = 0) → m = 0
section
variables (R M)
/-- In a non-trivial module, zero is not non-degenerate. -/
lemma not_nondegenerate_zero [nontrivial M] : ¬(0 : bilin_form R M).nondegenerate :=
let ⟨m, hm⟩ := exists_ne (0 : M) in λ h, hm (h m $ λ n, rfl)
end
lemma nondegenerate.ne_zero [nontrivial M] {B : bilin_form R M} (h : B.nondegenerate) : B ≠ 0 :=
λ h0, not_nondegenerate_zero R M $ h0 ▸ h
/-- A bilinear form is nondegenerate if and only if it has a trivial kernel. -/
theorem nondegenerate_iff_ker_eq_bot {B : bilin_form R₂ M₂} :
B.nondegenerate ↔ B.to_lin.ker = ⊥ :=
begin
rw linear_map.ker_eq_bot',
split; intro h,
{ refine λ m hm, h _ (λ x, _),
rw [← to_lin_apply, hm], refl },
{ intros m hm, apply h,
ext x, exact hm x }
end
lemma nondegenerate.ker_eq_bot {B : bilin_form R₂ M₂} (h : B.nondegenerate) :
B.to_lin.ker = ⊥ := nondegenerate_iff_ker_eq_bot.mp h
/-- The restriction of a nondegenerate bilinear form `B` onto a submodule `W` is
nondegenerate if `disjoint W (B.orthogonal W)`. -/
lemma nondegenerate_restrict_of_disjoint_orthogonal
(B : bilin_form R₁ M₁) (b : sym_bilin_form.is_sym B)
{W : submodule R₁ M₁} (hW : disjoint W (B.orthogonal W)) :
(B.restrict W).nondegenerate :=
begin
rintro ⟨x, hx⟩ b₁,
rw [submodule.mk_eq_zero, ← submodule.mem_bot R₁],
refine hW ⟨hx, λ y hy, _⟩,
specialize b₁ ⟨y, hy⟩,
rwa [restrict_apply, submodule.coe_mk, submodule.coe_mk, b] at b₁
end
/-- An orthogonal basis with respect to a nondegenerate bilinear form has no self-orthogonal
elements. -/
lemma is_Ortho.not_is_ortho_basis_self_of_nondegenerate
{n : Type w} [nontrivial R] {B : bilin_form R M} {v : basis n R M}
(h : B.is_Ortho v) (hB : B.nondegenerate) (i : n) :
¬B.is_ortho (v i) (v i) :=
begin
intro ho,
refine v.ne_zero i (hB (v i) $ λ m, _),
obtain ⟨vi, rfl⟩ := v.repr.symm.surjective m,
rw [basis.repr_symm_apply, finsupp.total_apply, finsupp.sum, sum_right],
apply finset.sum_eq_zero,
rintros j -,
rw smul_right,
convert mul_zero _ using 2,
obtain rfl | hij := eq_or_ne i j,
{ exact ho },
{ exact h i j hij },
end
/-- Given an orthogonal basis with respect to a bilinear form, the bilinear form is nondegenerate
iff the basis has no elements which are self-orthogonal. -/
lemma is_Ortho.nondegenerate_iff_not_is_ortho_basis_self {n : Type w} [nontrivial R]
[no_zero_divisors R] (B : bilin_form R M) (v : basis n R M) (hO : B.is_Ortho v) :
B.nondegenerate ↔ ∀ i, ¬B.is_ortho (v i) (v i) :=
begin
refine ⟨hO.not_is_ortho_basis_self_of_nondegenerate, λ ho m hB, _⟩,
obtain ⟨vi, rfl⟩ := v.repr.symm.surjective m,
rw linear_equiv.map_eq_zero_iff,
ext i,
rw [finsupp.zero_apply],
specialize hB (v i),
simp_rw [basis.repr_symm_apply, finsupp.total_apply, finsupp.sum, sum_left, smul_left] at hB,
rw finset.sum_eq_single i at hB,
{ exact eq_zero_of_ne_zero_of_mul_right_eq_zero (ho i) hB, },
{ intros j hj hij, convert mul_zero _ using 2, exact hO j i hij, },
{ intros hi, convert zero_mul _ using 2, exact finsupp.not_mem_support_iff.mp hi }
end
section
lemma to_lin_restrict_ker_eq_inf_orthogonal
(B : bilin_form K V) (W : subspace K V) (b : sym_bilin_form.is_sym B) :
(B.to_lin.dom_restrict W).ker.map W.subtype = (W ⊓ B.orthogonal ⊤ : subspace K V) :=
begin
ext x, split; intro hx,
{ rcases hx with ⟨⟨x, hx⟩, hker, rfl⟩,
erw linear_map.mem_ker at hker,
split,
{ simp [hx] },
{ intros y _,
rw [is_ortho, b],
change (B.to_lin.dom_restrict W) ⟨x, hx⟩ y = 0,
rw hker, refl } },
{ simp_rw [submodule.mem_map, linear_map.mem_ker],
refine ⟨⟨x, hx.1⟩, _, rfl⟩,
ext y, change B x y = 0,
rw b,
exact hx.2 _ submodule.mem_top }
end
lemma to_lin_restrict_range_dual_annihilator_comap_eq_orthogonal
(B : bilin_form K V) (W : subspace K V) :
(B.to_lin.dom_restrict W).range.dual_annihilator_comap = B.orthogonal W :=
begin
ext x, split; rw [mem_orthogonal_iff]; intro hx,
{ intros y hy,
rw submodule.mem_dual_annihilator_comap_iff at hx,
refine hx (B.to_lin.dom_restrict W ⟨y, hy⟩) ⟨⟨y, hy⟩, rfl⟩ },
{ rw submodule.mem_dual_annihilator_comap_iff,
rintro _ ⟨⟨w, hw⟩, rfl⟩,
exact hx w hw }
end
variable [finite_dimensional K V]
open finite_dimensional
lemma finrank_add_finrank_orthogonal
{B : bilin_form K V} {W : subspace K V} (b₁ : sym_bilin_form.is_sym B) :
finrank K W + finrank K (B.orthogonal W) =
finrank K V + finrank K (W ⊓ B.orthogonal ⊤ : subspace K V) :=
begin
rw [← to_lin_restrict_ker_eq_inf_orthogonal _ _ b₁,
← to_lin_restrict_range_dual_annihilator_comap_eq_orthogonal _ _,
finrank_map_subtype_eq],
conv_rhs { rw [← @subspace.finrank_add_finrank_dual_annihilator_comap_eq K V _ _ _ _
(B.to_lin.dom_restrict W).range,
add_comm, ← add_assoc, add_comm (finrank K ↥((B.to_lin.dom_restrict W).ker)),
linear_map.finrank_range_add_finrank_ker] },
end
/-- A subspace is complement to its orthogonal complement with respect to some
bilinear form if that bilinear form restricted on to the subspace is nondegenerate. -/
lemma restrict_nondegenerate_of_is_compl_orthogonal
{B : bilin_form K V} {W : subspace K V}
(b₁ : sym_bilin_form.is_sym B) (b₂ : (B.restrict W).nondegenerate) :
is_compl W (B.orthogonal W) :=
begin
have : W ⊓ B.orthogonal W = ⊥,
{ rw eq_bot_iff,
intros x hx,
obtain ⟨hx₁, hx₂⟩ := submodule.mem_inf.1 hx,
refine subtype.mk_eq_mk.1 (b₂ ⟨x, hx₁⟩ _),
rintro ⟨n, hn⟩,
rw [restrict_apply, submodule.coe_mk, submodule.coe_mk, b₁],
exact hx₂ n hn },
refine ⟨this ▸ le_refl _, _⟩,
{ rw top_le_iff,
refine eq_top_of_finrank_eq _,
refine le_antisymm (submodule.finrank_le _) _,
conv_rhs { rw ← add_zero (finrank K _) },
rw [← finrank_bot K V, ← this, submodule.dim_sup_add_dim_inf_eq,
finrank_add_finrank_orthogonal b₁],
exact nat.le.intro rfl }
end
/-- A subspace is complement to its orthogonal complement with respect to some bilinear form
if and only if that bilinear form restricted on to the subspace is nondegenerate. -/
theorem restrict_nondegenerate_iff_is_compl_orthogonal
{B : bilin_form K V} {W : subspace K V} (b₁ : sym_bilin_form.is_sym B) :
(B.restrict W).nondegenerate ↔ is_compl W (B.orthogonal W) :=
⟨λ b₂, restrict_nondegenerate_of_is_compl_orthogonal b₁ b₂,
λ h, B.nondegenerate_restrict_of_disjoint_orthogonal b₁ h.1⟩
/-- Given a nondegenerate bilinear form `B` on a finite-dimensional vector space, `B.to_dual` is
the linear equivalence between a vector space and its dual with the underlying linear map
`B.to_lin`. -/
noncomputable def to_dual (B : bilin_form K V) (b : B.nondegenerate) :
V ≃ₗ[K] module.dual K V :=
B.to_lin.linear_equiv_of_injective
(linear_map.ker_eq_bot.mp $ b.ker_eq_bot) subspace.dual_finrank_eq.symm
lemma to_dual_def {B : bilin_form K V} (b : B.nondegenerate) {m n : V} :
B.to_dual b m n = B m n := rfl
section dual_basis
variables {ι : Type*} [decidable_eq ι] [fintype ι]
/-- The `B`-dual basis `B.dual_basis hB b` to a finite basis `b` satisfies
`B (B.dual_basis hB b i) (b j) = B (b i) (B.dual_basis hB b j) = if i = j then 1 else 0`,
where `B` is a nondegenerate (symmetric) bilinear form and `b` is a finite basis. -/
noncomputable def dual_basis (B : bilin_form K V) (hB : B.nondegenerate) (b : basis ι K V) :
basis ι K V :=
b.dual_basis.map (B.to_dual hB).symm
@[simp] lemma dual_basis_repr_apply (B : bilin_form K V) (hB : B.nondegenerate) (b : basis ι K V)
(x i) : (B.dual_basis hB b).repr x i = B x (b i) :=
by rw [dual_basis, basis.map_repr, linear_equiv.symm_symm, linear_equiv.trans_apply,
basis.dual_basis_repr, to_dual_def]
lemma apply_dual_basis_left (B : bilin_form K V) (hB : B.nondegenerate) (b : basis ι K V)
(i j) : B (B.dual_basis hB b i) (b j) = if j = i then 1 else 0 :=
by rw [dual_basis, basis.map_apply, basis.coe_dual_basis, ← to_dual_def hB,
linear_equiv.apply_symm_apply, basis.coord_apply, basis.repr_self,
finsupp.single_apply]
lemma apply_dual_basis_right (B : bilin_form K V) (hB : B.nondegenerate)
(sym : sym_bilin_form.is_sym B) (b : basis ι K V)
(i j) : B (b i) (B.dual_basis hB b j) = if i = j then 1 else 0 :=
by rw [sym, apply_dual_basis_left]
end dual_basis
end
/-! We note that we cannot use `bilin_form.restrict_nondegenerate_iff_is_compl_orthogonal` for the
lemma below since the below lemma does not require `V` to be finite dimensional. However,
`bilin_form.restrict_nondegenerate_iff_is_compl_orthogonal` does not require `B` to be nondegenerate
on the whole space. -/
/-- The restriction of a symmetric, non-degenerate bilinear form on the orthogonal complement of
the span of a singleton is also non-degenerate. -/
lemma restrict_orthogonal_span_singleton_nondegenerate (B : bilin_form K V)
(b₁ : nondegenerate B) (b₂ : sym_bilin_form.is_sym B) {x : V} (hx : ¬ B.is_ortho x x) :
nondegenerate $ B.restrict $ B.orthogonal (K ∙ x) :=
begin
refine λ m hm, submodule.coe_eq_zero.1 (b₁ m.1 (λ n, _)),
have : n ∈ (K ∙ x) ⊔ B.orthogonal (K ∙ x) :=
(span_singleton_sup_orthogonal_eq_top hx).symm ▸ submodule.mem_top,
rcases submodule.mem_sup.1 this with ⟨y, hy, z, hz, rfl⟩,
specialize hm ⟨z, hz⟩,
rw restrict at hm,
erw [add_right, show B m.1 y = 0, by rw b₂; exact m.2 y hy, hm, add_zero]
end
section linear_adjoints
lemma comp_left_injective (B : bilin_form R₁ M₁) (b : B.nondegenerate) :
function.injective B.comp_left :=
λ φ ψ h, begin
ext w,
refine eq_of_sub_eq_zero (b _ _),
intro v,
rw [sub_left, ← comp_left_apply, ← comp_left_apply, ← h, sub_self]
end
lemma is_adjoint_pair_unique_of_nondegenerate (B : bilin_form R₁ M₁) (b : B.nondegenerate)
(φ ψ₁ ψ₂ : M₁ →ₗ[R₁] M₁) (hψ₁ : is_adjoint_pair B B ψ₁ φ) (hψ₂ : is_adjoint_pair B B ψ₂ φ) :
ψ₁ = ψ₂ :=
B.comp_left_injective b $ ext $ λ v w, by rw [comp_left_apply, comp_left_apply, hψ₁, hψ₂]
variable [finite_dimensional K V]
/-- Given bilinear forms `B₁, B₂` where `B₂` is nondegenerate, `symm_comp_of_nondegenerate`
is the linear map `B₂.to_lin⁻¹ ∘ B₁.to_lin`. -/
noncomputable def symm_comp_of_nondegenerate
(B₁ B₂ : bilin_form K V) (b₂ : B₂.nondegenerate) : V →ₗ[K] V :=
(B₂.to_dual b₂).symm.to_linear_map.comp B₁.to_lin
lemma comp_symm_comp_of_nondegenerate_apply (B₁ : bilin_form K V)
{B₂ : bilin_form K V} (b₂ : B₂.nondegenerate) (v : V) :
to_lin B₂ (B₁.symm_comp_of_nondegenerate B₂ b₂ v) = to_lin B₁ v :=
by erw [symm_comp_of_nondegenerate, linear_equiv.apply_symm_apply (B₂.to_dual b₂) _]
@[simp]
lemma symm_comp_of_nondegenerate_left_apply (B₁ : bilin_form K V)
{B₂ : bilin_form K V} (b₂ : B₂.nondegenerate) (v w : V) :
B₂ (symm_comp_of_nondegenerate B₁ B₂ b₂ w) v = B₁ w v :=
begin
conv_lhs { rw [← bilin_form.to_lin_apply, comp_symm_comp_of_nondegenerate_apply] },
refl,
end
/-- Given the nondegenerate bilinear form `B` and the linear map `φ`,
`left_adjoint_of_nondegenerate` provides the left adjoint of `φ` with respect to `B`.
The lemma proving this property is `bilin_form.is_adjoint_pair_left_adjoint_of_nondegenerate`. -/
noncomputable def left_adjoint_of_nondegenerate
(B : bilin_form K V) (b : B.nondegenerate) (φ : V →ₗ[K] V) : V →ₗ[K] V :=
symm_comp_of_nondegenerate (B.comp_right φ) B b
lemma is_adjoint_pair_left_adjoint_of_nondegenerate
(B : bilin_form K V) (b : B.nondegenerate) (φ : V →ₗ[K] V) :
is_adjoint_pair B B (B.left_adjoint_of_nondegenerate b φ) φ :=
λ x y, (B.comp_right φ).symm_comp_of_nondegenerate_left_apply b y x
/-- Given the nondegenerate bilinear form `B`, the linear map `φ` has a unique left adjoint given by
`bilin_form.left_adjoint_of_nondegenerate`. -/
theorem is_adjoint_pair_iff_eq_of_nondegenerate
(B : bilin_form K V) (b : B.nondegenerate) (ψ φ : V →ₗ[K] V) :
is_adjoint_pair B B ψ φ ↔ ψ = B.left_adjoint_of_nondegenerate b φ :=
⟨λ h, B.is_adjoint_pair_unique_of_nondegenerate b φ ψ _ h
(is_adjoint_pair_left_adjoint_of_nondegenerate _ _ _),
λ h, h.symm ▸ is_adjoint_pair_left_adjoint_of_nondegenerate _ _ _⟩
end linear_adjoints
section det
open matrix
variables {A : Type*} [comm_ring A] [is_domain A] [module A M₃] (B₃ : bilin_form A M₃)
variables {ι : Type*} [decidable_eq ι] [fintype ι]
theorem _root_.matrix.nondegenerate.to_bilin' {M : matrix ι ι R₃} (h : M.nondegenerate) :
(to_bilin' M).nondegenerate :=
λ x hx, h.eq_zero_of_ortho (λ y,
by simpa only [to_bilin'_apply, dot_product, mul_vec, finset.mul_sum, mul_assoc] using hx y)
theorem nondegenerate_of_det_ne_zero' (M : matrix ι ι A) (h : M.det ≠ 0) :
(to_bilin' M).nondegenerate :=
(matrix.nondegenerate_of_det_ne_zero h).to_bilin'
theorem nondegenerate_of_det_ne_zero (b : basis ι A M₃) (h : (to_matrix b B₃).det ≠ 0) :
B₃.nondegenerate :=
begin
intros x hx,
refine b.equiv_fun.map_eq_zero_iff.mp (nondegenerate_of_det_ne_zero' _ h _ (λ w, _)),
convert hx (b.equiv_fun.symm w),
rw [bilin_form.to_matrix, linear_equiv.trans_apply, to_bilin'_to_matrix', congr_apply,
linear_equiv.symm_apply_apply]
end
end det
end bilin_form
|
4fa5908fad543cfbd3cf2ece391baa2c0f4ab8b2 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/measure_theory/constructions/prod.lean | b9092bd1daf90ff2b74b83b761cfe46ef40d475d | [
"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 | 51,930 | lean | /-
Copyright (c) 2020 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import measure_theory.measure.giry_monad
import dynamics.ergodic.measure_preserving
import measure_theory.integral.set_integral
/-!
# The product measure
In this file we define and prove properties about the binary product measure. If `α` and `β` have
σ-finite measures `μ` resp. `ν` then `α × β` can be equipped with a σ-finite measure `μ.prod ν` that
satisfies `(μ.prod ν) s = ∫⁻ x, ν {y | (x, y) ∈ s} ∂μ`.
We also have `(μ.prod ν) (s ×ˢ t) = μ s * ν t`, i.e. the measure of a rectangle is the product of
the measures of the sides.
We also prove Tonelli's theorem and Fubini's theorem.
## Main definition
* `measure_theory.measure.prod`: The product of two measures.
## Main results
* `measure_theory.measure.prod_apply` states `μ.prod ν s = ∫⁻ x, ν {y | (x, y) ∈ s} ∂μ`
for measurable `s`. `measure_theory.measure.prod_apply_symm` is the reversed version.
* `measure_theory.measure.prod_prod` states `μ.prod ν (s ×ˢ t) = μ s * ν t` for measurable sets
`s` and `t`.
* `measure_theory.lintegral_prod`: Tonelli's theorem. It states that for a measurable function
`α × β → ℝ≥0∞` we have `∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ`. The version
for functions `α → β → ℝ≥0∞` is reversed, and called `lintegral_lintegral`. Both versions have
a variant with `_symm` appended, where the order of integration is reversed.
The lemma `measurable.lintegral_prod_right'` states that the inner integral of the right-hand side
is measurable.
* `measure_theory.integrable_prod_iff` states that a binary function is integrable iff both
* `y ↦ f (x, y)` is integrable for almost every `x`, and
* the function `x ↦ ∫ ∥f (x, y)∥ dy` is integrable.
* `measure_theory.integral_prod`: Fubini's theorem. It states that for a integrable function
`α × β → E` (where `E` is a second countable Banach space) we have
`∫ z, f z ∂(μ.prod ν) = ∫ x, ∫ y, f (x, y) ∂ν ∂μ`. This theorem has the same variants as
Tonelli's theorem. The lemma `measure_theory.integrable.integral_prod_right` states that the
inner integral of the right-hand side is integrable.
## Implementation Notes
Many results are proven twice, once for functions in curried form (`α → β → γ`) and one for
functions in uncurried form (`α × β → γ`). The former often has an assumption
`measurable (uncurry f)`, which could be inconvenient to discharge, but for the latter it is more
common that the function has to be given explicitly, since Lean cannot synthesize the function by
itself. We name the lemmas about the uncurried form with a prime.
Tonelli's theorem and Fubini's theorem have a different naming scheme, since the version for the
uncurried version is reversed.
## Tags
product measure, Fubini's theorem, Tonelli's theorem, Fubini-Tonelli theorem
-/
noncomputable theory
open_locale classical topological_space ennreal measure_theory
open set function real ennreal
open measure_theory measurable_space measure_theory.measure
open topological_space (hiding generate_from)
open filter (hiding prod_eq map)
variables {α α' β β' γ E : Type*}
/-- Rectangles formed by π-systems form a π-system. -/
lemma is_pi_system.prod {C : set (set α)} {D : set (set β)} (hC : is_pi_system C)
(hD : is_pi_system D) : is_pi_system (image2 (×ˢ) C D) :=
begin
rintro _ ⟨s₁, t₁, hs₁, ht₁, rfl⟩ _ ⟨s₂, t₂, hs₂, ht₂, rfl⟩ hst,
rw [prod_inter_prod] at hst ⊢, rw [prod_nonempty_iff] at hst,
exact mem_image2_of_mem (hC _ hs₁ _ hs₂ hst.1) (hD _ ht₁ _ ht₂ hst.2)
end
/-- Rectangles of countably spanning sets are countably spanning. -/
lemma is_countably_spanning.prod {C : set (set α)} {D : set (set β)}
(hC : is_countably_spanning C) (hD : is_countably_spanning D) :
is_countably_spanning (image2 (×ˢ) C D) :=
begin
rcases ⟨hC, hD⟩ with ⟨⟨s, h1s, h2s⟩, t, h1t, h2t⟩,
refine ⟨λ n, (s n.unpair.1) ×ˢ (t n.unpair.2), λ n, mem_image2_of_mem (h1s _) (h1t _), _⟩,
rw [Union_unpair_prod, h2s, h2t, univ_prod_univ]
end
variables [measurable_space α] [measurable_space α'] [measurable_space β] [measurable_space β']
variables [measurable_space γ]
variables {μ : measure α} {ν : measure β} {τ : measure γ}
variables [normed_group E]
/-! ### Measurability
Before we define the product measure, we can talk about the measurability of operations on binary
functions. We show that if `f` is a binary measurable function, then the function that integrates
along one of the variables (using either the Lebesgue or Bochner integral) is measurable.
-/
/-- The product of generated σ-algebras is the one generated by rectangles, if both generating sets
are countably spanning. -/
lemma generate_from_prod_eq {α β} {C : set (set α)} {D : set (set β)}
(hC : is_countably_spanning C) (hD : is_countably_spanning D) :
@prod.measurable_space _ _ (generate_from C) (generate_from D) =
generate_from (image2 (×ˢ) C D) :=
begin
apply le_antisymm,
{ refine sup_le _ _; rw [comap_generate_from];
apply generate_from_le; rintro _ ⟨s, hs, rfl⟩,
{ rcases hD with ⟨t, h1t, h2t⟩,
rw [← prod_univ, ← h2t, prod_Union],
apply measurable_set.Union,
intro n, apply measurable_set_generate_from,
exact ⟨s, t n, hs, h1t n, rfl⟩ },
{ rcases hC with ⟨t, h1t, h2t⟩,
rw [← univ_prod, ← h2t, Union_prod_const],
apply measurable_set.Union,
rintro n, apply measurable_set_generate_from,
exact mem_image2_of_mem (h1t n) hs } },
{ apply generate_from_le, rintro _ ⟨s, t, hs, ht, rfl⟩, rw [prod_eq],
apply (measurable_fst _).inter (measurable_snd _),
{ exact measurable_set_generate_from hs },
{ exact measurable_set_generate_from ht } }
end
/-- If `C` and `D` generate the σ-algebras on `α` resp. `β`, then rectangles formed by `C` and `D`
generate the σ-algebra on `α × β`. -/
lemma generate_from_eq_prod {C : set (set α)} {D : set (set β)} (hC : generate_from C = ‹_›)
(hD : generate_from D = ‹_›) (h2C : is_countably_spanning C) (h2D : is_countably_spanning D) :
generate_from (image2 (×ˢ) C D) = prod.measurable_space :=
by rw [← hC, ← hD, generate_from_prod_eq h2C h2D]
/-- The product σ-algebra is generated from boxes, i.e. `s ×ˢ t` for sets `s : set α` and
`t : set β`. -/
lemma generate_from_prod :
generate_from (image2 (×ˢ) {s : set α | measurable_set s} {t : set β | measurable_set t}) =
prod.measurable_space :=
generate_from_eq_prod generate_from_measurable_set generate_from_measurable_set
is_countably_spanning_measurable_set is_countably_spanning_measurable_set
/-- Rectangles form a π-system. -/
lemma is_pi_system_prod :
is_pi_system (image2 (×ˢ) {s : set α | measurable_set s} {t : set β | measurable_set t}) :=
is_pi_system_measurable_set.prod is_pi_system_measurable_set
/-- If `ν` is a finite measure, and `s ⊆ α × β` is measurable, then `x ↦ ν { y | (x, y) ∈ s }` is
a measurable function. `measurable_measure_prod_mk_left` is strictly more general. -/
lemma measurable_measure_prod_mk_left_finite [is_finite_measure ν] {s : set (α × β)}
(hs : measurable_set s) : measurable (λ x, ν (prod.mk x ⁻¹' s)) :=
begin
refine induction_on_inter generate_from_prod.symm is_pi_system_prod _ _ _ _ hs,
{ simp [measurable_zero, const_def] },
{ rintro _ ⟨s, t, hs, ht, rfl⟩, simp only [mk_preimage_prod_right_eq_if, measure_if],
exact measurable_const.indicator hs },
{ intros t ht h2t,
simp_rw [preimage_compl, measure_compl (measurable_prod_mk_left ht) (measure_ne_top ν _)],
exact h2t.const_sub _ },
{ intros f h1f h2f h3f, simp_rw [preimage_Union],
have : ∀ b, ν (⋃ i, prod.mk b ⁻¹' f i) = ∑' i, ν (prod.mk b ⁻¹' f i) :=
λ b, measure_Union (λ i j hij, disjoint.preimage _ (h1f i j hij))
(λ i, measurable_prod_mk_left (h2f i)),
simp_rw [this], apply measurable.ennreal_tsum h3f },
end
/-- If `ν` is a σ-finite measure, and `s ⊆ α × β` is measurable, then `x ↦ ν { y | (x, y) ∈ s }` is
a measurable function. -/
lemma measurable_measure_prod_mk_left [sigma_finite ν] {s : set (α × β)}
(hs : measurable_set s) : measurable (λ x, ν (prod.mk x ⁻¹' s)) :=
begin
have : ∀ x, measurable_set (prod.mk x ⁻¹' s) := λ x, measurable_prod_mk_left hs,
simp only [← @supr_restrict_spanning_sets _ _ ν, this],
apply measurable_supr, intro i,
haveI := fact.mk (measure_spanning_sets_lt_top ν i),
exact measurable_measure_prod_mk_left_finite hs
end
/-- If `μ` is a σ-finite measure, and `s ⊆ α × β` is measurable, then `y ↦ μ { x | (x, y) ∈ s }` is
a measurable function. -/
lemma measurable_measure_prod_mk_right {μ : measure α} [sigma_finite μ] {s : set (α × β)}
(hs : measurable_set s) : measurable (λ y, μ ((λ x, (x, y)) ⁻¹' s)) :=
measurable_measure_prod_mk_left (measurable_set_swap_iff.mpr hs)
lemma measurable.map_prod_mk_left [sigma_finite ν] : measurable (λ x : α, map (prod.mk x) ν) :=
begin
apply measurable_of_measurable_coe, intros s hs,
simp_rw [map_apply measurable_prod_mk_left hs],
exact measurable_measure_prod_mk_left hs
end
lemma measurable.map_prod_mk_right {μ : measure α} [sigma_finite μ] :
measurable (λ y : β, map (λ x : α, (x, y)) μ) :=
begin
apply measurable_of_measurable_coe, intros s hs,
simp_rw [map_apply measurable_prod_mk_right hs],
exact measurable_measure_prod_mk_right hs
end
/-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of)
Tonelli's theorem is measurable. -/
lemma measurable.lintegral_prod_right' [sigma_finite ν] :
∀ {f : α × β → ℝ≥0∞} (hf : measurable f), measurable (λ x, ∫⁻ y, f (x, y) ∂ν) :=
begin
have m := @measurable_prod_mk_left,
refine measurable.ennreal_induction _ _ _,
{ intros c s hs, simp only [← indicator_comp_right],
suffices : measurable (λ x, c * ν (prod.mk x ⁻¹' s)),
{ simpa [lintegral_indicator _ (m hs)] },
exact (measurable_measure_prod_mk_left hs).const_mul _ },
{ rintro f g - hf hg h2f h2g, simp_rw [pi.add_apply, lintegral_add (hf.comp m) (hg.comp m)],
exact h2f.add h2g },
{ intros f hf h2f h3f,
have := measurable_supr h3f,
have : ∀ x, monotone (λ n y, f n (x, y)) := λ x i j hij y, h2f hij (x, y),
simpa [lintegral_supr (λ n, (hf n).comp m), this] }
end
/-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of)
Tonelli's theorem is measurable.
This version has the argument `f` in curried form. -/
lemma measurable.lintegral_prod_right [sigma_finite ν] {f : α → β → ℝ≥0∞}
(hf : measurable (uncurry f)) : measurable (λ x, ∫⁻ y, f x y ∂ν) :=
hf.lintegral_prod_right'
/-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of)
the symmetric version of Tonelli's theorem is measurable. -/
lemma measurable.lintegral_prod_left' [sigma_finite μ] {f : α × β → ℝ≥0∞}
(hf : measurable f) : measurable (λ y, ∫⁻ x, f (x, y) ∂μ) :=
(measurable_swap_iff.mpr hf).lintegral_prod_right'
/-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of)
the symmetric version of Tonelli's theorem is measurable.
This version has the argument `f` in curried form. -/
lemma measurable.lintegral_prod_left [sigma_finite μ] {f : α → β → ℝ≥0∞}
(hf : measurable (uncurry f)) : measurable (λ y, ∫⁻ x, f x y ∂μ) :=
hf.lintegral_prod_left'
lemma measurable_set_integrable [sigma_finite ν] ⦃f : α → β → E⦄
(hf : strongly_measurable (uncurry f)) : measurable_set {x | integrable (f x) ν} :=
begin
simp_rw [integrable, hf.of_uncurry_left.ae_strongly_measurable, true_and],
exact measurable_set_lt (measurable.lintegral_prod_right hf.ennnorm) measurable_const
end
section
variables [normed_space ℝ E] [complete_space E]
/-- The Bochner integral is measurable. This shows that the integrand of (the right-hand-side of)
Fubini's theorem is measurable.
This version has `f` in curried form. -/
lemma measure_theory.strongly_measurable.integral_prod_right [sigma_finite ν] ⦃f : α → β → E⦄
(hf : strongly_measurable (uncurry f)) : strongly_measurable (λ x, ∫ y, f x y ∂ν) :=
begin
borelize E,
haveI : separable_space (range (uncurry f) ∪ {0} : set E) :=
hf.separable_space_range_union_singleton,
let s : ℕ → simple_func (α × β) E := simple_func.approx_on _ hf.measurable
(range (uncurry f) ∪ {0}) 0 (by simp),
let s' : ℕ → α → simple_func β E := λ n x, (s n).comp (prod.mk x) measurable_prod_mk_left,
let f' : ℕ → α → E := λ n, {x | integrable (f x) ν}.indicator
(λ x, (s' n x).integral ν),
have hf' : ∀ n, strongly_measurable (f' n),
{ intro n, refine strongly_measurable.indicator _ (measurable_set_integrable hf),
have : ∀ x, (s' n x).range.filter (λ x, x ≠ 0) ⊆ (s n).range,
{ intros x, refine finset.subset.trans (finset.filter_subset _ _) _, intro y,
simp_rw [simple_func.mem_range], rintro ⟨z, rfl⟩, exact ⟨(x, z), rfl⟩ },
simp only [simple_func.integral_eq_sum_of_subset (this _)],
refine finset.strongly_measurable_sum _ (λ x _, _),
refine (measurable.ennreal_to_real _).strongly_measurable.smul_const _,
simp only [simple_func.coe_comp, preimage_comp] {single_pass := tt},
apply measurable_measure_prod_mk_left,
exact (s n).measurable_set_fiber x },
have h2f' : tendsto f' at_top (𝓝 (λ (x : α), ∫ (y : β), f x y ∂ν)),
{ rw [tendsto_pi_nhds], intro x,
by_cases hfx : integrable (f x) ν,
{ have : ∀ n, integrable (s' n x) ν,
{ intro n, apply (hfx.norm.add hfx.norm).mono' (s' n x).ae_strongly_measurable,
apply eventually_of_forall, intro y,
simp_rw [s', simple_func.coe_comp], exact simple_func.norm_approx_on_zero_le _ _ (x, y) n },
simp only [f', hfx, simple_func.integral_eq_integral _ (this _), indicator_of_mem,
mem_set_of_eq],
refine tendsto_integral_of_dominated_convergence (λ y, ∥f x y∥ + ∥f x y∥)
(λ n, (s' n x).ae_strongly_measurable) (hfx.norm.add hfx.norm) _ _,
{ exact λ n, eventually_of_forall (λ y, simple_func.norm_approx_on_zero_le _ _ (x, y) n) },
{ refine eventually_of_forall (λ y, simple_func.tendsto_approx_on _ _ _),
apply subset_closure,
simp [-uncurry_apply_pair], } },
{ simpa [f', hfx, integral_undef] using @tendsto_const_nhds _ _ _ (0 : E) _, } },
exact strongly_measurable_of_tendsto _ hf' h2f'
end
/-- The Bochner integral is measurable. This shows that the integrand of (the right-hand-side of)
Fubini's theorem is measurable. -/
lemma measure_theory.strongly_measurable.integral_prod_right' [sigma_finite ν] ⦃f : α × β → E⦄
(hf : strongly_measurable f) : strongly_measurable (λ x, ∫ y, f (x, y) ∂ν) :=
by { rw [← uncurry_curry f] at hf, exact hf.integral_prod_right }
/-- The Bochner integral is measurable. This shows that the integrand of (the right-hand-side of)
the symmetric version of Fubini's theorem is measurable.
This version has `f` in curried form. -/
lemma measure_theory.strongly_measurable.integral_prod_left [sigma_finite μ] ⦃f : α → β → E⦄
(hf : strongly_measurable (uncurry f)) : strongly_measurable (λ y, ∫ x, f x y ∂μ) :=
(hf.comp_measurable measurable_swap).integral_prod_right'
/-- The Bochner integral is measurable. This shows that the integrand of (the right-hand-side of)
the symmetric version of Fubini's theorem is measurable. -/
lemma measure_theory.strongly_measurable.integral_prod_left' [sigma_finite μ] ⦃f : α × β → E⦄
(hf : strongly_measurable f) : strongly_measurable (λ y, ∫ x, f (x, y) ∂μ) :=
(hf.comp_measurable measurable_swap).integral_prod_right'
end
/-! ### The product measure -/
namespace measure_theory
namespace measure
/-- The binary product of measures. They are defined for arbitrary measures, but we basically
prove all properties under the assumption that at least one of them is σ-finite. -/
@[irreducible] protected def prod (μ : measure α) (ν : measure β) : measure (α × β) :=
bind μ $ λ x : α, map (prod.mk x) ν
instance prod.measure_space {α β} [measure_space α] [measure_space β] : measure_space (α × β) :=
{ volume := volume.prod volume }
variables {μ ν} [sigma_finite ν]
lemma volume_eq_prod (α β) [measure_space α] [measure_space β] :
(volume : measure (α × β)) = (volume : measure α).prod (volume : measure β) :=
rfl
lemma prod_apply {s : set (α × β)} (hs : measurable_set s) :
μ.prod ν s = ∫⁻ x, ν (prod.mk x ⁻¹' s) ∂μ :=
by simp_rw [measure.prod, bind_apply hs measurable.map_prod_mk_left,
map_apply measurable_prod_mk_left hs]
/-- The product measure of the product of two sets is the product of their measures. Note that we
do not need the sets to be measurable. -/
@[simp] lemma prod_prod (s : set α) (t : set β) : μ.prod ν (s ×ˢ t) = μ s * ν t :=
begin
apply le_antisymm,
{ set ST := (to_measurable μ s) ×ˢ (to_measurable ν t),
have hSTm : measurable_set ST :=
(measurable_set_to_measurable _ _).prod (measurable_set_to_measurable _ _),
calc μ.prod ν (s ×ˢ t) ≤ μ.prod ν ST :
measure_mono $ set.prod_mono (subset_to_measurable _ _) (subset_to_measurable _ _)
... = μ (to_measurable μ s) * ν (to_measurable ν t) :
by simp_rw [prod_apply hSTm, mk_preimage_prod_right_eq_if, measure_if,
lintegral_indicator _ (measurable_set_to_measurable _ _), lintegral_const,
restrict_apply_univ, mul_comm]
... = μ s * ν t : by rw [measure_to_measurable, measure_to_measurable] },
{ /- Formalization is based on https://mathoverflow.net/a/254134/136589 -/
set ST := to_measurable (μ.prod ν) (s ×ˢ t),
have hSTm : measurable_set ST := measurable_set_to_measurable _ _,
have hST : s ×ˢ t ⊆ ST := subset_to_measurable _ _,
set f : α → ℝ≥0∞ := λ x, ν (prod.mk x ⁻¹' ST),
have hfm : measurable f := measurable_measure_prod_mk_left hSTm,
set s' : set α := {x | ν t ≤ f x},
have hss' : s ⊆ s' := λ x hx, measure_mono (λ y hy, hST $ mk_mem_prod hx hy),
calc μ s * ν t ≤ μ s' * ν t : mul_le_mul_right' (measure_mono hss') _
... = ∫⁻ x in s', ν t ∂μ : by rw [set_lintegral_const, mul_comm]
... ≤ ∫⁻ x in s', f x ∂μ : set_lintegral_mono measurable_const hfm (λ x, id)
... ≤ ∫⁻ x, f x ∂μ : lintegral_mono' restrict_le_self le_rfl
... = μ.prod ν ST : (prod_apply hSTm).symm
... = μ.prod ν (s ×ˢ t) : measure_to_measurable _ }
end
lemma ae_measure_lt_top {s : set (α × β)} (hs : measurable_set s)
(h2s : (μ.prod ν) s ≠ ∞) : ∀ᵐ x ∂μ, ν (prod.mk x ⁻¹' s) < ∞ :=
by { simp_rw [prod_apply hs] at h2s, refine ae_lt_top (measurable_measure_prod_mk_left hs) h2s }
lemma integrable_measure_prod_mk_left {s : set (α × β)}
(hs : measurable_set s) (h2s : (μ.prod ν) s ≠ ∞) :
integrable (λ x, (ν (prod.mk x ⁻¹' s)).to_real) μ :=
begin
refine ⟨(measurable_measure_prod_mk_left hs).ennreal_to_real.ae_measurable.ae_strongly_measurable,
_⟩,
simp_rw [has_finite_integral, ennnorm_eq_of_real to_real_nonneg],
convert h2s.lt_top using 1, simp_rw [prod_apply hs], apply lintegral_congr_ae,
refine (ae_measure_lt_top hs h2s).mp _, apply eventually_of_forall, intros x hx,
rw [lt_top_iff_ne_top] at hx, simp [of_real_to_real, hx],
end
/-- Note: the assumption `hs` cannot be dropped. For a counterexample, see
Walter Rudin *Real and Complex Analysis*, example (c) in section 8.9. -/
lemma measure_prod_null {s : set (α × β)}
(hs : measurable_set s) : μ.prod ν s = 0 ↔ (λ x, ν (prod.mk x ⁻¹' s)) =ᵐ[μ] 0 :=
by simp_rw [prod_apply hs, lintegral_eq_zero_iff (measurable_measure_prod_mk_left hs)]
/-- Note: the converse is not true without assuming that `s` is measurable. For a counterexample,
see Walter Rudin *Real and Complex Analysis*, example (c) in section 8.9. -/
lemma measure_ae_null_of_prod_null {s : set (α × β)}
(h : μ.prod ν s = 0) : (λ x, ν (prod.mk x ⁻¹' s)) =ᵐ[μ] 0 :=
begin
obtain ⟨t, hst, mt, ht⟩ := exists_measurable_superset_of_null h,
simp_rw [measure_prod_null mt] at ht,
rw [eventually_le_antisymm_iff],
exact ⟨eventually_le.trans_eq
(eventually_of_forall $ λ x, (measure_mono (preimage_mono hst) : _)) ht,
eventually_of_forall $ λ x, zero_le _⟩
end
/-- Note: the converse is not true. For a counterexample, see
Walter Rudin *Real and Complex Analysis*, example (c) in section 8.9. -/
lemma ae_ae_of_ae_prod {p : α × β → Prop} (h : ∀ᵐ z ∂μ.prod ν, p z) :
∀ᵐ x ∂ μ, ∀ᵐ y ∂ ν, p (x, y) :=
measure_ae_null_of_prod_null h
/-- `μ.prod ν` has finite spanning sets in rectangles of finite spanning sets. -/
noncomputable! def finite_spanning_sets_in.prod {ν : measure β} {C : set (set α)} {D : set (set β)}
(hμ : μ.finite_spanning_sets_in C) (hν : ν.finite_spanning_sets_in D) :
(μ.prod ν).finite_spanning_sets_in (image2 (×ˢ) C D) :=
begin
haveI := hν.sigma_finite,
refine ⟨λ n, hμ.set n.unpair.1 ×ˢ hν.set n.unpair.2,
λ n, mem_image2_of_mem (hμ.set_mem _) (hν.set_mem _), λ n, _, _⟩,
{ rw [prod_prod],
exact mul_lt_top (hμ.finite _).ne (hν.finite _).ne },
{ simp_rw [Union_unpair_prod, hμ.spanning, hν.spanning, univ_prod_univ] }
end
lemma prod_fst_absolutely_continuous : map prod.fst (μ.prod ν) ≪ μ :=
begin
refine absolutely_continuous.mk (λ s hs h2s, _),
rw [map_apply measurable_fst hs, ← prod_univ, prod_prod, h2s, zero_mul],
end
lemma prod_snd_absolutely_continuous : map prod.snd (μ.prod ν) ≪ ν :=
begin
refine absolutely_continuous.mk (λ s hs h2s, _),
rw [map_apply measurable_snd hs, ← univ_prod, prod_prod, h2s, mul_zero]
end
variables [sigma_finite μ]
instance prod.sigma_finite : sigma_finite (μ.prod ν) :=
(μ.to_finite_spanning_sets_in.prod ν.to_finite_spanning_sets_in).sigma_finite
/-- A measure on a product space equals the product measure if they are equal on rectangles
with as sides sets that generate the corresponding σ-algebras. -/
lemma prod_eq_generate_from {μ : measure α} {ν : measure β} {C : set (set α)}
{D : set (set β)} (hC : generate_from C = ‹_›)
(hD : generate_from D = ‹_›) (h2C : is_pi_system C) (h2D : is_pi_system D)
(h3C : μ.finite_spanning_sets_in C) (h3D : ν.finite_spanning_sets_in D)
{μν : measure (α × β)}
(h₁ : ∀ (s ∈ C) (t ∈ D), μν (s ×ˢ t) = μ s * ν t) : μ.prod ν = μν :=
begin
refine (h3C.prod h3D).ext
(generate_from_eq_prod hC hD h3C.is_countably_spanning h3D.is_countably_spanning).symm
(h2C.prod h2D) _,
{ rintro _ ⟨s, t, hs, ht, rfl⟩, haveI := h3D.sigma_finite,
rw [h₁ s hs t ht, prod_prod] }
end
/-- A measure on a product space equals the product measure if they are equal on rectangles. -/
lemma prod_eq {μν : measure (α × β)}
(h : ∀ s t, measurable_set s → measurable_set t → μν (s ×ˢ t) = μ s * ν t) : μ.prod ν = μν :=
prod_eq_generate_from generate_from_measurable_set generate_from_measurable_set
is_pi_system_measurable_set is_pi_system_measurable_set
μ.to_finite_spanning_sets_in ν.to_finite_spanning_sets_in (λ s hs t ht, h s t hs ht)
lemma prod_swap : map prod.swap (μ.prod ν) = ν.prod μ :=
begin
refine (prod_eq _).symm,
intros s t hs ht,
simp_rw [map_apply measurable_swap (hs.prod ht), preimage_swap_prod, prod_prod, mul_comm]
end
lemma prod_apply_symm {s : set (α × β)} (hs : measurable_set s) :
μ.prod ν s = ∫⁻ y, μ ((λ x, (x, y)) ⁻¹' s) ∂ν :=
by { rw [← prod_swap, map_apply measurable_swap hs],
simp only [prod_apply (measurable_swap hs)], refl }
lemma prod_assoc_prod [sigma_finite τ] :
map measurable_equiv.prod_assoc ((μ.prod ν).prod τ) = μ.prod (ν.prod τ) :=
begin
refine (prod_eq_generate_from generate_from_measurable_set generate_from_prod
is_pi_system_measurable_set is_pi_system_prod μ.to_finite_spanning_sets_in
(ν.to_finite_spanning_sets_in.prod τ.to_finite_spanning_sets_in) _).symm,
rintro s hs _ ⟨t, u, ht, hu, rfl⟩, rw [mem_set_of_eq] at hs ht hu,
simp_rw [map_apply (measurable_equiv.measurable _) (hs.prod (ht.prod hu)),
measurable_equiv.prod_assoc, measurable_equiv.coe_mk, equiv.prod_assoc_preimage,
prod_prod, mul_assoc]
end
/-! ### The product of specific measures -/
lemma prod_restrict (s : set α) (t : set β) :
(μ.restrict s).prod (ν.restrict t) = (μ.prod ν).restrict (s ×ˢ t) :=
begin
refine prod_eq (λ s' t' hs' ht', _),
rw [restrict_apply (hs'.prod ht'), prod_inter_prod, prod_prod, restrict_apply hs',
restrict_apply ht']
end
lemma restrict_prod_eq_prod_univ (s : set α) :
(μ.restrict s).prod ν = (μ.prod ν).restrict (s ×ˢ (univ : set β)) :=
begin
have : ν = ν.restrict set.univ := measure.restrict_univ.symm,
rwa [this, measure.prod_restrict, ← this],
end
lemma prod_dirac (y : β) : μ.prod (dirac y) = map (λ x, (x, y)) μ :=
begin
refine prod_eq (λ s t hs ht, _),
simp_rw [map_apply measurable_prod_mk_right (hs.prod ht), mk_preimage_prod_left_eq_if, measure_if,
dirac_apply' _ ht, ← indicator_mul_right _ (λ x, μ s), pi.one_apply, mul_one]
end
lemma dirac_prod (x : α) : (dirac x).prod ν = map (prod.mk x) ν :=
begin
refine prod_eq (λ s t hs ht, _),
simp_rw [map_apply measurable_prod_mk_left (hs.prod ht), mk_preimage_prod_right_eq_if, measure_if,
dirac_apply' _ hs, ← indicator_mul_left _ _ (λ x, ν t), pi.one_apply, one_mul]
end
lemma dirac_prod_dirac {x : α} {y : β} : (dirac x).prod (dirac y) = dirac (x, y) :=
by rw [prod_dirac, map_dirac measurable_prod_mk_right]
lemma prod_sum {ι : Type*} [fintype ι] (ν : ι → measure β) [∀ i, sigma_finite (ν i)] :
μ.prod (sum ν) = sum (λ i, μ.prod (ν i)) :=
begin
refine prod_eq (λ s t hs ht, _),
simp_rw [sum_apply _ (hs.prod ht), sum_apply _ ht, prod_prod, ennreal.tsum_mul_left]
end
lemma sum_prod {ι : Type*} [fintype ι] (μ : ι → measure α) [∀ i, sigma_finite (μ i)] :
(sum μ).prod ν = sum (λ i, (μ i).prod ν) :=
begin
refine prod_eq (λ s t hs ht, _),
simp_rw [sum_apply _ (hs.prod ht), sum_apply _ hs, prod_prod, ennreal.tsum_mul_right]
end
lemma prod_add (ν' : measure β) [sigma_finite ν'] : μ.prod (ν + ν') = μ.prod ν + μ.prod ν' :=
by { refine prod_eq (λ s t hs ht, _), simp_rw [add_apply, prod_prod, left_distrib] }
lemma add_prod (μ' : measure α) [sigma_finite μ'] : (μ + μ').prod ν = μ.prod ν + μ'.prod ν :=
by { refine prod_eq (λ s t hs ht, _), simp_rw [add_apply, prod_prod, right_distrib] }
@[simp] lemma zero_prod (ν : measure β) : (0 : measure α).prod ν = 0 :=
by { rw measure.prod, exact bind_zero_left _ }
@[simp] lemma prod_zero (μ : measure α) : μ.prod (0 : measure β) = 0 :=
by simp [measure.prod]
lemma map_prod_map {δ} [measurable_space δ] {f : α → β} {g : γ → δ}
{μa : measure α} {μc : measure γ} (hfa : sigma_finite (map f μa))
(hgc : sigma_finite (map g μc)) (hf : measurable f) (hg : measurable g) :
(map f μa).prod (map g μc) = map (prod.map f g) (μa.prod μc) :=
begin
haveI := hgc.of_map μc hg.ae_measurable,
refine prod_eq (λ s t hs ht, _),
rw [map_apply (hf.prod_map hg) (hs.prod ht), map_apply hf hs, map_apply hg ht],
exact prod_prod (f ⁻¹' s) (g ⁻¹' t)
end
end measure
open measure
namespace measure_preserving
variables {δ : Type*} [measurable_space δ] {μa : measure α} {μb : measure β}
{μc : measure γ} {μd : measure δ}
lemma skew_product [sigma_finite μb] [sigma_finite μd]
{f : α → β} (hf : measure_preserving f μa μb) {g : α → γ → δ}
(hgm : measurable (uncurry g)) (hg : ∀ᵐ x ∂μa, map (g x) μc = μd) :
measure_preserving (λ p : α × γ, (f p.1, g p.1 p.2)) (μa.prod μc) (μb.prod μd) :=
begin
classical,
have : measurable (λ p : α × γ, (f p.1, g p.1 p.2)) := (hf.1.comp measurable_fst).prod_mk hgm,
/- if `μa = 0`, then the lemma is trivial, otherwise we can use `hg`
to deduce `sigma_finite μc`. -/
rcases eq_or_ne μa 0 with (rfl|ha),
{ rw [← hf.map_eq, zero_prod, measure.map_zero, zero_prod],
exact ⟨this, by simp only [measure.map_zero]⟩ },
haveI : sigma_finite μc,
{ rcases (ae_ne_bot.2 ha).nonempty_of_mem hg with ⟨x, hx : map (g x) μc = μd⟩,
exact sigma_finite.of_map _ hgm.of_uncurry_left.ae_measurable (by rwa hx) },
-- Thus we can apply `measure.prod_eq` to prove equality of measures.
refine ⟨this, (prod_eq $ λ s t hs ht, _).symm⟩,
rw [map_apply this (hs.prod ht)],
refine (prod_apply (this $ hs.prod ht)).trans _,
have : ∀ᵐ x ∂μa, μc ((λ y, (f x, g x y)) ⁻¹' s ×ˢ t) = indicator (f ⁻¹' s) (λ y, μd t) x,
{ refine hg.mono (λ x hx, _), unfreezingI { subst hx },
simp only [mk_preimage_prod_right_fn_eq_if, indicator_apply, mem_preimage],
split_ifs,
exacts [(map_apply hgm.of_uncurry_left ht).symm, measure_empty] },
simp only [preimage_preimage],
rw [lintegral_congr_ae this, lintegral_indicator _ (hf.1 hs),
set_lintegral_const, hf.measure_preimage hs, mul_comm]
end
/-- If `f : α → β` sends the measure `μa` to `μb` and `g : γ → δ` sends the measure `μc` to `μd`,
then `prod.map f g` sends `μa.prod μc` to `μb.prod μd`. -/
protected lemma prod [sigma_finite μb] [sigma_finite μd] {f : α → β} {g : γ → δ}
(hf : measure_preserving f μa μb) (hg : measure_preserving g μc μd) :
measure_preserving (prod.map f g) (μa.prod μc) (μb.prod μd) :=
have measurable (uncurry $ λ _ : α, g), from (hg.1.comp measurable_snd),
hf.skew_product this $ filter.eventually_of_forall $ λ _, hg.map_eq
end measure_preserving
namespace quasi_measure_preserving
lemma prod_of_right {f : α × β → γ} {μ : measure α} {ν : measure β} {τ : measure γ}
(hf : measurable f) [sigma_finite ν]
(h2f : ∀ᵐ x ∂μ, quasi_measure_preserving (λ y, f (x, y)) ν τ) :
quasi_measure_preserving f (μ.prod ν) τ :=
begin
refine ⟨hf, _⟩,
refine absolutely_continuous.mk (λ s hs h2s, _),
simp_rw [map_apply hf hs, prod_apply (hf hs), preimage_preimage,
lintegral_congr_ae (h2f.mono (λ x hx, hx.preimage_null h2s)), lintegral_zero],
end
lemma prod_of_left {α β γ} [measurable_space α] [measurable_space β]
[measurable_space γ] {f : α × β → γ} {μ : measure α} {ν : measure β} {τ : measure γ}
(hf : measurable f) [sigma_finite μ] [sigma_finite ν]
(h2f : ∀ᵐ y ∂ν, quasi_measure_preserving (λ x, f (x, y)) μ τ) :
quasi_measure_preserving f (μ.prod ν) τ :=
begin
rw [← prod_swap],
convert (quasi_measure_preserving.prod_of_right (hf.comp measurable_swap) h2f).comp
((measurable_swap.measure_preserving (ν.prod μ)).symm measurable_equiv.prod_comm)
.quasi_measure_preserving,
ext ⟨x, y⟩, refl,
end
end quasi_measure_preserving
end measure_theory
open measure_theory.measure
section
lemma ae_measurable.prod_swap [sigma_finite μ] [sigma_finite ν] {f : β × α → γ}
(hf : ae_measurable f (ν.prod μ)) : ae_measurable (λ (z : α × β), f z.swap) (μ.prod ν) :=
by { rw ← prod_swap at hf, exact hf.comp_measurable measurable_swap }
lemma measure_theory.ae_strongly_measurable.prod_swap
{γ : Type*} [topological_space γ] [sigma_finite μ] [sigma_finite ν] {f : β × α → γ}
(hf : ae_strongly_measurable f (ν.prod μ)) :
ae_strongly_measurable (λ (z : α × β), f z.swap) (μ.prod ν) :=
by { rw ← prod_swap at hf, exact hf.comp_measurable measurable_swap }
lemma ae_measurable.fst [sigma_finite ν] {f : α → γ}
(hf : ae_measurable f μ) : ae_measurable (λ (z : α × β), f z.1) (μ.prod ν) :=
hf.comp_measurable' measurable_fst prod_fst_absolutely_continuous
lemma ae_measurable.snd [sigma_finite ν] {f : β → γ}
(hf : ae_measurable f ν) : ae_measurable (λ (z : α × β), f z.2) (μ.prod ν) :=
hf.comp_measurable' measurable_snd prod_snd_absolutely_continuous
lemma measure_theory.ae_strongly_measurable.fst {γ} [topological_space γ] [sigma_finite ν]
{f : α → γ} (hf : ae_strongly_measurable f μ) :
ae_strongly_measurable (λ (z : α × β), f z.1) (μ.prod ν) :=
hf.comp_measurable' measurable_fst prod_fst_absolutely_continuous
lemma measure_theory.ae_strongly_measurable.snd {γ} [topological_space γ] [sigma_finite ν]
{f : β → γ} (hf : ae_strongly_measurable f ν) :
ae_strongly_measurable (λ (z : α × β), f z.2) (μ.prod ν) :=
hf.comp_measurable' measurable_snd prod_snd_absolutely_continuous
/-- The Bochner integral is a.e.-measurable.
This shows that the integrand of (the right-hand-side of) Fubini's theorem is a.e.-measurable. -/
lemma measure_theory.ae_strongly_measurable.integral_prod_right' [sigma_finite ν]
[normed_space ℝ E] [complete_space E]
⦃f : α × β → E⦄ (hf : ae_strongly_measurable f (μ.prod ν)) :
ae_strongly_measurable (λ x, ∫ y, f (x, y) ∂ν) μ :=
⟨λ x, ∫ y, hf.mk f (x, y) ∂ν, hf.strongly_measurable_mk.integral_prod_right',
by { filter_upwards [ae_ae_of_ae_prod hf.ae_eq_mk] with _ hx using integral_congr_ae hx }⟩
lemma measure_theory.ae_strongly_measurable.prod_mk_left
{γ : Type*} [sigma_finite ν] [topological_space γ] {f : α × β → γ}
(hf : ae_strongly_measurable f (μ.prod ν)) : ∀ᵐ x ∂μ, ae_strongly_measurable (λ y, f (x, y)) ν :=
begin
filter_upwards [ae_ae_of_ae_prod hf.ae_eq_mk] with x hx,
exact ⟨λ y, hf.mk f (x, y), hf.strongly_measurable_mk.comp_measurable measurable_prod_mk_left, hx⟩
end
end
namespace measure_theory
/-! ### The Lebesgue integral on a product -/
variables [sigma_finite ν]
lemma lintegral_prod_swap [sigma_finite μ] (f : α × β → ℝ≥0∞)
(hf : ae_measurable f (μ.prod ν)) : ∫⁻ z, f z.swap ∂(ν.prod μ) = ∫⁻ z, f z ∂(μ.prod ν) :=
by { rw ← prod_swap at hf, rw [← lintegral_map' hf measurable_swap.ae_measurable, prod_swap] }
/-- **Tonelli's Theorem**: For `ℝ≥0∞`-valued measurable functions on `α × β`,
the integral of `f` is equal to the iterated integral. -/
lemma lintegral_prod_of_measurable :
∀ (f : α × β → ℝ≥0∞) (hf : measurable f), ∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ :=
begin
have m := @measurable_prod_mk_left,
refine measurable.ennreal_induction _ _ _,
{ intros c s hs, simp only [← indicator_comp_right],
simp [lintegral_indicator, m hs, hs, lintegral_const_mul, measurable_measure_prod_mk_left hs,
prod_apply] },
{ rintro f g - hf hg h2f h2g,
simp [lintegral_add, measurable.lintegral_prod_right', hf.comp m, hg.comp m,
hf, hg, h2f, h2g] },
{ intros f hf h2f h3f,
have kf : ∀ x n, measurable (λ y, f n (x, y)) := λ x n, (hf n).comp m,
have k2f : ∀ x, monotone (λ n y, f n (x, y)) := λ x i j hij y, h2f hij (x, y),
have lf : ∀ n, measurable (λ x, ∫⁻ y, f n (x, y) ∂ν) := λ n, (hf n).lintegral_prod_right',
have l2f : monotone (λ n x, ∫⁻ y, f n (x, y) ∂ν) := λ i j hij x, lintegral_mono (k2f x hij),
simp only [lintegral_supr hf h2f, lintegral_supr (kf _), k2f, lintegral_supr lf l2f, h3f] },
end
/-- **Tonelli's Theorem**: For `ℝ≥0∞`-valued almost everywhere measurable functions on `α × β`,
the integral of `f` is equal to the iterated integral. -/
lemma lintegral_prod (f : α × β → ℝ≥0∞) (hf : ae_measurable f (μ.prod ν)) :
∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ :=
begin
have A : ∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ z, hf.mk f z ∂(μ.prod ν) :=
lintegral_congr_ae hf.ae_eq_mk,
have B : ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ = ∫⁻ x, ∫⁻ y, hf.mk f (x, y) ∂ν ∂μ,
{ apply lintegral_congr_ae,
filter_upwards [ae_ae_of_ae_prod hf.ae_eq_mk] with _ ha using lintegral_congr_ae ha, },
rw [A, B, lintegral_prod_of_measurable _ hf.measurable_mk],
apply_instance
end
/-- The symmetric verion of Tonelli's Theorem: For `ℝ≥0∞`-valued almost everywhere measurable
functions on `α × β`, the integral of `f` is equal to the iterated integral, in reverse order. -/
lemma lintegral_prod_symm [sigma_finite μ] (f : α × β → ℝ≥0∞)
(hf : ae_measurable f (μ.prod ν)) : ∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ y, ∫⁻ x, f (x, y) ∂μ ∂ν :=
by { simp_rw [← lintegral_prod_swap f hf], exact lintegral_prod _ hf.prod_swap }
/-- The symmetric verion of Tonelli's Theorem: For `ℝ≥0∞`-valued measurable
functions on `α × β`, the integral of `f` is equal to the iterated integral, in reverse order. -/
lemma lintegral_prod_symm' [sigma_finite μ] (f : α × β → ℝ≥0∞)
(hf : measurable f) : ∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ y, ∫⁻ x, f (x, y) ∂μ ∂ν :=
lintegral_prod_symm f hf.ae_measurable
/-- The reversed version of **Tonelli's Theorem**. In this version `f` is in curried form, which
makes it easier for the elaborator to figure out `f` automatically. -/
lemma lintegral_lintegral ⦃f : α → β → ℝ≥0∞⦄
(hf : ae_measurable (uncurry f) (μ.prod ν)) :
∫⁻ x, ∫⁻ y, f x y ∂ν ∂μ = ∫⁻ z, f z.1 z.2 ∂(μ.prod ν) :=
(lintegral_prod _ hf).symm
/-- The reversed version of **Tonelli's Theorem** (symmetric version). In this version `f` is in
curried form, which makes it easier for the elaborator to figure out `f` automatically. -/
lemma lintegral_lintegral_symm [sigma_finite μ] ⦃f : α → β → ℝ≥0∞⦄
(hf : ae_measurable (uncurry f) (μ.prod ν)) :
∫⁻ x, ∫⁻ y, f x y ∂ν ∂μ = ∫⁻ z, f z.2 z.1 ∂(ν.prod μ) :=
(lintegral_prod_symm _ hf.prod_swap).symm
/-- Change the order of Lebesgue integration. -/
lemma lintegral_lintegral_swap [sigma_finite μ] ⦃f : α → β → ℝ≥0∞⦄
(hf : ae_measurable (uncurry f) (μ.prod ν)) :
∫⁻ x, ∫⁻ y, f x y ∂ν ∂μ = ∫⁻ y, ∫⁻ x, f x y ∂μ ∂ν :=
(lintegral_lintegral hf).trans (lintegral_prod_symm _ hf)
lemma lintegral_prod_mul {f : α → ℝ≥0∞} {g : β → ℝ≥0∞}
(hf : ae_measurable f μ) (hg : ae_measurable g ν) :
∫⁻ z, f z.1 * g z.2 ∂(μ.prod ν) = ∫⁻ x, f x ∂μ * ∫⁻ y, g y ∂ν :=
by simp [lintegral_prod _ (hf.fst.mul hg.snd), lintegral_lintegral_mul hf hg]
/-! ### Integrability on a product -/
section
lemma integrable.swap [sigma_finite μ] ⦃f : α × β → E⦄
(hf : integrable f (μ.prod ν)) : integrable (f ∘ prod.swap) (ν.prod μ) :=
⟨hf.ae_strongly_measurable.prod_swap,
(lintegral_prod_swap _ hf.ae_strongly_measurable.ennnorm : _).le.trans_lt hf.has_finite_integral⟩
lemma integrable_swap_iff [sigma_finite μ] ⦃f : α × β → E⦄ :
integrable (f ∘ prod.swap) (ν.prod μ) ↔ integrable f (μ.prod ν) :=
⟨λ hf, by { convert hf.swap, ext ⟨x, y⟩, refl }, λ hf, hf.swap⟩
lemma has_finite_integral_prod_iff ⦃f : α × β → E⦄ (h1f : strongly_measurable f) :
has_finite_integral f (μ.prod ν) ↔ (∀ᵐ x ∂ μ, has_finite_integral (λ y, f (x, y)) ν) ∧
has_finite_integral (λ x, ∫ y, ∥f (x, y)∥ ∂ν) μ :=
begin
simp only [has_finite_integral, lintegral_prod_of_measurable _ h1f.ennnorm],
have : ∀ x, ∀ᵐ y ∂ν, 0 ≤ ∥f (x, y)∥ := λ x, eventually_of_forall (λ y, norm_nonneg _),
simp_rw [integral_eq_lintegral_of_nonneg_ae (this _)
(h1f.norm.comp_measurable measurable_prod_mk_left).ae_strongly_measurable,
ennnorm_eq_of_real to_real_nonneg, of_real_norm_eq_coe_nnnorm],
-- this fact is probably too specialized to be its own lemma
have : ∀ {p q r : Prop} (h1 : r → p), (r ↔ p ∧ q) ↔ (p → (r ↔ q)) :=
λ p q r h1, by rw [← and.congr_right_iff, and_iff_right_of_imp h1],
rw [this],
{ intro h2f, rw lintegral_congr_ae,
refine h2f.mp _, apply eventually_of_forall, intros x hx, dsimp only,
rw [of_real_to_real], rw [← lt_top_iff_ne_top], exact hx },
{ intro h2f, refine ae_lt_top _ h2f.ne, exact h1f.ennnorm.lintegral_prod_right' },
end
lemma has_finite_integral_prod_iff' ⦃f : α × β → E⦄ (h1f : ae_strongly_measurable f (μ.prod ν)) :
has_finite_integral f (μ.prod ν) ↔ (∀ᵐ x ∂ μ, has_finite_integral (λ y, f (x, y)) ν) ∧
has_finite_integral (λ x, ∫ y, ∥f (x, y)∥ ∂ν) μ :=
begin
rw [has_finite_integral_congr h1f.ae_eq_mk,
has_finite_integral_prod_iff h1f.strongly_measurable_mk],
apply and_congr,
{ apply eventually_congr,
filter_upwards [ae_ae_of_ae_prod h1f.ae_eq_mk.symm],
assume x hx,
exact has_finite_integral_congr hx },
{ apply has_finite_integral_congr,
filter_upwards [ae_ae_of_ae_prod h1f.ae_eq_mk.symm] with _ hx
using integral_congr_ae (eventually_eq.fun_comp hx _), },
{ apply_instance, },
end
/-- A binary function is integrable if the function `y ↦ f (x, y)` is integrable for almost every
`x` and the function `x ↦ ∫ ∥f (x, y)∥ dy` is integrable. -/
lemma integrable_prod_iff ⦃f : α × β → E⦄ (h1f : ae_strongly_measurable f (μ.prod ν)) :
integrable f (μ.prod ν) ↔
(∀ᵐ x ∂ μ, integrable (λ y, f (x, y)) ν) ∧ integrable (λ x, ∫ y, ∥f (x, y)∥ ∂ν) μ :=
by simp [integrable, h1f, has_finite_integral_prod_iff', h1f.norm.integral_prod_right',
h1f.prod_mk_left]
/-- A binary function is integrable if the function `x ↦ f (x, y)` is integrable for almost every
`y` and the function `y ↦ ∫ ∥f (x, y)∥ dx` is integrable. -/
lemma integrable_prod_iff' [sigma_finite μ] ⦃f : α × β → E⦄
(h1f : ae_strongly_measurable f (μ.prod ν)) :
integrable f (μ.prod ν) ↔
(∀ᵐ y ∂ ν, integrable (λ x, f (x, y)) μ) ∧ integrable (λ y, ∫ x, ∥f (x, y)∥ ∂μ) ν :=
by { convert integrable_prod_iff (h1f.prod_swap) using 1, rw [integrable_swap_iff] }
lemma integrable.prod_left_ae [sigma_finite μ] ⦃f : α × β → E⦄
(hf : integrable f (μ.prod ν)) : ∀ᵐ y ∂ ν, integrable (λ x, f (x, y)) μ :=
((integrable_prod_iff' hf.ae_strongly_measurable).mp hf).1
lemma integrable.prod_right_ae [sigma_finite μ] ⦃f : α × β → E⦄
(hf : integrable f (μ.prod ν)) : ∀ᵐ x ∂ μ, integrable (λ y, f (x, y)) ν :=
hf.swap.prod_left_ae
lemma integrable.integral_norm_prod_left ⦃f : α × β → E⦄
(hf : integrable f (μ.prod ν)) : integrable (λ x, ∫ y, ∥f (x, y)∥ ∂ν) μ :=
((integrable_prod_iff hf.ae_strongly_measurable).mp hf).2
lemma integrable.integral_norm_prod_right [sigma_finite μ] ⦃f : α × β → E⦄
(hf : integrable f (μ.prod ν)) : integrable (λ y, ∫ x, ∥f (x, y)∥ ∂μ) ν :=
hf.swap.integral_norm_prod_left
end
variables [normed_space ℝ E] [complete_space E]
lemma integrable.integral_prod_left ⦃f : α × β → E⦄
(hf : integrable f (μ.prod ν)) : integrable (λ x, ∫ y, f (x, y) ∂ν) μ :=
integrable.mono hf.integral_norm_prod_left hf.ae_strongly_measurable.integral_prod_right' $
eventually_of_forall $ λ x, (norm_integral_le_integral_norm _).trans_eq $
(norm_of_nonneg $ integral_nonneg_of_ae $ eventually_of_forall $
λ y, (norm_nonneg (f (x, y)) : _)).symm
lemma integrable.integral_prod_right [sigma_finite μ] ⦃f : α × β → E⦄
(hf : integrable f (μ.prod ν)) : integrable (λ y, ∫ x, f (x, y) ∂μ) ν :=
hf.swap.integral_prod_left
/-! ### The Bochner integral on a product -/
variables [sigma_finite μ]
lemma integral_prod_swap (f : α × β → E)
(hf : ae_strongly_measurable f (μ.prod ν)) : ∫ z, f z.swap ∂(ν.prod μ) = ∫ z, f z ∂(μ.prod ν) :=
begin
rw ← prod_swap at hf,
rw [← integral_map measurable_swap.ae_measurable hf, prod_swap]
end
variables {E' : Type*} [normed_group E'] [complete_space E'] [normed_space ℝ E']
/-! Some rules about the sum/difference of double integrals. They follow from `integral_add`, but
we separate them out as separate lemmas, because they involve quite some steps. -/
/-- Integrals commute with addition inside another integral. `F` can be any function. -/
lemma integral_fn_integral_add ⦃f g : α × β → E⦄ (F : E → E')
(hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) :
∫ x, F (∫ y, f (x, y) + g (x, y) ∂ν) ∂μ = ∫ x, F (∫ y, f (x, y) ∂ν + ∫ y, g (x, y) ∂ν) ∂μ :=
begin
refine integral_congr_ae _,
filter_upwards [hf.prod_right_ae, hg.prod_right_ae] with _ h2f h2g,
simp [integral_add h2f h2g],
end
/-- Integrals commute with subtraction inside another integral.
`F` can be any measurable function. -/
lemma integral_fn_integral_sub ⦃f g : α × β → E⦄ (F : E → E')
(hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) :
∫ x, F (∫ y, f (x, y) - g (x, y) ∂ν) ∂μ = ∫ x, F (∫ y, f (x, y) ∂ν - ∫ y, g (x, y) ∂ν) ∂μ :=
begin
refine integral_congr_ae _,
filter_upwards [hf.prod_right_ae, hg.prod_right_ae] with _ h2f h2g,
simp [integral_sub h2f h2g],
end
/-- Integrals commute with subtraction inside a lower Lebesgue integral.
`F` can be any function. -/
lemma lintegral_fn_integral_sub ⦃f g : α × β → E⦄
(F : E → ℝ≥0∞) (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) :
∫⁻ x, F (∫ y, f (x, y) - g (x, y) ∂ν) ∂μ = ∫⁻ x, F (∫ y, f (x, y) ∂ν - ∫ y, g (x, y) ∂ν) ∂μ :=
begin
refine lintegral_congr_ae _,
filter_upwards [hf.prod_right_ae, hg.prod_right_ae] with _ h2f h2g,
simp [integral_sub h2f h2g],
end
/-- Double integrals commute with addition. -/
lemma integral_integral_add ⦃f g : α × β → E⦄
(hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) :
∫ x, ∫ y, f (x, y) + g (x, y) ∂ν ∂μ = ∫ x, ∫ y, f (x, y) ∂ν ∂μ + ∫ x, ∫ y, g (x, y) ∂ν ∂μ :=
(integral_fn_integral_add id hf hg).trans $
integral_add hf.integral_prod_left hg.integral_prod_left
/-- Double integrals commute with addition. This is the version with `(f + g) (x, y)`
(instead of `f (x, y) + g (x, y)`) in the LHS. -/
lemma integral_integral_add' ⦃f g : α × β → E⦄
(hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) :
∫ x, ∫ y, (f + g) (x, y) ∂ν ∂μ = ∫ x, ∫ y, f (x, y) ∂ν ∂μ + ∫ x, ∫ y, g (x, y) ∂ν ∂μ :=
integral_integral_add hf hg
/-- Double integrals commute with subtraction. -/
lemma integral_integral_sub ⦃f g : α × β → E⦄
(hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) :
∫ x, ∫ y, f (x, y) - g (x, y) ∂ν ∂μ = ∫ x, ∫ y, f (x, y) ∂ν ∂μ - ∫ x, ∫ y, g (x, y) ∂ν ∂μ :=
(integral_fn_integral_sub id hf hg).trans $
integral_sub hf.integral_prod_left hg.integral_prod_left
/-- Double integrals commute with subtraction. This is the version with `(f - g) (x, y)`
(instead of `f (x, y) - g (x, y)`) in the LHS. -/
lemma integral_integral_sub' ⦃f g : α × β → E⦄
(hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) :
∫ x, ∫ y, (f - g) (x, y) ∂ν ∂μ = ∫ x, ∫ y, f (x, y) ∂ν ∂μ - ∫ x, ∫ y, g (x, y) ∂ν ∂μ :=
integral_integral_sub hf hg
/-- The map that sends an L¹-function `f : α × β → E` to `∫∫f` is continuous. -/
lemma continuous_integral_integral :
continuous (λ (f : α × β →₁[μ.prod ν] E), ∫ x, ∫ y, f (x, y) ∂ν ∂μ) :=
begin
rw [continuous_iff_continuous_at], intro g,
refine tendsto_integral_of_L1 _ (L1.integrable_coe_fn g).integral_prod_left
(eventually_of_forall $ λ h, (L1.integrable_coe_fn h).integral_prod_left) _,
simp_rw [← lintegral_fn_integral_sub (λ x, (∥x∥₊ : ℝ≥0∞)) (L1.integrable_coe_fn _)
(L1.integrable_coe_fn g)],
refine tendsto_of_tendsto_of_tendsto_of_le_of_le tendsto_const_nhds _ (λ i, zero_le _) _,
{ exact λ i, ∫⁻ x, ∫⁻ y, ∥i (x, y) - g (x, y)∥₊ ∂ν ∂μ },
swap, { exact λ i, lintegral_mono (λ x, ennnorm_integral_le_lintegral_ennnorm _) },
show tendsto (λ (i : α × β →₁[μ.prod ν] E),
∫⁻ x, ∫⁻ (y : β), ∥i (x, y) - g (x, y)∥₊ ∂ν ∂μ) (𝓝 g) (𝓝 0),
have : ∀ (i : α × β →₁[μ.prod ν] E), measurable (λ z, (∥i z - g z∥₊ : ℝ≥0∞)) :=
λ i, ((Lp.strongly_measurable i).sub (Lp.strongly_measurable g)).ennnorm,
simp_rw [← lintegral_prod_of_measurable _ (this _), ← L1.of_real_norm_sub_eq_lintegral,
← of_real_zero],
refine (continuous_of_real.tendsto 0).comp _,
rw [← tendsto_iff_norm_tendsto_zero], exact tendsto_id
end
/-- **Fubini's Theorem**: For integrable functions on `α × β`,
the Bochner integral of `f` is equal to the iterated Bochner integral.
`integrable_prod_iff` can be useful to show that the function in question in integrable.
`measure_theory.integrable.integral_prod_right` is useful to show that the inner integral
of the right-hand side is integrable. -/
lemma integral_prod : ∀ (f : α × β → E) (hf : integrable f (μ.prod ν)),
∫ z, f z ∂(μ.prod ν) = ∫ x, ∫ y, f (x, y) ∂ν ∂μ :=
begin
apply integrable.induction,
{ intros c s hs h2s,
simp_rw [integral_indicator hs, ← indicator_comp_right,
function.comp, integral_indicator (measurable_prod_mk_left hs),
set_integral_const, integral_smul_const,
integral_to_real (measurable_measure_prod_mk_left hs).ae_measurable
(ae_measure_lt_top hs h2s.ne), prod_apply hs] },
{ intros f g hfg i_f i_g hf hg,
simp_rw [integral_add' i_f i_g, integral_integral_add' i_f i_g, hf, hg] },
{ exact is_closed_eq continuous_integral continuous_integral_integral },
{ intros f g hfg i_f hf, convert hf using 1,
{ exact integral_congr_ae hfg.symm },
{ refine integral_congr_ae _,
refine (ae_ae_of_ae_prod hfg).mp _,
apply eventually_of_forall, intros x hfgx,
exact integral_congr_ae (ae_eq_symm hfgx) } }
end
/-- Symmetric version of **Fubini's Theorem**: For integrable functions on `α × β`,
the Bochner integral of `f` is equal to the iterated Bochner integral.
This version has the integrals on the right-hand side in the other order. -/
lemma integral_prod_symm (f : α × β → E) (hf : integrable f (μ.prod ν)) :
∫ z, f z ∂(μ.prod ν) = ∫ y, ∫ x, f (x, y) ∂μ ∂ν :=
by { simp_rw [← integral_prod_swap f hf.ae_strongly_measurable], exact integral_prod _ hf.swap }
/-- Reversed version of **Fubini's Theorem**. -/
lemma integral_integral {f : α → β → E} (hf : integrable (uncurry f) (μ.prod ν)) :
∫ x, ∫ y, f x y ∂ν ∂μ = ∫ z, f z.1 z.2 ∂(μ.prod ν) :=
(integral_prod _ hf).symm
/-- Reversed version of **Fubini's Theorem** (symmetric version). -/
lemma integral_integral_symm {f : α → β → E} (hf : integrable (uncurry f) (μ.prod ν)) :
∫ x, ∫ y, f x y ∂ν ∂μ = ∫ z, f z.2 z.1 ∂(ν.prod μ) :=
(integral_prod_symm _ hf.swap).symm
/-- Change the order of Bochner integration. -/
lemma integral_integral_swap ⦃f : α → β → E⦄ (hf : integrable (uncurry f) (μ.prod ν)) :
∫ x, ∫ y, f x y ∂ν ∂μ = ∫ y, ∫ x, f x y ∂μ ∂ν :=
(integral_integral hf).trans (integral_prod_symm _ hf)
/-- **Fubini's Theorem** for set integrals. -/
lemma set_integral_prod (f : α × β → E) {s : set α} {t : set β}
(hf : integrable_on f (s ×ˢ t) (μ.prod ν)) :
∫ z in s ×ˢ t, f z ∂(μ.prod ν) = ∫ x in s, ∫ y in t, f (x, y) ∂ν ∂μ :=
begin
simp only [← measure.prod_restrict s t, integrable_on] at hf ⊢,
exact integral_prod f hf
end
end measure_theory
|
419537d0251ce760288b4e37e681ab3c0fabb34b | 3f7026ea8bef0825ca0339a275c03b911baef64d | /src/algebra/Mon/basic.lean | 8bcfef9cc1f2eba0d7b16146d2ba34a9022820fd | [
"Apache-2.0"
] | permissive | rspencer01/mathlib | b1e3afa5c121362ef0881012cc116513ab09f18c | c7d36292c6b9234dc40143c16288932ae38fdc12 | refs/heads/master | 1,595,010,346,708 | 1,567,511,503,000 | 1,567,511,503,000 | 206,071,681 | 0 | 0 | Apache-2.0 | 1,567,513,643,000 | 1,567,513,643,000 | null | UTF-8 | Lean | false | false | 2,197 | lean | /- Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
Introduce Mon -- the category of monoids.
Currently only the basic setup.
-/
import category_theory.concrete_category algebra.group
universes u v
open category_theory
/-- The category of monoids and monoid morphisms. -/
@[reducible] def Mon : Type (u+1) := bundled monoid
/-- The category of commutative monoids and monoid morphisms. -/
@[reducible] def CommMon : Type (u+1) := bundled comm_monoid
namespace Mon
instance (x : Mon) : monoid x := x.str
instance concrete_is_monoid_hom : concrete_category @is_monoid_hom :=
⟨by introsI α ia; apply_instance,
by introsI α β γ ia ib ic f g hf hg; apply_instance⟩
def of (X : Type u) [monoid X] : Mon := ⟨X⟩
abbreviation forget : Mon.{u} ⥤ Type u := forget
instance hom_is_monoid_hom {R S : Mon} (f : R ⟶ S) : is_monoid_hom (f : R → S) := f.2
/-- Morphisms in `Mon` are defined using `subtype is_monoid_hom`,
so we provide a canonical bijection with `R →* S`. -/
def hom_equiv_monoid_hom (R S : Mon) : (R ⟶ S) ≃ (R →* S) :=
{ to_fun := λ f, @as_monoid_hom _ _ _ _ f.val f.property,
inv_fun := λ f, ⟨f, f.is_monoid_hom⟩,
right_inv := λ f, by rcases f; refl,
left_inv := λ f, by rcases f; refl }
end Mon
namespace CommMon
instance (x : CommMon) : comm_monoid x := x.str
@[reducible] def is_comm_monoid_hom {α β} [comm_monoid α] [comm_monoid β] (f : α → β) : Prop :=
is_monoid_hom f
instance concrete_is_comm_monoid_hom : concrete_category @is_comm_monoid_hom :=
⟨by introsI α ia; apply_instance,
by introsI α β γ ia ib ic f g hf hg; apply_instance⟩
def of (X : Type u) [comm_monoid X] : CommMon := ⟨X⟩
abbreviation forget : CommMon.{u} ⥤ Type u := forget
instance hom_is_comm_monoid_hom {R S : CommMon} (f : R ⟶ S) :
is_comm_monoid_hom (f : R → S) := f.2
/-- The forgetful functor from commutative monoids to monoids. -/
def forget_to_Mon : CommMon ⥤ Mon :=
concrete_functor
(by intros _ c; exact { ..c })
(by introsI _ _ _ _ f i; exact { ..i })
instance : faithful (forget_to_Mon) := {}
end CommMon
|
eb4693023c3a3826fa9c55a84fb49e08cee5b2b1 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/ring_theory/adjoin_root.lean | 6cbe1d691a6b27ae5b7eb800eb46494f57447ddd | [
"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 | 19,845 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Chris Hughes
-/
import data.polynomial.field_division
import linear_algebra.finite_dimensional
import ring_theory.adjoin.basic
import ring_theory.power_basis
import ring_theory.principal_ideal_domain
/-!
# Adjoining roots of polynomials
This file defines the commutative ring `adjoin_root f`, the ring R[X]/(f) obtained from a
commutative ring `R` and a polynomial `f : R[X]`. If furthermore `R` is a field and `f` is
irreducible, the field structure on `adjoin_root f` is constructed.
## Main definitions and results
The main definitions are in the `adjoin_root` namespace.
* `mk f : R[X] →+* adjoin_root f`, the natural ring homomorphism.
* `of f : R →+* adjoin_root f`, the natural ring homomorphism.
* `root f : adjoin_root f`, the image of X in R[X]/(f).
* `lift (i : R →+* S) (x : S) (h : f.eval₂ i x = 0) : (adjoin_root f) →+* S`, the ring
homomorphism from R[X]/(f) to S extending `i : R →+* S` and sending `X` to `x`.
* `lift_hom (x : S) (hfx : aeval x f = 0) : adjoin_root f →ₐ[R] S`, the algebra
homomorphism from R[X]/(f) to S extending `algebra_map R S` and sending `X` to `x`
* `equiv : (adjoin_root f →ₐ[F] E) ≃ {x // x ∈ (f.map (algebra_map F E)).roots}` a
bijection between algebra homomorphisms from `adjoin_root` and roots of `f` in `S`
-/
noncomputable theory
open_locale classical
open_locale big_operators polynomial
universes u v w
variables {R : Type u} {S : Type v} {K : Type w}
open polynomial ideal
/-- Adjoin a root of a polynomial `f` to a commutative ring `R`. We define the new ring
as the quotient of `polynomial R` by the principal ideal generated by `f`. -/
def adjoin_root [comm_ring R] (f : R[X]) : Type u :=
polynomial R ⧸ (span {f} : ideal R[X])
namespace adjoin_root
section comm_ring
variables [comm_ring R] (f : R[X])
instance : comm_ring (adjoin_root f) := ideal.quotient.comm_ring _
instance : inhabited (adjoin_root f) := ⟨0⟩
instance : decidable_eq (adjoin_root f) := classical.dec_eq _
/-- Ring homomorphism from `R[x]` to `adjoin_root f` sending `X` to the `root`. -/
def mk : R[X] →+* adjoin_root f := ideal.quotient.mk _
@[elab_as_eliminator]
theorem induction_on {C : adjoin_root f → Prop} (x : adjoin_root f)
(ih : ∀ p : R[X], C (mk f p)) : C x :=
quotient.induction_on' x ih
/-- Embedding of the original ring `R` into `adjoin_root f`. -/
def of : R →+* adjoin_root f := (mk f).comp C
instance [comm_semiring S] [algebra S R] : algebra S (adjoin_root f) :=
ideal.quotient.algebra S
instance [comm_semiring S] [comm_semiring K] [has_scalar S K] [algebra S R] [algebra K R]
[is_scalar_tower S K R] :
is_scalar_tower S K (adjoin_root f) :=
submodule.quotient.is_scalar_tower _ _
instance [comm_semiring S] [comm_semiring K] [algebra S R] [algebra K R] [smul_comm_class S K R] :
smul_comm_class S K (adjoin_root f) :=
submodule.quotient.smul_comm_class _ _
@[simp] lemma algebra_map_eq : algebra_map R (adjoin_root f) = of f := rfl
variables (S)
lemma algebra_map_eq' [comm_semiring S] [algebra S R] :
algebra_map S (adjoin_root f) = (of f).comp (algebra_map S R) := rfl
variables {S}
/-- The adjoined root. -/
def root : adjoin_root f := mk f X
variables {f}
instance adjoin_root.has_coe_t : has_coe_t R (adjoin_root f) := ⟨of f⟩
@[simp] lemma mk_eq_mk {g h : R[X]} : mk f g = mk f h ↔ f ∣ g - h :=
ideal.quotient.eq.trans ideal.mem_span_singleton
@[simp] lemma mk_self : mk f f = 0 :=
quotient.sound' (mem_span_singleton.2 $ by simp)
@[simp] lemma mk_C (x : R) : mk f (C x) = x := rfl
@[simp] lemma mk_X : mk f X = root f := rfl
@[simp] lemma aeval_eq (p : R[X]) : aeval (root f) p = mk f p :=
polynomial.induction_on p (λ x, by { rw aeval_C, refl })
(λ p q ihp ihq, by rw [alg_hom.map_add, ring_hom.map_add, ihp, ihq])
(λ n x ih, by { rw [alg_hom.map_mul, aeval_C, alg_hom.map_pow, aeval_X,
ring_hom.map_mul, mk_C, ring_hom.map_pow, mk_X], refl })
theorem adjoin_root_eq_top : algebra.adjoin R ({root f} : set (adjoin_root f)) = ⊤ :=
algebra.eq_top_iff.2 $ λ x, induction_on f x $ λ p,
(algebra.adjoin_singleton_eq_range_aeval R (root f)).symm ▸ ⟨p, aeval_eq p⟩
@[simp] lemma eval₂_root (f : R[X]) : f.eval₂ (of f) (root f) = 0 :=
by rw [← algebra_map_eq, ← aeval_def, aeval_eq, mk_self]
lemma is_root_root (f : R[X]) : is_root (f.map (of f)) (root f) :=
by rw [is_root, eval_map, eval₂_root]
lemma is_algebraic_root (hf : f ≠ 0) : is_algebraic R (root f) :=
⟨f, hf, eval₂_root f⟩
variables [comm_ring S]
/-- Lift a ring homomorphism `i : R →+* S` to `adjoin_root f →+* S`. -/
def lift (i : R →+* S) (x : S) (h : f.eval₂ i x = 0) : (adjoin_root f) →+* S :=
begin
apply ideal.quotient.lift _ (eval₂_ring_hom i x),
intros g H,
rcases mem_span_singleton.1 H with ⟨y, hy⟩,
rw [hy, ring_hom.map_mul, coe_eval₂_ring_hom, h, zero_mul]
end
variables {i : R →+* S} {a : S} (h : f.eval₂ i a = 0)
@[simp] lemma lift_mk (g : R[X]) : lift i a h (mk f g) = g.eval₂ i a :=
ideal.quotient.lift_mk _ _ _
@[simp] lemma lift_root : lift i a h (root f) = a := by rw [root, lift_mk, eval₂_X]
@[simp] lemma lift_of {x : R} : lift i a h x = i x :=
by rw [← mk_C x, lift_mk, eval₂_C]
@[simp] lemma lift_comp_of : (lift i a h).comp (of f) = i :=
ring_hom.ext $ λ _, @lift_of _ _ _ _ _ _ _ h _
variables (f) [algebra R S]
/-- Produce an algebra homomorphism `adjoin_root f →ₐ[R] S` sending `root f` to
a root of `f` in `S`. -/
def lift_hom (x : S) (hfx : aeval x f = 0) : adjoin_root f →ₐ[R] S :=
{ commutes' := λ r, show lift _ _ hfx r = _, from lift_of hfx,
.. lift (algebra_map R S) x hfx }
@[simp] lemma coe_lift_hom (x : S) (hfx : aeval x f = 0) :
(lift_hom f x hfx : adjoin_root f →+* S) = lift (algebra_map R S) x hfx := rfl
@[simp] lemma aeval_alg_hom_eq_zero (ϕ : adjoin_root f →ₐ[R] S) : aeval (ϕ (root f)) f = 0 :=
begin
have h : ϕ.to_ring_hom.comp (of f) = algebra_map R S := ring_hom.ext_iff.mpr (ϕ.commutes),
rw [aeval_def, ←h, ←ring_hom.map_zero ϕ.to_ring_hom, ←eval₂_root f, hom_eval₂],
refl,
end
@[simp] lemma lift_hom_eq_alg_hom (f : R[X]) (ϕ : adjoin_root f →ₐ[R] S) :
lift_hom f (ϕ (root f)) (aeval_alg_hom_eq_zero f ϕ) = ϕ :=
begin
suffices : ϕ.equalizer (lift_hom f (ϕ (root f)) (aeval_alg_hom_eq_zero f ϕ)) = ⊤,
{ exact (alg_hom.ext (λ x, (set_like.ext_iff.mp (this) x).mpr algebra.mem_top)).symm },
rw [eq_top_iff, ←adjoin_root_eq_top, algebra.adjoin_le_iff, set.singleton_subset_iff],
exact (@lift_root _ _ _ _ _ _ _ (aeval_alg_hom_eq_zero f ϕ)).symm,
end
variables (hfx : aeval a f = 0)
@[simp] lemma lift_hom_mk {g : R[X]} : lift_hom f a hfx (mk f g) = aeval a g :=
lift_mk hfx g
@[simp] lemma lift_hom_root : lift_hom f a hfx (root f) = a :=
lift_root hfx
@[simp] lemma lift_hom_of {x : R} : lift_hom f a hfx (of f x) = algebra_map _ _ x :=
lift_of hfx
end comm_ring
section irreducible
variables [field K] {f : K[X]} [irreducible f]
instance is_maximal_span : is_maximal (span {f} : ideal K[X]) :=
principal_ideal_ring.is_maximal_of_irreducible ‹irreducible f›
noncomputable instance field : field (adjoin_root f) :=
{ ..adjoin_root.comm_ring f,
..ideal.quotient.field (span {f} : ideal K[X]) }
lemma coe_injective : function.injective (coe : K → adjoin_root f) :=
(of f).injective
variable (f)
lemma mul_div_root_cancel :
((X - C (root f)) * (f.map (of f) / (X - C (root f))) : polynomial (adjoin_root f)) =
f.map (of f) :=
mul_div_eq_iff_is_root.2 $ is_root_root _
end irreducible
section power_basis
variables [comm_ring R] {g : R[X]}
lemma is_integral_root' (hg : g.monic) : is_integral R (root g) :=
⟨g, hg, eval₂_root g⟩
/-- `adjoin_root.mod_by_monic_hom` sends the equivalence class of `f` mod `g` to `f %ₘ g`.
This is a well-defined right inverse to `adjoin_root.mk`, see `adjoin_root.mk_left_inverse`. -/
def mod_by_monic_hom (hg : g.monic) :
adjoin_root g →ₗ[R] R[X] :=
(submodule.liftq _ (polynomial.mod_by_monic_hom g)
(λ f (hf : f ∈ (ideal.span {g}).restrict_scalars R),
(mem_ker_mod_by_monic hg).mpr (ideal.mem_span_singleton.mp hf))).comp $
(submodule.quotient.restrict_scalars_equiv R (ideal.span {g} : ideal R[X]))
.symm.to_linear_map
@[simp] lemma mod_by_monic_hom_mk (hg : g.monic) (f : R[X]) :
mod_by_monic_hom hg (mk g f) = f %ₘ g := rfl
lemma mk_left_inverse (hg : g.monic) :
function.left_inverse (mk g) (mod_by_monic_hom hg) :=
λ f, induction_on g f $ λ f, begin
rw [mod_by_monic_hom_mk hg, mk_eq_mk, mod_by_monic_eq_sub_mul_div _ hg,
sub_sub_cancel_left, dvd_neg],
apply dvd_mul_right
end
lemma mk_surjective (hg : g.monic) : function.surjective (mk g) :=
(mk_left_inverse hg).surjective
/-- The elements `1, root g, ..., root g ^ (d - 1)` form a basis for `adjoin_root g`,
where `g` is a monic polynomial of degree `d`. -/
@[simps] def power_basis_aux' (hg : g.monic) :
basis (fin g.nat_degree) R (adjoin_root g) :=
basis.of_equiv_fun
{ to_fun := λ f i, (mod_by_monic_hom hg f).coeff i,
inv_fun := λ c, mk g $ ∑ (i : fin g.nat_degree), monomial i (c i),
map_add' := λ f₁ f₂, funext $ λ i,
by simp only [(mod_by_monic_hom hg).map_add, coeff_add, pi.add_apply],
map_smul' := λ f₁ f₂, funext $ λ i,
by simp only [(mod_by_monic_hom hg).map_smul, coeff_smul, pi.smul_apply, ring_hom.id_apply],
left_inv := λ f, induction_on g f (λ f, eq.symm $ mk_eq_mk.mpr $
by { simp only [mod_by_monic_hom_mk, sum_mod_by_monic_coeff hg degree_le_nat_degree],
rw [mod_by_monic_eq_sub_mul_div _ hg, sub_sub_cancel],
exact dvd_mul_right _ _ }),
right_inv := λ x, funext $ λ i, begin
nontriviality R,
simp only [mod_by_monic_hom_mk],
rw [(mod_by_monic_eq_self_iff hg).mpr, finset_sum_coeff, finset.sum_eq_single i];
try { simp only [coeff_monomial, eq_self_iff_true, if_true] },
{ intros j _ hj, exact if_neg (fin.coe_injective.ne hj) },
{ intros, have := finset.mem_univ i, contradiction },
{ refine (degree_sum_le _ _).trans_lt ((finset.sup_lt_iff _).mpr (λ j _, _)),
{ exact bot_lt_iff_ne_bot.mpr (mt degree_eq_bot.mp hg.ne_zero) },
{ refine (degree_monomial_le _ _).trans_lt _,
rw [degree_eq_nat_degree hg.ne_zero, with_bot.coe_lt_coe],
exact j.2 } },
end}
/-- The power basis `1, root g, ..., root g ^ (d - 1)` for `adjoin_root g`,
where `g` is a monic polynomial of degree `d`. -/
@[simps] def power_basis' (hg : g.monic) : power_basis R (adjoin_root g) :=
{ gen := root g,
dim := g.nat_degree,
basis := power_basis_aux' hg,
basis_eq_pow := λ i, begin
simp only [power_basis_aux', basis.coe_of_equiv_fun, linear_equiv.coe_symm_mk],
rw finset.sum_eq_single i,
{ rw [function.update_same, monomial_one_right_eq_X_pow, (mk g).map_pow, mk_X] },
{ intros j _ hj,
rw ← monomial_zero_right _,
convert congr_arg _ (function.update_noteq hj _ _) }, -- Fix `decidable_eq` mismatch
{ intros, have := finset.mem_univ i, contradiction },
end}
variables [field K] {f : K[X]}
lemma is_integral_root (hf : f ≠ 0) : is_integral K (root f) :=
is_algebraic_iff_is_integral.mp (is_algebraic_root hf)
lemma minpoly_root (hf : f ≠ 0) : minpoly K (root f) = f * C (f.leading_coeff⁻¹) :=
begin
have f'_monic : monic _ := monic_mul_leading_coeff_inv hf,
refine (minpoly.unique K _ f'_monic _ _).symm,
{ rw [alg_hom.map_mul, aeval_eq, mk_self, zero_mul] },
intros q q_monic q_aeval,
have commutes : (lift (algebra_map K (adjoin_root f)) (root f) q_aeval).comp (mk q) = mk f,
{ ext,
{ simp only [ring_hom.comp_apply, mk_C, lift_of], refl },
{ simp only [ring_hom.comp_apply, mk_X, lift_root] } },
rw [degree_eq_nat_degree f'_monic.ne_zero, degree_eq_nat_degree q_monic.ne_zero,
with_bot.coe_le_coe, nat_degree_mul hf, nat_degree_C, add_zero],
apply nat_degree_le_of_dvd,
{ have : mk f q = 0, by rw [←commutes, ring_hom.comp_apply, mk_self, ring_hom.map_zero],
rwa [←ideal.mem_span_singleton, ←ideal.quotient.eq_zero_iff_mem] },
{ exact q_monic.ne_zero },
{ rwa [ne.def, C_eq_zero, inv_eq_zero, leading_coeff_eq_zero] },
end
/-- The elements `1, root f, ..., root f ^ (d - 1)` form a basis for `adjoin_root f`,
where `f` is an irreducible polynomial over a field of degree `d`. -/
def power_basis_aux (hf : f ≠ 0) : basis (fin f.nat_degree) K (adjoin_root f) :=
begin
set f' := f * C (f.leading_coeff⁻¹) with f'_def,
have deg_f' : f'.nat_degree = f.nat_degree,
{ rw [nat_degree_mul hf, nat_degree_C, add_zero],
{ rwa [ne.def, C_eq_zero, inv_eq_zero, leading_coeff_eq_zero] } },
have minpoly_eq : minpoly K (root f) = f' := minpoly_root hf,
apply @basis.mk _ _ _ (λ (i : fin f.nat_degree), (root f ^ i.val)),
{ rw [← deg_f', ← minpoly_eq],
exact (is_integral_root hf).linear_independent_pow },
{ rw _root_.eq_top_iff,
rintros y -,
rw [← deg_f', ← minpoly_eq],
apply (is_integral_root hf).mem_span_pow,
obtain ⟨g⟩ := y,
use g,
rw aeval_eq,
refl }
end
/-- The power basis `1, root f, ..., root f ^ (d - 1)` for `adjoin_root f`,
where `f` is an irreducible polynomial over a field of degree `d`. -/
@[simps] def power_basis (hf : f ≠ 0) :
power_basis K (adjoin_root f) :=
{ gen := root f,
dim := f.nat_degree,
basis := power_basis_aux hf,
basis_eq_pow := basis.mk_apply _ _ }
lemma minpoly_power_basis_gen (hf : f ≠ 0) :
minpoly K (power_basis hf).gen = f * C (f.leading_coeff⁻¹) :=
by rw [power_basis_gen, minpoly_root hf]
lemma minpoly_power_basis_gen_of_monic (hf : f.monic) (hf' : f ≠ 0 := hf.ne_zero) :
minpoly K (power_basis hf').gen = f :=
by rw [minpoly_power_basis_gen hf', hf.leading_coeff, inv_one, C.map_one, mul_one]
end power_basis
section equiv
section is_domain
variables [comm_ring R] [is_domain R] [comm_ring S] [is_domain S] [algebra R S]
variables (g : R[X]) (pb : _root_.power_basis R S)
/-- If `S` is an extension of `R` with power basis `pb` and `g` is a monic polynomial over `R`
such that `pb.gen` has a minimal polynomial `g`, then `S` is isomorphic to `adjoin_root g`.
Compare `power_basis.equiv_of_root`, which would require
`h₂ : aeval pb.gen (minpoly R (root g)) = 0`; that minimal polynomial is not
guaranteed to be identical to `g`. -/
@[simps {fully_applied := ff}]
def equiv' (h₁ : aeval (root g) (minpoly R pb.gen) = 0) (h₂ : aeval pb.gen g = 0) :
adjoin_root g ≃ₐ[R] S :=
{ to_fun := adjoin_root.lift_hom g pb.gen h₂,
inv_fun := pb.lift (root g) h₁,
left_inv := λ x, induction_on g x $ λ f, by rw [lift_hom_mk, pb.lift_aeval, aeval_eq],
right_inv := λ x, begin
obtain ⟨f, hf, rfl⟩ := pb.exists_eq_aeval x,
rw [pb.lift_aeval, aeval_eq, lift_hom_mk]
end,
.. adjoin_root.lift_hom g pb.gen h₂ }
@[simp] lemma equiv'_to_alg_hom
(h₁ : aeval (root g) (minpoly R pb.gen) = 0) (h₂ : aeval pb.gen g = 0) :
(equiv' g pb h₁ h₂).to_alg_hom = adjoin_root.lift_hom g pb.gen h₂ :=
rfl
@[simp] lemma equiv'_symm_to_alg_hom
(h₁ : aeval (root g) (minpoly R pb.gen) = 0) (h₂ : aeval pb.gen g = 0) :
(equiv' g pb h₁ h₂).symm.to_alg_hom = pb.lift (root g) h₁ :=
rfl
end is_domain
section field
variables (K) (L F : Type*) [field F] [field K] [field L] [algebra F K] [algebra F L]
variables (pb : _root_.power_basis F K)
/-- If `L` is a field extension of `F` and `f` is a polynomial over `F` then the set
of maps from `F[x]/(f)` into `L` is in bijection with the set of roots of `f` in `L`. -/
def equiv (f : F[X]) (hf : f ≠ 0) :
(adjoin_root f →ₐ[F] L) ≃ {x // x ∈ (f.map (algebra_map F L)).roots} :=
(power_basis hf).lift_equiv'.trans ((equiv.refl _).subtype_equiv (λ x,
begin
rw [power_basis_gen, minpoly_root hf, polynomial.map_mul, roots_mul,
polynomial.map_C, roots_C, add_zero, equiv.refl_apply],
{ rw ← polynomial.map_mul, exact map_monic_ne_zero (monic_mul_leading_coeff_inv hf) }
end))
end field
end equiv
section
open ideal double_quot polynomial
variables [comm_ring R] (I : ideal R) (f : polynomial R)
/-- The natural isomorphism `R[α]/(I[α]) ≅ R[α]/((I[x] ⊔ (f)) / (f))` for `α` a root of
`f : polynomial R` and `I : ideal R`.
See `adjoin_root.quot_map_of_equiv` for the isomorphism with `(R/I)[X] / (f mod I)`. -/
def quot_map_of_equiv_quot_map_C_map_span_mk :
adjoin_root f ⧸ I.map (of f) ≃+* adjoin_root f ⧸ (I.map C).map (span {f})^.quotient.mk :=
ideal.quot_equiv_of_eq (by rw [of, adjoin_root.mk, ideal.map_map])
@[simp]
lemma quot_map_of_equiv_quot_map_C_map_span_mk_mk (x : adjoin_root f) :
quot_map_of_equiv_quot_map_C_map_span_mk I f (ideal.quotient.mk (I.map (of f)) x) =
ideal.quotient.mk _ x :=
rfl
/-- The natural isomorphism `R[α]/((I[x] ⊔ (f)) / (f)) ≅ (R[x]/I[x])/((f) ⊔ I[x] / I[x])`
for `α` a root of `f : polynomial R` and `I : ideal R`-/
def quot_map_C_map_span_mk_equiv_quot_map_C_quot_map_span_mk :
(adjoin_root f) ⧸ ((I.map (C : R →+* R[X]))).map (span {f})^.quotient.mk ≃+*
(R[X] ⧸ map C I) ⧸ (span {f}).map (I.map C)^.quotient.mk :=
quot_quot_equiv_comm (span ({f} : set (polynomial R))) (I.map (C : R →+* polynomial R))
@[simp]
lemma quot_map_C_map_span_mk_equiv_quot_map_C_quot_map_span_mk_mk (p : R[X]) :
quot_map_C_map_span_mk_equiv_quot_map_C_quot_map_span_mk I f (ideal.quotient.mk _ (mk f p)) =
quot_quot_mk (I.map C) (span {f}) p :=
rfl
/-- The natural isomorphism `(R/I)[x]/(f mod I) ≅ (R[x]/I*R[x])/(f mod I[x])` where
`f : polynomial R` and `I : ideal R`-/
def polynomial.quot_quot_equiv_comm :
(R ⧸ I)[X] ⧸ span ({f.map (I^.quotient.mk)} : set (polynomial (R ⧸ I))) ≃+*
(R[X] ⧸ map C I) ⧸ span ({(ideal.quotient.mk (I.map C)) f} : set (R[X] ⧸ map C I)) :=
quotient_equiv (span ({f.map (I^.quotient.mk)} : set (polynomial (R ⧸ I))))
(span {ideal.quotient.mk (I.map polynomial.C) f})
(polynomial_quotient_equiv_quotient_polynomial I)
(by rw [map_span, set.image_singleton, ring_equiv.coe_to_ring_hom,
polynomial_quotient_equiv_quotient_polynomial_map_mk I f])
@[simp]
lemma polynomial.quot_quot_equiv_comm_mk_mk (p : R[X]) :
(polynomial.quot_quot_equiv_comm I f).symm (ideal.quotient.mk _ (ideal.quotient.mk _ p)) =
(ideal.quotient.mk _ (p.map I^.quotient.mk)) :=
by simp only [polynomial.quot_quot_equiv_comm, quotient_equiv_symm_mk,
polynomial_quotient_equiv_quotient_polynomial_symm_mk]
/-- The natural isomorphism `R[α]/I[α] ≅ (R/I)[X]/(f mod I)` for `α` a root of `f : polynomial R`
and `I : ideal R`-/
def quot_map_of_equiv : (adjoin_root f) ⧸ (I.map (of f)) ≃+*
polynomial (R ⧸ I) ⧸ (span ({f.map (I^.quotient.mk)} : set (polynomial (R ⧸ I)))) :=
(quot_map_of_equiv_quot_map_C_map_span_mk I f).trans
((quot_map_C_map_span_mk_equiv_quot_map_C_quot_map_span_mk I f).trans
((ideal.quot_equiv_of_eq
(show (span ({f} : set (polynomial R))).map (I.map (C : R →+* polynomial R))^.quotient.mk =
span ({(ideal.quotient.mk (I.map polynomial.C)) f} : set (polynomial R ⧸ map C I)),
from by rw [map_span, set.image_singleton])).trans
(polynomial.quot_quot_equiv_comm I f).symm))
@[simp]
lemma quot_adjoin_root_equiv_quot_polynomial_quot_mk_of (p : R[X]) :
quot_map_of_equiv I f (ideal.quotient.mk (I.map (of f)) (mk f p)) =
ideal.quotient.mk (span ({f.map (I^.quotient.mk)} : set (polynomial (R ⧸ I))))
(p.map I^.quotient.mk) :=
by rw [quot_map_of_equiv, ring_equiv.trans_apply, ring_equiv.trans_apply, ring_equiv.trans_apply,
quot_map_of_equiv_quot_map_C_map_span_mk_mk,
quot_map_C_map_span_mk_equiv_quot_map_C_quot_map_span_mk_mk,quot_quot_mk, ring_hom.comp_apply,
quot_equiv_of_eq_mk, polynomial.quot_quot_equiv_comm_mk_mk]
end
end adjoin_root
|
b8026afbed1ec238d4c9eece38e2d4b2bab3dfac | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/notation6.lean | a98117c8e5361e1da1cb3957e8a3d8f1c9085cfb | [
"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 | 146 | lean | import logic data.num
open num
notation `o` := (10:num)
check 11
constant f : num → num
check o + 1
check f o + o + o
eval 9 + (1:num)
eval o+4
|
af4738cee2ce7364d0d30c0425026fc513627e21 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /src/Lean/Meta/Instances.lean | ba760dd3cd2314cca34f1391d776fb89316cb54d | [
"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 | 5,634 | 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.ScopedEnvExtension
import Lean.Meta.GlobalInstances
import Lean.Meta.DiscrTree
namespace Lean.Meta
structure InstanceEntry where
keys : Array DiscrTree.Key
val : Expr
priority : Nat
globalName? : Option Name := none
deriving Inhabited
instance : BEq InstanceEntry where
beq e₁ e₂ := e₁.val == e₂.val
instance : ToFormat InstanceEntry where
format e := match e.globalName? with
| some n => format n
| _ => "<local>"
structure Instances where
discrTree : DiscrTree InstanceEntry := DiscrTree.empty
instanceNames : Std.PHashSet Name := {}
erased : Std.PHashSet Name := {}
deriving Inhabited
def addInstanceEntry (d : Instances) (e : InstanceEntry) : Instances :=
match e.globalName? with
| some n => { d with discrTree := d.discrTree.insertCore e.keys e, instanceNames := d.instanceNames.insert n }
| none => { d with discrTree := d.discrTree.insertCore e.keys e }
def Instances.eraseCore (d : Instances) (declName : Name) : Instances :=
{ d with erased := d.erased.insert declName, instanceNames := d.instanceNames.erase declName }
def Instances.erase [Monad m] [MonadError m] (d : Instances) (declName : Name) : m Instances := do
unless d.instanceNames.contains declName do
throwError "'{declName}' does not have [instance] attribute"
return d.eraseCore declName
builtin_initialize instanceExtension : SimpleScopedEnvExtension InstanceEntry Instances ←
registerSimpleScopedEnvExtension {
name := `instanceExt
initial := {}
addEntry := addInstanceEntry
}
private def mkInstanceKey (e : Expr) : MetaM (Array DiscrTree.Key) := do
let type ← inferType e
withNewMCtxDepth do
let (_, _, type) ← forallMetaTelescopeReducing type
DiscrTree.mkPath type
def addInstance (declName : Name) (attrKind : AttributeKind) (prio : Nat) : MetaM Unit := do
let c ← mkConstWithLevelParams declName
let keys ← mkInstanceKey c
addGlobalInstance declName attrKind
instanceExtension.add { keys := keys, val := c, priority := prio, globalName? := declName } attrKind
builtin_initialize
registerBuiltinAttribute {
name := `instance
descr := "type class instance"
add := fun declName stx attrKind => do
let prio ← getAttrParamOptPrio stx[1]
discard <| addInstance declName attrKind prio |>.run {} {}
erase := fun declName => do
let s := instanceExtension.getState (← getEnv)
let s ← s.erase declName
modifyEnv fun env => instanceExtension.modifyState env fun _ => s
}
def getGlobalInstancesIndex : CoreM (DiscrTree InstanceEntry) :=
return Meta.instanceExtension.getState (← getEnv) |>.discrTree
def getErasedInstances : CoreM (Std.PHashSet Name) :=
return Meta.instanceExtension.getState (← getEnv) |>.erased
/-! # Default instance support -/
structure DefaultInstanceEntry where
className : Name
instanceName : Name
priority : Nat
abbrev PrioritySet := Std.RBTree Nat (fun x y => compare y x)
structure DefaultInstances where
defaultInstances : NameMap (List (Name × Nat)) := {}
priorities : PrioritySet := {}
deriving Inhabited
def addDefaultInstanceEntry (d : DefaultInstances) (e : DefaultInstanceEntry) : DefaultInstances :=
let d := { d with priorities := d.priorities.insert e.priority }
match d.defaultInstances.find? e.className with
| some insts => { d with defaultInstances := d.defaultInstances.insert e.className <| (e.instanceName, e.priority) :: insts }
| none => { d with defaultInstances := d.defaultInstances.insert e.className [(e.instanceName, e.priority)] }
builtin_initialize defaultInstanceExtension : SimplePersistentEnvExtension DefaultInstanceEntry DefaultInstances ←
registerSimplePersistentEnvExtension {
name := `defaultInstanceExt
addEntryFn := addDefaultInstanceEntry
addImportedFn := fun es => (mkStateFromImportedEntries addDefaultInstanceEntry {} es)
}
def addDefaultInstance (declName : Name) (prio : Nat := 0) : MetaM Unit := do
match (← getEnv).find? declName with
| none => throwError "unknown constant '{declName}'"
| some info =>
forallTelescopeReducing info.type fun _ type => do
match type.getAppFn with
| Expr.const className _ =>
unless isClass (← getEnv) className do
throwError "invalid default instance '{declName}', it has type '({className} ...)', but {className}' is not a type class"
setEnv <| defaultInstanceExtension.addEntry (← getEnv) { className := className, instanceName := declName, priority := prio }
| _ => throwError "invalid default instance '{declName}', type must be of the form '(C ...)' where 'C' is a type class"
builtin_initialize
registerBuiltinAttribute {
name := `defaultInstance
descr := "type class default instance"
add := fun declName stx kind => do
let prio ← getAttrParamOptPrio stx[1]
unless kind == AttributeKind.global do throwError "invalid attribute 'defaultInstance', must be global"
discard <| addDefaultInstance declName prio |>.run {} {}
}
def getDefaultInstancesPriorities [Monad m] [MonadEnv m] : m PrioritySet :=
return defaultInstanceExtension.getState (← getEnv) |>.priorities
def getDefaultInstances [Monad m] [MonadEnv m] (className : Name) : m (List (Name × Nat)) :=
return defaultInstanceExtension.getState (← getEnv) |>.defaultInstances.find? className |>.getD []
end Lean.Meta
|
c3895dcb4d35e8fa51f2ad2e8006ecad73db9fda | f4bff2062c030df03d65e8b69c88f79b63a359d8 | /src/game/cardinality/finite_inj.lean | 22daf02c2da2afb327e02d5666ee91d4b57779a1 | [
"Apache-2.0"
] | permissive | adastra7470/real-number-game | 776606961f52db0eb824555ed2f8e16f92216ea3 | f9dcb7d9255a79b57e62038228a23346c2dc301b | refs/heads/master | 1,669,221,575,893 | 1,594,669,800,000 | 1,594,669,800,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 690 | lean | import data.real.basic
import topology.basic
open function
open set
namespace xena -- hide
/-
# Chapter 7 : Cardinality
## Level 2
A classical result about finite sets.
-/
-- begin hide
local attribute [instance] classical.prop_decidable
-- end hide
/- Lemma
If $f : X \to Y$ is an injective function and $Y$ is finite, then
$X$ is also finite.
-/
theorem finite_inj (X Y : set ℝ) (f : X → Y) (hY : finite Y) :
injective f → finite X :=
begin
intro hf,
have h1 := finite.fintype hY, -- can't get f(X) ⊆ Y, type coercion problem
--have H1 := card_image_of_injective,
sorry,
end
end xena -- hide
-- begin hide
--#check finite_subsets_of_finite
-- end hide
|
b8c1e4b1bfb9f397fba510d2a56e52ad3f3e922f | 66a6486e19b71391cc438afee5f081a4257564ec | /univalent_subcategory.hlean | a70b128a125122f6351f8fc0f1acca539ec1c30b | [
"Apache-2.0"
] | permissive | spiceghello/Spectral | c8ccd1e32d4b6a9132ccee20fcba44b477cd0331 | 20023aa3de27c22ab9f9b4a177f5a1efdec2b19f | refs/heads/master | 1,611,263,374,078 | 1,523,349,717,000 | 1,523,349,717,000 | 92,312,239 | 0 | 0 | null | 1,495,642,470,000 | 1,495,642,470,000 | null | UTF-8 | Lean | false | false | 14,847 | hlean | import homotopy.sphere2 algebra.category.functor.attributes
open eq pointed sigma is_equiv equiv fiber algebra group is_trunc function prod prod.ops iso functor
namespace category
section univ_subcat
parameters {C : Precategory} {D : Category} (F : functor C D) (p : is_embedding F) (q : fully_faithful F)
variables {a b : carrier C}
include p q
definition eq_equiv_iso_of_fully_faithful : a = b ≃ a ≅ b :=
equiv.mk !ap !p -- a = b ≃ F a = F b
⬝e equiv.mk iso_of_eq !iso_of_path_equiv -- F a = F b ≃ F a ≅ F b
⬝e equiv.symm !iso_equiv_F_iso_F -- F a ≅ F b ≃ a ≅ b
definition eq_equiv_iso_of_fully_faithful_homot : @eq_equiv_iso_of_fully_faithful a b ~ iso_of_eq :=
begin
intro r,
esimp [eq_equiv_iso_of_fully_faithful],
refine _ ⬝ left_inv (iso_equiv_F_iso_F F _ _) _,
apply ap (inv (to_fun !iso_equiv_F_iso_F)),
apply symm,
induction r,
apply respect_refl
end
definition is_univalent_domain_of_fully_faithful_embedding : is_univalent C :=
begin
intros,
apply homotopy_closed eq_equiv_iso_of_fully_faithful eq_equiv_iso_of_fully_faithful_homot
end
end univ_subcat
definition precategory_Group.{u} [instance] [constructor] : precategory.{u+1 u} Group :=
begin
fapply precategory.mk,
{ exact λG H, G →g H },
{ exact _ },
{ exact λG H K ψ φ, ψ ∘g φ },
{ exact λG, gid G },
{ intros, apply homomorphism_eq, esimp },
{ intros, apply homomorphism_eq, esimp },
{ intros, apply homomorphism_eq, esimp }
end
definition precategory_AbGroup.{u} [instance] [constructor] : precategory.{u+1 u} AbGroup :=
begin
fapply precategory.mk,
{ exact λG H, G →g H },
{ exact _ },
{ exact λG H K ψ φ, ψ ∘g φ },
{ exact λG, gid G },
{ intros, apply homomorphism_eq, esimp },
{ intros, apply homomorphism_eq, esimp },
{ intros, apply homomorphism_eq, esimp }
end
definition Group_is_iso_of_is_equiv {G H : Group} (φ : G →g H) (H : is_equiv (group_fun φ)) :
is_iso φ :=
begin
fconstructor,
{ exact (isomorphism.mk φ H)⁻¹ᵍ },
{ apply homomorphism_eq, rexact left_inv φ },
{ apply homomorphism_eq, rexact right_inv φ }
end
definition Group_is_equiv_of_is_iso {G H : Group} (φ : G ⟶ H) (Hφ : is_iso φ) :
is_equiv (group_fun φ) :=
begin
fapply adjointify,
{ exact group_fun φ⁻¹ʰ },
{ note p := right_inverse φ, exact ap010 group_fun p },
{ note p := left_inverse φ, exact ap010 group_fun p }
end
definition Group_iso_equiv (G H : Group) : (G ≅ H) ≃ (G ≃g H) :=
begin
fapply equiv.MK,
{ intro φ, induction φ with φ φi, constructor, exact Group_is_equiv_of_is_iso φ _ },
{ intro v, induction v with φ φe, constructor, exact Group_is_iso_of_is_equiv φ _ },
{ intro v, induction v with φ φe, apply isomorphism_eq, reflexivity },
{ intro φ, induction φ with φ φi, apply iso_eq, reflexivity }
end
definition Group_props.{u} {A : Type.{u}} (v : (A → A → A) × (A → A) × A) : Prop.{u} :=
begin
induction v with m v, induction v with i o,
fapply trunctype.mk,
{ exact is_set A × (Πa, m a o = a) × (Πa, m o a = a) × (Πa b c, m (m a b) c = m a (m b c)) ×
(Πa, m (i a) a = o) },
{ apply is_trunc_of_imp_is_trunc, intro v, induction v with H v,
have is_prop (Πa, m a o = a), from _,
have is_prop (Πa, m o a = a), from _,
have is_prop (Πa b c, m (m a b) c = m a (m b c)), from _,
have is_prop (Πa, m (i a) a = o), from _,
apply is_trunc_prod }
end
definition AbGroup_props.{u} {A : Type.{u}} (v : (A → A → A) × (A → A) × A) : Prop.{u} :=
begin
induction v with m v, induction v with i o,
fapply trunctype.mk,
{ exact is_set A × (Πa, m a o = a) × (Πa, m o a = a) × (Πa b c, m (m a b) c = m a (m b c)) ×
(Πa, m (i a) a = o) × (Πa b, m a b = m b a)},
{ apply is_trunc_of_imp_is_trunc, intro v, induction v with H v,
have is_prop (Πa, m a o = a), from _,
have is_prop (Πa, m o a = a), from _,
have is_prop (Πa b c, m (m a b) c = m a (m b c)), from _,
have is_prop (Πa, m (i a) a = o), from _,
have is_prop (Πa b, m a b = m b a), from _,
apply is_trunc_prod }
end
definition AbGroup_sigma.{u} : AbGroup.{u} ≃ Σ A : Type.{u}, ab_group A :=
begin repeat (assumption | induction a with a b | intro a | fconstructor) end
definition Group_sigma.{u} : Group.{u} ≃ Σ A : Type.{u}, group A :=
begin
fconstructor, exact λ a, dpair (Group.carrier a) (Group.struct' a),
repeat (assumption | induction a with a b | intro a | fconstructor)
end
definition group.sigma_char.{u} (A : Type) :
group.{u} A ≃ Σ (v : (A → A → A) × (A → A) × A), Group_props v :=
begin
fapply equiv.MK,
{intro g, induction g with m s ma o om mo i mi,
repeat (fconstructor; do 2 try assumption), },
{intro v, induction v with x v, repeat induction x with y x,
repeat induction v with x v, constructor, repeat assumption },
{ intro, repeat induction b with b x, induction x,
repeat induction x_1 with v x_1, reflexivity },
{ intro v, repeat induction v with x v, reflexivity },
end
definition Group.sigma_char2.{u} :
Group.{u} ≃ Σ(A : Type.{u}) (v : (A → A → A) × (A → A) × A), Group_props v :=
Group_sigma ⬝e sigma_equiv_sigma_right group.sigma_char
definition ab_group.sigma_char.{u} (A : Type) :
ab_group.{u} A ≃ Σ (v : (A → A → A) × (A → A) × A), AbGroup_props v :=
begin
fapply equiv.MK,
{intro g, induction g with m s ma o om mo i mi,
repeat (fconstructor; do 2 try assumption), },
{intro v, induction v with x v, repeat induction x with y x,
repeat induction v with x v, constructor, repeat assumption },
{ intro, repeat induction b with b x, induction x,
repeat induction x_1 with v x_1, reflexivity },
{ intro v, repeat induction v with x v, reflexivity },
end
definition AbGroup_Group_props {A : Type} (v : (A → A → A) × (A → A) × A) :
AbGroup_props v ≃ Group_props v × ∀ a b, v.1 a b = v.1 b a :=
begin
fapply equiv.MK, induction v with m v, induction v with i e,
intro, fconstructor, repeat induction a with b a, repeat (fconstructor; assumption), assumption,
exact a.2.2.2.2.2, intro, induction a, repeat induction v with b v, repeat induction a with b a,
repeat (fconstructor; assumption), assumption, intro b,
assert H : is_prop (Group_props v × ∀ a b, v.1 a b = v.1 b a),
apply is_trunc_prod, assert K : is_set A, induction b, induction v, induction a_1, induction a_2_1, assumption,
exact _, apply is_prop.elim, intro, apply is_prop.elim,
end
open sigma.ops
definition sigma_prod_equiv_sigma_sigma {A} {B C : A→Type} : (Σa, B a × C a) ≃ Σ p : (Σa, B a), C p.1 :=
sigma_equiv_sigma_right (λa, !sigma.equiv_prod⁻¹ᵉ) ⬝e !sigma_assoc_equiv
definition ab_group_equiv_group_comm (A : Type) : ab_group A ≃ Σ (g : group A), ∀ a b : A, a * b = b * a :=
begin
refine !ab_group.sigma_char ⬝e _,
refine sigma_equiv_sigma_right AbGroup_Group_props ⬝e _,
refine sigma_prod_equiv_sigma_sigma ⬝e _,
apply equiv.symm, apply sigma_equiv_sigma !group.sigma_char, intros,
induction a, reflexivity
end
section
local attribute group.to_has_mul group.to_has_inv [coercion]
theorem inv_eq_of_mul_eq {A : Type} (G H : group A) (p : @mul A G ~2 @mul A H) :
@inv A G ~ @inv A H :=
begin
have foo : Π(g : A), @inv A G g = (@inv A G g * g) * @inv A H g,
from λg, !mul_inv_cancel_right⁻¹,
cases G with Gs Gm Gh1 G1 Gh2 Gh3 Gi Gh4,
cases H with Hs Hm Hh1 H1 Hh2 Hh3 Hi Hh4,
change Gi ~ Hi, intro g, have p' : Gm ~2 Hm, from p,
calc
Gi g = Hm (Hm (Gi g) g) (Hi g) : foo
... = Hm (Gm (Gi g) g) (Hi g) : by rewrite p'
... = Hm G1 (Hi g) : by rewrite Gh4
... = Gm G1 (Hi g) : by rewrite p'
... = Hi g : Gh2
end
theorem one_eq_of_mul_eq {A : Type} (G H : group A)
(p : @mul A (group.to_has_mul G) ~2 @mul A (group.to_has_mul H)) :
@one A (group.to_has_one G) = @one A (group.to_has_one H) :=
begin
cases G with Gm Gs Gh1 G1 Gh2 Gh3 Gi Gh4,
cases H with Hm Hs Hh1 H1 Hh2 Hh3 Hi Hh4,
exact (Hh2 G1)⁻¹ ⬝ (p H1 G1)⁻¹ ⬝ Gh3 H1,
end
end
definition group_of_Group_props.{u} {A : Type.{u}} {m : A → A → A} {i : A → A} {o : A}
(H : Group_props (m, (i, o))) : group A :=
⦃group, mul := m, inv := i, one := o, is_set_carrier := H.1,
mul_one := H.2.1, one_mul := H.2.2.1, mul_assoc := H.2.2.2.1, mul_left_inv := H.2.2.2.2⦄
theorem Group_eq_equiv_lemma2 {A : Type} {m m' : A → A → A} {i i' : A → A} {o o' : A}
(H : Group_props (m, (i, o))) (H' : Group_props (m', (i', o'))) :
(m, (i, o)) = (m', (i', o')) ≃ (m ~2 m') :=
begin
have is_set A, from pr1 H,
apply equiv_of_is_prop,
{ intro p, exact apd100 (eq_pr1 p)},
{ intro p, apply prod_eq (eq_of_homotopy2 p),
apply prod_eq: esimp [Group_props] at *; esimp,
{ apply eq_of_homotopy,
exact inv_eq_of_mul_eq (group_of_Group_props H) (group_of_Group_props H') p },
{ exact one_eq_of_mul_eq (group_of_Group_props H) (group_of_Group_props H') p }}
end
open Group
theorem Group_eq_equiv_lemma {G H : Group}
(p : (sigma_char2 G).1 = (sigma_char2 H).1) :
((sigma_char2 G).2 =[p] (sigma_char2 H).2) ≃
(is_mul_hom (equiv_of_eq (proof p qed : Group.carrier G = Group.carrier H))) :=
begin
refine !sigma_pathover_equiv_of_is_prop ⬝e _,
induction G with G g, induction H with H h,
esimp [sigma_char2] at p,
esimp [sigma_functor] at p, esimp [Group_sigma] at *,
induction p,
refine !pathover_idp ⬝e _,
induction g with s m ma o om mo i mi, induction h with σ μ μa ε εμ με ι μι,
exact Group_eq_equiv_lemma2 (sigma_char2 (Group.mk G (group.mk s m ma o om mo i mi))).2.2
(sigma_char2 (Group.mk G (group.mk σ μ μa ε εμ με ι μι))).2.2
end
definition isomorphism.sigma_char (G H : Group) : (G ≃g H) ≃ Σ(e : G ≃ H), is_mul_hom e :=
begin
fapply equiv.MK,
{ intro φ, exact ⟨equiv_of_isomorphism φ, to_respect_mul φ⟩ },
{ intro v, induction v with e p, exact isomorphism_of_equiv e p },
{ intro v, induction v with e p, induction e, reflexivity },
{ intro φ, induction φ with φ H, induction φ, reflexivity },
end
definition Group_eq_equiv (G H : Group) : G = H ≃ (G ≃g H) :=
begin
refine (eq_equiv_fn_eq_of_equiv sigma_char2 G H) ⬝e _,
refine !sigma_eq_equiv ⬝e _,
refine sigma_equiv_sigma_right Group_eq_equiv_lemma ⬝e _,
transitivity (Σ(e : (sigma_char2 G).1 ≃ (sigma_char2 H).1),
@is_mul_hom _ _ _ _ (to_fun e)), apply sigma_ua,
exact !isomorphism.sigma_char⁻¹ᵉ
end
definition to_fun_Group_eq_equiv {G H : Group} (p : G = H)
: Group_eq_equiv G H p ~ isomorphism_of_eq p :=
begin induction p, reflexivity end
definition Group_eq2 {G H : Group} {p q : G = H}
(r : isomorphism_of_eq p ~ isomorphism_of_eq q) : p = q :=
begin
apply eq_of_fn_eq_fn (Group_eq_equiv G H),
apply isomorphism_eq,
intro g, refine to_fun_Group_eq_equiv p g ⬝ r g ⬝ (to_fun_Group_eq_equiv q g)⁻¹,
end
definition Group_eq_equiv_Group_iso (G₁ G₂ : Group) : G₁ = G₂ ≃ G₁ ≅ G₂ :=
Group_eq_equiv G₁ G₂ ⬝e (Group_iso_equiv G₁ G₂)⁻¹ᵉ
definition category_Group.{u} : category Group.{u} :=
category.mk precategory_Group
begin
intro G H,
apply is_equiv_of_equiv_of_homotopy (Group_eq_equiv_Group_iso G H),
intro p, induction p, fapply iso_eq, apply homomorphism_eq, reflexivity
end
definition AbGroup_to_Group [constructor] : functor (Precategory.mk AbGroup _)
(Category.mk Group category_Group)
:= mk (λ x : AbGroup, (x : Group)) (λ a b x, x) (λ x, rfl) begin intros, reflexivity end
definition is_set_group (X : Type) : is_set (group X) :=
begin
apply is_trunc_of_imp_is_trunc, intros, assert H : is_set X, exact @group.is_set_carrier X a, clear a,
apply is_trunc_equiv_closed, apply equiv.symm,
apply group.sigma_char
end
definition ab_group_to_group (A : Type) (g : ab_group A) : group A := _
definition group_comm_to_group (A : Type) : (Σ g : group A, ∀ (a b : A), a*b = b*a) → group A := pr1
definition is_embedding_group_comm_to_group (A : Type) : is_embedding (group_comm_to_group A) :=
begin
unfold group_comm_to_group,
intros, induction a,
assert H : is_set A, induction a, assumption,
assert H :is_set (group A), apply is_set_group,
induction a', fconstructor, intros, apply sigma_eq,
apply is_prop.elimo, intro, esimp at *, assumption, intros,
apply is_prop.elim, intros, apply is_prop.elim, intros, apply is_prop.elim
end
definition ab_group_to_group_homot (A : Type) :
@ab_group_to_group A ~ group_comm_to_group A ∘ ab_group_equiv_group_comm A :=
begin intro, induction x, reflexivity end
definition is_embedding_ab_group_to_group (A : Type) : is_embedding (@ab_group_to_group A) :=
begin
apply is_embedding_homotopy_closed_rev (ab_group_to_group_homot A), apply is_embedding_compose,
exact is_embedding_group_comm_to_group A, apply is_embedding_of_is_equiv
end
definition is_embedding_total_of_is_embedding_fiber {A} {B C : A → Type} {f : Π a, B a → C a}
: (∀ a, is_embedding (f a)) → is_embedding (total f) :=
begin
intro e, fapply is_embedding_of_is_prop_fiber, intro p, induction p with a c,
assert H : (fiber (total f) ⟨a, c⟩)≃ fiber (f a) c,
apply fiber_total_equiv,
assert H2 : is_prop (fiber (f a) c),
apply is_prop_fiber_of_is_embedding,
apply is_trunc_equiv_closed -1 (H⁻¹ᵉ),
end
definition AbGroup_to_Group_homot : AbGroup_to_Group ~ Group_sigma⁻¹ ∘ total ab_group_to_group ∘ AbGroup_sigma :=
begin intro g, induction g, reflexivity end
definition is_embedding_AbGroup_to_Group : is_embedding AbGroup_to_Group :=
begin
apply is_embedding_homotopy_closed_rev AbGroup_to_Group_homot,
apply is_embedding_compose,
apply is_embedding_of_is_equiv,
apply is_embedding_compose,
apply is_embedding_total_of_is_embedding_fiber is_embedding_ab_group_to_group,
apply is_embedding_of_is_equiv
end
definition is_univalent_AbGroup : is_univalent precategory_AbGroup :=
begin
apply is_univalent_domain_of_fully_faithful_embedding AbGroup_to_Group is_embedding_AbGroup_to_Group, intros, apply is_equiv_id
end
definition category_AbGroup : category AbGroup := category.mk precategory_AbGroup is_univalent_AbGroup
definition Grp.{u} [constructor] : Category := category.Mk Group.{u} category_Group
definition AbGrp [constructor] : Category := category.Mk AbGroup category_AbGroup
end category
|
4d8b0f640a699585e8d010cabc16d6dcef24c0ad | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /library/init/classical.lean | afad3988d1ff2815966a62867b61adddb5ed4512 | [
"Apache-2.0"
] | permissive | soonhokong/lean-osx | 4a954262c780e404c1369d6c06516161d07fcb40 | 3670278342d2f4faa49d95b46d86642d7875b47c | refs/heads/master | 1,611,410,334,552 | 1,474,425,686,000 | 1,474,425,686,000 | 12,043,103 | 5 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 6,539 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad
-/
prelude
import init.subtype init.funext
namespace classical
open subtype
universe variables u v
/- the axiom -/
-- In the presence of classical logic, we could prove this from a weaker statement:
-- axiom indefinite_description {A : Type u} {P : A->Prop} (H : ∃x, P x) : {x : A, P x}
axiom strong_indefinite_description {A : Type u} (P : A → Prop) (H : nonempty A) :
{ x \ (∃ y : A, P y) → P x}
theorem exists_true_of_nonempty {A : Type u} (H : nonempty A) : ∃ x : A, true :=
nonempty.elim H (take x, ⟨x, trivial⟩)
noncomputable definition inhabited_of_nonempty {A : Type u} (H : nonempty A) : inhabited A :=
⟨elt_of (strong_indefinite_description (λa, true) H)⟩
noncomputable definition inhabited_of_exists {A : Type u} {P : A → Prop} (H : ∃ x, P x) : inhabited A :=
inhabited_of_nonempty (exists.elim H (λ w Hw, ⟨w⟩))
/- the Hilbert epsilon function -/
noncomputable definition epsilon {A : Type u} [H : nonempty A] (P : A → Prop) : A :=
elt_of (strong_indefinite_description P H)
theorem epsilon_spec_aux {A : Type u} (H : nonempty A) (P : A → Prop) (Hex : ∃ y, P y) :
P (@epsilon A H P) :=
have aux : (∃ y, P y) → P (elt_of (strong_indefinite_description P H)), from has_property (strong_indefinite_description P H),
aux Hex
theorem epsilon_spec {A : Type u} {P : A → Prop} (Hex : ∃ y, P y) :
P (@epsilon A (nonempty_of_exists Hex) P) :=
epsilon_spec_aux (nonempty_of_exists Hex) P Hex
theorem epsilon_singleton {A : Type u} (a : A) : @epsilon A ⟨a⟩ (λ x, x = a) = a :=
@epsilon_spec A (λ x, x = a) ⟨a, rfl⟩
noncomputable definition some {A : Type u} {P : A → Prop} (H : ∃ x, P x) : A :=
@epsilon A (nonempty_of_exists H) P
theorem some_spec {A : Type u} {P : A → Prop} (H : ∃ x, P x) : P (some H) :=
epsilon_spec H
/- the axiom of choice -/
theorem axiom_of_choice {A : Type u} {B : A → Type v} {R : Π x, B x → Prop} (H : ∀ x, ∃ y, R x y) :
∃ (f : Π x, B x), ∀ x, R x (f x) :=
have H : ∀ x, R x (some (H x)), from take x, some_spec (H x),
⟨_, H⟩
theorem skolem {A : Type u} {B : A → Type v} {P : Π x, B x → Prop} :
(∀ x, ∃ y, P x y) ↔ ∃ (f : Π x, B x) , (∀ x, P x (f x)) :=
iff.intro
(assume H : (∀ x, ∃ y, P x y), axiom_of_choice H)
(assume H : (∃ (f : Π x, B x), (∀ x, P x (f x))),
take x, exists.elim H (λ (fw : ∀x, B x) (Hw : ∀x, P x (fw x)),
⟨fw x, Hw x⟩))
/-
Prove excluded middle using Hilbert's choice
The proof follows Diaconescu proof that shows that the axiom of choice implies the excluded middle.
-/
section diaconescu
parameter p : Prop
private definition U (x : Prop) : Prop := x = true ∨ p
private definition V (x : Prop) : Prop := x = false ∨ p
private noncomputable definition u := epsilon U
private noncomputable definition v := epsilon V
private lemma u_def : U u :=
epsilon_spec ⟨true, or.inl rfl⟩
private lemma v_def : V v :=
epsilon_spec ⟨false, or.inl rfl⟩
private lemma not_uv_or_p : ¬(u = v) ∨ p :=
or.elim u_def
(assume Hut : u = true,
or.elim v_def
(assume Hvf : v = false,
have Hne : ¬(u = v), from eq.symm Hvf ▸ eq.symm Hut ▸ true_ne_false,
or.inl Hne)
(assume Hp : p, or.inr Hp))
(assume Hp : p, or.inr Hp)
private lemma p_implies_uv : p → u = v :=
assume Hp : p,
have Hpred : U = V, from
funext (take x : Prop,
have Hl : (x = true ∨ p) → (x = false ∨ p), from
assume A, or.inr Hp,
have Hr : (x = false ∨ p) → (x = true ∨ p), from
assume A, or.inr Hp,
show (x = true ∨ p) = (x = false ∨ p), from
propext (iff.intro Hl Hr)),
have H' : epsilon U = epsilon V, from Hpred ▸ rfl,
show u = v, from H'
theorem em : p ∨ ¬p :=
have H : ¬(u = v) → ¬p, from mt p_implies_uv,
or.elim not_uv_or_p
(assume Hne : ¬(u = v), or.inr (H Hne))
(assume Hp : p, or.inl Hp)
end diaconescu
theorem prop_complete (a : Prop) : a = true ∨ a = false :=
or.elim (em a)
(λ t, or.inl (propext (iff.intro (λ h, trivial) (λ h, t))))
(λ f, or.inr (propext (iff.intro (λ h, absurd h f) (λ h, false.elim h))))
definition eq_true_or_eq_false := prop_complete
section aux
attribute [elab_as_eliminator]
theorem cases_true_false (P : Prop → Prop) (H1 : P true) (H2 : P false) (a : Prop) : P a :=
or.elim (prop_complete a)
(assume Ht : a = true, eq.symm Ht ▸ H1)
(assume Hf : a = false, eq.symm Hf ▸ H2)
theorem cases_on (a : Prop) {P : Prop → Prop} (H1 : P true) (H2 : P false) : P a :=
cases_true_false P H1 H2 a
-- this supercedes by_cases in decidable
definition by_cases {p q : Prop} (Hpq : p → q) (Hnpq : ¬p → q) : q :=
or.elim (em p) (assume Hp, Hpq Hp) (assume Hnp, Hnpq Hnp)
-- this supercedes by_contradiction in decidable
theorem by_contradiction {p : Prop} (H : ¬p → false) : p :=
by_cases
(assume H1 : p, H1)
(assume H1 : ¬p, false.rec _ (H H1))
theorem eq_false_or_eq_true (a : Prop) : a = false ∨ a = true :=
cases_true_false (λ x, x = false ∨ x = true)
(or.inr rfl)
(or.inl rfl)
a
theorem eq.of_iff {a b : Prop} (H : a ↔ b) : a = b :=
iff.elim (assume H1 H2, propext (iff.intro H1 H2)) H
theorem iff_eq_eq {a b : Prop} : (a ↔ b) = (a = b) :=
propext (iff.intro
(assume H, eq.of_iff H)
(assume H, iff.of_eq H))
lemma eq_false {a : Prop} : (a = false) = (¬ a) :=
have (a ↔ false) = (¬ a), from propext (iff_false a),
eq.subst (@iff_eq_eq a false) this
lemma eq_true {a : Prop} : (a = true) = a :=
have (a ↔ true) = a, from propext (iff_true a),
eq.subst (@iff_eq_eq a true) this
end aux
/- All propositions are decidable -/
noncomputable definition decidable_inhabited (a : Prop) : inhabited (decidable a) :=
inhabited_of_nonempty
(or.elim (em a)
(assume Ha, ⟨is_true Ha⟩)
(assume Hna, ⟨is_false Hna⟩))
local attribute decidable_inhabited [instance]
noncomputable definition prop_decidable (a : Prop) : decidable a :=
arbitrary (decidable a)
local attribute prop_decidable [instance]
noncomputable definition type_decidable_eq (A : Type u) : decidable_eq A :=
λ a b, prop_decidable (a = b)
noncomputable definition type_decidable (A : Type u) : sum A (A → false) :=
match (prop_decidable (nonempty A)) with
| (is_true Hp) := sum.inl (inhabited.value (inhabited_of_nonempty Hp))
| (is_false Hn) := sum.inr (λ a, absurd (nonempty.intro a) Hn)
end
end classical
|
dade32ff5782f69cb48bb2057931593a1d323d60 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /test/nth_rewrite.lean | df1d99d10028d4ec407727194b4695ba04bd8978 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 3,162 | lean | /-
Copyright (c) 2018 Keeley Hoek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Keeley Hoek, Scott Morrison
-/
import tactic.nth_rewrite
import data.nat.basic
import data.vector
structure F :=
(a : ℕ)
(v : vector ℕ a)
(p : v.val = [])
example (f : F) : f.v.val = [] :=
begin
nth_rewrite 0 [f.p],
end
structure cat :=
(O : Type)
(H : O → O → Type)
(i : Π o : O, H o o)
(c : Π {X Y Z : O} (f : H X Y) (g : H Y Z), H X Z)
(li : Π {X Y : O} (f : H X Y), c (i X) f = f)
(ri : Π {X Y : O} (f : H X Y), c f (i Y) = f)
(a : Π {W X Y Z : O} (f : H W X) (g : H X Y) (h : H Y Z), c (c f g) h = c f (c g h))
open tactic
example (C : cat) (W X Y Z : C.O) (f : C.H X Y) (g : C.H W X) (h k : C.H Y Z) :
C.c (C.c g f) h = C.c g (C.c f h) :=
begin
nth_rewrite 0 [C.a],
end
example (C : cat) (X Y : C.O) (f : C.H X Y) : C.c f (C.i Y) = f :=
begin
nth_rewrite 0 [C.ri],
end
-- The next two examples fail when using the kabstract backend.
axiom foo : [1] = [2]
example : [[1], [1], [1]] = [[1], [2], [1]] :=
begin
nth_rewrite_lhs 1 [foo],
end
axiom foo' : [6] = [7]
axiom bar' : [[5],[5]] = [[6],[6]]
example : [[7],[6]] = [[5],[5]] :=
begin
nth_rewrite_lhs 0 foo',
nth_rewrite_rhs 0 bar',
nth_rewrite_lhs 0 ←foo',
nth_rewrite_lhs 0 ←foo',
end
axiom wowzer : (3, 3) = (5, 2)
axiom kachow (n : ℕ) : (4, n) = (5, n)
axiom pchew (n : ℕ) : (n, 5) = (5, n)
axiom smash (n m : ℕ) : (n, m) = (1, 1)
example : [(3, 3), (5, 9), (5, 9)] = [(4, 5), (3, 6), (1, 1)] :=
begin
nth_rewrite_lhs 0 wowzer,
nth_rewrite_lhs 2 ←pchew,
nth_rewrite_rhs 0 pchew,
nth_rewrite_rhs 0 smash,
nth_rewrite_rhs 1 smash,
nth_rewrite_rhs 2 smash,
nth_rewrite_lhs 0 smash,
nth_rewrite_lhs 1 smash,
nth_rewrite_lhs 2 smash,
end
example (a b c : ℕ) : c + a + b = a + c + b :=
begin
nth_rewrite_rhs 1 add_comm,
end
-- With the `kabstract` backend, we only find one rewrite, even though there are obviously two.
-- The problem is that `(a + b) + c` matches directly, so the WHOLE THING gets replaced with a
-- metavariable, per the `kabstract` strategy. This is devastating to the search, since we cannot
-- see inside this metavariable.
-- I still think it's fixable. Because all applications have an order, I'm pretty sure we can't
-- miss any rewrites if we also look inside every thing we chunk-up into a metavariable as well.
-- In almost every case this will bring up no results (with the exception of situations like this
-- one), so there should be essentially no change in complexity.
example (x y : Prop) (h₁ : x ↔ y) (h₂ : x ↔ x ∧ x) : x ∧ x ↔ x :=
begin
nth_rewrite_rhs 1 [h₁] at h₂,
nth_rewrite_rhs 0 [← h₁] at h₂,
nth_rewrite_rhs 0 h₂,
end
example (x y : ℕ) (h₁ : x = y) (h₂ : x = x + x) : x + x = x :=
begin
nth_rewrite_rhs 1 [h₁] at h₂,
nth_rewrite_rhs 0 [← h₁] at h₂,
nth_rewrite_rhs 0 h₂,
end
example (x y z : ℕ) (h1 : x = y) (h2 : y = z) :
x + x + x + y = y + y + x + x :=
begin
nth_rewrite 2 [h1, h2], -- h2 is not used
nth_rewrite 2 [h2],
repeat { rw h1 },
repeat { rw h2 },
end
|
f50d8d1a8cd2c829a76e0e7a5469ea9ccd1d38de | 57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d | /stage0/src/Lean/Meta/AbstractNestedProofs.lean | ed4a917119f995f52acfbf92fbf03524e716735b | [
"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 | 2,615 | 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.Closure
namespace Lean.Meta
namespace AbstractNestedProofs
def isNonTrivialProof (e : Expr) : MetaM Bool := do
if !(← isProof e) then
pure false
else
e.withApp fun f args =>
pure $ !f.isAtomic || args.any fun arg => !arg.isAtomic
structure Context where
baseName : Name
structure State where
nextIdx : Nat := 1
abbrev M := ReaderT Context $ MonadCacheT Expr Expr $ StateRefT State MetaM
private def mkAuxLemma (e : Expr) : M Expr := do
let ctx ← read
let s ← get
let lemmaName ← mkAuxName (ctx.baseName ++ `proof) s.nextIdx
modify fun s => { s with nextIdx := s.nextIdx + 1 }
mkAuxDefinitionFor lemmaName e
partial def visit (e : Expr) : M Expr := do
if e.isAtomic then
pure e
else
let visitBinders (xs : Array Expr) (k : M Expr) : M Expr := do
let localInstances ← getLocalInstances
let mut lctx ← getLCtx
for x in xs do
let xFVarId := x.fvarId!
let localDecl ← getLocalDecl xFVarId
let type ← visit localDecl.type
let localDecl := localDecl.setType type
let localDecl ← match localDecl.value? with
| some value => do let value ← visit value; pure $ localDecl.setValue value
| none => pure localDecl
lctx :=lctx.modifyLocalDecl xFVarId fun _ => localDecl
withLCtx lctx localInstances k
checkCache e fun _ => do
if (← isNonTrivialProof e) then
mkAuxLemma e
else match e with
| Expr.lam _ _ _ _ => lambdaLetTelescope e fun xs b => visitBinders xs do mkLambdaFVars xs (← visit b)
| Expr.letE _ _ _ _ _ => lambdaLetTelescope e fun xs b => visitBinders xs do mkLambdaFVars xs (← visit b)
| Expr.forallE _ _ _ _ => forallTelescope e fun xs b => visitBinders xs do mkForallFVars xs (← visit b)
| Expr.mdata _ b _ => return e.updateMData! (← visit b)
| Expr.proj _ _ b _ => return e.updateProj! (← visit b)
| Expr.app _ _ _ => e.withApp fun f args => return mkAppN f (← args.mapM visit)
| _ => pure e
end AbstractNestedProofs
/-- Replace proofs nested in `e` with new lemmas. The new lemmas have names of the form `mainDeclName.proof_<idx>` -/
def abstractNestedProofs (mainDeclName : Name) (e : Expr) : MetaM Expr :=
AbstractNestedProofs.visit e |>.run { baseName := mainDeclName } |>.run |>.run' { nextIdx := 1 }
end Lean.Meta
|
688a859cb2a465ff48213aa96e8fdf8b49a77d5e | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /stage0/src/Init/Data/Option/Basic.lean | 895628da58a0c2bf670cf4eade100c13293d3e86 | [
"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,874 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Core
import Init.Control.Basic
import Init.Coe
namespace Option
def toMonad [Monad m] [Alternative m] : Option α → m α
| none => failure
| some a => pure a
@[inline] def toBool : Option α → Bool
| some _ => true
| none => false
@[inline] def isSome : Option α → Bool
| some _ => true
| none => false
@[inline] def isNone : Option α → Bool
| some _ => false
| none => true
@[inline] def isEqSome [BEq α] : Option α → α → Bool
| some a, b => a == b
| none, _ => false
@[inline] protected def bind : Option α → (α → Option β) → Option β
| none, _ => none
| some a, b => b a
@[inline] protected def mapM [Monad m] (f : α → m β) (o : Option α) : m (Option β) := do
if let some a := o then
return some (← f a)
else
return none
theorem map_id : (Option.map id : Option α → Option α) = id :=
funext (fun o => match o with | none => rfl | some _ => rfl)
instance : Functor Option where
map := Option.map
@[inline] protected def filter (p : α → Bool) : Option α → Option α
| some a => if p a then some a else none
| none => none
@[inline] protected def all (p : α → Bool) : Option α → Bool
| some a => p a
| none => true
@[inline] protected def any (p : α → Bool) : Option α → Bool
| some a => p a
| none => false
@[macroInline] protected def orElse : Option α → (Unit → Option α) → Option α
| some a, _ => some a
| none, b => b ()
instance : OrElse (Option α) where
orElse := Option.orElse
@[inline] protected def lt (r : α → α → Prop) : Option α → Option α → Prop
| none, some _ => True
| some x, some y => r x y
| _, _ => False
instance (r : α → α → Prop) [s : DecidableRel r] : DecidableRel (Option.lt r)
| none, some _ => isTrue trivial
| some x, some y => s x y
| some _, none => isFalse not_false
| none, none => isFalse not_false
end Option
deriving instance DecidableEq for Option
deriving instance BEq for Option
instance [LT α] : LT (Option α) where
lt := Option.lt (· < ·)
instance : Functor Option where
map := Option.map
instance : Monad Option where
pure := Option.some
bind := Option.bind
instance : Alternative Option where
failure := Option.none
orElse := Option.orElse
def liftOption [Alternative m] : Option α → m α
| some a => pure a
| none => failure
@[inline] protected def Option.tryCatch (x : Option α) (handle : Unit → Option α) : Option α :=
match x with
| some _ => x
| none => handle ()
instance : MonadExceptOf Unit Option where
throw := fun _ => Option.none
tryCatch := Option.tryCatch
|
fef8de4082c0d5003c508bec4346ce399f05e5da | 75c54c8946bb4203e0aaf196f918424a17b0de99 | /src/bv_tauto.lean | a1578f913cfe3df50b9d4cf0abdbc8c8f3c9cd93 | [
"Apache-2.0"
] | permissive | urkud/flypitch | 261e2a45f1038130178575406df8aea78255ba77 | 2250f5eda14b6ef9fc3e4e1f4a9ac4005634de5c | refs/heads/master | 1,653,266,469,246 | 1,577,819,679,000 | 1,577,819,679,000 | 259,862,235 | 1 | 0 | Apache-2.0 | 1,588,147,244,000 | 1,588,147,244,000 | null | UTF-8 | Lean | false | false | 3,312 | lean | import .to_mathlib
local infix ` ⟹ `:65 := lattice.imp
namespace lattice
lemma context_or_elim' {β} [complete_boolean_algebra β] {Γ a b c : β} (H : Γ ≤ a ⊔ b) (H_left : ∀ {Γ'} (H_le : Γ' ≤ Γ) (H_le' : Γ' ≤ a), Γ' ≤ c) (H_right : ∀ {Γ'} (H_le : Γ' ≤ Γ) (H_le' : Γ' ≤ b), Γ' ≤ c) : Γ ≤ c :=
begin
bv_or_elim_at H,
{ specialize @H_left Γ_1 (by simp[Γ_1]) ‹_›, from ‹_› },
{ specialize @H_right Γ_1 (by simp[Γ_1]) ‹_›, from ‹_› }
end
end lattice
namespace tactic
namespace interactive
section bv_tauto
open lean.parser lean interactive.types interactive
local postfix `?`:9001 := optional
-- takes `e`, a proof that Γ' ≤ Γ, and specializes hypotheses of the form `Γ ≤ b` to `Γ' ≤ b`
meta def context_switch_core (e : expr) : tactic unit :=
do `(%%Γ' ≤ %%Γ) <- infer_type e,
ctx <- local_context >>=
(λ l, l.mfilter (λ H,
((do Γ'' <- (infer_type H) >>= lhs_of_le,
succeeds (is_def_eq Γ'' Γ))) <|> return ff)),
ctx.mmap' ((λ H, do let n := get_name H,
prf <- to_expr ``(le_trans %%e %%H),
note n none prf,
tactic.clear H) : expr → tactic unit)
meta def context_switch (p : parse texpr): tactic unit :=
do e <- to_expr ``(%%p),
context_switch_core e
-- faster version of bv_or_elim
-- TODO(jesse): `cases`-like handling of new names for the split hypotheses
-- TODO(jesse): add similar versions with bv_impl_intro and bv_exists_elim
meta def bv_or_elim_core (p : expr) : tactic unit :=
do n <- get_unused_name "Γ",
n_H <- get_unused_name "H_le",
`[apply lattice.context_or_elim' %%p];
propagate_tags ((intro_lst [n,n_H]) >> skip);
tactic.clear p;
resolve_name n_H >>= context_switch; intro none
meta def bv_or_elim (n : parse ident) : tactic unit :=
resolve_name n >>= to_expr >>= bv_or_elim_core
meta def auto_or_elim_aux : list expr → tactic unit
| [] := tactic.fail "auto_or_elim failed"
| (e::es) := (do `(%%Γ ≤ %%x ⊔ %%y) <- infer_type e,
let n := get_name e,
Γ₁ <- get_current_context >>= whnf,
Γ₂ <- whnf Γ,
guard (Γ₁ =ₐ Γ₂),
bv_or_elim_core e,
try assumption)
<|> auto_or_elim_aux es
meta def auto_or_elim_step : tactic unit := local_context >>= auto_or_elim_aux
meta def goal_is_bv_false : tactic unit :=
do rhs <- target >>= rhs_of_le,
match rhs with
| `(⊥) := skip
| _ := fail "not ⊥"
end
meta def bv_tauto_step : tactic unit :=
do (goal_is_bv_false >> skip) <|> `[refine _root_.lattice.bv_by_contra _] >> bv_imp_intro none,
`[try {unfold _root_.lattice.imp at *}],
`[try {simp only with bv_push_neg at *}],
try bv_split,
try bv_contradiction
-- TODO(jesse): also automatically case on existentials
meta def bv_tauto (n : option ℕ := none) : tactic unit :=
match n with
| none := bv_tauto_step *> (done <|> (auto_or_elim_step; bv_tauto))
| (some k) := iterate_at_most k bv_tauto_step
end
end bv_tauto
end interactive
end tactic
example {𝔹} [lattice.nontrivial_complete_boolean_algebra 𝔹] {a b c : 𝔹} : ( a ⟹ b ) ⊓ ( b ⟹ c ) ≤ a ⟹ c :=
begin
tidy_context, bv_tauto
end
|
677b7107e0b0882e5dab813792557dd8a03a1272 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/measure_theory/probability_mass_function/basic.lean | 0ead7a926a30f294aba14105c6bb180f0625e649 | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 6,826 | 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, Devon Tuma
-/
import topology.instances.ennreal
import measure_theory.measure.measure_space
/-!
# Probability mass functions
This file is about probability mass functions or discrete probability measures:
a function `α → ℝ≥0` such that the values have (infinite) sum `1`.
Construction of monadic `pure` and `bind` is found in `probability_mass_function/monad.lean`,
other constructions of `pmf`s are found in `probability_mass_function/constructions.lean`.
Given `p : pmf α`, `pmf.to_outer_measure` constructs an `outer_measure` on `α`,
by assigning each set the sum of the probabilities of each of its elements.
Under this outer measure, every set is Carathéodory-measurable,
so we can further extend this to a `measure` on `α`, see `pmf.to_measure`.
`pmf.to_measure.is_probability_measure` shows this associated measure is a probability measure.
## Tags
probability mass function, discrete probability measure
-/
noncomputable theory
variables {α : Type*} {β : Type*} {γ : Type*}
open_locale classical big_operators nnreal ennreal
/-- A probability mass function, or discrete probability measures is a function `α → ℝ≥0` such that
the values have (infinite) sum `1`. -/
def {u} pmf (α : Type u) : Type u := { f : α → ℝ≥0 // has_sum f 1 }
namespace pmf
instance : has_coe_to_fun (pmf α) (λ p, α → ℝ≥0) := ⟨λ p a, p.1 a⟩
@[ext] protected lemma ext : ∀ {p q : pmf α}, (∀ a, p a = q a) → p = q
| ⟨f, hf⟩ ⟨g, hg⟩ eq := subtype.eq $ funext eq
lemma has_sum_coe_one (p : pmf α) : has_sum p 1 := p.2
lemma summable_coe (p : pmf α) : summable p := (p.has_sum_coe_one).summable
@[simp] lemma tsum_coe (p : pmf α) : ∑' a, p a = 1 := p.has_sum_coe_one.tsum_eq
/-- The support of a `pmf` is the set where it is nonzero. -/
def support (p : pmf α) : set α := function.support p
@[simp] lemma mem_support_iff (p : pmf α) (a : α) : a ∈ p.support ↔ p a ≠ 0 := iff.rfl
lemma apply_eq_zero_iff (p : pmf α) (a : α) : p a = 0 ↔ a ∉ p.support :=
by rw [mem_support_iff, not_not]
lemma coe_le_one (p : pmf α) (a : α) : p a ≤ 1 :=
has_sum_le (by { intro b, split_ifs; simp only [h, zero_le'] })
(has_sum_ite_eq a (p a)) (has_sum_coe_one p)
section outer_measure
open measure_theory measure_theory.outer_measure
/-- Construct an `outer_measure` from a `pmf`, by assigning measure to each set `s : set α` equal
to the sum of `p x` for for each `x ∈ α` -/
def to_outer_measure (p : pmf α) : outer_measure α :=
outer_measure.sum (λ (x : α), p x • dirac x)
lemma to_outer_measure_apply (p : pmf α) (s : set α) :
p.to_outer_measure s = ∑' x, s.indicator (λ x, (p x : ℝ≥0∞)) x :=
tsum_congr (λ x, smul_dirac_apply (p x) x s)
lemma to_outer_measure_apply' (p : pmf α) (s : set α) :
p.to_outer_measure s = ↑(∑' (x : α), s.indicator p x) :=
by simp only [ennreal.coe_tsum (nnreal.indicator_summable (summable_coe p) s),
ennreal.coe_indicator, to_outer_measure_apply]
@[simp]
lemma to_outer_measure_apply_finset (p : pmf α) (s : finset α) :
p.to_outer_measure s = ∑ x in s, (p x : ℝ≥0∞) :=
begin
refine (to_outer_measure_apply p s).trans ((@tsum_eq_sum _ _ _ _ _ _ s _).trans _),
{ exact λ x hx, set.indicator_of_not_mem hx _ },
{ exact finset.sum_congr rfl (λ x hx, set.indicator_of_mem hx _) }
end
@[simp]
lemma to_outer_measure_apply_fintype [fintype α] (p : pmf α) (s : set α) :
p.to_outer_measure s = ∑ x, (s.indicator (λ x, (p x : ℝ≥0∞)) x) :=
(p.to_outer_measure_apply s).trans (tsum_eq_sum (λ x h, absurd (finset.mem_univ x) h))
lemma to_outer_measure_apply_eq_zero_iff (p : pmf α) (s : set α) :
p.to_outer_measure s = 0 ↔ disjoint p.support s :=
begin
rw [to_outer_measure_apply', ennreal.coe_eq_zero,
tsum_eq_zero_iff (nnreal.indicator_summable (summable_coe p) s)],
exact function.funext_iff.symm.trans set.indicator_eq_zero',
end
@[simp]
lemma to_outer_measure_caratheodory (p : pmf α) :
(to_outer_measure p).caratheodory = ⊤ :=
begin
refine (eq_top_iff.2 $ le_trans (le_Inf $ λ x hx, _) (le_sum_caratheodory _)),
obtain ⟨y, hy⟩ := hx,
exact ((le_of_eq (dirac_caratheodory y).symm).trans
(le_smul_caratheodory _ _)).trans (le_of_eq hy),
end
end outer_measure
section measure
open measure_theory
/-- Since every set is Carathéodory-measurable under `pmf.to_outer_measure`,
we can further extend this `outer_measure` to a `measure` on `α` -/
def to_measure [measurable_space α] (p : pmf α) : measure α :=
p.to_outer_measure.to_measure ((to_outer_measure_caratheodory p).symm ▸ le_top)
variables [measurable_space α]
lemma to_measure_apply_eq_to_outer_measure_apply (p : pmf α) (s : set α) (hs : measurable_set s) :
p.to_measure s = p.to_outer_measure s :=
to_measure_apply p.to_outer_measure _ hs
lemma to_outer_measure_apply_le_to_measure_apply (p : pmf α) (s : set α) :
p.to_outer_measure s ≤ p.to_measure s :=
le_to_measure_apply p.to_outer_measure _ s
lemma to_measure_apply (p : pmf α) (s : set α) (hs : measurable_set s) :
p.to_measure s = ∑' x, s.indicator (λ x, (p x : ℝ≥0∞)) x :=
(p.to_measure_apply_eq_to_outer_measure_apply s hs).trans (p.to_outer_measure_apply s)
lemma to_measure_apply' (p : pmf α) (s : set α) (hs : measurable_set s) :
p.to_measure s = ↑(∑' x, s.indicator p x) :=
(p.to_measure_apply_eq_to_outer_measure_apply s hs).trans (p.to_outer_measure_apply' s)
@[simp]
lemma to_measure_apply_finset [measurable_singleton_class α] (p : pmf α) (s : finset α) :
p.to_measure s = ∑ x in s, (p x : ℝ≥0∞) :=
(p.to_measure_apply_eq_to_outer_measure_apply s s.measurable_set).trans
(p.to_outer_measure_apply_finset s)
lemma to_measure_apply_of_finite [measurable_singleton_class α] (p : pmf α) (s : set α)
(hs : s.finite) : p.to_measure s = ∑' x, s.indicator (λ x, (p x : ℝ≥0∞)) x :=
(p.to_measure_apply_eq_to_outer_measure_apply s hs.measurable_set).trans
(p.to_outer_measure_apply s)
@[simp]
lemma to_measure_apply_fintype [measurable_singleton_class α] [fintype α] (p : pmf α) (s : set α) :
p.to_measure s = ∑ x, s.indicator (λ x, (p x : ℝ≥0∞)) x :=
(p.to_measure_apply_eq_to_outer_measure_apply s (set.finite.of_fintype s).measurable_set).trans
(p.to_outer_measure_apply_fintype s)
/-- The measure associated to a `pmf` by `to_measure` is a probability measure -/
instance to_measure.is_probability_measure (p : pmf α) : is_probability_measure (p.to_measure) :=
⟨by simpa only [measurable_set.univ, to_measure_apply_eq_to_outer_measure_apply, set.indicator_univ,
to_outer_measure_apply', ennreal.coe_eq_one] using tsum_coe p⟩
end measure
end pmf
|
16b38d203a336893bf1ea8d3a76c0c3305cb6c92 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /test/ring.lean | 82c99e1c65feb5b55f92f64f004fa0c89250812c | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 3,513 | lean | import tactic.ring
import data.real.basic
import algebra.parity
example (x y : ℕ) : x + y = y + x := by ring
example (x y : ℕ) : x + y + y = 2 * y + x := by ring
example (x y : ℕ) : x + id y = y + id x := by ring!
example {α} [comm_ring α] (x y : α) : x + y + y - x = 2 * y := by ring
example (x y : ℚ) : x / 2 + x / 2 = x := by ring
example (x y : ℚ) : (x + y) ^ 3 = x ^ 3 + y ^ 3 + 3 * (x * y ^ 2 + x ^ 2 * y) := by ring
example (x y : ℝ) : (x + y) ^ 3 = x ^ 3 + y ^ 3 + 3 * (x * y ^ 2 + x ^ 2 * y) := by ring
example {α} [comm_semiring α] (x : α) : (x + 1) ^ 6 = (1 + x) ^ 6 := by try_for 15000 {ring}
example (n : ℕ) : (n / 2) + (n / 2) = 2 * (n / 2) := by ring
example {α} [field α] [char_zero α] (a : α) : a / 2 = a / 2 := by ring
example {α} [linear_ordered_field α] (a b c : α) :
a * (-c / b) * (-c / b) + -c + c = a * (c / b * (c / b)) := by ring
example {α} [linear_ordered_field α] (a b c : α) :
b ^ 2 - 4 * c * a = -(4 * c * a) + b ^ 2 := by ring
example (x : ℚ) : x ^ (2 + 2) = x^4 := by ring_nf -- TODO: ring should work?
example {α} [comm_ring α] (x : α) : x ^ 2 = x * x := by ring
example {α} [linear_ordered_field α] (a b c : α) :
b ^ 2 - 4 * c * a = -(4 * c * a) + b ^ 2 := by ring
example {α} [linear_ordered_field α] (a b c : α) :
b ^ 2 - 4 * a * c = 4 * a * 0 + b * b - 4 * a * c := by ring
example {α} [comm_semiring α] (x y z : α) (n : ℕ) :
(x + y) * (z * (y * y) + (x * x ^ n + (1 + ↑n) * x ^ n * y)) =
x * (x * x ^ n) + ((2 + ↑n) * (x * x ^ n) * y + (x * z + (z * y + (1 + ↑n) * x ^ n)) * (y * y)) := by ring
example {α} [comm_ring α] (a b c d e : α) :
(-(a * b) + c + d) * e = (c + (d + -a * b)) * e := by ring
example (a n s: ℕ) : a * (n - s) = (n - s) * a := by ring
example (x y z : ℚ) (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) :
x / (y / z) + y ⁻¹ + 1 / (y * -x) = -1/ (x * y) + (x * z + 1) / y :=
begin
field_simp,
ring
end
example {A : ℤ} (f : ℤ → ℤ) : f 0 = f (A - A) := by ring_nf
example {A : ℤ} (f : ℤ → ℤ) : f 0 = f (A + -A) := by ring_nf
example {a b c : ℝ} (h : 0 < a ^ 4 + b ^ 4 + c ^ 4) :
a ^ 4 / (a ^ 4 + b ^ 4 + c ^ 4) +
b ^ 4 / (b ^ 4 + c ^ 4 + a ^ 4) +
c ^ 4 / (c ^ 4 + a ^ 4 + b ^ 4)
= 1 :=
begin
ring_nf at ⊢ h,
field_simp [h.ne'],
end
example (a b c d x y : ℚ) (hx : x ≠ 0) (hy : y ≠ 0) :
a + b / x - c / x^2 + d / x^3 = a + x⁻¹ * (y * b / y + (d / x - c) / x) :=
begin
field_simp,
ring
end
example : (876544 : ℤ) * -1 + (1000000 - 123456) = 0 := by ring
example (x y : ℝ) (hx : x ≠ 0) (hy : y ≠ 0) :
2 * x ^ 3 * 2 / (24 * x) = x ^ 2 / 6 :=
begin
field_simp,
ring
end
-- this proof style is not recommended practice
example (A B : ℕ) (H : B * A = 2) : A * B = 2 := by {ring_nf, exact H}
example (a : ℤ) : odd ((2 * a + 1) ^ 2) :=
begin
use 2 * a ^ 2 + 2 * a,
ring_nf,
end
example {x y : ℝ}
(hxy : -y ^ 2 + x ^ 2 = -(5 * y) + 5 * x) :
x ^ 2 - y ^ 2 = 5 * x - 5 * y :=
begin
ring_nf at hxy ⊢,
exact hxy
end
example {α} [field α] {x y : α}
(h : 0 = (1 - x) ^ 2 * (x * (2 ^ 2 * y ^ 2 + 4 * (1 - x) ^ 2))) :
0 = x * ((2 ^ 2 * y ^ 2 + 4 * (1 - x) ^ 2) * (1 - x) ^ 2) :=
by transitivity; [exact h, ring]
-- `ring_nf` should descend into the subexpressions `x * -a` and `-a * x`:
example {a x : ℚ} : x * -a = - a * x := by ring_nf
example (f : ℤ → ℤ) (a b : ℤ) : f (2 * a + b) + b = b + f (b + a + a) :=
begin
success_if_fail {{ ring_nf {recursive := ff} }},
ring_nf
end
|
b39806a995400612ba12c3190ff6cfaa3d166bdc | b074a51e20fdb737b2d4c635dd292fc54685e010 | /src/data/mv_polynomial.lean | 146ece5a09575c7070985b04cf4ace653c4be5db | [
"Apache-2.0"
] | permissive | minchaowu/mathlib | 2daf6ffdb5a56eeca403e894af88bcaaf65aec5e | 879da1cf04c2baa9eaa7bd2472100bc0335e5c73 | refs/heads/master | 1,609,628,676,768 | 1,564,310,105,000 | 1,564,310,105,000 | 99,461,307 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 42,193 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Johan Commelin, Mario Carneiro
Multivariate Polynomial
-/
import algebra.ring
import data.finsupp data.polynomial data.equiv.algebra
open set function finsupp lattice
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
/-- Multivariate polynomial, where `σ` is the index set of the variables and
`α` is the coefficient ring -/
def mv_polynomial (σ : Type*) (α : Type*) [comm_semiring α] := (σ →₀ ℕ) →₀ α
namespace mv_polynomial
variables {σ : Type*} {a a' a₁ a₂ : α} {e : ℕ} {n m : σ} {s : σ →₀ ℕ}
variables [decidable_eq σ] [decidable_eq α]
section comm_semiring
variables [comm_semiring α] {p q : mv_polynomial σ α}
instance : decidable_eq (mv_polynomial σ α) := finsupp.decidable_eq
instance : has_zero (mv_polynomial σ α) := finsupp.has_zero
instance : has_one (mv_polynomial σ α) := finsupp.has_one
instance : has_add (mv_polynomial σ α) := finsupp.has_add
instance : has_mul (mv_polynomial σ α) := finsupp.has_mul
instance : comm_semiring (mv_polynomial σ α) := finsupp.comm_semiring
/-- `monomial s a` is the monomial `a * X^s` -/
def monomial (s : σ →₀ ℕ) (a : α) : mv_polynomial σ α := single s a
/-- `C a` is the constant polynomial with value `a` -/
def C (a : α) : mv_polynomial σ α := monomial 0 a
/-- `X n` is the polynomial with value X_n -/
def X (n : σ) : mv_polynomial σ α := monomial (single n 1) 1
@[simp] lemma C_0 : C 0 = (0 : mv_polynomial σ α) := by simp [C, monomial]; refl
@[simp] lemma C_1 : C 1 = (1 : mv_polynomial σ α) := rfl
lemma C_mul_monomial : C a * monomial s a' = monomial s (a * a') :=
by simp [C, monomial, single_mul_single]
@[simp] lemma C_add : (C (a + a') : mv_polynomial σ α) = C a + C a' := single_add
@[simp] lemma C_mul : (C (a * a') : mv_polynomial σ α) = C a * C a' := C_mul_monomial.symm
@[simp] lemma C_pow (a : α) (n : ℕ) : (C (a^n) : mv_polynomial σ α) = (C a)^n :=
by induction n; simp [pow_succ, *]
instance : is_semiring_hom (C : α → mv_polynomial σ α) :=
{ map_zero := C_0,
map_one := C_1,
map_add := λ a a', C_add,
map_mul := λ a a', C_mul }
lemma C_eq_coe_nat (n : ℕ) : (C ↑n : mv_polynomial σ α) = n :=
by induction n; simp [nat.succ_eq_add_one, *]
lemma X_pow_eq_single : X n ^ e = monomial (single n e) (1 : α) :=
begin
induction e,
{ simp [X], refl },
{ simp [pow_succ, e_ih],
simp [X, monomial, single_mul_single, nat.succ_eq_add_one] }
end
lemma monomial_add_single : monomial (s + single n e) a = (monomial s a * X n ^ e) :=
by rw [X_pow_eq_single, monomial, monomial, monomial, single_mul_single]; simp
lemma monomial_single_add : monomial (single n e + s) a = (X n ^ e * monomial s a) :=
by rw [X_pow_eq_single, monomial, monomial, monomial, single_mul_single]; simp
lemma monomial_eq : monomial s a = C a * (s.prod $ λn e, X n ^ e : mv_polynomial σ α) :=
begin
apply @finsupp.induction σ ℕ _ _ _ _ s,
{ simp [C, prod_zero_index]; exact (mul_one _).symm },
{ assume n e s hns he ih,
simp [prod_add_index, prod_single_index, pow_zero, pow_add, (mul_assoc _ _ _).symm, ih.symm,
monomial_add_single] }
end
@[recursor 7]
lemma induction_on {M : mv_polynomial σ α → Prop} (p : mv_polynomial σ α)
(h_C : ∀a, M (C a)) (h_add : ∀p q, M p → M q → M (p + q)) (h_X : ∀p n, M p → M (p * X n)) :
M p :=
have ∀s a, M (monomial s a),
begin
assume s a,
apply @finsupp.induction σ ℕ _ _ _ _ s,
{ show M (monomial 0 a), from h_C a, },
{ assume n e p hpn he ih,
have : ∀e:ℕ, M (monomial p a * X n ^ e),
{ intro e,
induction e,
{ simp [ih] },
{ simp [ih, pow_succ', (mul_assoc _ _ _).symm, h_X, e_ih] } },
simp [monomial_add_single, this] }
end,
finsupp.induction p
(by have : M (C 0) := h_C 0; rwa [C_0] at this)
(assume s a p hsp ha hp, h_add _ _ (this s a) hp)
lemma hom_eq_hom [semiring γ]
(f g : mv_polynomial σ α → γ) (hf : is_semiring_hom f) (hg : is_semiring_hom g)
(hC : ∀a:α, f (C a) = g (C a)) (hX : ∀n:σ, f (X n) = g (X n)) (p : mv_polynomial σ α) :
f p = g p :=
mv_polynomial.induction_on p hC
begin assume p q hp hq, rw [is_semiring_hom.map_add f, is_semiring_hom.map_add g, hp, hq] end
begin assume p n hp, rw [is_semiring_hom.map_mul f, is_semiring_hom.map_mul g, hp, hX] end
lemma is_id (f : mv_polynomial σ α → mv_polynomial σ α) (hf : is_semiring_hom f)
(hC : ∀a:α, f (C a) = (C a)) (hX : ∀n:σ, f (X n) = (X n)) (p : mv_polynomial σ α) :
f p = p :=
hom_eq_hom f id hf is_semiring_hom.id hC hX p
section coeff
def tmp.coe : has_coe_to_fun (mv_polynomial σ α) := by delta mv_polynomial; apply_instance
local attribute [instance] tmp.coe
def coeff (m : σ →₀ ℕ) (p : mv_polynomial σ α) : α := p m
lemma ext (p q : mv_polynomial σ α) :
(∀ m, coeff m p = coeff m q) → p = q := ext
lemma ext_iff (p q : mv_polynomial σ α) :
(∀ m, coeff m p = coeff m q) ↔ p = q :=
⟨ext p q, λ h m, by rw h⟩
@[simp] lemma coeff_add (m : σ →₀ ℕ) (p q : mv_polynomial σ α) :
coeff m (p + q) = coeff m p + coeff m q := add_apply
@[simp] lemma coeff_zero (m : σ →₀ ℕ) :
coeff m (0 : mv_polynomial σ α) = 0 := rfl
@[simp] lemma coeff_zero_X (i : σ) : coeff 0 (X i : mv_polynomial σ α) = 0 := rfl
instance coeff.is_add_monoid_hom (m : σ →₀ ℕ) :
is_add_monoid_hom (coeff m : mv_polynomial σ α → α) :=
{ map_add := coeff_add m,
map_zero := coeff_zero m }
lemma coeff_sum {X : Type*} (s : finset X) (f : X → mv_polynomial σ α) (m : σ →₀ ℕ) :
coeff m (s.sum f) = s.sum (λ x, coeff m (f x)) :=
(finset.sum_hom _).symm
lemma monic_monomial_eq (m) : monomial m (1:α) = (m.prod $ λn e, X n ^ e : mv_polynomial σ α) :=
by simp [monomial_eq]
@[simp] lemma coeff_monomial (m n) (a) :
coeff m (monomial n a : mv_polynomial σ α) = if n = m then a else 0 :=
single_apply
@[simp] lemma coeff_C (m) (a) :
coeff m (C a : mv_polynomial σ α) = if 0 = m then a else 0 :=
single_apply
lemma coeff_X_pow (i : σ) (m) (k : ℕ) :
coeff m (X i ^ k : mv_polynomial σ α) = if single i k = m then 1 else 0 :=
begin
have := coeff_monomial m (finsupp.single i k) (1:α),
rwa [@monomial_eq _ _ (1:α) (finsupp.single i k) _ _ _,
C_1, one_mul, finsupp.prod_single_index] at this,
exact pow_zero _
end
lemma coeff_X' (i : σ) (m) :
coeff m (X i : mv_polynomial σ α) = if single i 1 = m then 1 else 0 :=
by rw [← coeff_X_pow, pow_one]
@[simp] lemma coeff_X (i : σ) :
coeff (single i 1) (X i : mv_polynomial σ α) = 1 :=
by rw [coeff_X', if_pos rfl]
@[simp] lemma coeff_C_mul (m) (a : α) (p : mv_polynomial σ α) : coeff m (C a * p) = a * coeff m p :=
begin
rw [mul_def, C, monomial],
simp only [sum_single_index, zero_mul, single_zero, zero_add, sum_zero],
convert sum_apply,
simp only [single_apply, finsupp.sum],
rw finset.sum_eq_single m,
{ rw if_pos rfl, refl },
{ intros m' hm' H, apply if_neg, exact H },
{ intros hm, rw if_pos rfl, rw not_mem_support_iff at hm, simp [hm] }
end
lemma coeff_mul (p q : mv_polynomial σ α) (n : σ →₀ ℕ) :
coeff n (p * q) = finset.sum (antidiagonal n).support (λ x, coeff x.1 p * coeff x.2 q) :=
begin
rw mul_def,
have := @finset.sum_sigma (σ →₀ ℕ) α _ _ p.support (λ _, q.support)
(λ x, if (x.1 + x.2 = n) then coeff x.1 p * coeff x.2 q else 0),
convert this.symm using 1; clear this,
{ rw [coeff],
repeat {rw sum_apply, apply finset.sum_congr rfl, intros, dsimp only},
exact single_apply },
{ have : (antidiagonal n).support.filter (λ x, x.1 ∈ p.support ∧ x.2 ∈ q.support) ⊆
(antidiagonal n).support := finset.filter_subset _,
rw [← finset.sum_sdiff this, finset.sum_eq_zero, zero_add], swap,
{ intros x hx,
rw [finset.mem_sdiff, not_iff_not_of_iff (finset.mem_filter),
not_and, not_and, not_mem_support_iff] at hx,
by_cases H : x.1 ∈ p.support,
{ rw [coeff, coeff, hx.2 hx.1 H, mul_zero] },
{ rw not_mem_support_iff at H, rw [coeff, H, zero_mul] } },
symmetry,
rw [← finset.sum_sdiff (finset.filter_subset _), finset.sum_eq_zero, zero_add], swap,
{ intros x hx,
rw [finset.mem_sdiff, not_iff_not_of_iff (finset.mem_filter), not_and] at hx,
rw if_neg,
exact hx.2 hx.1 },
{ apply finset.sum_bij, swap 5,
{ intros x hx, exact (x.1, x.2) },
{ intros x hx, rw [finset.mem_filter, finset.mem_sigma] at hx,
simpa [finset.mem_filter, mem_antidiagonal_support] using hx.symm },
{ intros x hx, rw finset.mem_filter at hx, rw if_pos hx.2 },
{ rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl, simpa using and.intro },
{ rintros ⟨i,j⟩ hij, refine ⟨⟨i,j⟩, _, _⟩, { apply_instance },
{ rw [finset.mem_filter, mem_antidiagonal_support] at hij,
simpa [finset.mem_filter, finset.mem_sigma] using hij.symm },
{ refl } } },
all_goals { apply_instance } }
end
@[simp] lemma coeff_mul_X (m) (s : σ) (p : mv_polynomial σ α) :
coeff (m + single s 1) (p * X s) = coeff m p :=
begin
have : (m, single s 1) ∈ (m + single s 1).antidiagonal.support := mem_antidiagonal_support.2 rfl,
rw [coeff_mul, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _),
finset.sum_eq_zero, add_zero, coeff_X, mul_one],
rintros ⟨i,j⟩ hij,
rw [finset.mem_erase, mem_antidiagonal_support] at hij,
by_cases H : single s 1 = j,
{ subst j, simpa using hij },
{ rw [coeff_X', if_neg H, mul_zero] },
end
lemma coeff_mul_X' (m) (s : σ) (p : mv_polynomial σ α) :
coeff m (p * X s) = if s ∈ m.support then coeff (m - single s 1) p else 0 :=
begin
split_ifs with h h,
{ conv_rhs {rw ← coeff_mul_X _ s},
congr' 1, ext t,
by_cases hj : s = t,
{ subst t, simp only [nat_sub_apply, add_apply, single_eq_same],
refine (nat.sub_add_cancel $ nat.pos_of_ne_zero _).symm, rwa mem_support_iff at h },
{ simp [single_eq_of_ne hj] } },
{ delta coeff, rw ← not_mem_support_iff, intro hm, apply h,
have H := support_mul _ _ hm, simp only [finset.mem_bind] at H,
rcases H with ⟨j, hj, i', hi', H⟩,
delta X monomial at hi', rw mem_support_single at hi', cases hi', subst i',
erw finset.mem_singleton at H, subst m,
rw [mem_support_iff, add_apply, single_apply, if_pos rfl],
intro H, rw [add_eq_zero_iff] at H, exact one_ne_zero H.2 }
end
end coeff
section eval₂
variables [comm_semiring β]
variables (f : α → β) (g : σ → β)
/-- Evaluate a polynomial `p` given a valuation `g` of all the variables
and a ring hom `f` from the scalar ring to the target -/
def eval₂ (p : mv_polynomial σ α) : β :=
p.sum (λs a, f a * s.prod (λn e, g n ^ e))
@[simp] lemma eval₂_zero : (0 : mv_polynomial σ α).eval₂ f g = 0 :=
finsupp.sum_zero_index
variables [is_semiring_hom f]
@[simp] lemma eval₂_add : (p + q).eval₂ f g = p.eval₂ f g + q.eval₂ f g :=
finsupp.sum_add_index
(by simp [is_semiring_hom.map_zero f])
(by simp [add_mul, is_semiring_hom.map_add f])
@[simp] lemma eval₂_monomial : (monomial s a).eval₂ f g = f a * s.prod (λn e, g n ^ e) :=
finsupp.sum_single_index (by simp [is_semiring_hom.map_zero f])
@[simp] lemma eval₂_C (a) : (C a).eval₂ f g = f a :=
by simp [eval₂_monomial, C, prod_zero_index]
@[simp] lemma eval₂_one : (1 : mv_polynomial σ α).eval₂ f g = 1 :=
(eval₂_C _ _ _).trans (is_semiring_hom.map_one f)
@[simp] lemma eval₂_X (n) : (X n).eval₂ f g = g n :=
by simp [eval₂_monomial,
is_semiring_hom.map_one f, X, prod_single_index, pow_one]
lemma eval₂_mul_monomial :
∀{s a}, (p * monomial s a).eval₂ f g = p.eval₂ f g * f a * s.prod (λn e, g n ^ e) :=
begin
apply mv_polynomial.induction_on p,
{ assume a' s a,
simp [C_mul_monomial, eval₂_monomial, is_semiring_hom.map_mul f] },
{ assume p q ih_p ih_q, simp [add_mul, eval₂_add, ih_p, ih_q] },
{ assume p n ih s a,
from calc (p * X n * monomial s a).eval₂ f g = (p * monomial (single n 1 + s) a).eval₂ f g :
by simp [monomial_single_add, -add_comm, pow_one, mul_assoc]
... = (p * monomial (single n 1) 1).eval₂ f g * f a * s.prod (λn e, g n ^ e) :
by simp [ih, prod_single_index, prod_add_index, pow_one, pow_add, mul_assoc, mul_left_comm,
is_semiring_hom.map_one f, -add_comm] }
end
@[simp] lemma eval₂_mul : ∀{p}, (p * q).eval₂ f g = p.eval₂ f g * q.eval₂ f g :=
begin
apply mv_polynomial.induction_on q,
{ simp [C, eval₂_monomial, eval₂_mul_monomial, prod_zero_index] },
{ simp [mul_add, eval₂_add] {contextual := tt} },
{ simp [X, eval₂_monomial, eval₂_mul_monomial, (mul_assoc _ _ _).symm] { contextual := tt} }
end
@[simp] lemma eval₂_pow {p:mv_polynomial σ α} : ∀{n:ℕ}, (p ^ n).eval₂ f g = (p.eval₂ f g)^n
| 0 := eval₂_one _ _
| (n + 1) := by rw [pow_add, pow_one, pow_add, pow_one, eval₂_mul, eval₂_pow]
instance eval₂.is_semiring_hom : is_semiring_hom (eval₂ f g) :=
{ map_zero := eval₂_zero _ _,
map_one := eval₂_one _ _,
map_add := λ p q, eval₂_add _ _,
map_mul := λ p q, eval₂_mul _ _ }
lemma eval₂_comp_left {γ} [comm_semiring γ]
(k : β → γ) [is_semiring_hom k]
(f : α → β) [is_semiring_hom f] (g : σ → β)
(p) : k (eval₂ f g p) = eval₂ (k ∘ f) (k ∘ g) p :=
by apply mv_polynomial.induction_on p; simp [
eval₂_add, is_semiring_hom.map_add k,
eval₂_mul, is_semiring_hom.map_mul k] {contextual := tt}
@[simp] lemma eval₂_eta (p : mv_polynomial σ α) : eval₂ C X p = p :=
by apply mv_polynomial.induction_on p;
simp [eval₂_add, eval₂_mul] {contextual := tt}
lemma eval₂_congr (g₁ g₂ : σ → β)
(h : ∀ {i : σ} {c : σ →₀ ℕ}, i ∈ c.support → coeff c p ≠ 0 → g₁ i = g₂ i) :
p.eval₂ f g₁ = p.eval₂ f g₂ :=
begin
apply finset.sum_congr rfl,
intros c hc, dsimp, congr' 1,
apply finset.prod_congr rfl,
intros i hi, dsimp, congr' 1,
apply h hi,
rwa finsupp.mem_support_iff at hc
end
@[simp] lemma eval₂_prod [decidable_eq γ] (s : finset γ) (p : γ → mv_polynomial σ α) :
eval₂ f g (s.prod p) = s.prod (λ x, eval₂ f g $ p x) :=
(finset.prod_hom _).symm
@[simp] lemma eval₂_sum [decidable_eq γ] (s : finset γ) (p : γ → mv_polynomial σ α) :
eval₂ f g (s.sum p) = s.sum (λ x, eval₂ f g $ p x) :=
(finset.sum_hom _).symm
attribute [to_additive mv_polynomial.eval₂_sum] eval₂_prod
lemma eval₂_assoc [decidable_eq γ] (q : γ → mv_polynomial σ α) (p : mv_polynomial γ α) :
eval₂ f (λ t, eval₂ f g (q t)) p = eval₂ f g (eval₂ C q p) :=
by { rw eval₂_comp_left (eval₂ f g), congr, funext, simp }
end eval₂
section eval
variables {f : σ → α}
/-- Evaluate a polynomial `p` given a valuation `f` of all the variables -/
def eval (f : σ → α) : mv_polynomial σ α → α := eval₂ id f
@[simp] lemma eval_zero : (0 : mv_polynomial σ α).eval f = 0 := eval₂_zero _ _
@[simp] lemma eval_add : (p + q).eval f = p.eval f + q.eval f := eval₂_add _ _
lemma eval_monomial : (monomial s a).eval f = a * s.prod (λn e, f n ^ e) :=
eval₂_monomial _ _
@[simp] lemma eval_C : ∀ a, (C a).eval f = a := eval₂_C _ _
@[simp] lemma eval_X : ∀ n, (X n).eval f = f n := eval₂_X _ _
@[simp] lemma eval_mul : (p * q).eval f = p.eval f * q.eval f := eval₂_mul _ _
instance eval.is_semiring_hom : is_semiring_hom (eval f) :=
eval₂.is_semiring_hom _ _
theorem eval_assoc {τ} [decidable_eq τ]
(f : σ → mv_polynomial τ α) (g : τ → α)
(p : mv_polynomial σ α) :
p.eval (eval g ∘ f) = (eval₂ C f p).eval g :=
begin
rw eval₂_comp_left (eval g),
unfold eval, congr; funext a; simp
end
end eval
section map
variables [comm_semiring β] [decidable_eq β]
variables (f : α → β) [is_semiring_hom f]
/-- `map f p` maps a polynomial `p` across a ring hom `f` -/
def map : mv_polynomial σ α → mv_polynomial σ β := eval₂ (C ∘ f) X
@[simp] theorem map_monomial (s : σ →₀ ℕ) (a : α) : map f (monomial s a) = monomial s (f a) :=
(eval₂_monomial _ _).trans monomial_eq.symm
@[simp] theorem map_C : ∀ (a : α), map f (C a : mv_polynomial σ α) = C (f a) := map_monomial _ _
@[simp] theorem map_X : ∀ (n : σ), map f (X n : mv_polynomial σ α) = X n := eval₂_X _ _
@[simp] theorem map_one : map f (1 : mv_polynomial σ α) = 1 := eval₂_one _ _
@[simp] theorem map_add (p q : mv_polynomial σ α) :
map f (p + q) = map f p + map f q := eval₂_add _ _
@[simp] theorem map_mul (p q : mv_polynomial σ α) :
map f (p * q) = map f p * map f q := eval₂_mul _ _
@[simp] lemma map_pow (p : mv_polynomial σ α) (n : ℕ) :
map f (p^n) = (map f p)^n := eval₂_pow _ _
instance map.is_semiring_hom :
is_semiring_hom (map f : mv_polynomial σ α → mv_polynomial σ β) :=
eval₂.is_semiring_hom _ _
theorem map_id : ∀ (p : mv_polynomial σ α), map id p = p := eval₂_eta
theorem map_map [comm_semiring γ] [decidable_eq γ]
(g : β → γ) [is_semiring_hom g]
(p : mv_polynomial σ α) :
map g (map f p) = map (g ∘ f) p :=
(eval₂_comp_left (map g) (C ∘ f) X p).trans $
by congr; funext a; simp
theorem eval₂_eq_eval_map (g : σ → β) (p : mv_polynomial σ α) :
p.eval₂ f g = (map f p).eval g :=
begin
unfold map eval,
rw eval₂_comp_left (eval₂ id g),
congr; funext a; simp
end
lemma eval₂_comp_right {γ} [comm_semiring γ]
(k : β → γ) [is_semiring_hom k]
(f : α → β) [is_semiring_hom f] (g : σ → β)
(p) : k (eval₂ f g p) = eval₂ k (k ∘ g) (map f p) :=
begin
apply mv_polynomial.induction_on p,
{ intro r, rw [eval₂_C, map_C, eval₂_C] },
{ intros p q hp hq, rw [eval₂_add, is_semiring_hom.map_add k, map_add, eval₂_add, hp, hq] },
{ intros p s hp,
rw [eval₂_mul, is_semiring_hom.map_mul k, map_mul, eval₂_mul, map_X, hp, eval₂_X, eval₂_X] }
end
lemma map_eval₂ [decidable_eq γ] [decidable_eq δ]
(f : α → β) [is_semiring_hom f] (g : γ → mv_polynomial δ α) (p : mv_polynomial γ α) :
map f (eval₂ C g p) = eval₂ C (map f ∘ g) (map f p) :=
begin
apply mv_polynomial.induction_on p,
{ intro r, rw [eval₂_C, map_C, map_C, eval₂_C] },
{ intros p q hp hq, rw [eval₂_add, map_add, hp, hq, map_add, eval₂_add] },
{ intros p s hp,
rw [eval₂_mul, map_mul, hp, map_mul, map_X, eval₂_mul, eval₂_X, eval₂_X] }
end
lemma coeff_map (p : mv_polynomial σ α) : ∀ (m : σ →₀ ℕ), coeff m (p.map f) = f (coeff m p) :=
begin
apply mv_polynomial.induction_on p; clear p,
{ intros r m, rw [map_C], simp only [coeff_C], split_ifs, {refl}, rw is_semiring_hom.map_zero f },
{ intros p q hp hq m, simp only [hp, hq, map_add, coeff_add], rw is_semiring_hom.map_add f },
{ intros p i hp m, simp only [hp, map_mul, map_X],
simp only [hp, mem_support_iff, coeff_mul_X'],
split_ifs, {refl},
rw is_semiring_hom.map_zero f }
end
lemma map_injective (hf : function.injective f) :
function.injective (map f : mv_polynomial σ α → mv_polynomial σ β) :=
λ p q h, ext _ _ $ λ m, hf $
begin
rw ← ext_iff at h,
specialize h m,
rw [coeff_map, coeff_map] at h,
exact h
end
end map
section degrees
section comm_semiring
def degrees (p : mv_polynomial σ α) : multiset σ :=
p.support.sup (λs:σ →₀ ℕ, s.to_multiset)
lemma degrees_monomial (s : σ →₀ ℕ) (a : α) : degrees (monomial s a) ≤ s.to_multiset :=
finset.sup_le $ assume t h,
begin
have := finsupp.support_single_subset h,
rw [finset.singleton_eq_singleton, finset.mem_singleton] at this,
rw this
end
lemma degrees_monomial_eq (s : σ →₀ ℕ) (a : α) (ha : a ≠ 0) :
degrees (monomial s a) = s.to_multiset :=
le_antisymm (degrees_monomial s a) $ finset.le_sup $
by rw [monomial, finsupp.support_single_ne_zero ha,
finset.singleton_eq_singleton, finset.mem_singleton]
lemma degrees_C (a : α) : degrees (C a : mv_polynomial σ α) = 0 :=
multiset.le_zero.1 $ degrees_monomial _ _
lemma degrees_X (n : σ) : degrees (X n : mv_polynomial σ α) ≤ {n} :=
le_trans (degrees_monomial _ _) $ le_of_eq $ to_multiset_single _ _
lemma degrees_zero : degrees (0 : mv_polynomial σ α) = 0 := degrees_C 0
lemma degrees_one : degrees (1 : mv_polynomial σ α) = 0 := degrees_C 1
lemma degrees_add (p q : mv_polynomial σ α) : (p + q).degrees ≤ p.degrees ⊔ q.degrees :=
begin
refine finset.sup_le (assume b hb, _),
cases finset.mem_union.1 (finsupp.support_add hb),
{ exact le_sup_left_of_le (finset.le_sup h) },
{ exact le_sup_right_of_le (finset.le_sup h) },
end
lemma degrees_sum {ι : Type*} [decidable_eq ι] (s : finset ι) (f : ι → mv_polynomial σ α) :
(s.sum f).degrees ≤ s.sup (λi, (f i).degrees) :=
begin
refine s.induction _ _,
{ simp only [finset.sum_empty, finset.sup_empty, degrees_zero], exact le_refl _ },
{ assume i s his ih,
rw [finset.sup_insert, finset.sum_insert his],
exact le_trans (degrees_add _ _) (sup_le_sup_left ih _) }
end
lemma degrees_mul (p q : mv_polynomial σ α) : (p * q).degrees ≤ p.degrees + q.degrees :=
begin
refine finset.sup_le (assume b hb, _),
have := support_mul p q hb,
simp only [finset.mem_bind, finset.singleton_eq_singleton, finset.mem_singleton] at this,
rcases this with ⟨a₁, h₁, a₂, h₂, rfl⟩,
rw [finsupp.to_multiset_add],
exact add_le_add (finset.le_sup h₁) (finset.le_sup h₂)
end
lemma degrees_prod {ι : Type*} [decidable_eq ι] (s : finset ι) (f : ι → mv_polynomial σ α) :
(s.prod f).degrees ≤ s.sum (λi, (f i).degrees) :=
begin
refine s.induction _ _,
{ simp only [finset.prod_empty, finset.sum_empty, degrees_one] },
{ assume i s his ih,
rw [finset.prod_insert his, finset.sum_insert his],
exact le_trans (degrees_mul _ _) (add_le_add_left ih _) }
end
lemma degrees_pow (p : mv_polynomial σ α) :
∀(n : ℕ), (p^n).degrees ≤ add_monoid.smul n p.degrees
| 0 := begin rw [pow_zero, degrees_one], exact multiset.zero_le _ end
| (n + 1) := le_trans (degrees_mul _ _) (add_le_add_left (degrees_pow n) _)
end comm_semiring
end degrees
section vars
/-- `vars p` is the set of variables appearing in the polynomial `p` -/
def vars (p : mv_polynomial σ α) : finset σ := p.degrees.to_finset
@[simp] lemma vars_0 : (0 : mv_polynomial σ α).vars = ∅ :=
by rw [vars, degrees_zero, multiset.to_finset_zero]
@[simp] lemma vars_monomial (h : a ≠ 0) : (monomial s a).vars = s.support :=
by rw [vars, degrees_monomial_eq _ _ h, finsupp.to_finset_to_multiset]
@[simp] lemma vars_C : (C a : mv_polynomial σ α).vars = ∅ :=
by rw [vars, degrees_C, multiset.to_finset_zero]
@[simp] lemma vars_X (h : 0 ≠ (1 : α)) : (X n : mv_polynomial σ α).vars = {n} :=
by rw [X, vars_monomial h.symm, finsupp.support_single_ne_zero zero_ne_one.symm]
end vars
section degree_of
/-- `degree_of n p` gives the highest power of X_n that appears in `p` -/
def degree_of (n : σ) (p : mv_polynomial σ α) : ℕ := p.degrees.count n
end degree_of
section total_degree
/-- `total_degree p` gives the maximum |s| over the monomials X^s in `p` -/
def total_degree (p : mv_polynomial σ α) : ℕ := p.support.sup (λs, s.sum $ λn e, e)
lemma total_degree_eq (p : mv_polynomial σ α) :
p.total_degree = p.support.sup (λm, m.to_multiset.card) :=
begin
rw [total_degree],
congr, funext m,
exact (finsupp.card_to_multiset _).symm
end
lemma total_degree_le_degrees_card (p : mv_polynomial σ α) :
p.total_degree ≤ p.degrees.card :=
begin
rw [total_degree_eq],
exact finset.sup_le (assume s hs, multiset.card_le_of_le $ finset.le_sup hs)
end
lemma total_degree_C (a : α) : (C a : mv_polynomial σ α).total_degree = 0 :=
nat.eq_zero_of_le_zero $ finset.sup_le $ assume n hn,
have _ := finsupp.support_single_subset hn,
begin
rw [finset.singleton_eq_singleton, finset.mem_singleton] at this,
subst this,
exact le_refl _
end
lemma total_degree_zero : (0 : mv_polynomial σ α).total_degree = 0 :=
by rw [← C_0]; exact total_degree_C (0 : α)
lemma total_degree_one : (1 : mv_polynomial σ α).total_degree = 0 :=
total_degree_C (1 : α)
lemma total_degree_add (a b : mv_polynomial σ α) :
(a + b).total_degree ≤ max a.total_degree b.total_degree :=
finset.sup_le $ assume n hn,
have _ := finsupp.support_add hn,
begin
rcases finset.mem_union.1 this,
{ exact le_max_left_of_le (finset.le_sup h) },
{ exact le_max_right_of_le (finset.le_sup h) }
end
lemma total_degree_mul (a b : mv_polynomial σ α) :
(a * b).total_degree ≤ a.total_degree + b.total_degree :=
finset.sup_le $ assume n hn,
have _ := finsupp.support_mul a b hn,
begin
simp only [finset.mem_bind, finset.mem_singleton, finset.singleton_eq_singleton] at this,
rcases this with ⟨a₁, h₁, a₂, h₂, rfl⟩,
rw [finsupp.sum_add_index],
{ exact add_le_add (finset.le_sup h₁) (finset.le_sup h₂) },
{ assume a, refl },
{ assume a b₁ b₂, refl }
end
lemma total_degree_list_prod :
∀(s : list (mv_polynomial σ α)), s.prod.total_degree ≤ (s.map mv_polynomial.total_degree).sum
| [] := by rw [@list.prod_nil (mv_polynomial σ α) _, total_degree_one]; refl
| (p :: ps) :=
begin
rw [@list.prod_cons (mv_polynomial σ α) _, list.map, list.sum_cons],
exact le_trans (total_degree_mul _ _) (add_le_add_left (total_degree_list_prod ps) _)
end
lemma total_degree_multiset_prod (s : multiset (mv_polynomial σ α)) :
s.prod.total_degree ≤ (s.map mv_polynomial.total_degree).sum :=
begin
refine quotient.induction_on s (assume l, _),
rw [multiset.quot_mk_to_coe, multiset.coe_prod, multiset.coe_map, multiset.coe_sum],
exact total_degree_list_prod l
end
lemma total_degree_finset_prod {ι : Type*}
(s : finset ι) (f : ι → mv_polynomial σ α) :
(s.prod f).total_degree ≤ s.sum (λi, (f i).total_degree) :=
begin
refine le_trans (total_degree_multiset_prod _) _,
rw [multiset.map_map],
refl
end
end total_degree
end comm_semiring
section comm_ring
variable [comm_ring α]
variables {p q : mv_polynomial σ α}
instance : ring (mv_polynomial σ α) := finsupp.ring
instance : comm_ring (mv_polynomial σ α) := finsupp.comm_ring
instance : has_scalar α (mv_polynomial σ α) := finsupp.has_scalar
instance : module α (mv_polynomial σ α) := finsupp.module _ α
instance C.is_ring_hom : is_ring_hom (C : α → mv_polynomial σ α) :=
by apply is_ring_hom.of_semiring
variables (σ a a')
lemma C_sub : (C (a - a') : mv_polynomial σ α) = C a - C a' := is_ring_hom.map_sub _
@[simp] lemma C_neg : (C (-a) : mv_polynomial σ α) = -C a := is_ring_hom.map_neg _
@[simp] lemma coeff_sub (m : σ →₀ ℕ) (p q : mv_polynomial σ α) :
coeff m (p - q) = coeff m p - coeff m q := finsupp.sub_apply
instance coeff.is_add_group_hom (m : σ →₀ ℕ) :
is_add_group_hom (coeff m : mv_polynomial σ α → α) :=
{ map_add := coeff_add m }
variables {σ} (p)
theorem C_mul' : mv_polynomial.C a * p = a • p :=
begin
apply finsupp.induction p,
{ exact (mul_zero $ mv_polynomial.C a).trans (@smul_zero α (mv_polynomial σ α) _ _ _ a).symm },
intros p b f haf hb0 ih,
rw [mul_add, ih, @smul_add α (mv_polynomial σ α) _ _ _ a], congr' 1,
rw [finsupp.mul_def, finsupp.smul_single, mv_polynomial.C, mv_polynomial.monomial],
rw [finsupp.sum_single_index, finsupp.sum_single_index, zero_add, smul_eq_mul],
{ rw [mul_zero, finsupp.single_zero] },
{ rw finsupp.sum_single_index,
all_goals { rw [zero_mul, finsupp.single_zero] } }
end
lemma smul_eq_C_mul (p : mv_polynomial σ α) (a : α) : a • p = C a * p :=
begin
rw [← finsupp.sum_single p, @finsupp.smul_sum (σ →₀ ℕ) α α, finsupp.mul_sum],
refine finset.sum_congr rfl (assume n _, _),
simp only [finsupp.smul_single],
exact C_mul_monomial.symm
end
@[simp] lemma smul_eval (x) (p : mv_polynomial σ α) (s) : (s • p).eval x = s * p.eval x :=
by rw [smul_eq_C_mul, eval_mul, eval_C]
section degrees
lemma degrees_neg [comm_ring α] (p : mv_polynomial σ α) : (- p).degrees = p.degrees :=
by rw [degrees, finsupp.support_neg]; refl
lemma degrees_sub [comm_ring α] (p q : mv_polynomial σ α) :
(p - q).degrees ≤ p.degrees ⊔ q.degrees :=
le_trans (degrees_add p (-q)) $ by rw [degrees_neg]
end degrees
section eval₂
variables [comm_ring β]
variables (f : α → β) [is_ring_hom f] (g : σ → β)
instance eval₂.is_ring_hom : is_ring_hom (eval₂ f g) :=
by apply is_ring_hom.of_semiring
lemma eval₂_sub : (p - q).eval₂ f g = p.eval₂ f g - q.eval₂ f g := is_ring_hom.map_sub _
@[simp] lemma eval₂_neg : (-p).eval₂ f g = -(p.eval₂ f g) := is_ring_hom.map_neg _
lemma hom_C (f : mv_polynomial σ ℤ → β) [is_ring_hom f] (n : ℤ) : f (C n) = (n : β) :=
congr_fun (int.eq_cast' (f ∘ C)) n
/-- A ring homomorphism f : Z[X_1, X_2, ...] -> R
is determined by the evaluations f(X_1), f(X_2), ... -/
@[simp] lemma eval₂_hom_X {α : Type u} [decidable_eq α] (c : ℤ → β) [is_ring_hom c]
(f : mv_polynomial α ℤ → β) [is_ring_hom f] (x : mv_polynomial α ℤ) :
eval₂ c (f ∘ X) x = f x :=
mv_polynomial.induction_on x
(λ n, by { rw [hom_C f, eval₂_C, int.eq_cast' c], refl })
(λ p q hp hq, by { rw [eval₂_add, hp, hq], exact (is_ring_hom.map_add f).symm })
(λ p n hp, by { rw [eval₂_mul, eval₂_X, hp], exact (is_ring_hom.map_mul f).symm })
end eval₂
section eval
variables (f : σ → α)
instance eval.is_ring_hom : is_ring_hom (eval f) := eval₂.is_ring_hom _ _
lemma eval_sub : (p - q).eval f = p.eval f - q.eval f := is_ring_hom.map_sub _
@[simp] lemma eval_neg : (-p).eval f = -(p.eval f) := is_ring_hom.map_neg _
end eval
section map
variables [decidable_eq β] [comm_ring β]
variables (f : α → β) [is_ring_hom f]
instance map.is_ring_hom : is_ring_hom (map f : mv_polynomial σ α → mv_polynomial σ β) :=
eval₂.is_ring_hom _ _
lemma map_sub : (p - q).map f = p.map f - q.map f := is_ring_hom.map_sub _
@[simp] lemma map_neg : (-p).map f = -(p.map f) := is_ring_hom.map_neg _
end map
end comm_ring
section rename
variables {α} [comm_semiring α] [decidable_eq α] [decidable_eq β] [decidable_eq γ] [decidable_eq δ]
def rename (f : β → γ) : mv_polynomial β α → mv_polynomial γ α :=
eval₂ C (X ∘ f)
instance rename.is_semiring_hom (f : β → γ) :
is_semiring_hom (rename f : mv_polynomial β α → mv_polynomial γ α) :=
by unfold rename; apply_instance
@[simp] lemma rename_C (f : β → γ) (a : α) : rename f (C a) = C a :=
eval₂_C _ _ _
@[simp] lemma rename_X (f : β → γ) (b : β) : rename f (X b : mv_polynomial β α) = X (f b) :=
eval₂_X _ _ _
@[simp] lemma rename_zero (f : β → γ) :
rename f (0 : mv_polynomial β α) = 0 :=
eval₂_zero _ _
@[simp] lemma rename_one (f : β → γ) :
rename f (1 : mv_polynomial β α) = 1 :=
eval₂_one _ _
@[simp] lemma rename_add (f : β → γ) (p q : mv_polynomial β α) :
rename f (p + q) = rename f p + rename f q :=
eval₂_add _ _
@[simp] lemma rename_sub {α} [comm_ring α] [decidable_eq α]
(f : β → γ) (p q : mv_polynomial β α) :
rename f (p - q) = rename f p - rename f q :=
eval₂_sub _ _ _
@[simp] lemma rename_mul (f : β → γ) (p q : mv_polynomial β α) :
rename f (p * q) = rename f p * rename f q :=
eval₂_mul _ _
@[simp] lemma rename_pow (f : β → γ) (p : mv_polynomial β α) (n : ℕ) :
rename f (p^n) = (rename f p)^n :=
eval₂_pow _ _
lemma map_rename [comm_semiring β] (f : α → β) [is_semiring_hom f]
(g : γ → δ) (p : mv_polynomial γ α) :
map f (rename g p) = rename g (map f p) :=
mv_polynomial.induction_on p
(λ a, by simp)
(λ p q hp hq, by simp [hp, hq])
(λ p n hp, by simp [hp])
@[simp] lemma rename_rename (f : β → γ) (g : γ → δ) (p : mv_polynomial β α) :
rename g (rename f p) = rename (g ∘ f) p :=
show rename g (eval₂ C (X ∘ f) p) = _,
by simp only [eval₂_comp_left (rename g) C (X ∘ f) p, (∘), rename_C, rename_X]; refl
@[simp] lemma rename_id (p : mv_polynomial β α) : rename id p = p :=
eval₂_eta p
lemma rename_monomial (f : β → γ) (p : β →₀ ℕ) (a : α) :
rename f (monomial p a) = monomial (p.map_domain f) a :=
begin
rw [rename, eval₂_monomial, monomial_eq, finsupp.prod_map_domain_index],
{ exact assume n, pow_zero _ },
{ exact assume n i₁ i₂, pow_add _ _ _ }
end
lemma rename_eq (f : β → γ) (p : mv_polynomial β α) :
rename f p = finsupp.map_domain (finsupp.map_domain f) p :=
begin
simp only [rename, eval₂, finsupp.map_domain],
congr, ext s a : 2,
rw [← monomial, monomial_eq, finsupp.prod_sum_index],
congr, ext n i : 2,
rw [finsupp.prod_single_index],
exact pow_zero _,
exact assume a, pow_zero _,
exact assume a b c, pow_add _ _ _
end
lemma injective_rename (f : β → γ) (hf : function.injective f) :
function.injective (rename f : mv_polynomial β α → mv_polynomial γ α) :=
have (rename f : mv_polynomial β α → mv_polynomial γ α) =
finsupp.map_domain (finsupp.map_domain f) := funext (rename_eq f),
begin
rw this,
exact finsupp.injective_map_domain (finsupp.injective_map_domain hf)
end
lemma total_degree_rename_le (f : β → γ) (p : mv_polynomial β α) :
(p.rename f).total_degree ≤ p.total_degree :=
finset.sup_le $ assume b,
begin
assume h,
rw rename_eq at h,
have h' := finsupp.map_domain_support h,
rcases finset.mem_image.1 h' with ⟨s, hs, rfl⟩,
rw finsupp.sum_map_domain_index,
exact le_trans (le_refl _) (finset.le_sup hs),
exact assume _, rfl,
exact assume _ _ _, rfl
end
section
variables [comm_semiring β] (f : α → β) [is_semiring_hom f]
variables (k : γ → δ) (g : δ → β) (p : mv_polynomial γ α)
lemma eval₂_rename : (p.rename k).eval₂ f g = p.eval₂ f (g ∘ k) :=
by apply mv_polynomial.induction_on p; { intros, simp [*] }
lemma rename_eval₂ (g : δ → mv_polynomial γ α) :
(p.eval₂ C (g ∘ k)).rename k = (p.rename k).eval₂ C (rename k ∘ g) :=
by apply mv_polynomial.induction_on p; { intros, simp [*] }
lemma rename_prodmk_eval₂ (d : δ) (g : γ → mv_polynomial γ α) :
(p.eval₂ C g).rename (prod.mk d) = p.eval₂ C (λ x, (g x).rename (prod.mk d)) :=
by apply mv_polynomial.induction_on p; { intros, simp [*] }
lemma eval₂_rename_prodmk (g : δ × γ → β) (d : δ) :
(rename (prod.mk d) p).eval₂ f g = eval₂ f (λ i, g (d, i)) p :=
by apply mv_polynomial.induction_on p; { intros, simp [*] }
lemma eval_rename_prodmk (g : δ × γ → α) (d : δ) :
(rename (prod.mk d) p).eval g = eval (λ i, g (d, i)) p :=
eval₂_rename_prodmk id _ _ _
end
end rename
lemma eval₂_cast_comp {β : Type u} {γ : Type v} [decidable_eq β] [decidable_eq γ] (f : γ → β)
{α : Type w} [comm_ring α] (c : ℤ → α) [is_ring_hom c] (g : β → α) (x : mv_polynomial γ ℤ) :
eval₂ c (g ∘ f) x = eval₂ c g (rename f x) :=
mv_polynomial.induction_on x
(λ n, by simp only [eval₂_C, rename_C])
(λ p q hp hq, by simp only [hp, hq, rename, eval₂_add])
(λ p n hp, by simp only [hp, rename, eval₂_X, eval₂_mul])
instance rename.is_ring_hom
{α} [comm_ring α] [decidable_eq α] [decidable_eq β] [decidable_eq γ] (f : β → γ) :
is_ring_hom (rename f : mv_polynomial β α → mv_polynomial γ α) :=
@is_ring_hom.of_semiring (mv_polynomial β α) (mv_polynomial γ α) _ _ (rename f)
(rename.is_semiring_hom f)
section equiv
variables (α) [comm_ring α]
variables [decidable_eq β] [decidable_eq γ] [decidable_eq δ]
set_option class.instance_max_depth 40
def pempty_ring_equiv : mv_polynomial pempty α ≃r α :=
{ to_fun := mv_polynomial.eval₂ id $ pempty.elim,
inv_fun := C,
left_inv := is_id _ (by apply_instance) (assume a, by rw [eval₂_C]; refl) (assume a, a.elim),
right_inv := λ r, eval₂_C _ _ _,
hom := eval₂.is_ring_hom _ _ }
def punit_ring_equiv : mv_polynomial punit α ≃r polynomial α :=
{ to_fun := eval₂ polynomial.C (λu:punit, polynomial.X),
inv_fun := polynomial.eval₂ mv_polynomial.C (X punit.star),
left_inv :=
begin
refine is_id _ _ _ _,
apply is_semiring_hom.comp (eval₂ polynomial.C (λu:punit, polynomial.X)) _; apply_instance,
{ assume a, rw [eval₂_C, polynomial.eval₂_C] },
{ rintros ⟨⟩, rw [eval₂_X, polynomial.eval₂_X] }
end,
right_inv := assume p, polynomial.induction_on p
(assume a, by rw [polynomial.eval₂_C, mv_polynomial.eval₂_C])
(assume p q hp hq, by rw [polynomial.eval₂_add, mv_polynomial.eval₂_add, hp, hq])
(assume p n hp,
by rw [polynomial.eval₂_mul, polynomial.eval₂_pow, polynomial.eval₂_X, polynomial.eval₂_C,
eval₂_mul, eval₂_C, eval₂_pow, eval₂_X]),
hom := eval₂.is_ring_hom _ _ }
def ring_equiv_of_equiv (e : β ≃ γ) : mv_polynomial β α ≃r mv_polynomial γ α :=
{ to_fun := rename e,
inv_fun := rename e.symm,
left_inv := λ p, by simp only [rename_rename, (∘), e.symm_apply_apply]; exact rename_id p,
right_inv := λ p, by simp only [rename_rename, (∘), e.apply_symm_apply]; exact rename_id p,
hom := rename.is_ring_hom e }
def ring_equiv_congr [comm_ring γ] (e : α ≃r γ) : mv_polynomial β α ≃r mv_polynomial β γ :=
{ to_fun := map e.to_fun,
inv_fun := map e.symm.to_fun,
left_inv := assume p,
have (e.symm.to_equiv.to_fun ∘ e.to_equiv.to_fun) = id,
{ ext a, exact e.to_equiv.symm_apply_apply a },
by simp only [map_map, this, map_id],
right_inv := assume p,
have (e.to_equiv.to_fun ∘ e.symm.to_equiv.to_fun) = id,
{ ext a, exact e.to_equiv.apply_symm_apply a },
by simp only [map_map, this, map_id],
hom := map.is_ring_hom e.to_fun }
section
variables (β γ δ)
instance ring_on_sum : ring (mv_polynomial (β ⊕ γ) α) := by apply_instance
instance ring_on_iter : ring (mv_polynomial β (mv_polynomial γ α)) := by apply_instance
def sum_to_iter : mv_polynomial (β ⊕ γ) α → mv_polynomial β (mv_polynomial γ α) :=
eval₂ (C ∘ C) (λbc, sum.rec_on bc X (C ∘ X))
instance is_semiring_hom_C_C :
is_semiring_hom (C ∘ C : α → mv_polynomial β (mv_polynomial γ α)) :=
@is_semiring_hom.comp _ _ _ _ C mv_polynomial.is_semiring_hom _ _ C mv_polynomial.is_semiring_hom
instance is_semiring_hom_sum_to_iter : is_semiring_hom (sum_to_iter α β γ) :=
eval₂.is_semiring_hom _ _
lemma sum_to_iter_C (a : α) : sum_to_iter α β γ (C a) = C (C a) :=
eval₂_C _ _ a
lemma sum_to_iter_Xl (b : β) : sum_to_iter α β γ (X (sum.inl b)) = X b :=
eval₂_X _ _ (sum.inl b)
lemma sum_to_iter_Xr (c : γ) : sum_to_iter α β γ (X (sum.inr c)) = C (X c) :=
eval₂_X _ _ (sum.inr c)
def iter_to_sum : mv_polynomial β (mv_polynomial γ α) → mv_polynomial (β ⊕ γ) α :=
eval₂ (eval₂ C (X ∘ sum.inr)) (X ∘ sum.inl)
section
instance is_semiring_hom_iter_to_sum : is_semiring_hom (iter_to_sum α β γ) :=
eval₂.is_semiring_hom _ _
end
lemma iter_to_sum_C_C (a : α) : iter_to_sum α β γ (C (C a)) = C a :=
eq.trans (eval₂_C _ _ (C a)) (eval₂_C _ _ _)
lemma iter_to_sum_X (b : β) : iter_to_sum α β γ (X b) = X (sum.inl b) :=
eval₂_X _ _ _
lemma iter_to_sum_C_X (c : γ) : iter_to_sum α β γ (C (X c)) = X (sum.inr c) :=
eq.trans (eval₂_C _ _ (X c)) (eval₂_X _ _ _)
def mv_polynomial_equiv_mv_polynomial [comm_ring δ]
(f : mv_polynomial β α → mv_polynomial γ δ) (hf : is_semiring_hom f)
(g : mv_polynomial γ δ → mv_polynomial β α) (hg : is_semiring_hom g)
(hfgC : ∀a, f (g (C a)) = C a)
(hfgX : ∀n, f (g (X n)) = X n)
(hgfC : ∀a, g (f (C a)) = C a)
(hgfX : ∀n, g (f (X n)) = X n) :
mv_polynomial β α ≃r mv_polynomial γ δ :=
{ to_fun := f, inv_fun := g,
left_inv := is_id _ (is_semiring_hom.comp _ _) hgfC hgfX,
right_inv := is_id _ (is_semiring_hom.comp _ _) hfgC hfgX,
hom := is_ring_hom.of_semiring f }
def sum_ring_equiv : mv_polynomial (β ⊕ γ) α ≃r mv_polynomial β (mv_polynomial γ α) :=
begin
apply @mv_polynomial_equiv_mv_polynomial α (β ⊕ γ) _ _ _ _ _ _ _ _
(sum_to_iter α β γ) _ (iter_to_sum α β γ) _,
{ assume p,
apply @hom_eq_hom _ _ _ _ _ _ _ _ _ _ _ _ _ p,
apply_instance,
{ apply @is_semiring_hom.comp _ _ _ _ _ _ _ _ _ _,
apply_instance,
apply @is_semiring_hom.comp _ _ _ _ _ _ _ _ _ _,
apply_instance,
{ apply @mv_polynomial.is_semiring_hom },
{ apply mv_polynomial.is_semiring_hom_iter_to_sum α β γ },
{ apply mv_polynomial.is_semiring_hom_sum_to_iter α β γ } },
{ apply mv_polynomial.is_semiring_hom },
{ assume a, rw [iter_to_sum_C_C α β γ, sum_to_iter_C α β γ] },
{ assume c, rw [iter_to_sum_C_X α β γ, sum_to_iter_Xr α β γ] } },
{ assume b, rw [iter_to_sum_X α β γ, sum_to_iter_Xl α β γ] },
{ assume a, rw [sum_to_iter_C α β γ, iter_to_sum_C_C α β γ] },
{ assume n, cases n with b c,
{ rw [sum_to_iter_Xl, iter_to_sum_X] },
{ rw [sum_to_iter_Xr, iter_to_sum_C_X] } },
{ apply mv_polynomial.is_semiring_hom_sum_to_iter α β γ },
{ apply mv_polynomial.is_semiring_hom_iter_to_sum α β γ }
end
instance option_ring : ring (mv_polynomial (option β) α) :=
mv_polynomial.ring
instance polynomial_ring : ring (polynomial (mv_polynomial β α)) :=
@comm_ring.to_ring _ polynomial.comm_ring
instance polynomial_ring2 : ring (mv_polynomial β (polynomial α)) :=
by apply_instance
def option_equiv_left : mv_polynomial (option β) α ≃r polynomial (mv_polynomial β α) :=
(ring_equiv_of_equiv α $ (equiv.option_equiv_sum_punit β).trans (equiv.sum_comm _ _)).trans $
(sum_ring_equiv α _ _).trans $
punit_ring_equiv _
def option_equiv_right : mv_polynomial (option β) α ≃r mv_polynomial β (polynomial α) :=
(ring_equiv_of_equiv α $ equiv.option_equiv_sum_punit.{0} β).trans $
(sum_ring_equiv α β unit).trans $
ring_equiv_congr (mv_polynomial unit α) (punit_ring_equiv α)
end
end equiv
end mv_polynomial
|
4cf077702002f9ce06b8ea95f59131fd230655be | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/eq1.lean | a238f7f10dab0037d4f5261c35312b2254312640 | [
"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 | 359 | lean | inductive day
| monday | tuesday | wednesday | thursday | friday | saturday | sunday
open day
definition next_weekday : day → day
| monday := tuesday
| tuesday := wednesday
| wednesday := thursday
| thursday := friday
| friday := monday
| saturday := monday
| sunday := monday
example : next_weekday (next_weekday monday) = wednesday :=
rfl
|
cbe23d15881b5eebaee99bc05687f948fdf6b3cb | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /archive/sensitivity.lean | 1bc055708e1d55183d41b8fabd4dddd2e543c8cf | [
"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 | 15,493 | lean | /-
Copyright (c) 2019 Reid Barton, Johan Commelin, Jesse Han, Chris Hughes, Robert Y. Lewis, and
Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton, Johan Commelin, Jesse Han, Chris Hughes, Robert Y. Lewis, and Patrick Massot
-/
import tactic.fin_cases
import tactic.apply_fun
import linear_algebra.finite_dimensional
import linear_algebra.dual
import analysis.normed_space.basic
/-!
# Huang's sensitivity theorem
A formalization of Hao Huang's sensitivity theorem: in the hypercube of
dimension n ≥ 1, if one colors more than half the vertices then at least one
vertex has at least √n colored neighbors.
A fun summer collaboration by
Reid Barton, Johan Commelin, Jesse Han, Chris Hughes, Robert Y. Lewis, and Patrick Massot,
based on Don Knuth's account of the story
(https://www.cs.stanford.edu/~knuth/papers/huang.pdf),
using the Lean theorem prover (https://leanprover.github.io/),
by Leonardo de Moura at Microsoft Research, and his collaborators
(https://leanprover.github.io/people/),
and using Lean's user maintained mathematics library
(https://github.com/leanprover-community/mathlib).
The project was developed at https://github.com/leanprover-community/lean-sensitivity
and is now archived at https://github.com/leanprover-community/mathlib/blob/master/archive/sensitivity.lean
-/
/-! The next two lines assert we do not want to give a constructive proof,
but rather use classical logic. -/
noncomputable theory
open_locale classical
/-! We also want to use the notation `∑` for sums. -/
open_locale big_operators
notation `|`x`|` := abs x
notation `√` := real.sqrt
open function bool linear_map fintype finite_dimensional dual_pair
/-!
### The hypercube
Notations:
- `ℕ` denotes natural numbers (including zero).
- `fin n` = {0, ⋯ , n - 1}.
- `bool` = {`tt`, `ff`}.
-/
/-- The hypercube in dimension `n`. -/
@[derive [inhabited, fintype]] def Q (n : ℕ) := fin n → bool
/-- The projection from `Q (n + 1)` to `Q n` forgetting the first value
(ie. the image of zero). -/
def π {n : ℕ} : Q (n + 1) → Q n := λ p, p ∘ fin.succ
namespace Q
/-! `n` will always denote a natural number. -/
variable (n : ℕ)
/-- `Q 0` has a unique element. -/
instance : unique (Q 0) :=
⟨⟨λ _, tt⟩, by { intro, ext x, fin_cases x }⟩
/-- `Q n` has 2^n elements. -/
lemma card : card (Q n) = 2^n :=
by simp [Q]
/-! Until the end of this namespace, `n` will be an implicit argument (still
a natural number). -/
variable {n}
lemma succ_n_eq (p q : Q (n+1)) : p = q ↔ (p 0 = q 0 ∧ π p = π q) :=
begin
split,
{ rintro rfl, exact ⟨rfl, rfl⟩, },
{ rintros ⟨h₀, h⟩,
ext x,
by_cases hx : x = 0,
{ rwa hx },
{ rw ← fin.succ_pred x hx,
convert congr_fun h (fin.pred x hx) } }
end
/-- The adjacency relation defining the graph structure on `Q n`:
`p.adjacent q` if there is an edge from `p` to `q` in `Q n`. -/
def adjacent {n : ℕ} (p : Q n) : set (Q n) := λ q, ∃! i, p i ≠ q i
/-- In `Q 0`, no two vertices are adjacent. -/
lemma not_adjacent_zero (p q : Q 0) : ¬ p.adjacent q :=
by rintros ⟨v, _⟩; apply fin_zero_elim v
/-- If `p` and `q` in `Q (n+1)` have different values at zero then they are adjacent
iff their projections to `Q n` are equal. -/
lemma adj_iff_proj_eq {p q : Q (n+1)} (h₀ : p 0 ≠ q 0) :
p.adjacent q ↔ π p = π q :=
begin
split,
{ rintros ⟨i, h_eq, h_uni⟩,
ext x, by_contradiction hx,
apply fin.succ_ne_zero x,
rw [h_uni _ hx, h_uni _ h₀] },
{ intro heq,
use [0, h₀],
intros y hy,
contrapose! hy,
rw ←fin.succ_pred _ hy,
apply congr_fun heq }
end
/-- If `p` and `q` in `Q (n+1)` have the same value at zero then they are adjacent
iff their projections to `Q n` are adjacent. -/
lemma adj_iff_proj_adj {p q : Q (n+1)} (h₀ : p 0 = q 0) :
p.adjacent q ↔ (π p).adjacent (π q) :=
begin
split,
{ rintros ⟨i, h_eq, h_uni⟩,
have h_i : i ≠ 0, from λ h_i, absurd h₀ (by rwa h_i at h_eq),
use [i.pred h_i,
show p (fin.succ (fin.pred i _)) ≠ q (fin.succ (fin.pred i _)),
by rwa fin.succ_pred],
intros y hy,
simp [eq.symm (h_uni _ hy)] },
{ rintros ⟨i, h_eq, h_uni⟩,
use [i.succ, h_eq],
intros y hy,
rw [←fin.pred_inj, fin.pred_succ],
{ apply h_uni,
change p (fin.pred _ _).succ ≠ q (fin.pred _ _).succ,
simp [hy] },
{ contrapose! hy,
rw [hy, h₀] },
{ apply fin.succ_ne_zero } }
end
@[symm] lemma adjacent.symm {p q : Q n} : p.adjacent q ↔ q.adjacent p :=
by simp only [adjacent, ne_comm]
end Q
/-! ### The vector space -/
/-- The free vector space on vertices of a hypercube, defined inductively. -/
def V : ℕ → Type
| 0 := ℝ
| (n+1) := V n × V n
namespace V
variables (n : ℕ)
/-! `V n` is a real vector space whose equality relation is computable. -/
instance : decidable_eq (V n) :=
by { induction n ; { dunfold V, resetI, apply_instance } }
instance : add_comm_group (V n) :=
by { induction n ; { dunfold V, resetI, apply_instance } }
instance : vector_space ℝ (V n) :=
by { induction n ; { dunfold V, resetI, apply_instance } }
end V
/-- The basis of `V` indexed by the hypercube, defined inductively. -/
noncomputable def e : Π {n}, Q n → V n
| 0 := λ _, (1:ℝ)
| (n+1) := λ x, cond (x 0) (e (π x), 0) (0, e (π x))
@[simp] lemma e_zero_apply (x : Q 0) : e x = (1 : ℝ) := rfl
/-- The dual basis to `e`, defined inductively. -/
noncomputable def ε : Π {n : ℕ} (p : Q n), V n →ₗ[ℝ] ℝ
| 0 _ := linear_map.id
| (n+1) p := cond (p 0) ((ε $ π p).comp $ linear_map.fst _ _ _) ((ε $ π p).comp $ linear_map.snd _ _ _)
variable {n : ℕ}
lemma duality (p q : Q n) : ε p (e q) = if p = q then 1 else 0 :=
begin
induction n with n IH,
{ rw (show p = q, from subsingleton.elim p q),
dsimp [ε, e],
simp },
{ dsimp [ε, e],
cases hp : p 0 ; cases hq : q 0,
all_goals {
repeat {rw cond_tt},
repeat {rw cond_ff},
simp only [linear_map.fst_apply, linear_map.snd_apply, linear_map.comp_apply, IH],
try { congr' 1, rw Q.succ_n_eq, finish },
try {
erw (ε _).map_zero,
have : p ≠ q, { intro h, rw p.succ_n_eq q at h, finish },
simp [this] } } }
end
/-- Any vector in `V n` annihilated by all `ε p`'s is zero. -/
lemma epsilon_total {v : V n} (h : ∀ p : Q n, (ε p) v = 0) : v = 0 :=
begin
induction n with n ih,
{ dsimp [ε] at h, exact h (λ _, tt) },
{ cases v with v₁ v₂,
ext ; change _ = (0 : V n) ; simp only ; apply ih ; intro p ;
[ let q : Q (n+1) := λ i, if h : i = 0 then tt else p (i.pred h),
let q : Q (n+1) := λ i, if h : i = 0 then ff else p (i.pred h)],
all_goals {
specialize h q,
rw [ε, show q 0 = tt, from rfl, cond_tt] at h <|> rw [ε, show q 0 = ff, from rfl, cond_ff] at h,
rwa show p = π q, by { ext, simp [q, fin.succ_ne_zero, π] } } }
end
/-- `e` and `ε` are dual families of vectors. It implies that `e` is indeed a basis
and `ε` computes coefficients of decompositions of vectors on that basis. -/
def dual_pair_e_ε (n : ℕ) : dual_pair (@e n) (@ε n) :=
{ eval := duality,
total := @epsilon_total _ }
/-! We will now derive the dimension of `V`, first as a cardinal in `dim_V` and,
since this cardinal is finite, as a natural number in `findim_V` -/
lemma dim_V : vector_space.dim ℝ (V n) = 2^n :=
have vector_space.dim ℝ (V n) = (2^n : ℕ),
by { rw [dim_eq_card_basis (dual_pair_e_ε _).is_basis, Q.card]; apply_instance },
by assumption_mod_cast
instance : finite_dimensional ℝ (V n) :=
finite_dimensional.of_finite_basis (dual_pair_e_ε _).is_basis
lemma findim_V : findim ℝ (V n) = 2^n :=
have _ := @dim_V n,
by rw ←findim_eq_dim at this; assumption_mod_cast
/-! ### The linear map -/
/-- The linear operator $f_n$ corresponding to Huang's matrix $A_n$,
defined inductively as a ℝ-linear map from `V n` to `V n`. -/
noncomputable def f : Π n, V n →ₗ[ℝ] V n
| 0 := 0
| (n+1) := linear_map.prod
(linear_map.coprod (f n) linear_map.id)
(linear_map.coprod linear_map.id (-f n))
/-! The preceding definition uses linear map constructions to automatically
get that `f` is linear, but its values are somewhat buried as a side-effect.
The next two lemmas unbury them. -/
@[simp] lemma f_zero : f 0 = 0 := rfl
lemma f_succ_apply (v : V (n+1)) :
f (n+1) v = (f n v.1 + v.2, v.1 - f n v.2) :=
begin
cases v,
rw f,
simp only [linear_map.id_apply, linear_map.prod_apply, prod.mk.inj_iff,
linear_map.neg_apply, sub_eq_add_neg, linear_map.coprod_apply],
exact ⟨rfl, rfl⟩
end
/-! In the next statement, the explicit conversion `(n : ℝ)` of `n` to a real number
is necessary since otherwise `n • v` refers to the multiplication defined
using only the addition of `V`. -/
lemma f_squared : ∀ v : V n, (f n) (f n v) = (n : ℝ) • v :=
begin
induction n with n IH; intro,
{ simpa only [nat.cast_zero, zero_smul] },
{ cases v, simp [f_succ_apply, IH, add_smul, add_assoc], abel }
end
/-! We now compute the matrix of `f` in the `e` basis (`p` is the line index,
`q` the column index). -/
lemma f_matrix :
∀ p q : Q n, |ε q (f n (e p))| = if q.adjacent p then 1 else 0 :=
begin
induction n with n IH,
{ intros p q,
dsimp [f],
simp [Q.not_adjacent_zero] },
{ intros p q,
have ite_nonneg : ite (π q = π p) (1 : ℝ) 0 ≥ 0,
{ split_ifs ; norm_num },
have f_map_zero := (show linear_map ℝ (V (n+0)) (V n), from f n).map_zero,
dsimp [e, ε, f], cases hp : p 0 ; cases hq : q 0,
all_goals
{ repeat {rw cond_tt}, repeat {rw cond_ff},
simp [f_map_zero, hp, hq, IH, duality, abs_of_nonneg ite_nonneg, Q.adj_iff_proj_eq,
Q.adj_iff_proj_adj] } }
end
/-- The linear operator $g_m$ corresponding to Knuth's matrix $B_m$. -/
noncomputable def g (m : ℕ) : V m →ₗ[ℝ] V (m+1) :=
linear_map.prod (f m + √(m+1) • linear_map.id) linear_map.id
/-! In the following lemmas, `m` will denote a natural number. -/
variables {m : ℕ}
/-! Again we unpack what are the values of `g`. -/
lemma g_apply : ∀ v, g m v = (f m v + √(m+1) • v, v) :=
by delta g; simp
lemma g_injective : injective (g m) :=
begin
rw g,
intros x₁ x₂ h,
simp only [linear_map.prod_apply, linear_map.id_apply, prod.mk.inj_iff] at h,
exact h.right
end
lemma f_image_g (w : V (m + 1)) (hv : ∃ v, g m v = w) :
f (m + 1) w = √(m + 1) • w :=
begin
rcases hv with ⟨v, rfl⟩,
have : √(m+1) * √(m+1) = m+1 :=
real.mul_self_sqrt (by exact_mod_cast zero_le _),
simp [this, f_succ_apply, g_apply, f_squared, smul_add, add_smul, smul_smul],
abel
end
/-!
### The main proof
In this section, in order to enforce that `n` is positive, we write it as
`m + 1` for some natural number `m`. -/
/-! `dim X` will denote the dimension of a subspace `X` as a cardinal. -/
notation `dim` X:70 := vector_space.dim ℝ ↥X
/-! `fdim X` will denote the (finite) dimension of a subspace `X` as a natural number. -/
notation `fdim` := findim ℝ
/-! `Span S` will denote the ℝ-subspace spanned by `S`. -/
notation `Span` := submodule.span ℝ
/-! `Card X` will denote the cardinal of a subset of a finite type, as a
natural number. -/
notation `Card` X:70 := X.to_finset.card
/-! In the following, `⊓` and `⊔` will denote intersection and sums of ℝ-subspaces,
equipped with their subspace structures. The notations come from the general
theory of lattices, with inf and sup (also known as meet and join). -/
/-- If a subset `H` of `Q (m+1)` has cardinal at least `2^m + 1` then the
subspace of `V (m+1)` spanned by the corresponding basis vectors non-trivially
intersects the range of `g m`. -/
lemma exists_eigenvalue (H : set (Q (m + 1))) (hH : Card H ≥ 2^m + 1) :
∃ y ∈ Span (e '' H) ⊓ (g m).range, y ≠ (0 : _) :=
begin
let W := Span (e '' H),
let img := (g m).range,
suffices : 0 < dim (W ⊓ img),
{ simp only [exists_prop],
exact_mod_cast exists_mem_ne_zero_of_dim_pos this },
have dim_le : dim (W ⊔ img) ≤ 2^(m + 1),
{ convert ← dim_submodule_le (W ⊔ img),
apply dim_V },
have dim_add : dim (W ⊔ img) + dim (W ⊓ img) = dim W + 2^m,
{ convert ← dim_sup_add_dim_inf_eq W img,
rw ← dim_eq_of_injective (g m) g_injective,
apply dim_V },
have dimW : dim W = card H,
{ have li : linear_independent ℝ (set.restrict e H) :=
linear_independent.comp (dual_pair_e_ε _).is_basis.1 _ subtype.val_injective,
have hdW := dim_span li,
rw set.range_restrict at hdW,
convert hdW,
rw [cardinal.mk_image_eq (dual_pair_e_ε _).is_basis.injective, cardinal.fintype_card] },
rw ← findim_eq_dim ℝ at ⊢ dim_le dim_add dimW,
rw [← findim_eq_dim ℝ, ← findim_eq_dim ℝ] at dim_add,
norm_cast at ⊢ dim_le dim_add dimW,
rw pow_succ' at dim_le,
rw set.to_finset_card at hH,
linarith
end
theorem huang_degree_theorem (H : set (Q (m + 1))) (hH : Card H ≥ 2^m + 1) :
∃ q, q ∈ H ∧ √(m + 1) ≤ Card (H ∩ q.adjacent) :=
begin
rcases exists_eigenvalue H hH with ⟨y, ⟨⟨y_mem_H, y_mem_g⟩, y_ne⟩⟩,
have coeffs_support : ((dual_pair_e_ε (m+1)).coeffs y).support ⊆ H.to_finset,
{ intros p p_in,
rw finsupp.mem_support_iff at p_in,
rw set.mem_to_finset,
exact (dual_pair_e_ε _).mem_of_mem_span y_mem_H p p_in },
obtain ⟨q, H_max⟩ : ∃ q : Q (m+1), ∀ q' : Q (m+1), |(ε q' : _) y| ≤ |ε q y|,
from fintype.exists_max _,
have H_q_pos : 0 < |ε q y|,
{ contrapose! y_ne,
exact epsilon_total (λ p, abs_nonpos_iff.mp (le_trans (H_max p) y_ne)) },
refine ⟨q, (dual_pair_e_ε _).mem_of_mem_span y_mem_H q (abs_pos_iff.mp H_q_pos), _⟩,
let s := √(m+1),
suffices : s * |ε q y| ≤ ↑(_) * |ε q y|,
from (mul_le_mul_right H_q_pos).mp ‹_›,
let coeffs := (dual_pair_e_ε (m+1)).coeffs,
calc
s * (abs (ε q y))
= abs (ε q (s • y)) : by rw [map_smul, smul_eq_mul, abs_mul, abs_of_nonneg (real.sqrt_nonneg _)]
... = abs (ε q (f (m+1) y)) : by rw [← f_image_g y (by simpa using y_mem_g)]
... = abs (ε q (f (m+1) (lc _ (coeffs y)))) : by rw (dual_pair_e_ε _).decomposition y
... = abs ((coeffs y).sum (λ (i : Q (m + 1)) (a : ℝ), a • ((ε q) ∘ (f (m + 1)) ∘ λ (i : Q (m + 1)), e i) i)): by
{ erw [(f $ m+1).map_finsupp_total, (ε q).map_finsupp_total, finsupp.total_apply] ; apply_instance }
... ≤ ∑ p in (coeffs y).support, |(coeffs y p) * (ε q $ f (m+1) $ e p)| : norm_sum_le _ $ λ p, coeffs y p * _
... = ∑ p in (coeffs y).support, |coeffs y p| * ite (q.adjacent p) 1 0 : by simp only [abs_mul, f_matrix]
... = ∑ p in (coeffs y).support.filter (Q.adjacent q), |coeffs y p| : by simp [finset.sum_filter]
... ≤ ∑ p in (coeffs y).support.filter (Q.adjacent q), |coeffs y q| : finset.sum_le_sum (λ p _, H_max p)
... = (finset.card ((coeffs y).support.filter (Q.adjacent q)): ℝ) * |coeffs y q| : by rw [finset.sum_const, nsmul_eq_mul]
... = (finset.card ((coeffs y).support ∩ (Q.adjacent q).to_finset): ℝ) * |coeffs y q| : by { congr' with x, simp, refl }
... ≤ (finset.card ((H ∩ Q.adjacent q).to_finset )) * |ε q y| :
(mul_le_mul_right H_q_pos).mpr (by {
norm_cast,
exact finset.card_le_of_subset (by rw set.to_finset_inter; convert finset.inter_subset_inter_right coeffs_support) })
end
|
c119ad9860f475d6239772a5141e235432a321b0 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/group_ring_action/invariant.lean | 83a3c28b1e1e0a98d0f7f9b39c5d20fa7d7db22e | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 1,781 | lean | /-
Copyright (c) 2021 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import algebra.hom.group_action
import ring_theory.subring.pointwise
/-! # Subrings invariant under an action
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.-/
section ring
variables (M R : Type*) [monoid M] [ring R] [mul_semiring_action M R]
variables (S : subring R)
open mul_action
variables {R}
/-- A typeclass for subrings invariant under a `mul_semiring_action`. -/
class is_invariant_subring : Prop :=
(smul_mem : ∀ (m : M) {x : R}, x ∈ S → m • x ∈ S)
instance is_invariant_subring.to_mul_semiring_action [is_invariant_subring M S] :
mul_semiring_action M S :=
{ smul := λ m x, ⟨m • x, is_invariant_subring.smul_mem m x.2⟩,
one_smul := λ s, subtype.eq $ one_smul M s,
mul_smul := λ m₁ m₂ s, subtype.eq $ mul_smul m₁ m₂ s,
smul_add := λ m s₁ s₂, subtype.eq $ smul_add m s₁ s₂,
smul_zero := λ m, subtype.eq $ smul_zero m,
smul_one := λ m, subtype.eq $ smul_one m,
smul_mul := λ m s₁ s₂, subtype.eq $ smul_mul' m s₁ s₂ }
end ring
section
variables (M : Type*) [monoid M]
variables {R' : Type*} [ring R'] [mul_semiring_action M R']
variables (U : subring R') [is_invariant_subring M U]
/-- The canonical inclusion from an invariant subring. -/
def is_invariant_subring.subtype_hom : U →+*[M] R' :=
{ map_smul' := λ m s, rfl, ..U.subtype }
@[simp] theorem is_invariant_subring.coe_subtype_hom :
(is_invariant_subring.subtype_hom M U : U → R') = coe := rfl
@[simp] theorem is_invariant_subring.coe_subtype_hom' :
(is_invariant_subring.subtype_hom M U : U →+* R') = U.subtype := rfl
end
|
2df8d61a89f07182d8addfc6853f22db86232946 | 957a80ea22c5abb4f4670b250d55534d9db99108 | /tests/lean/run/reserve.lean | 8945ca7b6c3dbc7edc0e2c7e6d8cf0b8fa1f7938 | [
"Apache-2.0"
] | permissive | GaloisInc/lean | aa1e64d604051e602fcf4610061314b9a37ab8cd | f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0 | refs/heads/master | 1,592,202,909,807 | 1,504,624,387,000 | 1,504,624,387,000 | 75,319,626 | 2 | 1 | Apache-2.0 | 1,539,290,164,000 | 1,480,616,104,000 | C++ | UTF-8 | Lean | false | false | 178 | lean | reserve infix `=?=`:50
reserve infixr `&&&`:25
notation a `=?=` b := eq a b
notation a `&&&` b := and a b
set_option pp.notation false
#check λ a b : nat, a =?= b &&& b =?= a
|
a1401d775e06c693bcef6c460e4ade1c861d1911 | 367134ba5a65885e863bdc4507601606690974c1 | /src/data/typevec.lean | c72e611a6cf29efe1df9e17d5734e5a979f66c0d | [
"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 | 24,476 | lean | /-
Copyright (c) 2018 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad, Mario Carneiro, Simon Hudon
-/
import data.fin2
import logic.function.basic
import tactic.basic
/-!
# Tuples of types, and their categorical structure.
## Features
* `typevec n` - n-tuples of types
* `α ⟹ β` - n-tuples of maps
* `f ⊚ g` - composition
Also, support functions for operating with n-tuples of types, such as:
* `append1 α β` - append type `β` to n-tuple `α` to obtain an (n+1)-tuple
* `drop α` - drops the last element of an (n+1)-tuple
* `last α` - returns the last element of an (n+1)-tuple
* `append_fun f g` - appends a function g to an n-tuple of functions
* `drop_fun f` - drops the last function from an n+1-tuple
* `last_fun f` - returns the last function of a tuple.
Since e.g. `append1 α.drop α.last` is propositionally equal to `α` but not definitionally equal
to it, we need support functions and lemmas to mediate between constructions.
-/
universes u v w
/--
n-tuples of types, as a category
-/
def typevec (n : ℕ) := fin2 n → Type*
instance {n} : inhabited (typevec.{u} n) := ⟨ λ _, punit ⟩
namespace typevec
variable {n : ℕ}
/-- arrow in the category of `typevec` -/
def arrow (α β : typevec n) := Π i : fin2 n, α i → β i
localized "infixl ` ⟹ `:40 := typevec.arrow" in mvfunctor
instance arrow.inhabited (α β : typevec n) [Π i, inhabited (β i)] : inhabited (α ⟹ β) :=
⟨ λ _ _, default _ ⟩
/-- identity of arrow composition -/
def id {α : typevec n} : α ⟹ α := λ i x, x
/-- arrow composition in the category of `typevec` -/
def comp {α β γ : typevec n} (g : β ⟹ γ) (f : α ⟹ β) : α ⟹ γ :=
λ i x, g i (f i x)
localized "infixr ` ⊚ `:80 := typevec.comp" in mvfunctor -- type as \oo
@[simp] theorem id_comp {α β : typevec n} (f : α ⟹ β) : id ⊚ f = f :=
rfl
@[simp] theorem comp_id {α β : typevec n} (f : α ⟹ β) : f ⊚ id = f :=
rfl
theorem comp_assoc {α β γ δ : typevec n} (h : γ ⟹ δ) (g : β ⟹ γ) (f : α ⟹ β) :
(h ⊚ g) ⊚ f = h ⊚ g ⊚ f := rfl
/--
Support for extending a typevec by one element.
-/
def append1 (α : typevec n) (β : Type*) : typevec (n+1)
| (fin2.fs i) := α i
| fin2.fz := β
infixl ` ::: `:67 := append1
/-- retain only a `n-length` prefix of the argument -/
def drop (α : typevec.{u} (n+1)) : typevec n := λ i, α i.fs
/-- take the last value of a `(n+1)-length` vector -/
def last (α : typevec.{u} (n+1)) : Type* := α fin2.fz
instance last.inhabited (α : typevec (n+1)) [inhabited (α fin2.fz)] : inhabited (last α) :=
⟨ (default (α fin2.fz) : α fin2.fz) ⟩
theorem drop_append1 {α : typevec n} {β : Type*} {i : fin2 n} : drop (append1 α β) i = α i := rfl
theorem drop_append1' {α : typevec n} {β : Type*} : drop (append1 α β) = α :=
by ext; apply drop_append1
theorem last_append1 {α : typevec n} {β : Type*} : last (append1 α β) = β := rfl
@[simp]
theorem append1_drop_last (α : typevec (n+1)) : append1 (drop α) (last α) = α :=
funext $ λ i, by cases i; refl
/-- cases on `(n+1)-length` vectors -/
@[elab_as_eliminator] def append1_cases
{C : typevec (n+1) → Sort u} (H : ∀ α β, C (append1 α β)) (γ) : C γ :=
by rw [← @append1_drop_last _ γ]; apply H
@[simp] theorem append1_cases_append1 {C : typevec (n+1) → Sort u}
(H : ∀ α β, C (append1 α β)) (α β) :
@append1_cases _ C H (append1 α β) = H α β := rfl
/-- append an arrow and a function for arbitrary source and target
type vectors -/
def split_fun {α α' : typevec (n+1)}
(f : drop α ⟹ drop α') (g : last α → last α') : α ⟹ α'
| (fin2.fs i) := f i
| fin2.fz := g
/-- append an arrow and a function as well as their respective source
and target types / typevecs -/
def append_fun {α α' : typevec n} {β β' : Type*}
(f : α ⟹ α') (g : β → β') : append1 α β ⟹ append1 α' β' := split_fun f g
infixl ` ::: ` := append_fun
/-- split off the prefix of an arrow -/
def drop_fun {α β : typevec (n+1)} (f : α ⟹ β) : drop α ⟹ drop β :=
λ i, f i.fs
/-- split off the last function of an arrow -/
def last_fun {α β : typevec (n+1)} (f : α ⟹ β) : last α → last β :=
f fin2.fz
/-- arrow in the category of `0-length` vectors -/
def nil_fun {α : typevec 0} {β : typevec 0} : α ⟹ β :=
λ i, fin2.elim0 i
theorem eq_of_drop_last_eq {α β : typevec (n+1)} {f g : α ⟹ β}
(h₀ : drop_fun f = drop_fun g) (h₁ : last_fun f = last_fun g) : f = g :=
by replace h₀ := congr_fun h₀;
ext1 (ieq | ⟨j, ieq⟩); apply_assumption
@[simp] theorem drop_fun_split_fun {α α' : typevec (n+1)}
(f : drop α ⟹ drop α') (g : last α → last α') :
drop_fun (split_fun f g) = f := rfl
/-- turn an equality into an arrow -/
def arrow.mp {α β : typevec n} (h : α = β) : α ⟹ β
| i := eq.mp (congr_fun h _)
/-- turn an equality into an arrow, with reverse direction -/
def arrow.mpr {α β : typevec n} (h : α = β) : β ⟹ α
| i := eq.mpr (congr_fun h _)
/-- decompose a vector into its prefix appended with its last element -/
def to_append1_drop_last {α : typevec (n+1)} : α ⟹ drop α ::: last α :=
arrow.mpr (append1_drop_last _)
/-- stitch two bits of a vector back together -/
def from_append1_drop_last {α : typevec (n+1)} : drop α ::: last α ⟹ α :=
arrow.mp (append1_drop_last _)
@[simp] theorem last_fun_split_fun {α α' : typevec (n+1)}
(f : drop α ⟹ drop α') (g : last α → last α') :
last_fun (split_fun f g) = g := rfl
@[simp] theorem drop_fun_append_fun {α α' : typevec n} {β β' : Type*} (f : α ⟹ α') (g : β → β') :
drop_fun (f ::: g) = f := rfl
@[simp] theorem last_fun_append_fun {α α' : typevec n} {β β' : Type*} (f : α ⟹ α') (g : β → β') :
last_fun (f ::: g) = g := rfl
theorem split_drop_fun_last_fun {α α' : typevec (n+1)} (f : α ⟹ α') :
split_fun (drop_fun f) (last_fun f) = f :=
eq_of_drop_last_eq rfl rfl
theorem split_fun_inj
{α α' : typevec (n+1)} {f f' : drop α ⟹ drop α'} {g g' : last α → last α'}
(H : split_fun f g = split_fun f' g') : f = f' ∧ g = g' :=
by rw [← drop_fun_split_fun f g, H, ← last_fun_split_fun f g, H]; simp
theorem append_fun_inj {α α' : typevec n} {β β' : Type*} {f f' : α ⟹ α'} {g g' : β → β'} :
f ::: g = f' ::: g' → f = f' ∧ g = g' :=
split_fun_inj
theorem split_fun_comp {α₀ α₁ α₂ : typevec (n+1)}
(f₀ : drop α₀ ⟹ drop α₁) (f₁ : drop α₁ ⟹ drop α₂)
(g₀ : last α₀ → last α₁) (g₁ : last α₁ → last α₂) :
split_fun (f₁ ⊚ f₀) (g₁ ∘ g₀) = split_fun f₁ g₁ ⊚ split_fun f₀ g₀ :=
eq_of_drop_last_eq rfl rfl
theorem append_fun_comp_split_fun
{α γ : typevec n} {β δ : Type*} {ε : typevec (n + 1)}
(f₀ : drop ε ⟹ α) (f₁ : α ⟹ γ)
(g₀ : last ε → β) (g₁ : β → δ) :
append_fun f₁ g₁ ⊚ split_fun f₀ g₀ = split_fun (f₁ ⊚ f₀) (g₁ ∘ g₀) :=
(split_fun_comp _ _ _ _).symm
lemma append_fun_comp {α₀ α₁ α₂ : typevec n} {β₀ β₁ β₂ : Type*}
(f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) (g₀ : β₀ → β₁) (g₁ : β₁ → β₂) :
f₁ ⊚ f₀ ::: g₁ ∘ g₀ = (f₁ ::: g₁) ⊚ (f₀ ::: g₀) :=
eq_of_drop_last_eq rfl rfl
lemma append_fun_comp' {α₀ α₁ α₂ : typevec n} {β₀ β₁ β₂ : Type*}
(f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) (g₀ : β₀ → β₁) (g₁ : β₁ → β₂) :
(f₁ ::: g₁) ⊚ (f₀ ::: g₀) = f₁ ⊚ f₀ ::: g₁ ∘ g₀ :=
eq_of_drop_last_eq rfl rfl
lemma nil_fun_comp {α₀ : typevec 0} (f₀ : α₀ ⟹ fin2.elim0) : nil_fun ⊚ f₀ = f₀ :=
funext $ λ x, fin2.elim0 x
theorem append_fun_comp_id {α : typevec n} {β₀ β₁ β₂ : Type*}
(g₀ : β₀ → β₁) (g₁ : β₁ → β₂) :
@id _ α ::: g₁ ∘ g₀ = (id ::: g₁) ⊚ (id ::: g₀) :=
eq_of_drop_last_eq rfl rfl
@[simp]
theorem drop_fun_comp {α₀ α₁ α₂ : typevec (n+1)} (f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) :
drop_fun (f₁ ⊚ f₀) = drop_fun f₁ ⊚ drop_fun f₀ := rfl
@[simp]
theorem last_fun_comp {α₀ α₁ α₂ : typevec (n+1)} (f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) :
last_fun (f₁ ⊚ f₀) = last_fun f₁ ∘ last_fun f₀ := rfl
theorem append_fun_aux {α α' : typevec n} {β β' : Type*}
(f : α ::: β ⟹ α' ::: β') : drop_fun f ::: last_fun f = f :=
eq_of_drop_last_eq rfl rfl
theorem append_fun_id_id {α : typevec n} {β : Type*} :
@typevec.id n α ::: @_root_.id β = typevec.id :=
eq_of_drop_last_eq rfl rfl
instance subsingleton0 : subsingleton (typevec 0) :=
⟨ λ a b, funext $ λ a, fin2.elim0 a ⟩
run_cmd do
mk_simp_attr `typevec,
tactic.add_doc_string `simp_attr.typevec
"simp set for the manipulation of typevec and arrow expressions"
local prefix `♯`:0 := cast (by try { simp }; congr' 1; try { simp })
/-- cases distinction for 0-length type vector -/
protected def cases_nil {β : typevec 0 → Sort*} (f : β fin2.elim0) :
Π v, β v :=
λ v, ♯ f
/-- cases distinction for (n+1)-length type vector -/
protected def cases_cons (n : ℕ) {β : typevec (n+1) → Sort*}
(f : Π t (v : typevec n), β (v ::: t)) :
Π v, β v :=
λ v : typevec (n+1), ♯ f v.last v.drop
protected lemma cases_nil_append1 {β : typevec 0 → Sort*} (f : β fin2.elim0) :
typevec.cases_nil f fin2.elim0 = f := rfl
protected lemma cases_cons_append1 (n : ℕ) {β : typevec (n+1) → Sort*}
(f : Π t (v : typevec n), β (v ::: t))
(v : typevec n) (α) :
typevec.cases_cons n f (v ::: α) = f α v := rfl
/-- cases distinction for an arrow in the category of 0-length type vectors -/
def typevec_cases_nil₃ {β : Π v v' : typevec 0, v ⟹ v' → Sort*}
(f : β fin2.elim0 fin2.elim0 nil_fun) :
Π v v' fs, β v v' fs :=
λ v v' fs,
begin
refine cast _ f; congr' 1; ext; try { intros; casesm fin2 0 }, refl
end
/-- cases distinction for an arrow in the category of (n+1)-length type vectors -/
def typevec_cases_cons₃ (n : ℕ) {β : Π v v' : typevec (n+1), v ⟹ v' → Sort*}
(F : Π t t' (f : t → t') (v v' : typevec n) (fs : v ⟹ v'), β (v ::: t) (v' ::: t') (fs ::: f)) :
Π v v' fs, β v v' fs :=
begin
intros v v',
rw [←append1_drop_last v, ←append1_drop_last v'],
intro fs,
rw [←split_drop_fun_last_fun fs],
apply F
end
/-- specialized cases distinction for an arrow in the category of 0-length type vectors -/
def typevec_cases_nil₂ {β : fin2.elim0 ⟹ fin2.elim0 → Sort*}
(f : β nil_fun) :
Π f, β f :=
begin
intro g, have : g = nil_fun, ext ⟨ ⟩,
rw this, exact f
end
/-- specialized cases distinction for an arrow in the category of (n+1)-length type vectors -/
def typevec_cases_cons₂ (n : ℕ) (t t' : Type*) (v v' : typevec (n))
{β : (v ::: t) ⟹ (v' ::: t') → Sort*} (F : Π (f : t → t') (fs : v ⟹ v'), β (fs ::: f)) :
Π fs, β fs :=
begin
intro fs,
rw [←split_drop_fun_last_fun fs],
apply F
end
lemma typevec_cases_nil₂_append_fun {β : fin2.elim0 ⟹ fin2.elim0 → Sort*}
(f : β nil_fun) :
typevec_cases_nil₂ f nil_fun = f := rfl
lemma typevec_cases_cons₂_append_fun (n : ℕ) (t t' : Type*)
(v v' : typevec (n)) {β : (v ::: t) ⟹ (v' ::: t') → Sort*}
(F : Π (f : t → t') (fs : v ⟹ v'), β (fs ::: f)) (f fs) :
typevec_cases_cons₂ n t t' v v' F (fs ::: f) = F f fs := rfl
/- for lifting predicates and relations -/
/-- `pred_last α p x` predicates `p` of the last element of `x : α.append1 β`. -/
def pred_last (α : typevec n) {β : Type*} (p : β → Prop) : Π ⦃i⦄, (α.append1 β) i → Prop
| (fin2.fs i) := λ x, true
| fin2.fz := p
/-- `rel_last α r x y` says that `p` the last elements of `x y : α.append1 β` are related by `r` and
all the other elements are equal. -/
def rel_last (α : typevec n) {β γ : Type*} (r : β → γ → Prop) :
Π ⦃i⦄, (α.append1 β) i → (α.append1 γ) i → Prop
| (fin2.fs i) := eq
| fin2.fz := r
section liftp'
open nat
/-- `repeat n t` is a `n-length` type vector that contains `n` occurences of `t` -/
def repeat : Π (n : ℕ) (t : Sort*), typevec n
| 0 t := fin2.elim0
| (nat.succ i) t := append1 (repeat i t) t
/-- `prod α β` is the pointwise product of the components of `α` and `β` -/
def prod : Π {n} (α β : typevec.{u} n), typevec n
| 0 α β := fin2.elim0
| (n+1) α β := prod (drop α) (drop β) ::: (last α × last β)
localized "infix ` ⊗ `:45 := typevec.prod" in mvfunctor
/-- `const x α` is an arrow that ignores its source and constructs a `typevec` that
contains nothing but `x` -/
protected def const {β} (x : β) : Π {n} (α : typevec n), α ⟹ repeat _ β
| (succ n) α (fin2.fs i) := const (drop α) _
| (succ n) α fin2.fz := λ _, x
open function (uncurry)
/-- vector of equality on a product of vectors -/
def repeat_eq : Π {n} (α : typevec n), α ⊗ α ⟹ repeat _ Prop
| 0 α := nil_fun
| (succ n) α := repeat_eq (drop α) ::: uncurry eq
lemma const_append1 {β γ} (x : γ) {n} (α : typevec n) :
typevec.const x (α ::: β) = append_fun (typevec.const x α) (λ _, x) :=
by ext i : 1; cases i; refl
lemma eq_nil_fun {α β : typevec 0} (f : α ⟹ β) : f = nil_fun :=
by ext x; cases x
lemma id_eq_nil_fun {α : typevec 0} : @id _ α = nil_fun :=
by ext x; cases x
lemma const_nil {β} (x : β) (α : typevec 0) : typevec.const x α = nil_fun :=
by ext i : 1; cases i; refl
@[typevec]
lemma repeat_eq_append1 {β} {n} (α : typevec n) :
repeat_eq (α ::: β) = split_fun (repeat_eq α) (uncurry eq) :=
by induction n; refl
@[typevec]
lemma repeat_eq_nil (α : typevec 0) : repeat_eq α = nil_fun :=
by ext i : 1; cases i; refl
/-- predicate on a type vector to constrain only the last object -/
def pred_last' (α : typevec n) {β : Type*} (p : β → Prop) : α ::: β ⟹ repeat (n+1) Prop :=
split_fun (typevec.const true α) p
/-- predicate on the product of two type vectors to constrain only their last object -/
def rel_last' (α : typevec n) {β : Type*} (p : β → β → Prop) :
(α ::: β ⊗ α ::: β) ⟹ repeat (n+1) Prop :=
split_fun (repeat_eq α) (uncurry p)
/-- given `F : typevec.{u} (n+1) → Type u`, `curry F : Type u → typevec.{u} → Type u`,
i.e. its first argument can be fed in separately from the rest of the vector of arguments -/
def curry (F : typevec.{u} (n+1) → Type*) (α : Type u) (β : typevec.{u} n) : Type* :=
F (β ::: α)
instance curry.inhabited (F : typevec.{u} (n+1) → Type*) (α : Type u) (β : typevec.{u} n)
[I : inhabited (F $ β ::: α)]:
inhabited (curry F α β) := I
/-- arrow to remove one element of a `repeat` vector -/
def drop_repeat (α : Type*) : Π {n}, drop (repeat (succ n) α) ⟹ repeat n α
| (succ n) (fin2.fs i) := drop_repeat i
| (succ n) fin2.fz := _root_.id
/-- projection for a repeat vector -/
def of_repeat {α : Sort*} : Π {n i}, repeat n α i → α
| ._ fin2.fz := _root_.id
| ._ (fin2.fs i) := @of_repeat _ i
lemma const_iff_true {α : typevec n} {i x p} : of_repeat (typevec.const p α i x) ↔ p :=
by induction i; [refl, erw [typevec.const,@i_ih (drop α) x]]
-- variables {F : typevec.{u} n → Type*} [mvfunctor F]
variables {α β γ : typevec.{u} n}
variables (p : α ⟹ repeat n Prop) (r : α ⊗ α ⟹ repeat n Prop)
/-- left projection of a `prod` vector -/
def prod.fst : Π {n} {α β : typevec.{u} n}, α ⊗ β ⟹ α
| (succ n) α β (fin2.fs i) := @prod.fst _ (drop α) (drop β) i
| (succ n) α β fin2.fz := _root_.prod.fst
/-- right projection of a `prod` vector -/
def prod.snd : Π {n} {α β : typevec.{u} n}, α ⊗ β ⟹ β
| (succ n) α β (fin2.fs i) := @prod.snd _ (drop α) (drop β) i
| (succ n) α β fin2.fz := _root_.prod.snd
/-- introduce a product where both components are the same -/
def prod.diag : Π {n} {α : typevec.{u} n}, α ⟹ α ⊗ α
| (succ n) α (fin2.fs i) x := @prod.diag _ (drop α) _ x
| (succ n) α fin2.fz x := (x,x)
/-- constructor for `prod` -/
def prod.mk : Π {n} {α β : typevec.{u} n} (i : fin2 n), α i → β i → (α ⊗ β) i
| (succ n) α β (fin2.fs i) := prod.mk i
| (succ n) α β fin2.fz := _root_.prod.mk
@[simp]
lemma prod_fst_mk {α β : typevec n} (i : fin2 n) (a : α i) (b : β i) :
typevec.prod.fst i (prod.mk i a b) = a :=
by induction i; simp [prod.fst, prod.mk, *] at *
@[simp]
lemma prod_snd_mk {α β : typevec n} (i : fin2 n) (a : α i) (b : β i) :
typevec.prod.snd i (prod.mk i a b) = b :=
by induction i; simp [prod.snd, prod.mk, *] at *
/-- `prod` is functorial -/
protected def prod.map : Π {n} {α α' β β' : typevec.{u} n}, (α ⟹ β) → (α' ⟹ β') → α ⊗ α' ⟹ β ⊗ β'
| (succ n) α α' β β' x y (fin2.fs i) a :=
@prod.map _ (drop α) (drop α') (drop β) (drop β') (drop_fun x) (drop_fun y) _ a
| (succ n) α α' β β' x y fin2.fz a := (x _ a.1,y _ a.2)
localized "infix ` ⊗' `:45 := typevec.prod.map" in mvfunctor
theorem fst_prod_mk {α α' β β' : typevec n} (f : α ⟹ β) (g : α' ⟹ β') :
typevec.prod.fst ⊚ (f ⊗' g) = f ⊚ typevec.prod.fst :=
by ext i; induction i; [refl, apply i_ih]
theorem snd_prod_mk {α α' β β' : typevec n} (f : α ⟹ β) (g : α' ⟹ β') :
typevec.prod.snd ⊚ (f ⊗' g) = g ⊚ typevec.prod.snd :=
by ext i; induction i; [refl, apply i_ih]
theorem fst_diag {α : typevec n} : typevec.prod.fst ⊚ (prod.diag : α ⟹ _) = id :=
by ext i; induction i; [refl, apply i_ih]
theorem snd_diag {α : typevec n} : typevec.prod.snd ⊚ (prod.diag : α ⟹ _) = id :=
by ext i; induction i; [refl, apply i_ih]
lemma repeat_eq_iff_eq {α : typevec n} {i x y} :
of_repeat (repeat_eq α i (prod.mk _ x y)) ↔ x = y :=
by induction i; [refl, erw [repeat_eq,@i_ih (drop α) x y]]
/-- given a predicate vector `p` over vector `α`, `subtype_ p` is the type of vectors
that contain an `α` that satisfies `p` -/
def subtype_ : Π {n} {α : typevec.{u} n} (p : α ⟹ repeat n Prop), typevec n
| ._ α p fin2.fz := _root_.subtype (λ x, p fin2.fz x)
| ._ α p (fin2.fs i) := subtype_ (drop_fun p) i
/-- projection on `subtype_` -/
def subtype_val : Π {n} {α : typevec.{u} n} (p : α ⟹ repeat n Prop), subtype_ p ⟹ α
| (succ n) α p (fin2.fs i) := @subtype_val n _ _ i
| (succ n) α p fin2.fz := _root_.subtype.val
/-- arrow that rearranges the type of `subtype_` to turn a subtype of vector into
a vector of subtypes -/
def to_subtype : Π {n} {α : typevec.{u} n} (p : α ⟹ repeat n Prop),
(λ (i : fin2 n), { x // of_repeat $ p i x }) ⟹ subtype_ p
| (succ n) α p (fin2.fs i) x := to_subtype (drop_fun p) i x
| (succ n) α p fin2.fz x := x
/-- arrow that rearranges the type of `subtype_` to turn a vector of subtypes
into a subtype of vector -/
def of_subtype : Π {n} {α : typevec.{u} n} (p : α ⟹ repeat n Prop),
subtype_ p ⟹ (λ (i : fin2 n), { x // of_repeat $ p i x })
| (succ n) α p (fin2.fs i) x := of_subtype _ i x
| (succ n) α p fin2.fz x := x
/-- similar to `to_subtype` adapted to relations (i.e. predicate on product) -/
def to_subtype' : Π {n} {α : typevec.{u} n} (p : α ⊗ α ⟹ repeat n Prop),
(λ (i : fin2 n), { x : α i × α i // of_repeat $ p i (prod.mk _ x.1 x.2) }) ⟹ subtype_ p
| (succ n) α p (fin2.fs i) x := to_subtype' (drop_fun p) i x
| (succ n) α p fin2.fz x := ⟨x.val,cast (by congr; simp [prod.mk]) x.property⟩
/-- similar to `of_subtype` adapted to relations (i.e. predicate on product) -/
def of_subtype' : Π {n} {α : typevec.{u} n} (p : α ⊗ α ⟹ repeat n Prop),
subtype_ p ⟹ (λ (i : fin2 n), { x : α i × α i // of_repeat $ p i (prod.mk _ x.1 x.2) })
| ._ α p (fin2.fs i) x := of_subtype' _ i x
| ._ α p fin2.fz x := ⟨x.val,cast (by congr; simp [prod.mk]) x.property⟩
/-- similar to `diag` but the target vector is a `subtype_`
guaranteeing the equality of the components -/
def diag_sub : Π {n} {α : typevec.{u} n}, α ⟹ subtype_ (repeat_eq α)
| (succ n) α (fin2.fs i) x := @diag_sub _ (drop α) _ x
| (succ n) α fin2.fz x := ⟨(x,x), rfl⟩
lemma subtype_val_nil {α : typevec.{u} 0} (ps : α ⟹ repeat 0 Prop) :
typevec.subtype_val ps = nil_fun :=
funext $ by rintro ⟨ ⟩; refl
lemma diag_sub_val {n} {α : typevec.{u} n} :
subtype_val (repeat_eq α) ⊚ diag_sub = prod.diag :=
by ext i; induction i; [refl, apply i_ih]
lemma prod_id : Π {n} {α β : typevec.{u} n}, (id ⊗' id) = (id : α ⊗ β ⟹ _) :=
begin
intros, ext i a, induction i,
{ cases a, refl },
{ apply i_ih },
end
lemma append_prod_append_fun {n} {α α' β β' : typevec.{u} n}
{φ φ' ψ ψ' : Type u}
{f₀ : α ⟹ α'} {g₀ : β ⟹ β'}
{f₁ : φ → φ'} {g₁ : ψ → ψ'} :
(f₀ ⊗' g₀) ::: _root_.prod.map f₁ g₁ = ((f₀ ::: f₁) ⊗' (g₀ ::: g₁)) :=
by ext i a; cases i; [cases a, skip]; refl
end liftp'
@[simp]
lemma drop_fun_diag {α} :
drop_fun (@prod.diag (n+1) α) = prod.diag :=
by { ext i : 2, induction i; simp [drop_fun,*]; refl }
@[simp]
lemma drop_fun_subtype_val {α} (p : α ⟹ repeat (n+1) Prop) :
drop_fun (subtype_val p) = subtype_val _ := rfl
@[simp]
lemma last_fun_subtype_val {α} (p : α ⟹ repeat (n+1) Prop) :
last_fun (subtype_val p) = subtype.val := rfl
@[simp]
lemma drop_fun_to_subtype {α} (p : α ⟹ repeat (n+1) Prop) :
drop_fun (to_subtype p) = to_subtype _ :=
by { ext i : 2, induction i; simp [drop_fun,*]; refl }
@[simp]
lemma last_fun_to_subtype {α} (p : α ⟹ repeat (n+1) Prop) :
last_fun (to_subtype p) = _root_.id :=
by { ext i : 2, induction i; simp [drop_fun,*]; refl }
@[simp]
lemma drop_fun_of_subtype {α} (p : α ⟹ repeat (n+1) Prop) :
drop_fun (of_subtype p) = of_subtype _ :=
by { ext i : 2, induction i; simp [drop_fun,*]; refl }
@[simp]
lemma last_fun_of_subtype {α} (p : α ⟹ repeat (n+1) Prop) :
last_fun (of_subtype p) = _root_.id :=
by { ext i : 2, induction i; simp [drop_fun,*]; refl }
@[simp]
lemma drop_fun_rel_last {α : typevec n} {β}
(R : β → β → Prop) :
drop_fun (rel_last' α R) = repeat_eq α := rfl
attribute [simp] drop_append1'
open_locale mvfunctor
@[simp]
lemma drop_fun_prod {α α' β β' : typevec (n+1)} (f : α ⟹ β) (f' : α' ⟹ β') :
drop_fun (f ⊗' f') = (drop_fun f ⊗' drop_fun f') :=
by { ext i : 2, induction i; simp [drop_fun,*]; refl }
@[simp]
lemma last_fun_prod {α α' β β' : typevec (n+1)} (f : α ⟹ β) (f' : α' ⟹ β') :
last_fun (f ⊗' f') = _root_.prod.map (last_fun f) (last_fun f') :=
by { ext i : 1, induction i; simp [last_fun,*]; refl }
@[simp]
lemma drop_fun_from_append1_drop_last {α : typevec (n+1)} :
drop_fun (@from_append1_drop_last _ α) = id := rfl
@[simp]
lemma last_fun_from_append1_drop_last {α : typevec (n+1)} :
last_fun (@from_append1_drop_last _ α) = _root_.id := rfl
@[simp]
lemma drop_fun_id {α : typevec (n+1)} :
drop_fun (@typevec.id _ α) = id := rfl
@[simp]
lemma prod_map_id {α β : typevec n} :
(@typevec.id _ α ⊗' @typevec.id _ β) = id :=
by { ext i : 2, induction i; simp only [typevec.prod.map,*,drop_fun_id],
cases x, refl, refl }
@[simp]
lemma subtype_val_diag_sub {α : typevec n} :
subtype_val (repeat_eq α) ⊚ diag_sub = prod.diag :=
by { clear_except, ext i, induction i; [refl, apply i_ih], }
@[simp]
lemma to_subtype_of_subtype {α : typevec n} (p : α ⟹ repeat n Prop) :
to_subtype p ⊚ of_subtype p = id :=
by ext i x; induction i; dsimp only [id, to_subtype, comp, of_subtype] at *; simp *
@[simp]
lemma subtype_val_to_subtype {α : typevec n} (p : α ⟹ repeat n Prop) :
subtype_val p ⊚ to_subtype p = λ _, subtype.val :=
by ext i x; induction i; dsimp only [to_subtype, comp, subtype_val] at *; simp *
@[simp]
lemma to_subtype_of_subtype_assoc {α β : typevec n} (p : α ⟹ repeat n Prop)
(f : β ⟹ subtype_ p) :
@to_subtype n _ p ⊚ of_subtype _ ⊚ f = f :=
by rw [← comp_assoc,to_subtype_of_subtype]; simp
@[simp]
lemma to_subtype'_of_subtype' {α : typevec n} (r : α ⊗ α ⟹ repeat n Prop) :
to_subtype' r ⊚ of_subtype' r = id :=
by ext i x; induction i; dsimp only [id, to_subtype', comp, of_subtype'] at *; simp *
lemma subtype_val_to_subtype' {α : typevec n} (r : α ⊗ α ⟹ repeat n Prop) :
subtype_val r ⊚ to_subtype' r = λ i x, prod.mk i x.1.fst x.1.snd :=
by ext i x; induction i; dsimp only [id, to_subtype', comp, subtype_val, prod.mk] at *; simp *
end typevec
|
85fcd230047ab22975aee1c2d7e1a09f72348038 | f5f7e6fae601a5fe3cac7cc3ed353ed781d62419 | /src/data/complex/exponential.lean | 82df356961c72d128b0962631868fc66ccc739c8 | [
"Apache-2.0"
] | permissive | EdAyers/mathlib | 9ecfb2f14bd6caad748b64c9c131befbff0fb4e0 | ca5d4c1f16f9c451cf7170b10105d0051db79e1b | refs/heads/master | 1,626,189,395,845 | 1,555,284,396,000 | 1,555,284,396,000 | 144,004,030 | 0 | 0 | Apache-2.0 | 1,533,727,664,000 | 1,533,727,663,000 | null | UTF-8 | Lean | false | false | 47,424 | 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
-/
import algebra.archimedean
import data.nat.choose data.complex.basic
import tactic.linarith
local attribute [instance, priority 0] classical.prop_decidable
local notation `abs'` := _root_.abs
open is_absolute_value
section
open real is_absolute_value finset
lemma forall_ge_le_of_forall_le_succ {α : Type*} [preorder α] (f : ℕ → α) {m : ℕ}
(h : ∀ n ≥ m, f n.succ ≤ f n) : ∀ {l}, ∀ k ≥ m, k ≤ l → f l ≤ f k :=
begin
assume l k hkm hkl,
generalize hp : l - k = p,
have : l = k + p := add_comm p k ▸ (nat.sub_eq_iff_eq_add hkl).1 hp,
subst this,
clear hkl hp,
induction p with p ih,
{ simp },
{ exact le_trans (h _ (le_trans hkm (nat.le_add_right _ _))) ih }
end
variables {α : Type*} {β : Type*} [ring β]
[discrete_linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv]
lemma is_cau_of_decreasing_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a)
(hnm : ∀ n ≥ m, f n.succ ≤ f n) : is_cau_seq abs f :=
λ ε ε0,
let ⟨k, hk⟩ := archimedean.arch a ε0 in
have h : ∃ l, ∀ n ≥ m, a - add_monoid.smul l ε < f n :=
⟨k + k + 1, λ n hnm, lt_of_lt_of_le
(show a - add_monoid.smul (k + (k + 1)) ε < -abs (f n),
from lt_neg.1 $ lt_of_le_of_lt (ham n hnm) (begin
rw [neg_sub, lt_sub_iff_add_lt, add_monoid.add_smul],
exact add_lt_add_of_le_of_lt hk (lt_of_le_of_lt hk
(lt_add_of_pos_left _ ε0)),
end))
(neg_le.2 $ (abs_neg (f n)) ▸ le_abs_self _)⟩,
let l := nat.find h in
have hl : ∀ (n : ℕ), n ≥ m → f n > a - add_monoid.smul l ε := nat.find_spec h,
have hl0 : l ≠ 0 := λ hl0, not_lt_of_ge (ham m (le_refl _))
(lt_of_lt_of_le (by have := hl m (le_refl m); simpa [hl0] using this) (le_abs_self (f m))),
begin
cases classical.not_forall.1
(nat.find_min h (nat.pred_lt hl0)) with i hi,
rw [not_imp, not_lt] at hi,
existsi i,
assume j hj,
have hfij : f j ≤ f i := forall_ge_le_of_forall_le_succ f hnm _ hi.1 hj,
rw [abs_of_nonpos (sub_nonpos.2 hfij), neg_sub, sub_lt_iff_lt_add'],
exact calc f i ≤ a - add_monoid.smul (nat.pred l) ε : hi.2
... = a - add_monoid.smul l ε + ε :
by conv {to_rhs, rw [← nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hl0), succ_smul',
sub_add, add_sub_cancel] }
... < f j + ε : add_lt_add_right (hl j (le_trans hi.1 hj)) _
end
lemma is_cau_of_mono_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a)
(hnm : ∀ n ≥ m, f n ≤ f n.succ) : is_cau_seq abs f :=
begin
refine @eq.rec_on (ℕ → α) _ (is_cau_seq abs) _ _
(-⟨_, @is_cau_of_decreasing_bounded _ _ _ (λ n, -f n) a m (by simpa) (by simpa)⟩ : cau_seq α abs).2,
ext,
exact neg_neg _
end
lemma is_cau_series_of_abv_le_cau {f : ℕ → β} {g : ℕ → α} (n : ℕ) : (∀ m, n ≤ m → abv (f m) ≤ g m) →
is_cau_seq abs (λ n, (range n).sum g) → is_cau_seq abv (λ n, (range n).sum f) :=
begin
assume hm hg ε ε0,
cases hg (ε / 2) (div_pos ε0 (by norm_num)) with i hi,
existsi max n i,
assume j ji,
have hi₁ := hi j (le_trans (le_max_right n i) ji),
have hi₂ := hi (max n i) (le_max_right n i),
have sub_le := abs_sub_le ((range j).sum g) ((range i).sum g) ((range (max n i)).sum g),
have := add_lt_add hi₁ hi₂,
rw [abs_sub ((range (max n i)).sum g), add_halves ε] at this,
refine lt_of_le_of_lt (le_trans (le_trans _ (le_abs_self _)) sub_le) this,
generalize hk : j - max n i = k,
clear this hi₂ hi₁ hi ε0 ε hg sub_le,
rw nat.sub_eq_iff_eq_add ji at hk,
rw hk,
clear hk ji j,
induction k with k' hi,
{ simp [abv_zero abv] },
{ dsimp at *,
rw [nat.succ_add, sum_range_succ, sum_range_succ, add_assoc, add_assoc],
refine le_trans (abv_add _ _ _) _,
exact add_le_add (hm _ (le_add_of_nonneg_of_le (nat.zero_le _) (le_max_left _ _))) hi },
end
lemma is_cau_series_of_abv_cau {f : ℕ → β} : is_cau_seq abs (λ m, (range m).sum (λ n, abv (f n))) →
is_cau_seq abv (λ m, (range m).sum f) :=
is_cau_series_of_abv_le_cau 0 (λ n h, le_refl _)
lemma is_cau_geo_series {β : Type*} [field β] {abv : β → α} [is_absolute_value abv]
(x : β) (hx1 : abv x < 1) : is_cau_seq abv (λ n, (range n).sum (λ m, x ^ m)) :=
have hx1' : abv x ≠ 1 := λ h, by simpa [h, lt_irrefl] using hx1,
is_cau_series_of_abv_cau
begin
simp only [abv_pow abv, geom_sum hx1'] {eta := ff},
conv in (_ / _) { rw [← neg_div_neg_eq, neg_sub, neg_sub] },
refine @is_cau_of_mono_bounded _ _ _ _ ((1 : α) / (1 - abv x)) 0 _ _,
{ assume n hn,
rw abs_of_nonneg,
refine div_le_div_of_le_of_pos (sub_le_self _ (abv_pow abv x n ▸ abv_nonneg _ _))
(sub_pos.2 hx1),
refine div_nonneg (sub_nonneg.2 _) (sub_pos.2 hx1),
clear hn,
induction n with n ih,
{ simp },
{ rw [_root_.pow_succ, ← one_mul (1 : α)],
refine mul_le_mul (le_of_lt hx1) ih (abv_pow abv x n ▸ abv_nonneg _ _) (by norm_num) } },
{ assume n hn,
refine div_le_div_of_le_of_pos (sub_le_sub_left _ _) (sub_pos.2 hx1),
rw [← one_mul (_ ^ n), _root_.pow_succ],
exact mul_le_mul_of_nonneg_right (le_of_lt hx1) (pow_nonneg (abv_nonneg _ _) _) }
end
lemma is_cau_geo_series_const (a : α) {x : α} (hx1 : abs x < 1) : is_cau_seq abs (λ m, (range m).sum (λ n, a * x ^ n)) :=
have is_cau_seq abs (λ m, a * (range m).sum (λ n, x ^ n)) := (cau_seq.const abs a * ⟨_, is_cau_geo_series x hx1⟩).2,
by simpa only [mul_sum]
lemma series_ratio_test {f : ℕ → β} (n : ℕ) (r : α)
(hr0 : 0 ≤ r) (hr1 : r < 1) (h : ∀ m, n ≤ m → abv (f m.succ) ≤ r * abv (f m)) :
is_cau_seq abv (λ m, (range m).sum f) :=
have har1 : abs r < 1, by rwa abs_of_nonneg hr0,
begin
refine is_cau_series_of_abv_le_cau n.succ _ (is_cau_geo_series_const (abv (f n.succ) * r⁻¹ ^ n.succ) har1),
assume m hmn,
cases classical.em (r = 0) with r_zero r_ne_zero,
{ have m_pos := lt_of_lt_of_le (nat.succ_pos n) hmn,
have := h m.pred (nat.le_of_succ_le_succ (by rwa [nat.succ_pred_eq_of_pos m_pos])),
simpa [r_zero, nat.succ_pred_eq_of_pos m_pos, pow_succ] },
generalize hk : m - n.succ = k,
have r_pos : 0 < r := lt_of_le_of_ne hr0 (ne.symm r_ne_zero),
replace hk : m = k + n.succ := (nat.sub_eq_iff_eq_add hmn).1 hk,
induction k with k ih generalizing m n,
{ rw [hk, zero_add, mul_right_comm, ← pow_inv _ _ r_ne_zero, ← div_eq_mul_inv, mul_div_cancel],
exact (ne_of_lt (pow_pos r_pos _)).symm },
{ have kn : k + n.succ ≥ n.succ, by rw ← zero_add n.succ; exact add_le_add (zero_le _) (by simp),
rw [hk, nat.succ_add, pow_succ' r, ← mul_assoc],
exact le_trans (by rw mul_comm; exact h _ (nat.le_of_succ_le kn))
(mul_le_mul_of_nonneg_right (ih (k + n.succ) n h kn rfl) hr0) }
end
lemma sum_range_diag_flip {α : Type*} [add_comm_monoid α] (n : ℕ) (f : ℕ → ℕ → α) :
(range n).sum (λ m, (range (m + 1)).sum (λ k, f k (m - k))) =
(range n).sum (λ m, (range (n - m)).sum (f m)) :=
have h₁ : ((range n).sigma (range ∘ nat.succ)).sum
(λ (a : Σ m, ℕ), f (a.2) (a.1 - a.2)) =
(range n).sum (λ m, (range (m + 1)).sum
(λ k, f k (m - k))) := sum_sigma,
have h₂ : ((range n).sigma (λ m, range (n - m))).sum (λ a : Σ (m : ℕ), ℕ, f (a.1) (a.2)) =
(range n).sum (λ m, sum (range (n - m)) (f m)) := sum_sigma,
h₁ ▸ h₂ ▸ sum_bij
(λ a _, ⟨a.2, a.1 - a.2⟩)
(λ a ha, have h₁ : a.1 < n := mem_range.1 (mem_sigma.1 ha).1,
have h₂ : a.2 < nat.succ a.1 := mem_range.1 (mem_sigma.1 ha).2,
mem_sigma.2 ⟨mem_range.2 (lt_of_lt_of_le h₂ h₁),
mem_range.2 ((nat.sub_lt_sub_right_iff (nat.le_of_lt_succ h₂)).2 h₁)⟩)
(λ _ _, rfl)
(λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h,
have ha : a₁ < n ∧ a₂ ≤ a₁ :=
⟨mem_range.1 (mem_sigma.1 ha).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 ha).2)⟩,
have hb : b₁ < n ∧ b₂ ≤ b₁ :=
⟨mem_range.1 (mem_sigma.1 hb).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 hb).2)⟩,
have h : a₂ = b₂ ∧ _ := sigma.mk.inj h,
have h' : a₁ = b₁ - b₂ + a₂ := (nat.sub_eq_iff_eq_add ha.2).1 (eq_of_heq h.2),
sigma.mk.inj_iff.2
⟨nat.sub_add_cancel hb.2 ▸ h'.symm ▸ h.1 ▸ rfl,
(heq_of_eq h.1)⟩)
(λ ⟨a₁, a₂⟩ ha,
have ha : a₁ < n ∧ a₂ < n - a₁ :=
⟨mem_range.1 (mem_sigma.1 ha).1, (mem_range.1 (mem_sigma.1 ha).2)⟩,
⟨⟨a₂ + a₁, a₁⟩, ⟨mem_sigma.2 ⟨mem_range.2 (nat.lt_sub_right_iff_add_lt.1 ha.2),
mem_range.2 (nat.lt_succ_of_le (nat.le_add_left _ _))⟩,
sigma.mk.inj_iff.2 ⟨rfl, heq_of_eq (nat.add_sub_cancel _ _).symm⟩⟩⟩)
lemma abv_sum_le_sum_abv {γ : Type*} (f : γ → β) (s : finset γ) :
abv (s.sum f) ≤ s.sum (abv ∘ f) :=
by haveI := classical.dec_eq γ; exact
finset.induction_on s (by simp [abv_zero abv])
(λ a s has ih, by rw [sum_insert has, sum_insert has];
exact le_trans (abv_add abv _ _) (add_le_add_left ih _))
lemma sum_range_sub_sum_range {α : Type*} [add_comm_group α] {f : ℕ → α}
{n m : ℕ} (hnm : n ≤ m) : (range m).sum f - (range n).sum f =
((range m).filter (λ k, n ≤ k)).sum f :=
begin
rw [← sum_sdiff (@filter_subset _ (λ k, n ≤ k) _ (range m)),
sub_eq_iff_eq_add, ← eq_sub_iff_add_eq, add_sub_cancel'],
refine finset.sum_congr
(finset.ext.2 $ λ a, ⟨λ h, by simp at *; finish,
λ h, have ham : a < m := lt_of_lt_of_le (mem_range.1 h) hnm,
by simp * at *⟩)
(λ _ _, rfl),
end
lemma cauchy_product {a b : ℕ → β}
(ha : is_cau_seq abs (λ m, (range m).sum (λ n, abv (a n))))
(hb : is_cau_seq abv (λ m, (range m).sum b)) (ε : α) (ε0 : 0 < ε) :
∃ i : ℕ, ∀ j ≥ i, abv ((range j).sum a * (range j).sum b -
(range j).sum (λ n, (range (n + 1)).sum (λ m, a m * b (n - m)))) < ε :=
let ⟨Q, hQ⟩ := cau_seq.bounded ⟨_, hb⟩ in
let ⟨P, hP⟩ := cau_seq.bounded ⟨_, ha⟩ in
have hP0 : 0 < P, from lt_of_le_of_lt (abs_nonneg _) (hP 0),
have hPε0 : 0 < ε / (2 * P),
from div_pos ε0 (mul_pos (show (2 : α) > 0, from by norm_num) hP0),
let ⟨N, hN⟩ := cau_seq.cauchy₂ ⟨_, hb⟩ hPε0 in
have hQε0 : 0 < ε / (4 * Q),
from div_pos ε0 (mul_pos (show (0 : α) < 4, by norm_num) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))),
let ⟨M, hM⟩ := cau_seq.cauchy₂ ⟨_, ha⟩ hQε0 in
⟨2 * (max N M + 1), λ K hK,
have h₁ : sum (range K) (λ m, (range (m + 1)).sum (λ k, a k * b (m - k))) =
sum (range K) (λ m, sum (range (K - m)) (λ n, a m * b n)),
by simpa using sum_range_diag_flip K (λ m n, a m * b n),
have h₂ : (λ i, (range (K - i)).sum (λ k, a i * b k)) = (λ i, a i * (range (K - i)).sum b),
by simp [finset.mul_sum],
have h₃ : (range K).sum (λ i, a i * (range (K - i)).sum b) =
(range K).sum (λ i, a i * ((range (K - i)).sum b - (range K).sum b))
+ (range K).sum (λ i, a i * (range K).sum b),
by rw ← sum_add_distrib; simp [(mul_add _ _ _).symm],
have two_mul_two : (4 : α) = 2 * 2, by norm_num,
have hQ0 : Q ≠ 0, from λ h, by simpa [h, lt_irrefl] using hQε0,
have h2Q0 : 2 * Q ≠ 0, from mul_ne_zero two_ne_zero hQ0,
have hε : ε / (2 * P) * P + ε / (4 * Q) * (2 * Q) = ε,
by rw [← div_div_eq_div_mul, div_mul_cancel _ (ne.symm (ne_of_lt hP0)),
two_mul_two, mul_assoc, ← div_div_eq_div_mul, div_mul_cancel _ h2Q0, add_halves],
have hNMK : max N M + 1 < K,
from lt_of_lt_of_le (by rw two_mul; exact lt_add_of_pos_left _ (nat.succ_pos _)) hK,
have hKN : N < K,
from calc N ≤ max N M : le_max_left _ _
... < max N M + 1 : nat.lt_succ_self _
... < K : hNMK,
have hsumlesum : (range (max N M + 1)).sum (λ i, abv (a i) *
abv ((range (K - i)).sum b - (range K).sum b)) ≤ (range (max N M + 1)).sum
(λ i, abv (a i) * (ε / (2 * P))),
from sum_le_sum (λ m hmJ, mul_le_mul_of_nonneg_left
(le_of_lt (hN (K - m) K
(nat.le_sub_left_of_add_le (le_trans
(by rw two_mul; exact add_le_add (le_of_lt (mem_range.1 hmJ))
(le_trans (le_max_left _ _) (le_of_lt (lt_add_one _)))) hK))
(le_of_lt hKN))) (abv_nonneg abv _)),
have hsumltP : sum (range (max N M + 1)) (λ n, abv (a n)) < P :=
calc sum (range (max N M + 1)) (λ n, abv (a n))
= abs (sum (range (max N M + 1)) (λ n, abv (a n))) :
eq.symm (abs_of_nonneg (zero_le_sum (λ x h, abv_nonneg abv (a x))))
... < P : hP (max N M + 1),
begin
rw [h₁, h₂, h₃, sum_mul, ← sub_sub, sub_right_comm, sub_self, zero_sub, abv_neg abv],
refine lt_of_le_of_lt (abv_sum_le_sum_abv _ _) _,
suffices : (range (max N M + 1)).sum (λ (i : ℕ), abv (a i) * abv ((range (K - i)).sum b - (range K).sum b)) +
((range K).sum (λ (i : ℕ), abv (a i) * abv ((range (K - i)).sum b - (range K).sum b)) -(range (max N M + 1)).sum
(λ (i : ℕ), abv (a i) * abv ((range (K - i)).sum b - (range K).sum b))) < ε / (2 * P) * P + ε / (4 * Q) * (2 * Q),
{ rw hε at this, simpa [abv_mul abv] },
refine add_lt_add (lt_of_le_of_lt hsumlesum
(by rw [← sum_mul, mul_comm]; exact (mul_lt_mul_left hPε0).mpr hsumltP)) _,
rw sum_range_sub_sum_range (le_of_lt hNMK),
exact calc sum ((range K).filter (λ k, max N M + 1 ≤ k))
(λ i, abv (a i) * abv (sum (range (K - i)) b - sum (range K) b))
≤ sum ((range K).filter (λ k, max N M + 1 ≤ k)) (λ i, abv (a i) * (2 * Q)) :
sum_le_sum (λ n hn, begin
refine mul_le_mul_of_nonneg_left _ (abv_nonneg _ _),
rw sub_eq_add_neg,
refine le_trans (abv_add _ _ _) _,
rw [two_mul, abv_neg abv],
exact add_le_add (le_of_lt (hQ _)) (le_of_lt (hQ _)),
end)
... < ε / (4 * Q) * (2 * Q) :
by rw [← sum_mul, ← sum_range_sub_sum_range (le_of_lt hNMK)];
refine (mul_lt_mul_right $ by rw two_mul;
exact add_pos (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))
(lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))).2
(lt_of_le_of_lt (le_abs_self _)
(hM _ _ (le_trans (nat.le_succ_of_le (le_max_right _ _)) (le_of_lt hNMK))
(nat.le_succ_of_le (le_max_right _ _))))
end⟩
end
open finset
open cau_seq
namespace complex
lemma is_cau_abs_exp (z : ℂ) : is_cau_seq _root_.abs
(λ n, (range n).sum (λ m, abs (z ^ m / nat.fact m))) :=
let ⟨n, hn⟩ := exists_nat_gt (abs z) in
have hn0 : (0 : ℝ) < n, from lt_of_le_of_lt (abs_nonneg _) hn,
series_ratio_test n (complex.abs z / n) (div_nonneg_of_nonneg_of_pos (complex.abs_nonneg _) hn0)
(by rwa [div_lt_iff hn0, one_mul])
(λ m hm,
by rw [abs_abs, abs_abs, nat.fact_succ, pow_succ,
mul_comm m.succ, nat.cast_mul, ← div_div_eq_div_mul, mul_div_assoc,
mul_div_right_comm, abs_mul, abs_div, abs_cast_nat];
exact mul_le_mul_of_nonneg_right
(div_le_div_of_le_left (abs_nonneg _) (nat.cast_pos.2 (nat.succ_pos _)) hn0
(nat.cast_le.2 (le_trans hm (nat.le_succ _)))) (abs_nonneg _))
noncomputable theory
lemma is_cau_exp (z : ℂ) : is_cau_seq abs (λ n, (range n).sum (λ m, z ^ m / nat.fact m)) :=
is_cau_series_of_abv_cau (is_cau_abs_exp z)
def exp' (z : ℂ) : cau_seq ℂ complex.abs := ⟨λ n, (range n).sum (λ m, z ^ m / nat.fact m), is_cau_exp z⟩
def exp (z : ℂ) : ℂ := lim (exp' z)
def sin (z : ℂ) : ℂ := ((exp (-z * I) - exp (z * I)) * I) / 2
def cos (z : ℂ) : ℂ := (exp (z * I) + exp (-z * I)) / 2
def tan (z : ℂ) : ℂ := sin z / cos z
def sinh (z : ℂ) : ℂ := (exp z - exp (-z)) / 2
def cosh (z : ℂ) : ℂ := (exp z + exp (-z)) / 2
def tanh (z : ℂ) : ℂ := sinh z / cosh z
end complex
namespace real
open complex
def exp (x : ℝ) : ℝ := (exp x).re
def sin (x : ℝ) : ℝ := (sin x).re
def cos (x : ℝ) : ℝ := (cos x).re
def tan (x : ℝ) : ℝ := (tan x).re
def sinh (x : ℝ) : ℝ := (sinh x).re
def cosh (x : ℝ) : ℝ := (cosh x).re
def tanh (x : ℝ) : ℝ := (tanh x).re
end real
namespace complex
variables (x y : ℂ)
@[simp] lemma exp_zero : exp 0 = 1 :=
lim_eq_of_equiv_const $
λ ε ε0, ⟨1, λ j hj, begin
convert ε0,
cases j,
{ exact absurd hj (not_le_of_gt zero_lt_one) },
{ dsimp [exp'],
induction j with j ih,
{ dsimp [exp']; simp },
{ rw ← ih dec_trivial,
simp only [sum_range_succ, pow_succ],
simp } }
end⟩
lemma exp_add : exp (x + y) = exp x * exp y :=
show lim (⟨_, is_cau_exp (x + y)⟩ : cau_seq ℂ abs) =
lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp x⟩)
* lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp y⟩),
from
have hj : ∀ j : ℕ, (range j).sum
(λ m, (x + y) ^ m / m.fact) = (range j).sum
(λ i, (range (i + 1)).sum (λ k, x ^ k / k.fact *
(y ^ (i - k) / (i - k).fact))),
from assume j,
finset.sum_congr rfl (λ m hm, begin
rw [add_pow, div_eq_mul_inv, sum_mul],
refine finset.sum_congr rfl (λ i hi, _),
have h₁ : (choose m i : ℂ) ≠ 0 := nat.cast_ne_zero.2
(nat.pos_iff_ne_zero.1 (choose_pos (nat.le_of_lt_succ (mem_range.1 hi)))),
have h₂ := choose_mul_fact_mul_fact (nat.le_of_lt_succ $ finset.mem_range.1 hi),
rw [← h₂, nat.cast_mul, nat.cast_mul, mul_inv', mul_inv'],
simp only [mul_left_comm (choose m i : ℂ), mul_assoc, mul_left_comm (choose m i : ℂ)⁻¹,
mul_comm (choose m i : ℂ)],
rw inv_mul_cancel h₁,
simp [div_eq_mul_inv, mul_comm, mul_assoc, mul_left_comm]
end),
by rw lim_mul_lim;
exact eq.symm (lim_eq_lim_of_equiv (by dsimp; simp only [hj];
exact cauchy_product (is_cau_abs_exp x) (is_cau_exp y)))
lemma exp_nat_mul (x : ℂ) : ∀ n : ℕ, exp(n*x) = (exp x)^n
| 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero]
| (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul]
lemma exp_ne_zero : exp x ≠ 0 :=
λ h, @zero_ne_one ℂ _ $
by rw [← exp_zero, ← add_neg_self x, exp_add, h]; simp
lemma exp_neg : exp (-x) = (exp x)⁻¹ :=
by rw [← domain.mul_left_inj (exp_ne_zero x), ← exp_add];
simp [mul_inv_cancel (exp_ne_zero x)]
lemma exp_sub : exp (x - y) = exp x / exp y :=
by simp [exp_add, exp_neg, div_eq_mul_inv]
@[simp] lemma exp_conj : exp (conj x) = conj (exp x) :=
begin
dsimp [exp],
rw [← lim_conj],
refine congr_arg lim (cau_seq.ext (λ _, _)),
dsimp [exp', function.comp, cau_seq_conj],
rw ← sum_hom conj,
refine sum_congr rfl (λ n hn, _),
rw [conj_div, conj_pow, ← of_real_nat_cast, conj_of_real]
end
@[simp] lemma exp_of_real_im (x : ℝ) : (exp x).im = 0 :=
let ⟨r, hr⟩ := (eq_conj_iff_real (exp x)).1 (by rw [← exp_conj, conj_of_real]) in
by rw [hr, of_real_im]
lemma exp_of_real_re (x : ℝ) : (exp x).re = real.exp x := rfl
@[simp] lemma of_real_exp_of_real_re (x : ℝ) : ((exp x).re : ℂ) = exp x :=
complex.ext (by simp) (by simp)
@[simp] lemma of_real_exp (x : ℝ) : (real.exp x : ℂ) = exp x :=
complex.ext (by simp [real.exp]) (by simp [real.exp])
@[simp] lemma sin_zero : sin 0 = 0 := by simp [sin]
@[simp] lemma sin_neg : sin (-x) = -sin x :=
by simp [sin, exp_neg, (neg_div _ _).symm, add_mul]
lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y :=
begin
rw [← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _),
← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _)],
simp only [mul_add, add_mul, exp_add, div_mul_div, div_add_div_same,
mul_assoc, (div_div_eq_div_mul _ _ _).symm,
mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _), sin, cos],
simp [mul_add, add_mul, exp_add],
ring
end
@[simp] lemma cos_zero : cos 0 = 1 := by simp [cos]
@[simp] lemma cos_neg : cos (-x) = cos x :=
by simp [cos, exp_neg]
lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y :=
begin
rw [← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _),
← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _)],
simp only [mul_add, add_mul, mul_sub, sub_mul, exp_add, div_mul_div,
div_add_div_same, mul_assoc, (div_div_eq_div_mul _ _ _).symm,
mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _), sin, cos],
apply complex.ext; simp [mul_add, add_mul, exp_add]; ring
end
lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y :=
by simp [sin_add, sin_neg, cos_neg]
lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y :=
by simp [cos_add, sin_neg, cos_neg]
lemma sin_conj : sin (conj x) = conj (sin x) :=
begin
rw [sin, ← conj_neg_I, ← conj_mul, ← conj_neg, ← conj_mul,
exp_conj, exp_conj, ← conj_sub, sin, conj_div, conj_two,
← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _),
mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _),
mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _)],
apply complex.ext; simp [sin, neg_add],
end
@[simp] lemma sin_of_real_im (x : ℝ) : (sin x).im = 0 :=
let ⟨r, hr⟩ := (eq_conj_iff_real (sin x)).1 (by rw [← sin_conj, conj_of_real]) in
by rw [hr, of_real_im]
lemma sin_of_real_re (x : ℝ) : (sin x).re = real.sin x := rfl
@[simp] lemma of_real_sin_of_real_re (x : ℝ) : ((sin x).re : ℂ) = sin x :=
by apply complex.ext; simp
@[simp] lemma of_real_sin (x : ℝ) : (real.sin x : ℂ) = sin x :=
by simp [real.sin]
lemma cos_conj : cos (conj x) = conj (cos x) :=
begin
rw [cos, ← conj_neg_I, ← conj_mul, ← conj_neg, ← conj_mul,
exp_conj, exp_conj, cos, conj_div, conj_two,
← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _),
mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _),
mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _)],
apply complex.ext; simp
end
@[simp] lemma cos_of_real_im (x : ℝ) : (cos x).im = 0 :=
let ⟨r, hr⟩ := (eq_conj_iff_real (cos x)).1 (by rw [← cos_conj, conj_of_real]) in
by rw [hr, of_real_im]
lemma cos_of_real_re (x : ℝ) : (cos x).re = real.cos x := rfl
@[simp] lemma of_real_cos_of_real_re (x : ℝ) : ((cos x).re : ℂ) = cos x :=
by apply complex.ext; simp
@[simp] lemma of_real_cos (x : ℝ) : (real.cos x : ℂ) = cos x :=
by simp [real.cos, -cos_of_real_re]
@[simp] lemma tan_zero : tan 0 = 0 := by simp [tan]
lemma tan_eq_sin_div_cos : tan x = sin x / cos x := rfl
@[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div]
lemma tan_conj : tan (conj x) = conj (tan x) :=
by rw [tan, sin_conj, cos_conj, ← conj_div, tan]
@[simp] lemma tan_of_real_im (x : ℝ) : (tan x).im = 0 :=
let ⟨r, hr⟩ := (eq_conj_iff_real (tan x)).1 (by rw [← tan_conj, conj_of_real]) in
by rw [hr, of_real_im]
lemma tan_of_real_re (x : ℝ) : (tan x).re = real.tan x := rfl
@[simp] lemma of_real_tan_of_real_re (x : ℝ) : ((tan x).re : ℂ) = tan x :=
by apply complex.ext; simp
@[simp] lemma of_real_tan (x : ℝ) : (real.tan x : ℂ) = tan x :=
by simp [real.tan, -tan_of_real_re]
lemma sin_pow_two_add_cos_pow_two : sin x ^ 2 + cos x ^ 2 = 1 :=
begin
simp only [pow_two, mul_sub, sub_mul, mul_add, add_mul, div_eq_mul_inv,
neg_mul_eq_neg_mul_symm, exp_neg, mul_comm (exp _), mul_left_comm (exp _),
mul_assoc, mul_left_comm (exp _)⁻¹, inv_mul_cancel (exp_ne_zero _), mul_inv',
mul_one, one_mul, sin, cos],
apply complex.ext; simp [norm_sq]; ring
end
lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 :=
by rw [two_mul, cos_add, ← pow_two, ← pow_two, eq_sub_iff_add_eq.2 (sin_pow_two_add_cos_pow_two x)];
simp [two_mul]
lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x :=
by rw [two_mul, sin_add, two_mul, add_mul, mul_comm]
lemma cos_square : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 :=
by simp [cos_two_mul, div_add_div_same, mul_div_cancel_left, two_ne_zero', -one_div_eq_inv]
lemma sin_square : sin x ^ 2 = 1 - cos x ^ 2 :=
by { rw [←sin_pow_two_add_cos_pow_two x], simp }
lemma exp_mul_I : exp (x * I) = cos x + sin x * I :=
by rw [cos, sin, mul_comm (_ / 2) I, ← mul_div_assoc, mul_left_comm I, I_mul_I,
← add_div]; simp
lemma exp_add_mul_I : exp (x + y * I) = exp x * (cos y + sin y * I) :=
by rw [exp_add, exp_mul_I]
lemma exp_eq_exp_re_mul_sin_add_cos : exp x = exp x.re * (cos x.im + sin x.im * I) :=
by rw [← exp_add_mul_I, re_add_im]
theorem cos_add_sin_mul_I_pow (n : ℕ) (z : ℂ) : (cos z + sin z * I) ^ n = cos (↑n * z) + sin (↑n * z) * I :=
begin
rw [← exp_mul_I, ← exp_mul_I],
induction n with n ih,
{ rw [pow_zero, nat.cast_zero, zero_mul, zero_mul, exp_zero] },
{ rw [pow_succ', ih, nat.cast_succ, add_mul, add_mul, one_mul, exp_add] }
end
@[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh]
@[simp] lemma sinh_neg : sinh (-x) = -sinh x :=
by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul]
lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y :=
begin
rw [← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _),
← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _)],
simp only [mul_add, add_mul, exp_add, div_mul_div, div_add_div_same,
mul_assoc, (div_div_eq_div_mul _ _ _).symm,
mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _), sinh, cosh],
simp [mul_add, add_mul, exp_add],
ring
end
@[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh]
@[simp] lemma cosh_neg : cosh (-x) = cosh x :=
by simp [cosh, exp_neg]
lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y :=
begin
rw [← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _),
← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _)],
simp only [mul_add, add_mul, mul_sub, sub_mul, exp_add, div_mul_div,
div_add_div_same, mul_assoc, (div_div_eq_div_mul _ _ _).symm,
mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _), sinh, cosh],
apply complex.ext; simp [mul_add, add_mul, exp_add]; ring
end
lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y :=
by simp [sinh_add, sinh_neg, cosh_neg]
lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y :=
by simp [cosh_add, sinh_neg, cosh_neg]
lemma sinh_conj : sinh (conj x) = conj (sinh x) :=
by rw [sinh, ← conj_neg, exp_conj, exp_conj, ← conj_sub, sinh, conj_div, conj_two]
@[simp] lemma sinh_of_real_im (x : ℝ) : (sinh x).im = 0 :=
let ⟨r, hr⟩ := (eq_conj_iff_real (sinh x)).1 (by rw [← sinh_conj, conj_of_real]) in
by rw [hr, of_real_im]
lemma sinh_of_real_re (x : ℝ) : (sinh x).re = real.sinh x := rfl
@[simp] lemma of_real_sinh_of_real_re (x : ℝ) : ((sinh x).re : ℂ) = sinh x :=
by apply complex.ext; simp
@[simp] lemma of_real_sinh (x : ℝ) : (real.sinh x : ℂ) = sinh x :=
by simp [real.sinh]
lemma cosh_conj : cosh (conj x) = conj (cosh x) :=
by rw [cosh, ← conj_neg, exp_conj, exp_conj, ← conj_add, cosh, conj_div, conj_two]
@[simp] lemma cosh_of_real_im (x : ℝ) : (cosh x).im = 0 :=
let ⟨r, hr⟩ := (eq_conj_iff_real (cosh x)).1 (by rw [← cosh_conj, conj_of_real]) in
by rw [hr, of_real_im]
lemma cosh_of_real_re (x : ℝ) : (cosh x).re = real.cosh x := rfl
@[simp] lemma of_real_cosh_of_real_re (x : ℝ) : ((cosh x).re : ℂ) = cosh x :=
by apply complex.ext; simp
@[simp] lemma of_real_cosh (x : ℝ) : (real.cosh x : ℂ) = cosh x :=
by simp [real.cosh]
lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := rfl
@[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh]
@[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div]
lemma tanh_conj : tanh (conj x) = conj (tanh x) :=
by rw [tanh, sinh_conj, cosh_conj, ← conj_div, tanh]
@[simp] lemma tanh_of_real_im (x : ℝ) : (tanh x).im = 0 :=
let ⟨r, hr⟩ := (eq_conj_iff_real (tanh x)).1 (by rw [← tanh_conj, conj_of_real]) in
by rw [hr, of_real_im]
lemma tanh_of_real_re (x : ℝ) : (tanh x).re = real.tanh x := rfl
@[simp] lemma of_real_tanh_of_real_re (x : ℝ) : ((tanh x).re : ℂ) = tanh x :=
by apply complex.ext; simp
@[simp] lemma of_real_tanh (x : ℝ) : (real.tanh x : ℂ) = tanh x :=
by simp [real.tanh]
end complex
namespace real
open complex
variables (x y : ℝ)
@[simp] lemma exp_zero : exp 0 = 1 :=
by simp [real.exp]
lemma exp_add : exp (x + y) = exp x * exp y :=
by simp [exp_add, exp]
lemma exp_nat_mul (x : ℝ) : ∀ n : ℕ, exp(n*x) = (exp x)^n
| 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero]
| (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul]
lemma exp_ne_zero : exp x ≠ 0 :=
λ h, exp_ne_zero x $ by rw [exp, ← of_real_inj] at h; simp * at *
lemma exp_neg : exp (-x) = (exp x)⁻¹ :=
by rw [← of_real_inj, exp, of_real_exp_of_real_re, of_real_neg, exp_neg,
of_real_inv, of_real_exp]
lemma exp_sub : exp (x - y) = exp x / exp y :=
by simp [exp_add, exp_neg, div_eq_mul_inv]
@[simp] lemma sin_zero : sin 0 = 0 := by simp [sin]
@[simp] lemma sin_neg : sin (-x) = -sin x :=
by simp [sin, exp_neg, (neg_div _ _).symm, add_mul]
lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y :=
by rw [← of_real_inj]; simp [sin, sin_add]
@[simp] lemma cos_zero : cos 0 = 1 := by simp [cos]
@[simp] lemma cos_neg : cos (-x) = cos x :=
by simp [cos, exp_neg]
lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y :=
by rw ← of_real_inj; simp [cos, cos_add]
lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y :=
by simp [sin_add, sin_neg, cos_neg]
lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y :=
by simp [cos_add, sin_neg, cos_neg]
lemma tan_eq_sin_div_cos : tan x = sin x / cos x :=
if h : complex.cos x = 0 then by simp [sin, cos, tan, *, complex.tan, div_eq_mul_inv] at *
else
by rw [sin, cos, tan, complex.tan, ← of_real_inj, div_eq_mul_inv, mul_re];
simp [norm_sq, (div_div_eq_div_mul _ _ _).symm, div_self h]; refl
@[simp] lemma tan_zero : tan 0 = 0 := by simp [tan]
@[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div]
lemma sin_pow_two_add_cos_pow_two : sin x ^ 2 + cos x ^ 2 = 1 :=
by rw ← of_real_inj; simpa [sin, of_real_pow] using sin_pow_two_add_cos_pow_two x
lemma abs_sin_le_one : abs' (sin x) ≤ 1 :=
not_lt.1 $ λ h, lt_irrefl (1 * 1 : ℝ)
(calc 1 * 1 < abs' (sin x) * abs' (sin x) :
mul_lt_mul h (le_of_lt h) zero_lt_one (le_trans zero_le_one (le_of_lt h))
... = sin x ^ 2 : by rw [← _root_.abs_mul, abs_mul_self, pow_two]
... ≤ sin x ^ 2 + cos x ^ 2 : le_add_of_nonneg_right (pow_two_nonneg _)
... = 1 * 1 : by rw [sin_pow_two_add_cos_pow_two, one_mul])
lemma abs_cos_le_one : abs' (cos x) ≤ 1 :=
not_lt.1 $ λ h, lt_irrefl (1 * 1 : ℝ)
(calc 1 * 1 < abs' (cos x) * abs' (cos x) :
mul_lt_mul h (le_of_lt h) zero_lt_one (le_trans zero_le_one (le_of_lt h))
... = cos x ^ 2 : by rw [← _root_.abs_mul, abs_mul_self, pow_two]
... ≤ sin x ^ 2 + cos x ^ 2 : le_add_of_nonneg_left (pow_two_nonneg _)
... = 1 * 1 : by rw [sin_pow_two_add_cos_pow_two, one_mul])
lemma sin_le_one : sin x ≤ 1 :=
(abs_le.1 (abs_sin_le_one _)).2
lemma cos_le_one : cos x ≤ 1 :=
(abs_le.1 (abs_cos_le_one _)).2
lemma neg_one_le_sin : -1 ≤ sin x :=
(abs_le.1 (abs_sin_le_one _)).1
lemma neg_one_le_cos : -1 ≤ cos x :=
(abs_le.1 (abs_cos_le_one _)).1
lemma sin_pow_two_le_one : sin x ^ 2 ≤ 1 :=
by rw [pow_two, ← abs_mul_self, _root_.abs_mul];
exact mul_le_one (abs_sin_le_one _) (abs_nonneg _) (abs_sin_le_one _)
lemma cos_pow_two_le_one : cos x ^ 2 ≤ 1 :=
by rw [pow_two, ← abs_mul_self, _root_.abs_mul];
exact mul_le_one (abs_cos_le_one _) (abs_nonneg _) (abs_cos_le_one _)
lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 :=
by rw ← of_real_inj; simp [cos_two_mul, cos, pow_two]
lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x :=
by rw ← of_real_inj; simp [sin_two_mul, sin, pow_two]
lemma cos_square : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 :=
by simp [cos_two_mul, div_add_div_same, mul_div_cancel_left, two_ne_zero, -one_div_eq_inv]
lemma sin_square : sin x ^ 2 = 1 - cos x ^ 2 :=
by { rw [←sin_pow_two_add_cos_pow_two x], simp }
@[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh]
@[simp] lemma sinh_neg : sinh (-x) = -sinh x :=
by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul]
lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y :=
by rw ← of_real_inj; simp [sinh, sinh_add]
@[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh]
@[simp] lemma cosh_neg : cosh (-x) = cosh x :=
by simp [cosh, exp_neg]
lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y :=
by rw ← of_real_inj; simp [cosh, cosh_add]
lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y :=
by simp [sinh_add, sinh_neg, cosh_neg]
lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y :=
by simp [cosh_add, sinh_neg, cosh_neg]
lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x :=
if h : complex.cosh x = 0 then by simp [sinh, cosh, tanh, *, complex.tanh, div_eq_mul_inv] at *
else
by rw [sinh, cosh, tanh, complex.tanh, ← of_real_inj, div_eq_mul_inv, mul_re];
simp [norm_sq, (div_div_eq_div_mul _ _ _).symm, div_self h]; refl
@[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh]
@[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div]
open is_absolute_value
/- TODO make this private and prove ∀ x -/
lemma add_one_le_exp_of_nonneg {x : ℝ} (hx : 0 ≤ x) : x + 1 ≤ exp x :=
calc x + 1 ≤ lim (⟨(λ n : ℕ, ((exp' x) n).re), is_cau_seq_re (exp' x)⟩ : cau_seq ℝ abs') :
le_lim (cau_seq.le_of_exists ⟨2,
λ j hj, show x + (1 : ℝ) ≤ ((range j).sum (λ m, (x ^ m / m.fact : ℂ))).re,
from have h₁ : (((λ m : ℕ, (x ^ m / m.fact : ℂ)) ∘ nat.succ) 0).re = x, by simp,
have h₂ : ((x : ℂ) ^ 0 / nat.fact 0).re = 1, by simp,
begin
rw [← nat.sub_add_cancel hj, sum_range_succ', sum_range_succ',
add_re, add_re, h₁, h₂, add_assoc,
← @sum_hom _ _ _ _ _ _ _ complex.re
(is_add_group_hom.to_is_add_monoid_hom _)],
refine le_add_of_nonneg_of_le (zero_le_sum (λ m hm, _)) (le_refl _), dsimp [-nat.fact_succ],
rw [← of_real_pow, ← of_real_nat_cast, ← of_real_div, of_real_re],
exact div_nonneg (pow_nonneg hx _) (nat.cast_pos.2 (nat.fact_pos _)),
end⟩)
... = exp x : by rw [exp, complex.exp, ← cau_seq_re, lim_re]
lemma one_le_exp {x : ℝ} (hx : 0 ≤ x) : 1 ≤ exp x :=
by linarith using [add_one_le_exp_of_nonneg hx]
lemma exp_pos (x : ℝ) : 0 < exp x :=
(le_total 0 x).elim (lt_of_lt_of_le zero_lt_one ∘ one_le_exp)
(λ h, by rw [← neg_neg x, real.exp_neg];
exact inv_pos (lt_of_lt_of_le zero_lt_one (one_le_exp (neg_nonneg.2 h))))
@[simp] lemma abs_exp (x : ℝ) : abs' (exp x) = exp x :=
abs_of_nonneg (le_of_lt (exp_pos _))
lemma exp_lt_exp {x y : ℝ} (h : x < y) : exp x < exp y :=
by rw [← sub_add_cancel y x, real.exp_add];
exact (lt_mul_iff_one_lt_left (exp_pos _)).2
(lt_of_lt_of_le (by linarith) (add_one_le_exp_of_nonneg (by linarith)))
lemma exp_le_exp {x y : ℝ} : real.exp x ≤ real.exp y ↔ x ≤ y :=
⟨λ h, le_of_not_gt $ mt exp_lt_exp $ by simpa, λ h, by rw [←sub_add_cancel y x, real.exp_add];
exact (le_mul_iff_one_le_left (exp_pos _)).2 (one_le_exp (sub_nonneg.2 h))⟩
lemma exp_injective : function.injective exp :=
λ x y h, begin
rcases lt_trichotomy x y with h₁ | h₁ | h₁,
{ exact absurd h (ne_of_lt (exp_lt_exp h₁)) },
{ exact h₁ },
{ exact absurd h (ne.symm (ne_of_lt (exp_lt_exp h₁))) }
end
@[simp] lemma exp_eq_one_iff : exp x = 1 ↔ x = 0 :=
⟨by rw ← exp_zero; exact λ h, exp_injective h, λ h, by rw [h, exp_zero]⟩
end real
namespace complex
lemma sum_div_fact_le {α : Type*} [discrete_linear_ordered_field α] (n j : ℕ) (hn : 0 < n) :
(sum (filter (λ k, n ≤ k) (range j)) (λ m : ℕ, (1 / m.fact : α))) ≤ n.succ * (n.fact * n)⁻¹ :=
calc (filter (λ k, n ≤ k) (range j)).sum (λ m : ℕ, (1 / m.fact : α))
= (range (j - n)).sum (λ m, 1 / (m + n).fact) :
sum_bij (λ m _, m - n)
(λ m hm, mem_range.2 $ (nat.sub_lt_sub_right_iff (by simp at hm; tauto)).2
(by simp at hm; tauto))
(λ m hm, by rw nat.sub_add_cancel; simp at *; tauto)
(λ a₁ a₂ ha₁ ha₂ h,
by rwa [nat.sub_eq_iff_eq_add, ← nat.sub_add_comm, eq_comm, nat.sub_eq_iff_eq_add, add_right_inj, eq_comm] at h;
simp at *; tauto)
(λ b hb, ⟨b + n, mem_filter.2 ⟨mem_range.2 $ nat.add_lt_of_lt_sub_right (mem_range.1 hb), nat.le_add_left _ _⟩,
by rw nat.add_sub_cancel⟩)
... ≤ (range (j - n)).sum (λ m, (nat.fact n * n.succ ^ m)⁻¹) :
begin
refine sum_le_sum (assume m n, _),
rw [one_div_eq_inv, inv_le_inv],
{ rw [← nat.cast_pow, ← nat.cast_mul, nat.cast_le, add_comm],
exact nat.fact_mul_pow_le_fact },
{ exact nat.cast_pos.2 (nat.fact_pos _) },
{ exact mul_pos (nat.cast_pos.2 (nat.fact_pos _)) (pow_pos (nat.cast_pos.2 (nat.succ_pos _)) _) },
end
... = (nat.fact n)⁻¹ * (range (j - n)).sum (λ m, n.succ⁻¹ ^ m) :
by simp [mul_inv', mul_sum.symm, sum_mul.symm, -nat.fact_succ, mul_comm, inv_pow']
... = (n.succ - n.succ * n.succ⁻¹ ^ (j - n)) / (n.fact * n) :
have h₁ : (n.succ : α) ≠ 1, from @nat.cast_one α _ _ ▸ mt nat.cast_inj.1
(mt nat.succ_inj (nat.pos_iff_ne_zero.1 hn)),
have h₂ : (n.succ : α) ≠ 0, from nat.cast_ne_zero.2 (nat.succ_ne_zero _),
have h₃ : (n.fact * n : α) ≠ 0, from mul_ne_zero (nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 (nat.fact_pos _)))
(nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 hn)),
have h₄ : (n.succ - 1 : α) = n, by simp,
by rw [geom_sum_inv h₁ h₂, eq_div_iff_mul_eq _ _ h₃, mul_comm _ (n.fact * n : α),
← mul_assoc (n.fact⁻¹ : α), ← mul_inv', h₄, ← mul_assoc (n.fact * n : α),
mul_comm (n : α) n.fact, mul_inv_cancel h₃];
simp [mul_add, add_mul, mul_assoc, mul_comm]
... ≤ n.succ / (n.fact * n) :
begin
refine (div_le_div_right (mul_pos _ _)).2 _,
exact nat.cast_pos.2 (nat.fact_pos _),
exact nat.cast_pos.2 hn,
exact sub_le_self _ (mul_nonneg (nat.cast_nonneg _) (pow_nonneg (inv_nonneg.2 (nat.cast_nonneg _)) _))
end
lemma exp_bound {x : ℂ} (hx : abs x ≤ 1) {n : ℕ} (hn : 0 < n) :
abs (exp x - (range n).sum (λ m, x ^ m / m.fact)) ≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹) :=
begin
rw [← lim_const ((range n).sum _), exp, sub_eq_add_neg, ← lim_neg, lim_add, ← lim_abs],
refine lim_le (cau_seq.le_of_exists ⟨n, λ j hj, _⟩),
show abs ((range j).sum (λ m, x ^ m / m.fact) - (range n).sum (λ m, x ^ m / m.fact))
≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹),
rw sum_range_sub_sum_range hj,
exact calc abs (((range j).filter (λ k, n ≤ k)).sum (λ m : ℕ, (x ^ m / m.fact : ℂ)))
= abs (((range j).filter (λ k, n ≤ k)).sum (λ m : ℕ, (x ^ n * (x ^ (m - n) / m.fact) : ℂ))) :
congr_arg abs (sum_congr rfl (λ m hm, by rw [← mul_div_assoc, ← pow_add, nat.add_sub_cancel']; simp at hm; tauto))
... ≤ sum (filter (λ k, n ≤ k) (range j)) (λ m, abs (x ^ n * (_ / m.fact))) : abv_sum_le_sum_abv _ _
... ≤ sum (filter (λ k, n ≤ k) (range j)) (λ m, abs x ^ n * (1 / m.fact)) :
begin
refine sum_le_sum (λ m hm, _),
rw [abs_mul, abv_pow abs, abs_div, abs_cast_nat],
refine mul_le_mul_of_nonneg_left ((div_le_div_right _).2 _) _,
exact nat.cast_pos.2 (nat.fact_pos _),
rw abv_pow abs,
exact (pow_le_one _ (abs_nonneg _) hx),
exact pow_nonneg (abs_nonneg _) _
end
... = abs x ^ n * (((range j).filter (λ k, n ≤ k)).sum (λ m : ℕ, (1 / m.fact : ℝ))) :
by simp [abs_mul, abv_pow abs, abs_div, mul_sum.symm]
... ≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹) :
mul_le_mul_of_nonneg_left (sum_div_fact_le _ _ hn) (pow_nonneg (abs_nonneg _) _)
end
lemma abs_exp_sub_one_le {x : ℂ} (hx : abs x ≤ 1) :
abs (exp x - 1) ≤ 2 * abs x :=
calc abs (exp x - 1) = abs (exp x - (range 1).sum (λ m, x ^ m / m.fact)) :
by simp [sum_range_succ]
... ≤ abs x ^ 1 * ((nat.succ 1) * (nat.fact 1 * (1 : ℕ))⁻¹) :
exp_bound hx dec_trivial
... = 2 * abs x : by simp [two_mul, mul_two, mul_add, mul_comm]
end complex
namespace real
open complex finset
lemma cos_bound {x : ℝ} (hx : abs' x ≤ 1) : abs' (cos x - (1 - x ^ 2 / 2)) ≤ abs' x ^ 4 * (5 / 96) :=
calc abs' (cos x - (1 - x ^ 2 / 2)) = abs (complex.cos x - (1 - x ^ 2 / 2)) :
by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv]
... = abs ((complex.exp (x * I) + complex.exp (-x * I) - (2 - x ^ 2)) / 2) :
by simp [complex.cos, sub_div, add_div, neg_div, div_self (@two_ne_zero' ℂ _ _ _)]
... = abs (((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact)) +
((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact)))) / 2) :
congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin
simp only [sum_range_succ],
simp [pow_succ],
apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring
end)
... ≤ abs ((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact)) / 2) +
abs ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact)) / 2) :
by rw add_div; exact abs_add _ _
... = (abs ((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact))) / 2 +
abs ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact))) / 2) :
by simp [complex.abs_div]
... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2 +
(complex.abs (-x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2) :
add_le_add ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial))
((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial))
... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc]
lemma sin_bound {x : ℝ} (hx : abs' x ≤ 1) : abs' (sin x - (x - x ^ 3 / 6)) ≤ abs' x ^ 4 * (5 / 96) :=
calc abs' (sin x - (x - x ^ 3 / 6)) = abs (complex.sin x - (x - x ^ 3 / 6)) :
by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv]
... = abs (((complex.exp (-x * I) - complex.exp (x * I)) * I - (2 * x - x ^ 3 / 3)) / 2) :
by simp [complex.sin, sub_div, add_div, neg_div, mul_div_cancel_left _ (@two_ne_zero' ℂ _ _ _),
div_div_eq_div_mul, show (3 : ℂ) * 2 = 6, by norm_num]
... = abs ((((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact)) -
(complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact))) * I) / 2) :
congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin
simp only [sum_range_succ],
simp [pow_succ],
apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring
end)
... ≤ abs ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact)) * I / 2) +
abs (-((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact)) * I) / 2) :
by rw [sub_mul, sub_eq_add_neg, add_div]; exact abs_add _ _
... = (abs ((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact))) / 2 +
abs ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact))) / 2) :
by simp [complex.abs_div, complex.abs_mul]
... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2 +
(complex.abs (-x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2) :
add_le_add ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial))
((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial))
... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc]
lemma cos_pos_of_le_one {x : ℝ} (hx : abs' x ≤ 1) : 0 < cos x :=
calc 0 < (1 - x ^ 2 / 2) - abs' x ^ 4 * (5 / 96) :
sub_pos.2 $ lt_sub_iff_add_lt.2
(calc abs' x ^ 4 * (5 / 96) + x ^ 2 / 2
≤ 1 * (5 / 96) + 1 / 2 :
add_le_add
(mul_le_mul_of_nonneg_right (pow_le_one _ (abs_nonneg _) hx) (by norm_num))
((div_le_div_right (by norm_num)).2 (by rw [pow_two, ← abs_mul_self, _root_.abs_mul];
exact mul_le_one hx (abs_nonneg _) hx))
... < 1 : by norm_num)
... ≤ cos x : sub_le.1 (abs_sub_le_iff.1 (cos_bound hx)).2
lemma sin_pos_of_pos_of_le_one {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 1) : 0 < sin x :=
calc 0 < x - x ^ 3 / 6 - abs' x ^ 4 * (5 / 96) :
sub_pos.2 $ lt_sub_iff_add_lt.2
(calc abs' x ^ 4 * (5 / 96) + x ^ 3 / 6
≤ x * (5 / 96) + x / 6 :
add_le_add
(mul_le_mul_of_nonneg_right
(calc abs' x ^ 4 ≤ abs' x ^ 1 : pow_le_pow_of_le_one (abs_nonneg _)
(by rwa _root_.abs_of_nonneg (le_of_lt hx0))
dec_trivial
... = x : by simp [_root_.abs_of_nonneg (le_of_lt (hx0))]) (by norm_num))
((div_le_div_right (by norm_num)).2
(calc x ^ 3 ≤ x ^ 1 : pow_le_pow_of_le_one (le_of_lt hx0) hx dec_trivial
... = x : pow_one _))
... < x : by linarith)
... ≤ sin x : sub_le.1 (abs_sub_le_iff.1 (sin_bound
(by rwa [_root_.abs_of_nonneg (le_of_lt hx0)]))).2
lemma sin_pos_of_pos_of_le_two {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 2) : 0 < sin x :=
have x / 2 ≤ 1, from div_le_of_le_mul (by norm_num) (by simpa),
calc 0 < 2 * sin (x / 2) * cos (x / 2) :
mul_pos (mul_pos (by norm_num) (sin_pos_of_pos_of_le_one (half_pos hx0) this))
(cos_pos_of_le_one (by rwa [_root_.abs_of_nonneg (le_of_lt (half_pos hx0))]))
... = sin x : by rw [← sin_two_mul, two_mul, add_halves]
lemma cos_one_le : cos 1 ≤ 2 / 3 :=
calc cos 1 ≤ abs' (1 : ℝ) ^ 4 * (5 / 96) + (1 - 1 ^ 2 / 2) :
sub_le_iff_le_add.1 (abs_sub_le_iff.1 (cos_bound (by simp))).1
... ≤ 2 / 3 : by norm_num
lemma cos_one_pos : 0 < cos 1 := cos_pos_of_le_one (by simp)
lemma cos_two_neg : cos 2 < 0 :=
calc cos 2 = cos (2 * 1) : congr_arg cos (mul_one _).symm
... = _ : real.cos_two_mul 1
... ≤ 2 * (2 / 3) ^ 2 - 1 :
sub_le_sub_right (mul_le_mul_of_nonneg_left
(by rw [pow_two, pow_two]; exact
mul_self_le_mul_self (le_of_lt cos_one_pos)
cos_one_le)
(by norm_num)) _
... < 0 : by norm_num
end real
namespace complex
lemma abs_cos_add_sin_mul_I (x : ℝ) : abs (cos x + sin x * I) = 1 :=
have _ := real.sin_pow_two_add_cos_pow_two x,
by simp [abs, norm_sq, pow_two, *, sin_of_real_re, cos_of_real_re, mul_re] at *
lemma abs_exp_eq_iff_re_eq {x y : ℂ} : abs (exp x) = abs (exp y) ↔ x.re = y.re :=
by rw [exp_eq_exp_re_mul_sin_add_cos, exp_eq_exp_re_mul_sin_add_cos y,
abs_mul, abs_mul, abs_cos_add_sin_mul_I, abs_cos_add_sin_mul_I,
← of_real_exp, ← of_real_exp, abs_of_nonneg (le_of_lt (real.exp_pos _)),
abs_of_nonneg (le_of_lt (real.exp_pos _)), mul_one, mul_one];
exact ⟨λ h, real.exp_injective h, congr_arg _⟩
@[simp] lemma abs_exp_of_real (x : ℝ) : abs (exp x) = real.exp x :=
by rw [← of_real_exp]; exact abs_of_nonneg (le_of_lt (real.exp_pos _))
end complex
|
379c9fb8d6d408e27d5e60fa9e4eb9943d1e2ae7 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /tests/playground/uf1_new.lean | bb355fbcedb41f841baafe65388e15f4c911181a | [
"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 | 4,397 | lean | def StateT (m : Type → Type) (σ : Type) (α : Type) := (Unit × σ) → m (α × σ)
namespace StateT
variables {m : Type → Type} [Monad m] {σ : Type} {α β : Type}
@[inline] protected def pure (a : α) : StateT m σ α := λ ⟨_, s⟩, pure (a, s)
@[inline] protected def bind (x : StateT m σ α) (f : α → StateT m σ β) : StateT m σ β := λ p, do (a, s') ← x p, f a ((), s')
@[inline] def read : StateT m σ σ := λ ⟨_, s⟩, pure (s, s)
@[inline] def write (s' : σ) : StateT m σ Unit := λ ⟨_, s⟩, pure ((), s')
@[inline] def updt (f : σ → σ) : StateT m σ Unit := λ ⟨_, s⟩, pure ((), f s)
instance : Monad (StateT m σ) :=
{pure := @StateT.pure _ _ _, bind := @StateT.bind _ _ _}
end StateT
def ExceptT (m : Type → Type) (ε : Type) (α : Type) := m (Except ε α)
namespace ExceptT
variables {m : Type → Type} [Monad m] {ε : Type} {α β : Type}
@[inline] protected def pure (a : α) : ExceptT m ε α := (pure (Except.ok a) : m (Except ε α))
@[inline] protected def bind (x : ExceptT m ε α) (f : α → ExceptT m ε β) : ExceptT m ε β :=
(do { v ← x, match v with
| Except.error e := pure (Except.error e)
| Except.ok a := f a } : m (Except ε β))
@[inline] def error (e : ε) : ExceptT m ε α := (pure (Except.error e) : m (Except ε α))
@[inline] def lift (x : m α) : ExceptT m ε α := (do {a ← x, pure (Except.ok a) } : m (Except ε α))
instance : Monad (ExceptT m ε) :=
{pure := @ExceptT.pure _ _ _, bind := @ExceptT.bind _ _ _}
end ExceptT
abbreviation Node := Nat
structure nodeData :=
(find : Node) (rank : Nat := 0)
abbreviation ufData := Array nodeData
abbreviation M (α : Type) := ExceptT (StateT id ufData) String α
@[inline] def read : M ufData := ExceptT.lift StateT.read
@[inline] def write (s : ufData) : M Unit := ExceptT.lift (StateT.write s)
@[inline] def updt (f : ufData → ufData) : M Unit := ExceptT.lift (StateT.updt f)
def error {α : Type} (e : String) : M α := ExceptT.error e
def run {α : Type} (x : M α) (s : ufData := Array.nil) : Except String α × ufData :=
x ((), s)
def capacity : M Nat :=
do d ← read, pure d.size
def findEntryAux : Nat → Node → M nodeData
| 0 n := error "out of fuel"
| (i+1) n :=
do s ← read,
if h : n < s.size then
do { let e := s.read ⟨n, h⟩,
if e.find = n then pure e
else do e₁ ← findEntryAux i e.find,
updt (λ s, s.write' n e₁),
pure e₁ }
else error "invalid Node"
def findEntry (n : Node) : M nodeData :=
do c ← capacity,
findEntryAux c n
def find (n : Node) : M Node :=
do e ← findEntry n, pure e.find
def mk : M Node :=
do n ← capacity,
updt $ λ s, s.push {find := n, rank := 1},
pure n
def union (n₁ n₂ : Node) : M Unit :=
do r₁ ← findEntry n₁,
r₂ ← findEntry n₂,
if r₁.find = r₂.find then pure ()
else updt $ λ s,
if r₁.rank < r₂.rank then s.write' r₁.find { find := r₂.find }
else if r₁.rank = r₂.rank then
let s₁ := s.write' r₁.find { find := r₂.find } in
s₁.write' r₂.find { rank := r₂.rank + 1, .. r₂}
else s.write' r₂.find { find := r₁.find }
def mkNodes : Nat → M Unit
| 0 := pure ()
| (n+1) := mk *> mkNodes n
def checkEq (n₁ n₂ : Node) : M Unit :=
do r₁ ← find n₁, r₂ ← find n₂,
unless (r₁ = r₂) $ error "nodes are not equal"
def mergePackAux : Nat → Nat → Nat → M Unit
| 0 _ _ := pure ()
| (i+1) n d :=
do c ← capacity,
if (n+d) < c
then union n (n+d) *> mergePackAux i (n+1) d
else pure ()
def mergePack (d : Nat) : M Unit :=
do c ← capacity, mergePackAux c 0 d
def numEqsAux : Nat → Node → Nat → M Nat
| 0 _ r := pure r
| (i+1) n r :=
do c ← capacity,
if n < c
then do { n₁ ← find n, numEqsAux i (n+1) (if n = n₁ then r else r+1) }
else pure r
def numEqs : M Nat :=
do c ← capacity,
numEqsAux c 0 0
def test (n : Nat) : M Nat :=
if n < 2 then error "input must be greater than 1"
else do
mkNodes n,
mergePack 50000,
mergePack 10000,
mergePack 5000,
mergePack 1000,
numEqs
def main (xs : List String) : IO UInt32 :=
let n := xs.head.toNat in
match run (test n) with
| (Except.ok v, s) := IO.println ("ok " ++ toString v) *> pure 0
| (Except.error e, s) := IO.println ("Error : " ++ e) *> pure 1
|
108ae776470fe48883b5a7cd1e181e1eea18ba67 | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/deprecated/submonoid.lean | fe7b4598c6f544114e36f6df823b8b7f108211e6 | [
"Apache-2.0"
] | permissive | stjordanis/mathlib | 51e286d19140e3788ef2c470bc7b953e4991f0c9 | 2568d41bca08f5d6bf39d915434c8447e21f42ee | refs/heads/master | 1,631,748,053,501 | 1,627,938,886,000 | 1,627,938,886,000 | 228,728,358 | 0 | 0 | Apache-2.0 | 1,576,630,588,000 | 1,576,630,587,000 | null | UTF-8 | Lean | false | false | 17,153 | lean | /-
Copyright (c) 2018 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Kenny Lau, Johan Commelin, Mario Carneiro, Kevin Buzzard
-/
import group_theory.submonoid.basic
import algebra.big_operators.basic
import deprecated.group
/-!
# Unbundled submonoids
This file defines unbundled multiplicative and additive submonoids `is_submonoid` and
`is_add_submonoid`. These are not the preferred way to talk about submonoids and should
not be used for any new projects. The preferred way in mathlib are the bundled
versions `submonoid G` and `add_submonoid G`.
## Main definitions
`is_add_submonoid (S : set G)` : the predicate that `S` is the underlying subset of an additive
submonoid of `G`. The bundled variant `add_subgroup G` should be used in preference to this.
`is_submonoid (S : set G)` : the predicate that `S` is the underlying subset of a submonoid
of `G`. The bundled variant `submonoid G` should be used in preference to this.
## Tags
subgroup, subgroups, is_subgroup
## Tags
submonoid, submonoids, is_submonoid
-/
open_locale big_operators
variables {M : Type*} [monoid M] {s : set M}
variables {A : Type*} [add_monoid A] {t : set A}
/-- `s` is an additive submonoid: a set containing 0 and closed under addition.
Note that this structure is deprecated, and the bundled variant `add_submonoid A` should be
preferred. -/
structure is_add_submonoid (s : set A) : Prop :=
(zero_mem : (0:A) ∈ s)
(add_mem {a b} : a ∈ s → b ∈ s → a + b ∈ s)
/-- `s` is a submonoid: a set containing 1 and closed under multiplication.
Note that this structure is deprecated, and the bundled variant `submonoid M` should be
preferred. -/
@[to_additive]
structure is_submonoid (s : set M) : Prop :=
(one_mem : (1:M) ∈ s)
(mul_mem {a b} : a ∈ s → b ∈ s → a * b ∈ s)
lemma additive.is_add_submonoid
{s : set M} : ∀ (is : is_submonoid s), @is_add_submonoid (additive M) _ s
| ⟨h₁, h₂⟩ := ⟨h₁, @h₂⟩
theorem additive.is_add_submonoid_iff
{s : set M} : @is_add_submonoid (additive M) _ s ↔ is_submonoid s :=
⟨λ ⟨h₁, h₂⟩, ⟨h₁, @h₂⟩, additive.is_add_submonoid⟩
lemma multiplicative.is_submonoid
{s : set A} : ∀ (is : is_add_submonoid s), @is_submonoid (multiplicative A) _ s
| ⟨h₁, h₂⟩ := ⟨h₁, @h₂⟩
theorem multiplicative.is_submonoid_iff
{s : set A} : @is_submonoid (multiplicative A) _ s ↔ is_add_submonoid s :=
⟨λ ⟨h₁, h₂⟩, ⟨h₁, @h₂⟩, multiplicative.is_submonoid⟩
/-- The intersection of two submonoids of a monoid `M` is a submonoid of `M`. -/
@[to_additive "The intersection of two `add_submonoid`s of an `add_monoid` `M` is
an `add_submonoid` of M."]
lemma is_submonoid.inter {s₁ s₂ : set M} (is₁ : is_submonoid s₁) (is₂ : is_submonoid s₂) :
is_submonoid (s₁ ∩ s₂) :=
{ one_mem := ⟨is₁.one_mem, is₂.one_mem⟩,
mul_mem := λ x y hx hy,
⟨is₁.mul_mem hx.1 hy.1, is₂.mul_mem hx.2 hy.2⟩ }
/-- The intersection of an indexed set of submonoids of a monoid `M` is a submonoid of `M`. -/
@[to_additive "The intersection of an indexed set of `add_submonoid`s of an `add_monoid` `M` is
an `add_submonoid` of `M`."]
lemma is_submonoid.Inter {ι : Sort*} {s : ι → set M} (h : ∀ y : ι, is_submonoid (s y)) :
is_submonoid (set.Inter s) :=
{ one_mem := set.mem_Inter.2 $ λ y, (h y).one_mem,
mul_mem := λ x₁ x₂ h₁ h₂, set.mem_Inter.2 $
λ y, (h y).mul_mem (set.mem_Inter.1 h₁ y) (set.mem_Inter.1 h₂ y) }
/-- The union of an indexed, directed, nonempty set of submonoids of a monoid `M` is a submonoid
of `M`. -/
@[to_additive "The union of an indexed, directed, nonempty set
of `add_submonoid`s of an `add_monoid` `M` is an `add_submonoid` of `M`. "]
lemma is_submonoid_Union_of_directed {ι : Type*} [hι : nonempty ι]
{s : ι → set M} (hs : ∀ i, is_submonoid (s i))
(directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) :
is_submonoid (⋃i, s i) :=
{ one_mem := let ⟨i⟩ := hι in set.mem_Union.2 ⟨i, (hs i).one_mem⟩,
mul_mem := λ a b ha hb,
let ⟨i, hi⟩ := set.mem_Union.1 ha in
let ⟨j, hj⟩ := set.mem_Union.1 hb in
let ⟨k, hk⟩ := directed i j in
set.mem_Union.2 ⟨k, (hs k).mul_mem (hk.1 hi) (hk.2 hj)⟩ }
section powers
/-- The set of natural number powers `1, x, x², ...` of an element `x` of a monoid. -/
def powers (x : M) : set M := {y | ∃ n:ℕ, x^n = y}
/-- The set of natural number multiples `0, x, 2x, ...` of an element `x` of an `add_monoid`. -/
def multiples (x : A) : set A := {y | ∃ n:ℕ, n • x = y}
attribute [to_additive multiples] powers
/-- 1 is in the set of natural number powers of an element of a monoid. -/
lemma powers.one_mem {x : M} : (1 : M) ∈ powers x := ⟨0, pow_zero _⟩
/-- 0 is in the set of natural number multiples of an element of an `add_monoid`. -/
lemma multiples.zero_mem {x : A} : (0 : A) ∈ multiples x := ⟨0, zero_nsmul _⟩
attribute [to_additive] powers.one_mem
/-- An element of a monoid is in the set of that element's natural number powers. -/
lemma powers.self_mem {x : M} : x ∈ powers x := ⟨1, pow_one _⟩
/-- An element of an `add_monoid` is in the set of that element's natural number multiples. -/
lemma multiples.self_mem {x : A} : x ∈ multiples x := ⟨1, one_nsmul _⟩
attribute [to_additive] powers.self_mem
/-- The set of natural number powers of an element of a monoid is closed under multiplication. -/
lemma powers.mul_mem {x y z : M} : (y ∈ powers x) → (z ∈ powers x) → (y * z ∈ powers x) :=
λ ⟨n₁, h₁⟩ ⟨n₂, h₂⟩, ⟨n₁ + n₂, by simp only [pow_add, *]⟩
/-- The set of natural number multiples of an element of an `add_monoid` is closed under
addition. -/
lemma multiples.add_mem {x y z : A} :
(y ∈ multiples x) → (z ∈ multiples x) → (y + z ∈ multiples x) :=
@powers.mul_mem (multiplicative A) _ _ _ _
attribute [to_additive] powers.mul_mem
/-- The set of natural number powers of an element of a monoid `M` is a submonoid of `M`. -/
@[to_additive "The set of natural number multiples of an element of
an `add_monoid` `M` is an `add_submonoid` of `M`."]
lemma powers.is_submonoid (x : M) : is_submonoid (powers x) :=
{ one_mem := powers.one_mem,
mul_mem := λ y z, powers.mul_mem }
/-- A monoid is a submonoid of itself. -/
@[to_additive "An `add_monoid` is an `add_submonoid` of itself."]
lemma univ.is_submonoid : is_submonoid (@set.univ M) := by split; simp
/-- The preimage of a submonoid under a monoid hom is a submonoid of the domain. -/
@[to_additive "The preimage of an `add_submonoid` under an `add_monoid` hom is
an `add_submonoid` of the domain."]
lemma is_submonoid.preimage {N : Type*} [monoid N] {f : M → N} (hf : is_monoid_hom f)
{s : set N} (hs : is_submonoid s) : is_submonoid (f ⁻¹' s) :=
{ one_mem := show f 1 ∈ s, by rw is_monoid_hom.map_one hf; exact hs.one_mem,
mul_mem := λ a b (ha : f a ∈ s) (hb : f b ∈ s),
show f (a * b) ∈ s, by rw is_monoid_hom.map_mul hf; exact hs.mul_mem ha hb }
/-- The image of a submonoid under a monoid hom is a submonoid of the codomain. -/
@[to_additive "The image of an `add_submonoid` under an `add_monoid`
hom is an `add_submonoid` of the codomain."]
lemma is_submonoid.image {γ : Type*} [monoid γ] {f : M → γ} (hf : is_monoid_hom f)
{s : set M} (hs : is_submonoid s) : is_submonoid (f '' s) :=
{ one_mem := ⟨1, hs.one_mem, hf.map_one⟩,
mul_mem := λ a b ⟨x, hx⟩ ⟨y, hy⟩, ⟨x * y, hs.mul_mem hx.1 hy.1,
by rw [hf.map_mul, hx.2, hy.2]⟩ }
/-- The image of a monoid hom is a submonoid of the codomain. -/
@[to_additive "The image of an `add_monoid` hom is an `add_submonoid`
of the codomain."]
lemma range.is_submonoid {γ : Type*} [monoid γ] {f : M → γ} (hf : is_monoid_hom f) :
is_submonoid (set.range f) :=
by { rw ← set.image_univ, exact univ.is_submonoid.image hf }
/-- Submonoids are closed under natural powers. -/
lemma is_submonoid.pow_mem {a : M} (hs : is_submonoid s) (h : a ∈ s) : ∀ {n : ℕ}, a ^ n ∈ s
| 0 := by { rw pow_zero, exact hs.one_mem }
| (n + 1) := by { rw pow_succ, exact hs.mul_mem h is_submonoid.pow_mem }
/-- An `add_submonoid` is closed under multiplication by naturals. -/
lemma is_add_submonoid.smul_mem {a : A} (ht : is_add_submonoid t) :
∀ (h : a ∈ t) {n : ℕ}, n • a ∈ t :=
@is_submonoid.pow_mem (multiplicative A) _ _ _ (multiplicative.is_submonoid ht)
attribute [to_additive smul_mem] is_submonoid.pow_mem
/-- The set of natural number powers of an element of a submonoid is a subset of the submonoid. -/
lemma is_submonoid.power_subset {a : M} (hs : is_submonoid s) (h : a ∈ s) : powers a ⊆ s :=
assume x ⟨n, hx⟩, hx ▸ hs.pow_mem h
/-- The set of natural number multiples of an element of an `add_submonoid` is a subset of the
`add_submonoid`. -/
lemma is_add_submonoid.multiple_subset {a : A} (ht : is_add_submonoid t) :
a ∈ t → multiples a ⊆ t :=
@is_submonoid.power_subset (multiplicative A) _ _ _ (multiplicative.is_submonoid ht)
attribute [to_additive multiple_subset] is_submonoid.power_subset
end powers
namespace is_submonoid
/-- The product of a list of elements of a submonoid is an element of the submonoid. -/
@[to_additive "The sum of a list of elements of an `add_submonoid` is an element of the
`add_submonoid`."]
lemma list_prod_mem (hs : is_submonoid s) : ∀{l : list M}, (∀x∈l, x ∈ s) → l.prod ∈ s
| [] h := hs.one_mem
| (a::l) h :=
suffices a * l.prod ∈ s, by simpa,
have a ∈ s ∧ (∀x∈l, x ∈ s), by simpa using h,
hs.mul_mem this.1 (list_prod_mem this.2)
/-- The product of a multiset of elements of a submonoid of a `comm_monoid` is an element of
the submonoid. -/
@[to_additive "The sum of a multiset of elements of an `add_submonoid` of an `add_comm_monoid`
is an element of the `add_submonoid`. "]
lemma multiset_prod_mem {M} [comm_monoid M] {s : set M} (hs : is_submonoid s) (m : multiset M) :
(∀a∈m, a ∈ s) → m.prod ∈ s :=
begin
refine quotient.induction_on m (assume l hl, _),
rw [multiset.quot_mk_to_coe, multiset.coe_prod],
exact list_prod_mem hs hl
end
/-- The product of elements of a submonoid of a `comm_monoid` indexed by a `finset` is an element
of the submonoid. -/
@[to_additive "The sum of elements of an `add_submonoid` of an `add_comm_monoid` indexed by
a `finset` is an element of the `add_submonoid`."]
lemma finset_prod_mem {M A} [comm_monoid M] {s : set M} (hs : is_submonoid s) (f : A → M) :
∀(t : finset A), (∀b∈t, f b ∈ s) → ∏ b in t, f b ∈ s
| ⟨m, hm⟩ _ := multiset_prod_mem hs _ (by simpa)
end is_submonoid
namespace add_monoid
/-- The inductively defined membership predicate for the submonoid generated by a subset of a
monoid. -/
inductive in_closure (s : set A) : A → Prop
| basic {a : A} : a ∈ s → in_closure a
| zero : in_closure 0
| add {a b : A} : in_closure a → in_closure b → in_closure (a + b)
end add_monoid
namespace monoid
/-- The inductively defined membership predicate for the `add_submonoid` generated by a subset of an
add_monoid. -/
inductive in_closure (s : set M) : M → Prop
| basic {a : M} : a ∈ s → in_closure a
| one : in_closure 1
| mul {a b : M} : in_closure a → in_closure b → in_closure (a * b)
attribute [to_additive] monoid.in_closure
attribute [to_additive] monoid.in_closure.one
attribute [to_additive] monoid.in_closure.mul
/-- The inductively defined submonoid generated by a subset of a monoid. -/
@[to_additive "The inductively defined `add_submonoid` genrated by a subset of an `add_monoid`."]
def closure (s : set M) : set M := {a | in_closure s a }
@[to_additive]
lemma closure.is_submonoid (s : set M) : is_submonoid (closure s) :=
{ one_mem := in_closure.one, mul_mem := assume a b, in_closure.mul }
/-- A subset of a monoid is contained in the submonoid it generates. -/
@[to_additive "A subset of an `add_monoid` is contained in the `add_submonoid` it generates."]
theorem subset_closure {s : set M} : s ⊆ closure s :=
assume a, in_closure.basic
/-- The submonoid generated by a set is contained in any submonoid that contains the set. -/
@[to_additive "The `add_submonoid` generated by a set is contained in any `add_submonoid` that
contains the set."]
theorem closure_subset {s t : set M} (ht : is_submonoid t) (h : s ⊆ t) : closure s ⊆ t :=
assume a ha, by induction ha; simp [h _, *, is_submonoid.one_mem, is_submonoid.mul_mem]
/-- Given subsets `t` and `s` of a monoid `M`, if `s ⊆ t`, the submonoid of `M` generated by `s` is
contained in the submonoid generated by `t`. -/
@[to_additive "Given subsets `t` and `s` of an `add_monoid M`, if `s ⊆ t`, the `add_submonoid`
of `M` generated by `s` is contained in the `add_submonoid` generated by `t`."]
theorem closure_mono {s t : set M} (h : s ⊆ t) : closure s ⊆ closure t :=
closure_subset (closure.is_submonoid t) $ set.subset.trans h subset_closure
/-- The submonoid generated by an element of a monoid equals the set of natural number powers of
the element. -/
@[to_additive "The `add_submonoid` generated by an element of an `add_monoid` equals the set of
natural number multiples of the element."]
theorem closure_singleton {x : M} : closure ({x} : set M) = powers x :=
set.eq_of_subset_of_subset (closure_subset (powers.is_submonoid x) $ set.singleton_subset_iff.2 $
powers.self_mem) $ is_submonoid.power_subset (closure.is_submonoid _) $
set.singleton_subset_iff.1 $ subset_closure
/-- The image under a monoid hom of the submonoid generated by a set equals the submonoid generated
by the image of the set under the monoid hom. -/
@[to_additive "The image under an `add_monoid` hom of the `add_submonoid` generated by a set equals
the `add_submonoid` generated by the image of the set under the `add_monoid` hom."]
lemma image_closure {A : Type*} [monoid A] {f : M → A} (hf : is_monoid_hom f) (s : set M) :
f '' closure s = closure (f '' s) :=
le_antisymm
begin
rintros _ ⟨x, hx, rfl⟩,
apply in_closure.rec_on hx; intros,
{ solve_by_elim [subset_closure, set.mem_image_of_mem] },
{ rw [hf.map_one], apply is_submonoid.one_mem (closure.is_submonoid (f '' s))},
{ rw [hf.map_mul], solve_by_elim [(closure.is_submonoid _).mul_mem] }
end
(closure_subset (is_submonoid.image hf (closure.is_submonoid _)) $
set.image_subset _ subset_closure)
/-- Given an element `a` of the submonoid of a monoid `M` generated by a set `s`, there exists
a list of elements of `s` whose product is `a`. -/
@[to_additive "Given an element `a` of the `add_submonoid` of an `add_monoid M` generated by
a set `s`, there exists a list of elements of `s` whose sum is `a`."]
theorem exists_list_of_mem_closure {s : set M} {a : M} (h : a ∈ closure s) :
(∃l:list M, (∀x∈l, x ∈ s) ∧ l.prod = a) :=
begin
induction h,
case in_closure.basic : a ha { existsi ([a]), simp [ha] },
case in_closure.one { existsi ([]), simp },
case in_closure.mul : a b _ _ ha hb {
rcases ha with ⟨la, ha, eqa⟩,
rcases hb with ⟨lb, hb, eqb⟩,
existsi (la ++ lb),
simp [eqa.symm, eqb.symm, or_imp_distrib],
exact assume a, ⟨ha a, hb a⟩
}
end
/-- Given sets `s, t` of a commutative monoid `M`, `x ∈ M` is in the submonoid of `M` generated by
`s ∪ t` iff there exists an element of the submonoid generated by `s` and an element of the
submonoid generated by `t` whose product is `x`. -/
@[to_additive "Given sets `s, t` of a commutative `add_monoid M`, `x ∈ M` is in the `add_submonoid`
of `M` generated by `s ∪ t` iff there exists an element of the `add_submonoid` generated by `s`
and an element of the `add_submonoid` generated by `t` whose sum is `x`."]
theorem mem_closure_union_iff {M : Type*} [comm_monoid M] {s t : set M} {x : M} :
x ∈ closure (s ∪ t) ↔ ∃ y ∈ closure s, ∃ z ∈ closure t, y * z = x :=
⟨λ hx, let ⟨L, HL1, HL2⟩ := exists_list_of_mem_closure hx in HL2 ▸
list.rec_on L (λ _, ⟨1, (closure.is_submonoid _).one_mem, 1,
(closure.is_submonoid _).one_mem, mul_one _⟩)
(λ hd tl ih HL1, let ⟨y, hy, z, hz, hyzx⟩ := ih (list.forall_mem_of_forall_mem_cons HL1) in
or.cases_on (HL1 hd $ list.mem_cons_self _ _)
(λ hs, ⟨hd * y, (closure.is_submonoid _).mul_mem (subset_closure hs) hy, z, hz,
by rw [mul_assoc, list.prod_cons, ← hyzx]; refl⟩)
(λ ht, ⟨y, hy, z * hd, (closure.is_submonoid _).mul_mem hz (subset_closure ht),
by rw [← mul_assoc, list.prod_cons, ← hyzx, mul_comm hd]; refl⟩)) HL1,
λ ⟨y, hy, z, hz, hyzx⟩, hyzx ▸ (closure.is_submonoid _).mul_mem
(closure_mono (set.subset_union_left _ _) hy)
(closure_mono (set.subset_union_right _ _) hz)⟩
end monoid
/-- Create a bundled submonoid from a set `s` and `[is_submonoid s]`. -/
@[to_additive "Create a bundled additive submonoid from a set `s` and `[is_add_submonoid s]`."]
def submonoid.of {s : set M} (h : is_submonoid s) : submonoid M := ⟨s, h.1, h.2⟩
@[to_additive]
lemma submonoid.is_submonoid (S : submonoid M) : is_submonoid (S : set M) := ⟨S.2, S.3⟩
|
b17ac60b1f31d8af6bb866d1cb58da33e32b0f57 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/param_binder_update.lean | bc58d874d8da168667a7b1f7e73a5725a980ab2e | [
"Apache-2.0"
] | permissive | soonhokong/lean-osx | 4a954262c780e404c1369d6c06516161d07fcb40 | 3670278342d2f4faa49d95b46d86642d7875b47c | refs/heads/master | 1,611,410,334,552 | 1,474,425,686,000 | 1,474,425,686,000 | 12,043,103 | 5 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 1,130 | lean | section
parameter {A : Type*}
parameter A
-- definition id (a : A) := a
parameter {A}
definition id₂ (a : A) := a
end
check @id
check @id₂
section
parameters {A : Type*} {B : Type*}
definition foo1 (a : A) (b : B) := a
parameters {A} (B)
definition foo2 (a : A) (b : B) := a
parameters (A) {B}
definition foo3 (a : A) (b : B) := a
parameters (A) (B)
definition foo4 (a : A) (b : B) := a
check @foo1
check @foo2
check @foo3
check @foo4
end
check @foo1
check @foo2
check @foo3
check @foo4
section
variables {A : Type*} {B : Type*}
definition boo1 (a : A) (b : B) := a
variables {A} (B)
definition boo2 (a : A) (b : B) := a
variables (A) {B}
definition boo3 (a : A) (b : B) := a
variables (A) (B)
definition boo4 (a : A) (b : B) := a
check @boo1
check @boo2
check @boo3
check @boo4
end
section
variables {A : Type*} {B : Type*}
parameter (A) -- ERROR
variable (C) -- ERROR
variables (C) (D) -- ERROR
variables C -- ERROR
definition id3 (a : A) := a
parameter id3 -- ERROR
parameter (C : Type)
variables {C} -- ERROR
end
|
aec1714150655f3a74d97127df636fb0478013b3 | 5412d79aa1dc0b521605c38bef9f0d4557b5a29d | /tests/lean/run/newfrontend1.lean | ed8a462d3f682d3cc7d88361f21ad180766ffa01 | [
"Apache-2.0"
] | permissive | smunix/lean4 | a450ec0927dc1c74816a1bf2818bf8600c9fc9bf | 3407202436c141e3243eafbecb4b8720599b970a | refs/heads/master | 1,676,334,875,188 | 1,610,128,510,000 | 1,610,128,521,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,769 | lean | def x := 1
#check x
variables {α : Type}
def f (a : α) : α :=
a
def tst (xs : List Nat) : Nat :=
xs.foldl (init := 10) (· + ·)
#check tst [1, 2, 3]
#check fun x y : Nat => x + y
#check tst
#check (fun stx => if True then let e := stx; Pure.pure e else Pure.pure stx : Nat → Id Nat)
#check let x : Nat := 1; x
def foo (a : Nat) (b : Nat := 10) (c : Bool := Bool.true) : Nat :=
a + b
set_option pp.all true
#check foo 1
#check foo 3 (c := false)
def Nat.boo (a : Nat) :=
succ a -- succ here is resolved as `Nat.succ`.
#check Nat.boo
#check true
-- apply is still a valid identifier name
def apply := "hello"
#check apply
theorem simple1 (x y : Nat) (h : x = y) : x = y :=
by {
assumption
}
theorem simple2 (x y : Nat) : x = y → x = y :=
by {
intro h;
assumption
}
syntax "intro2" : tactic
macro_rules
| `(tactic| intro2) => `(tactic| intro; intro )
theorem simple3 (x y : Nat) : x = x → x = y → x = y :=
by {
intro2;
assumption
}
macro "intro3" : tactic => `(intro; intro; intro)
macro "check2" x:term : command => `(#check $x #check $x)
macro "foo" x:term "," y:term : term => `($x + $y + $x)
set_option pp.all false
check2 0+1
check2 foo 0,1
theorem simple4 (x y : Nat) : y = y → x = x → x = y → x = y :=
by {
intro3;
assumption
}
theorem simple5 (x y z : Nat) : y = z → x = x → x = y → x = z :=
by {
intro h1; intro _; intro h3;
exact Eq.trans h3 h1
}
theorem simple6 (x y z : Nat) : y = z → x = x → x = y → x = z :=
by {
intro h1; intro _; intro h3;
refine Eq.trans ?_ h1;
assumption
}
theorem simple7 (x y z : Nat) : y = z → x = x → x = y → x = z :=
by {
intro h1; intro _; intro h3;
refine! Eq.trans ?pre ?post;
exact y;
{ exact h3 }
{ exact h1 }
}
theorem simple8 (x y z : Nat) : y = z → x = x → x = y → x = z := by
intro h1; intro _; intro h3
refine! Eq.trans ?pre ?post
case post => exact h1
case pre => exact h3
theorem simple9 (x y z : Nat) : y = z → x = x → x = y → x = z := by
intros h1 _ h3
traceState
focus
refine! Eq.trans ?pre ?post
first
| exact h1
assumption
| exact y
exact h3
assumption
theorem simple9b (x y z : Nat) : y = z → x = x → x = y → x = z := by
intros h1 _ h3
traceState
focus
refine! Eq.trans ?pre ?post
first
| exact h1
| exact y; exact h3
assumption
theorem simple9c (x y z : Nat) : y = z → x = x → x = y → x = z := by
intros h1 _ h3
solve
| exact h1
| refine! Eq.trans ?pre ?post; exact y; exact h3; assumption
| exact h3
theorem simple9d (x y z : Nat) : y = z → x = x → x = y → x = z := by
intros h1 _ h3
refine! Eq.trans ?pre ?post
solve
| exact h1
| exact y
| exact h3
solve
| exact h1
| exact h3
solve
| exact h1
| assumption
namespace Foo
def Prod.mk := 1
#check (⟨2, 3⟩ : Prod _ _)
end Foo
theorem simple10 (x y z : Nat) : y = z → x = x → x = y → x = z :=
by {
intro h1; intro h2; intro h3;
skip;
apply Eq.trans;
exact h3;
assumption
}
theorem simple11 (x y z : Nat) : y = z → x = x → x = y → x = z :=
by {
intro h1; intro h2; intro h3;
apply @Eq.trans;
traceState;
exact h3;
assumption
}
theorem simple12 (x y z : Nat) : y = z → x = x → x = y → x = z :=
by {
intro h1; intro h2; intro h3;
apply @Eq.trans;
try exact h1; -- `exact h1` fails
traceState;
try exact h3;
traceState;
try exact h1;
}
theorem simple13 (x y z : Nat) : y = z → x = x → x = y → x = z := by
intros h1 h2 h3
traceState
apply @Eq.trans
case b => exact y
traceState
repeat assumption
theorem simple13b (x y z : Nat) : y = z → x = x → x = y → x = z := by {
intros h1 h2 h3;
traceState;
apply @Eq.trans;
case b => exact y;
traceState;
repeat assumption
}
theorem simple14 (x y z : Nat) : y = z → x = x → x = y → x = z := by
intros
apply @Eq.trans
case b => exact y
repeat assumption
theorem simple15 (x y z : Nat) : y = z → x = x → x = y → x = z :=
by {
intros h1 h2 h3;
revert y;
intros y h1 h3;
apply Eq.trans;
exact h3;
exact h1
}
theorem simple16 (x y z : Nat) : y = z → x = x → x = y → x = z :=
by {
intros h1 h2 h3;
try clear x; -- should fail
clear h2;
traceState;
apply Eq.trans;
exact h3;
exact h1
}
macro "blabla" : tactic => `(assumption)
-- Tactic head symbols do not become reserved words
def blabla := 100
#check blabla
theorem simple17 (x : Nat) (h : x = 0) : x = 0 :=
by blabla
theorem simple18 (x : Nat) (h : x = 0) : x = 0 :=
by blabla
theorem simple19 (x y : Nat) (h₁ : x = 0) (h₂ : x = y) : y = 0 :=
by subst x; subst y; exact rfl
theorem tstprec1 (x y z : Nat) : x + y * z = x + (y * z) :=
rfl
theorem tstprec2 (x y z : Nat) : y * z + x = (y * z) + x :=
rfl
set_option pp.all true
#check fun {α} (a : α) => a
#check @(fun α (a : α) => a)
#check
let myid := fun {α} (a : α) => a;
myid [myid 1]
-- In the following example, we need `@` otherwise we will try to insert mvars for α and [Add α],
-- and will fail to generate instance for [Add α]
#check @(fun α (s : Add α) (a : α) => a + a)
def g1 {α} (a₁ a₂ : α) {β} (b : β) : α × α × β :=
(a₁, a₂, b)
def id1 : {α : Type} → α → α :=
fun x => x
def listId : List ({α : Type} → α → α) :=
(fun x => x) :: []
def id2 : {α : Type} → α → α :=
@(fun α (x : α) => id1 x)
def id3 : {α : Type} → α → α :=
@(fun α x => id1 x)
def id4 : {α : Type} → α → α :=
fun x => id1 x
def id5 : {α : Type} → α → α :=
fun {α} x => id1 x
def id6 : {α : Type} → α → α :=
@(fun {α} x => id1 x)
def id7 : {α : Type} → α → α :=
fun {α} x => @id α x
def id8 : {α : Type} → α → α :=
fun {α} x => id (@id α x)
def altTst1 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) :=
⟨StateT.failure, StateT.orElse⟩
def altTst2 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) :=
⟨@(fun α => StateT.failure), @(fun α => StateT.orElse)⟩
def altTst3 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) :=
⟨fun {α} => StateT.failure, fun {α} => StateT.orElse⟩
#check_failure 1 + true
/-
universes u v
/-
MonadFunctorT.{u ?M_1 v} (λ (β : Type u), m α) (λ (β : Type u), m' α) n n'
-/
set_option pp.raw.maxDepth 100
set_option trace.Elab true
def adapt {m m' σ σ'} {n n' : Type → Type} [MonadFunctor m m' n n'] [MonadStateAdapter σ σ' m m'] : MonadStateAdapter σ σ' n n' :=
⟨fun split join => monadMap (adaptState split join : m α → m' α)⟩
-/
syntax "fn" (term:max)+ "=>" term : term
macro_rules
| `(fn $xs* => $b) => `(fun $xs* => $b)
set_option pp.all false
#check fn x => x+1
#check fn α (a : α) => a
def tst1 : {α : Type} → α → α :=
@(fn α a => a)
#check @tst1
syntax ident "==>" term : term
syntax "{" ident "}" "==>" term : term
macro_rules
| `($x:ident ==> $b) => `(fn $x => $b)
| `({$x:ident} ==> $b) => `(fun {$x:ident} => $b)
#check x ==> x+1
def tst2a : {α : Type} → α → α :=
@(α ==> a ==> a)
def tst2b : {α : Type} → α → α :=
{α} ==> a ==> a
#check @tst2a
#check @tst2b
def tst3a : {α : Type} → {β : Type} → α → β → α × β :=
@(α ==> @(β ==> a ==> b ==> (a, b)))
def tst3b : {α : Type} → {β : Type} → α → β → α × β :=
{α} ==> {β} ==> a ==> b ==> (a, b)
syntax "function" (term:max)+ "=>" term : term
macro_rules
| `(function $xs* => $b) => `(@(fun $xs* => $b))
def tst4 : {α : Type} → {β : Type} → α → β → α × β :=
function α β a b => (a, b)
theorem simple20 (x y z : Nat) : y = z → x = x → x = y → x = z :=
by intros h1 h2 h3;
try clear x; -- should fail
clear h2;
traceState;
apply Eq.trans;
exact h3;
exact h1
theorem simple21 (x y z : Nat) : y = z → x = x → y = x → x = z :=
fun h1 _ h3 =>
have x = y from by { apply Eq.symm; assumption };
Eq.trans this (by assumption)
theorem simple22 (x y z : Nat) : y = z → y = x → id (x = z + 0) :=
fun h1 h2 => show x = z + 0 by
apply Eq.trans
exact h2.symm
assumption
skip
theorem simple23 (x y z : Nat) : y = z → x = x → y = x → x = z :=
fun h1 _ h3 =>
have x = y by apply Eq.symm; assumption
Eq.trans this (by assumption)
theorem simple24 (x y z : Nat) : y = z → x = x → y = x → x = z :=
fun h1 _ h3 =>
have h : x = y by apply Eq.symm; assumption
Eq.trans h (by assumption)
def f1 (x : Nat) : Nat :=
let double x := x + x
let rec loop x :=
match x with
| 0 => 0
| x+1 => loop x + double x
loop x
#eval f1 5
def f2 (x : Nat) : String :=
let bad x : String := toString x
bad x
def f3 x y :=
x + y + 1
theorem f3eq x y : f3 x y = x + y + 1 :=
rfl
def f4 x y : String :=
if x > y + 1 then "hello" else "world"
|
61a517329123d93c55c9d6bf529db8918c8316cf | 4727251e0cd73359b15b664c3170e5d754078599 | /src/topology/order/hom/esakia.lean | 067ada35f16217b04112260fe9560cd7c0dbd561 | [
"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,876 | 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 order.hom.bounded
import order.hom.order
import topology.order.hom.basic
/-!
# Esakia morphisms
This file defines pseudo-epimorphisms and Esakia morphisms.
We use the `fun_like` design, so each type of morphisms has a companion typeclass which is meant to
be satisfied by itself and all stricter types.
## Types of morphisms
* `pseudo_epimorphism`: Pseudo-epimorphisms. Maps `f` such that `f a ≤ b` implies the existence of
`a'` such that `a ≤ a'` and `f a' = b`.
* `esakia_hom`: Esakia morphisms. Continuous pseudo-epimorphisms.
## Typeclasses
* `pseudo_epimorphism_class`
* `esakia_hom_class`
## References
* [Wikipedia, *Esakia space*](https://en.wikipedia.org/wiki/Esakia_space)
-/
open function
variables {F α β γ δ : Type*}
/-- The type of pseudo-epimorphisms, aka p-morphisms, aka bounded maps, from `α` to `β`. -/
structure pseudo_epimorphism (α β : Type*) [preorder α] [preorder β] extends α →o β :=
(exists_map_eq_of_map_le' ⦃a : α⦄ ⦃b : β⦄ : to_fun a ≤ b → ∃ c, a ≤ c ∧ to_fun c = b)
/-- The type of Esakia morphisms, aka continuous pseudo-epimorphisms, from `α` to `β`. -/
structure esakia_hom (α β : Type*) [topological_space α] [preorder α] [topological_space β]
[preorder β] extends α →Co β :=
(exists_map_eq_of_map_le' ⦃a : α⦄ ⦃b : β⦄ : to_fun a ≤ b → ∃ c, a ≤ c ∧ to_fun c = b)
/-- `pseudo_epimorphism_class F α β` states that `F` is a type of `⊔`-preserving morphisms.
You should extend this class when you extend `pseudo_epimorphism`. -/
class pseudo_epimorphism_class (F : Type*) (α β : out_param $ Type*) [preorder α] [preorder β]
extends rel_hom_class F ((≤) : α → α → Prop) ((≤) : β → β → Prop) :=
(exists_map_eq_of_map_le (f : F) ⦃a : α⦄ ⦃b : β⦄ : f a ≤ b → ∃ c, a ≤ c ∧ f c = b)
/-- `esakia_hom_class F α β` states that `F` is a type of lattice morphisms.
You should extend this class when you extend `esakia_hom`. -/
class esakia_hom_class (F : Type*) (α β : out_param $ Type*) [topological_space α] [preorder α]
[topological_space β] [preorder β]
extends continuous_order_hom_class F α β :=
(exists_map_eq_of_map_le (f : F) ⦃a : α⦄ ⦃b : β⦄ : f a ≤ b → ∃ c, a ≤ c ∧ f c = b)
export pseudo_epimorphism_class (exists_map_eq_of_map_le)
@[priority 100] -- See note [lower instance priority]
instance pseudo_epimorphism_class.to_top_hom_class [partial_order α] [order_top α] [preorder β]
[order_top β] [pseudo_epimorphism_class F α β] : top_hom_class F α β :=
⟨λ f, let ⟨b, h⟩ := exists_map_eq_of_map_le f (@le_top _ _ _ $ f ⊤) in
by rw [←top_le_iff.1 h.1, h.2]⟩
@[priority 100] -- See note [lower instance priority]
instance order_iso_class.to_pseudo_epimorphism_class [preorder α] [preorder β]
[order_iso_class F α β] : pseudo_epimorphism_class F α β :=
⟨λ f a b h, ⟨equiv_like.inv f b, (le_map_inv_iff f).2 h, equiv_like.right_inv _ _⟩⟩
@[priority 100] -- See note [lower instance priority]
instance esakia_hom_class.to_pseudo_epimorphism_class [topological_space α] [preorder α]
[topological_space β] [preorder β] [esakia_hom_class F α β] : pseudo_epimorphism_class F α β :=
{ .. ‹esakia_hom_class F α β› }
instance [preorder α] [preorder β] [pseudo_epimorphism_class F α β] :
has_coe_t F (pseudo_epimorphism α β) :=
⟨λ f, ⟨f, exists_map_eq_of_map_le f⟩⟩
instance [topological_space α] [preorder α] [topological_space β] [preorder β]
[esakia_hom_class F α β] : has_coe_t F (esakia_hom α β) :=
⟨λ f, ⟨f, exists_map_eq_of_map_le f⟩⟩
/-! ### Pseudo-epimorphisms -/
namespace pseudo_epimorphism
variables [preorder α] [preorder β] [preorder γ] [preorder δ]
instance : pseudo_epimorphism_class (pseudo_epimorphism α β) α β :=
{ coe := λ f, f.to_fun,
coe_injective' := λ f g h, by { obtain ⟨⟨_, _⟩, _⟩ := f, obtain ⟨⟨_, _⟩, _⟩ := g, congr' },
map_rel := λ f, f.monotone',
exists_map_eq_of_map_le := pseudo_epimorphism.exists_map_eq_of_map_le' }
/-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun`
directly. -/
instance : has_coe_to_fun (pseudo_epimorphism α β) (λ _, α → β) := fun_like.has_coe_to_fun
@[simp] lemma to_fun_eq_coe {f : pseudo_epimorphism α β} : f.to_fun = (f : α → β) := rfl
@[ext] lemma ext {f g : pseudo_epimorphism α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h
/-- Copy of a `pseudo_epimorphism` with a new `to_fun` equal to the old one. Useful to fix
definitional equalities. -/
protected def copy (f : pseudo_epimorphism α β) (f' : α → β) (h : f' = f) :
pseudo_epimorphism α β :=
⟨f.to_order_hom.copy f' h, by simpa only [h.symm, to_fun_eq_coe] using f.exists_map_eq_of_map_le'⟩
variables (α)
/-- `id` as a `pseudo_epimorphism`. -/
protected def id : pseudo_epimorphism α α := ⟨order_hom.id, λ a b h, ⟨b, h, rfl⟩⟩
instance : inhabited (pseudo_epimorphism α α) := ⟨pseudo_epimorphism.id α⟩
@[simp] lemma coe_id : ⇑(pseudo_epimorphism.id α) = id := rfl
@[simp] lemma coe_id_order_hom : (pseudo_epimorphism.id α : α →o α) = order_hom.id := rfl
variables {α}
@[simp] lemma id_apply (a : α) : pseudo_epimorphism.id α a = a := rfl
/-- Composition of `pseudo_epimorphism`s as a `pseudo_epimorphism`. -/
def comp (g : pseudo_epimorphism β γ) (f : pseudo_epimorphism α β) : pseudo_epimorphism α γ :=
⟨g.to_order_hom.comp f.to_order_hom, λ a b h₀, begin
obtain ⟨b, h₁, rfl⟩ := g.exists_map_eq_of_map_le' h₀,
obtain ⟨b, h₂, rfl⟩ := f.exists_map_eq_of_map_le' h₁,
exact ⟨b, h₂, rfl⟩,
end⟩
@[simp] lemma coe_comp (g : pseudo_epimorphism β γ) (f : pseudo_epimorphism α β) :
(g.comp f : α → γ) = g ∘ f := rfl
@[simp] lemma coe_comp_order_hom (g : pseudo_epimorphism β γ) (f : pseudo_epimorphism α β) :
(g.comp f : α →o γ) = (g : β →o γ).comp f := rfl
@[simp] lemma comp_apply (g : pseudo_epimorphism β γ) (f : pseudo_epimorphism α β) (a : α) :
(g.comp f) a = g (f a) := rfl
@[simp] lemma comp_assoc (h : pseudo_epimorphism γ δ) (g : pseudo_epimorphism β γ)
(f : pseudo_epimorphism α β) :
(h.comp g).comp f = h.comp (g.comp f) := rfl
@[simp] lemma comp_id (f : pseudo_epimorphism α β) : f.comp (pseudo_epimorphism.id α) = f :=
ext $ λ a, rfl
@[simp] lemma id_comp (f : pseudo_epimorphism α β) : (pseudo_epimorphism.id β).comp f = f :=
ext $ λ a, rfl
lemma cancel_right {g₁ g₂ : pseudo_epimorphism β γ} {f : pseudo_epimorphism α β}
(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 : pseudo_epimorphism β γ} {f₁ f₂ : pseudo_epimorphism α β} (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 pseudo_epimorphism
/-! ### Esakia morphisms -/
namespace esakia_hom
variables [topological_space α] [preorder α] [topological_space β] [preorder β]
[topological_space γ] [preorder γ] [topological_space δ] [preorder δ]
/-- Reinterpret an `esakia_hom` as a `pseudo_epimorphism`. -/
def to_pseudo_epimorphism (f : esakia_hom α β) : pseudo_epimorphism α β := { ..f }
instance : esakia_hom_class (esakia_hom α β) α β :=
{ coe := λ f, f.to_fun,
coe_injective' := λ f g h,
by { obtain ⟨⟨⟨_, _⟩, _⟩, _⟩ := f, obtain ⟨⟨⟨_, _⟩, _⟩, _⟩ := g, congr' },
map_rel := λ f, f.monotone',
map_continuous := λ f, f.continuous_to_fun,
exists_map_eq_of_map_le := λ f, f.exists_map_eq_of_map_le' }
/-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun`
directly. -/
instance : has_coe_to_fun (esakia_hom α β) (λ _, α → β) := fun_like.has_coe_to_fun
@[simp] lemma to_fun_eq_coe {f : esakia_hom α β} : f.to_fun = (f : α → β) := rfl
@[ext] lemma ext {f g : esakia_hom α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h
/-- Copy of an `esakia_hom` with a new `to_fun` equal to the old one. Useful to fix definitional
equalities. -/
protected def copy (f : esakia_hom α β) (f' : α → β) (h : f' = f) : esakia_hom α β :=
⟨f.to_continuous_order_hom.copy f' h,
by simpa only [h.symm, to_fun_eq_coe] using f.exists_map_eq_of_map_le'⟩
variables (α)
/-- `id` as an `esakia_hom`. -/
protected def id : esakia_hom α α := ⟨continuous_order_hom.id α, λ a b h, ⟨b, h, rfl⟩⟩
instance : inhabited (esakia_hom α α) := ⟨esakia_hom.id α⟩
@[simp] lemma coe_id : ⇑(esakia_hom.id α) = id := rfl
@[simp] lemma coe_id_continuous_order_hom :
(esakia_hom.id α : α →Co α) = continuous_order_hom.id α := rfl
@[simp] lemma coe_id_pseudo_epimorphism :
(esakia_hom.id α : pseudo_epimorphism α α) = pseudo_epimorphism.id α := rfl
variables {α}
@[simp] lemma id_apply (a : α) : esakia_hom.id α a = a := rfl
/-- Composition of `esakia_hom`s as an `esakia_hom`. -/
def comp (g : esakia_hom β γ) (f : esakia_hom α β) : esakia_hom α γ :=
⟨g.to_continuous_order_hom.comp f.to_continuous_order_hom, λ a b h₀, begin
obtain ⟨b, h₁, rfl⟩ := g.exists_map_eq_of_map_le' h₀,
obtain ⟨b, h₂, rfl⟩ := f.exists_map_eq_of_map_le' h₁,
exact ⟨b, h₂, rfl⟩,
end⟩
@[simp] lemma coe_comp (g : esakia_hom β γ) (f : esakia_hom α β) : (g.comp f : α → γ) = g ∘ f := rfl
@[simp] lemma comp_apply (g : esakia_hom β γ) (f : esakia_hom α β) (a : α) :
(g.comp f) a = g (f a) := rfl
@[simp] lemma coe_comp_continuous_order_hom (g : esakia_hom β γ) (f : esakia_hom α β) :
(g.comp f : α →Co γ) = (g : β →Co γ).comp f := rfl
@[simp] lemma coe_comp_pseudo_epimorphism (g : esakia_hom β γ) (f : esakia_hom α β) :
(g.comp f : pseudo_epimorphism α γ) = (g : pseudo_epimorphism β γ).comp f := rfl
@[simp] lemma comp_assoc (h : esakia_hom γ δ) (g : esakia_hom β γ) (f : esakia_hom α β) :
(h.comp g).comp f = h.comp (g.comp f) := rfl
@[simp] lemma comp_id (f : esakia_hom α β) : f.comp (esakia_hom.id α) = f := ext $ λ a, rfl
@[simp] lemma id_comp (f : esakia_hom α β) : (esakia_hom.id β).comp f = f := ext $ λ a, rfl
lemma cancel_right {g₁ g₂ : esakia_hom β γ} {f : esakia_hom α β} (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 : esakia_hom β γ} {f₁ f₂ : esakia_hom α β} (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 esakia_hom
|
992f48d36193f4e0e0cb4d57712fd85ad2f6cee2 | bdd56e6eb0f467437e368d613de75299495d4054 | /src/category_theory/limits/shapes/binary_products.lean | 635bd0dfda042ac3aa6d6fbde0b14b11a3dd2f2b | [] | no_license | truong111000/formalabstracts | 49a04c268ccee136e48e24e9d5dcb6fedea4b53e | 93a89a5c05c6fbc23eb9b914b60dcc353e609cd2 | refs/heads/master | 1,589,551,767,824 | 1,555,708,723,000 | 1,555,708,723,000 | 182,326,292 | 0 | 0 | null | 1,555,708,332,000 | 1,555,708,331,000 | null | UTF-8 | Lean | false | false | 1,220 | lean | -- Copyright (c) 2018 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison
import category_theory.limits.shapes.products
universes u v
open category_theory
namespace category_theory.limits
@[derive decidable_eq] inductive two : Type v
| left | right
def two.map {C : Type u} (X Y : C) : two → C
| two.left := X
| two.right := Y
variables {C : Type u} [𝒞 : category.{u} C]
include 𝒞
variables {X Y : C}
-- set_option pp.notation true
def binary_fan {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) : fan (two.map X Y) :=
{ X := P,
π := ⟨λ j, two.cases_on j π₁ π₂, λ x y f, by tidy⟩}
def binary_cofan {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) : cofan (two.map X Y) :=
{ X := P,
ι := { app := λ j, two.cases_on j ι₁ ι₂ }}
def fan.π₁ {f : two → C} (t : fan f) : t.X ⟶ f two.left := t.π.app two.left
def fan.π₂ {f : two → C} (t : fan f) : t.X ⟶ f two.right := t.π.app two.right
def cofan.ι₁ {f : two → C} (t : cofan f) : f two.left ⟶ t.X := t.ι.app two.left
def cofan.ι₂ {f : two → C} (t : cofan f) : f two.right ⟶ t.X := t.ι.app two.right
end category_theory.limits
|
a75188ee102eabeed8067e1aad32e5024ffb6662 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/category_theory/limits/shapes/kernels.lean | 4075b69931e173bd177cb1a8fa139fdca9f20ce8 | [
"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 | 27,058 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Markus Himmel
-/
import category_theory.limits.shapes.zero
/-!
# Kernels and cokernels
In a category with zero morphisms, the kernel of a morphism `f : X ⟶ Y` is
the equalizer of `f` and `0 : X ⟶ Y`. (Similarly the cokernel is the coequalizer.)
The basic definitions are
* `kernel : (X ⟶ Y) → C`
* `kernel.ι : kernel f ⟶ X`
* `kernel.condition : kernel.ι f ≫ f = 0` and
* `kernel.lift (k : W ⟶ X) (h : k ≫ f = 0) : W ⟶ kernel f` (as well as the dual versions)
## Main statements
Besides the definition and lifts, we prove
* `kernel.ι_zero_is_iso`: a kernel map of a zero morphism is an isomorphism
* `kernel.eq_zero_of_epi_kernel`: if `kernel.ι f` is an epimorphism, then `f = 0`
* `kernel.of_mono`: the kernel of a monomorphism is the zero object
* `kernel.lift_mono`: the lift of a monomorphism `k : W ⟶ X` such that `k ≫ f = 0`
is still a monomorphism
* `kernel.is_limit_cone_zero_cone`: if our category has a zero object, then the map from the zero
obect is a kernel map of any monomorphism
* `kernel.ι_of_zero`: `kernel.ι (0 : X ⟶ Y)` is an isomorphism
and the corresponding dual statements.
## Future work
* TODO: connect this with existing working in the group theory and ring theory libraries.
## Implementation notes
As with the other special shapes in the limits library, all the definitions here are given as
`abbreviation`s of the general statements for limits, so all the `simp` lemmas and theorems about
general limits can be used.
## References
* [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2]
-/
noncomputable theory
universes v u u'
open category_theory
open category_theory.limits.walking_parallel_pair
namespace category_theory.limits
variables {C : Type u} [category.{v} C]
variables [has_zero_morphisms C]
/-- A morphism `f` has a kernel if the functor `parallel_pair f 0` has a limit. -/
abbreviation has_kernel {X Y : C} (f : X ⟶ Y) : Prop := has_limit (parallel_pair f 0)
/-- A morphism `f` has a cokernel if the functor `parallel_pair f 0` has a colimit. -/
abbreviation has_cokernel {X Y : C} (f : X ⟶ Y) : Prop := has_colimit (parallel_pair f 0)
variables {X Y : C} (f : X ⟶ Y)
section
/-- A kernel fork is just a fork where the second morphism is a zero morphism. -/
abbreviation kernel_fork := fork f 0
variables {f}
@[simp, reassoc] lemma kernel_fork.condition (s : kernel_fork f) : fork.ι s ≫ f = 0 :=
by erw [fork.condition, has_zero_morphisms.comp_zero]
@[simp] lemma kernel_fork.app_one (s : kernel_fork f) : s.π.app one = 0 :=
by rw [←fork.app_zero_left, kernel_fork.condition]
/-- A morphism `ι` satisfying `ι ≫ f = 0` determines a kernel fork over `f`. -/
abbreviation kernel_fork.of_ι {Z : C} (ι : Z ⟶ X) (w : ι ≫ f = 0) : kernel_fork f :=
fork.of_ι ι $ by rw [w, has_zero_morphisms.comp_zero]
@[simp] lemma kernel_fork.ι_of_ι {X Y P : C} (f : X ⟶ Y) (ι : P ⟶ X) (w : ι ≫ f = 0) :
fork.ι (kernel_fork.of_ι ι w) = ι := rfl
section
local attribute [tidy] tactic.case_bash
/-- Every kernel fork `s` is isomorphic (actually, equal) to `fork.of_ι (fork.ι s) _`. -/
def iso_of_ι (s : fork f 0) : s ≅ fork.of_ι (fork.ι s) (fork.condition s) :=
cones.ext (iso.refl _) $ by tidy
/-- If `ι = ι'`, then `fork.of_ι ι _` and `fork.of_ι ι' _` are isomorphic. -/
def of_ι_congr {P : C} {ι ι' : P ⟶ X} {w : ι ≫ f = 0} (h : ι = ι') :
kernel_fork.of_ι ι w ≅ kernel_fork.of_ι ι' (by rw [←h, w]) :=
cones.ext (iso.refl _) $ by tidy
/-- If `F` is an equivalence, then applying `F` to a diagram indexing a (co)kernel of `f` yields
the diagram indexing the (co)kernel of `F.map f`. -/
def comp_nat_iso {D : Type u'} [category.{v} D] [has_zero_morphisms D] (F : C ⥤ D)
[is_equivalence F] : parallel_pair f 0 ⋙ F ≅ parallel_pair (F.map f) 0 :=
nat_iso.of_components (λ j, match j with
| zero := iso.refl _
| one := iso.refl _
end) $ by tidy
end
/-- If `s` is a limit kernel fork and `k : W ⟶ X` satisfies ``k ≫ f = 0`, then there is some
`l : W ⟶ s.X` such that `l ≫ fork.ι s = k`. -/
def kernel_fork.is_limit.lift' {s : kernel_fork f} (hs : is_limit s) {W : C} (k : W ⟶ X)
(h : k ≫ f = 0) : {l : W ⟶ s.X // l ≫ fork.ι s = k} :=
⟨hs.lift $ kernel_fork.of_ι _ h, hs.fac _ _⟩
/-- This is a slightly more convenient method to verify that a kernel fork is a limit cone. It
only asks for a proof of facts that carry any mathematical content -/
def is_limit_aux (t : kernel_fork f)
(lift : Π (s : kernel_fork f), s.X ⟶ t.X)
(fac : ∀ (s : kernel_fork f), lift s ≫ t.ι = s.ι)
(uniq : ∀ (s : kernel_fork f) (m : s.X ⟶ t.X) (w : m ≫ t.ι = s.ι), m = lift s) :
is_limit t :=
{ lift := lift,
fac' := λ s j, by { cases j, { exact fac s, }, { simp, }, },
uniq' := λ s m w, uniq s m (w limits.walking_parallel_pair.zero), }
/--
This is a more convenient formulation to show that a `kernel_fork` constructed using
`kernel_fork.of_ι` is a limit cone.
-/
def is_limit.of_ι {W : C} (g : W ⟶ X) (eq : g ≫ f = 0)
(lift : Π {W' : C} (g' : W' ⟶ X) (eq' : g' ≫ f = 0), W' ⟶ W)
(fac : ∀ {W' : C} (g' : W' ⟶ X) (eq' : g' ≫ f = 0), lift g' eq' ≫ g = g')
(uniq : ∀ {W' : C} (g' : W' ⟶ X) (eq' : g' ≫ f = 0) (m : W' ⟶ W) (w : m ≫ g = g'), m = lift g' eq') :
is_limit (kernel_fork.of_ι g eq) :=
is_limit_aux _ (λ s, lift s.ι s.condition) (λ s, fac s.ι s.condition) (λ s, uniq s.ι s.condition)
end
section
variables [has_kernel f]
/-- The kernel of a morphism, expressed as the equalizer with the 0 morphism. -/
abbreviation kernel : C := equalizer f 0
/-- The map from `kernel f` into the source of `f`. -/
abbreviation kernel.ι : kernel f ⟶ X := equalizer.ι f 0
@[simp] lemma equalizer_as_kernel : equalizer.ι f 0 = kernel.ι f := rfl
@[simp, reassoc] lemma kernel.condition : kernel.ι f ≫ f = 0 :=
kernel_fork.condition _
/-- Given any morphism `k : W ⟶ X` satisfying `k ≫ f = 0`, `k` factors through `kernel.ι f`
via `kernel.lift : W ⟶ kernel f`. -/
abbreviation kernel.lift {W : C} (k : W ⟶ X) (h : k ≫ f = 0) : W ⟶ kernel f :=
limit.lift (parallel_pair f 0) (kernel_fork.of_ι k h)
@[simp, reassoc]
lemma kernel.lift_ι {W : C} (k : W ⟶ X) (h : k ≫ f = 0) : kernel.lift f k h ≫ kernel.ι f = k :=
limit.lift_π _ _
@[simp]
lemma kernel.lift_zero {W : C} {h} : kernel.lift f (0 : W ⟶ X) h = 0 :=
by { ext, simp, }
instance kernel.lift_mono {W : C} (k : W ⟶ X) (h : k ≫ f = 0) [mono k] : mono (kernel.lift f k h) :=
⟨λ Z g g' w,
begin
replace w := w =≫ kernel.ι f,
simp only [category.assoc, kernel.lift_ι] at w,
exact (cancel_mono k).1 w,
end⟩
/-- Any morphism `k : W ⟶ X` satisfying `k ≫ f = 0` induces a morphism `l : W ⟶ kernel f` such that
`l ≫ kernel.ι f = k`. -/
def kernel.lift' {W : C} (k : W ⟶ X) (h : k ≫ f = 0) : {l : W ⟶ kernel f // l ≫ kernel.ι f = k} :=
⟨kernel.lift f k h, kernel.lift_ι _ _ _⟩
/-- Every kernel of the zero morphism is an isomorphism -/
instance kernel.ι_zero_is_iso : is_iso (kernel.ι (0 : X ⟶ Y)) :=
equalizer.ι_of_self _
lemma eq_zero_of_epi_kernel [epi (kernel.ι f)] : f = 0 :=
(cancel_epi (kernel.ι f)).1 (by simp)
/-- The kernel of a zero morphism is isomorphic to the source. -/
def kernel_zero_iso_source : kernel (0 : X ⟶ Y) ≅ X :=
equalizer.iso_source_of_self 0
@[simp] lemma kernel_zero_iso_source_hom :
kernel_zero_iso_source.hom = kernel.ι (0 : X ⟶ Y) := rfl
@[simp] lemma kernel_zero_iso_source_inv :
kernel_zero_iso_source.inv = kernel.lift (0 : X ⟶ Y) (𝟙 X) (by simp) := rfl
/-- If two morphisms are known to be equal, then their kernels are isomorphic. -/
def kernel_iso_of_eq {f g : X ⟶ Y} [has_kernel f] [has_kernel g] (h : f = g) :
kernel f ≅ kernel g :=
has_limit.iso_of_nat_iso (by simp[h])
@[simp]
lemma kernel_iso_of_eq_refl {h : f = f} : kernel_iso_of_eq h = iso.refl (kernel f) :=
by { ext, simp [kernel_iso_of_eq], }
@[simp]
lemma kernel_iso_of_eq_trans {f g h : X ⟶ Y} [has_kernel f] [has_kernel g] [has_kernel h]
(w₁ : f = g) (w₂ : g = h) :
kernel_iso_of_eq w₁ ≪≫ kernel_iso_of_eq w₂ = kernel_iso_of_eq (w₁.trans w₂) :=
by { unfreezingI { induction w₁, induction w₂, }, ext, simp [kernel_iso_of_eq], }
variables {f}
lemma kernel_not_epi_of_nonzero (w : f ≠ 0) : ¬epi (kernel.ι f) :=
λ I, by exactI w (eq_zero_of_epi_kernel f)
lemma kernel_not_iso_of_nonzero (w : f ≠ 0) : (is_iso (kernel.ι f)) → false :=
λ I, kernel_not_epi_of_nonzero w $ by { resetI, apply_instance }
/--
When `g` is an isomorphism, the kernel of `f ≫ g` is isomorphic to the kernel of `f`.
-/
def kernel_comp_is_iso {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z)
[has_kernel (f ≫ g)] [has_kernel f] [is_iso g] :
kernel (f ≫ g) ≅ kernel f :=
{ hom := kernel.lift _ (kernel.ι _) (by { rw [←cancel_mono g], simp, }),
inv := kernel.lift _ (kernel.ι _) (by simp), }
@[simp]
lemma kernel_comp_is_iso_hom_comp_kernel_ι {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z)
[has_kernel (f ≫ g)] [has_kernel f] [is_iso g] :
(kernel_comp_is_iso f g).hom ≫ kernel.ι f = kernel.ι (f ≫ g) :=
by simp [kernel_comp_is_iso]
@[simp]
lemma kernel_comp_is_iso_inv_comp_kernel_ι {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z)
[has_kernel (f ≫ g)] [has_kernel f] [is_iso g] :
(kernel_comp_is_iso f g).inv ≫ kernel.ι (f ≫ g) = kernel.ι f :=
by simp [kernel_comp_is_iso]
/--
When `f` is an isomorphism, the kernel of `f ≫ g` is isomorphic to the kernel of `g`.
-/
def kernel_is_iso_comp {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z)
[has_kernel (f ≫ g)] [is_iso f] [has_kernel g] :
kernel (f ≫ g) ≅ kernel g :=
{ hom := kernel.lift _ (kernel.ι _ ≫ f) (by simp),
inv := kernel.lift _ (kernel.ι _ ≫ inv f) (by simp), }
@[simp]
lemma kernel_is_iso_comp_hom_comp_kernel_ι {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z)
[has_kernel (f ≫ g)] [is_iso f] [has_kernel g] :
(kernel_is_iso_comp f g).hom ≫ kernel.ι g = kernel.ι (f ≫ g) ≫ f :=
by simp [kernel_is_iso_comp]
@[simp]
lemma kernel_is_iso_comp_inv_comp_kernel_ι {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z)
[has_kernel (f ≫ g)] [is_iso f] [has_kernel g] :
(kernel_is_iso_comp f g).inv ≫ kernel.ι (f ≫ g) = kernel.ι g ≫ (inv f) :=
by simp [kernel_is_iso_comp]
end
section has_zero_object
variables [has_zero_object C]
local attribute [instance] has_zero_object.has_zero
/-- The morphism from the zero object determines a cone on a kernel diagram -/
def kernel.zero_cone : cone (parallel_pair f 0) :=
{ X := 0,
π := { app := λ j, 0 }}
/-- The map from the zero object is a kernel of a monomorphism -/
def kernel.is_limit_cone_zero_cone [mono f] : is_limit (kernel.zero_cone f) :=
fork.is_limit.mk _ (λ s, 0)
(λ s, by { erw zero_comp,
convert (zero_of_comp_mono f _).symm,
exact kernel_fork.condition _ })
(λ _ _ _, zero_of_to_zero _)
/-- The kernel of a monomorphism is isomorphic to the zero object -/
def kernel.of_mono [has_kernel f] [mono f] : kernel f ≅ 0 :=
functor.map_iso (cones.forget _) $ is_limit.unique_up_to_iso
(limit.is_limit (parallel_pair f 0)) (kernel.is_limit_cone_zero_cone f)
/-- The kernel morphism of a monomorphism is a zero morphism -/
lemma kernel.ι_of_mono [has_kernel f] [mono f] : kernel.ι f = 0 :=
zero_of_source_iso_zero _ (kernel.of_mono f)
end has_zero_object
section transport
/-- If `i` is an isomorphism such that `l ≫ i.hom = f`, then any kernel of `f` is a kernel of `l`.-/
def is_kernel.of_comp_iso {Z : C} (l : X ⟶ Z) (i : Z ≅ Y) (h : l ≫ i.hom = f)
{s : kernel_fork f} (hs : is_limit s) : is_limit (kernel_fork.of_ι (fork.ι s) $
show fork.ι s ≫ l = 0, by simp [←i.comp_inv_eq.2 h.symm]) :=
fork.is_limit.mk _
(λ s, hs.lift $ kernel_fork.of_ι (fork.ι s) $ by simp [←h])
(λ s, by simp)
(λ s m h, by { apply fork.is_limit.hom_ext hs, simpa using h walking_parallel_pair.zero })
/-- If `i` is an isomorphism such that `l ≫ i.hom = f`, then the kernel of `f` is a kernel of `l`.-/
def kernel.of_comp_iso [has_kernel f]
{Z : C} (l : X ⟶ Z) (i : Z ≅ Y) (h : l ≫ i.hom = f) :
is_limit (kernel_fork.of_ι (kernel.ι f) $
show kernel.ι f ≫ l = 0, by simp [←i.comp_inv_eq.2 h.symm]) :=
is_kernel.of_comp_iso f l i h $ limit.is_limit _
/-- If `s` is any limit kernel cone over `f` and if `i` is an isomorphism such that
`i.hom ≫ s.ι = l`, then `l` is a kernel of `f`. -/
def is_kernel.iso_kernel {Z : C} (l : Z ⟶ X) {s : kernel_fork f} (hs : is_limit s)
(i : Z ≅ s.X) (h : i.hom ≫ fork.ι s = l) : is_limit (kernel_fork.of_ι l $
show l ≫ f = 0, by simp [←h]) :=
is_limit.of_iso_limit hs $ cones.ext i.symm $ λ j,
by { cases j, { exact (iso.eq_inv_comp i).2 h }, { simp } }
/-- If `i` is an isomorphism such that `i.hom ≫ kernel.ι f = l`, then `l` is a kernel of `f`. -/
def kernel.iso_kernel [has_kernel f]
{Z : C} (l : Z ⟶ X) (i : Z ≅ kernel f) (h : i.hom ≫ kernel.ι f = l) :
is_limit (kernel_fork.of_ι l $ by simp [←h]) :=
is_kernel.iso_kernel f l (limit.is_limit _) i h
end transport
section
variables (X Y)
/-- The kernel morphism of a zero morphism is an isomorphism -/
def kernel.ι_of_zero : is_iso (kernel.ι (0 : X ⟶ Y)) :=
equalizer.ι_of_self _
end
section
/-- A cokernel cofork is just a cofork where the second morphism is a zero morphism. -/
abbreviation cokernel_cofork := cofork f 0
variables {f}
@[simp, reassoc] lemma cokernel_cofork.condition (s : cokernel_cofork f) : f ≫ cofork.π s = 0 :=
by rw [cofork.condition, zero_comp]
@[simp] lemma cokernel_cofork.app_zero (s : cokernel_cofork f) : s.ι.app zero = 0 :=
by rw [←cofork.left_app_one, cokernel_cofork.condition]
/-- A morphism `π` satisfying `f ≫ π = 0` determines a cokernel cofork on `f`. -/
abbreviation cokernel_cofork.of_π {Z : C} (π : Y ⟶ Z) (w : f ≫ π = 0) : cokernel_cofork f :=
cofork.of_π π $ by rw [w, zero_comp]
@[simp] lemma cokernel_cofork.π_of_π {X Y P : C} (f : X ⟶ Y) (π : Y ⟶ P) (w : f ≫ π = 0) :
cofork.π (cokernel_cofork.of_π π w) = π := rfl
/-- Every cokernel cofork `s` is isomorphic (actually, equal) to `cofork.of_π (cofork.π s) _`. -/
def iso_of_π (s : cofork f 0) : s ≅ cofork.of_π (cofork.π s) (cofork.condition s) :=
cocones.ext (iso.refl _) $ λ j, by cases j; tidy
/-- If `π = π'`, then `cokernel_cofork.of_π π _` and `cokernel_cofork.of_π π' _` are isomorphic. -/
def of_π_congr {P : C} {π π' : Y ⟶ P} {w : f ≫ π = 0} (h : π = π') :
cokernel_cofork.of_π π w ≅ cokernel_cofork.of_π π' (by rw [←h, w]) :=
cocones.ext (iso.refl _) $ λ j, by cases j; tidy
/-- If `s` is a colimit cokernel cofork, then every `k : Y ⟶ W` satisfying `f ≫ k = 0` induces
`l : s.X ⟶ W` such that `cofork.π s ≫ l = k`. -/
def cokernel_cofork.is_colimit.desc' {s : cokernel_cofork f} (hs : is_colimit s) {W : C} (k : Y ⟶ W)
(h : f ≫ k = 0) : {l : s.X ⟶ W // cofork.π s ≫ l = k} :=
⟨hs.desc $ cokernel_cofork.of_π _ h, hs.fac _ _⟩
/--
This is a slightly more convenient method to verify that a cokernel cofork is a colimit cocone.
It only asks for a proof of facts that carry any mathematical content -/
def is_colimit_aux (t : cokernel_cofork f)
(desc : Π (s : cokernel_cofork f), t.X ⟶ s.X)
(fac : ∀ (s : cokernel_cofork f), t.π ≫ desc s = s.π)
(uniq : ∀ (s : cokernel_cofork f) (m : t.X ⟶ s.X) (w : t.π ≫ m = s.π), m = desc s) :
is_colimit t :=
{ desc := desc,
fac' := λ s j, by { cases j, { simp, }, { exact fac s, }, },
uniq' := λ s m w, uniq s m (w limits.walking_parallel_pair.one), }
/--
This is a more convenient formulation to show that a `cokernel_cofork` constructed using
`cokernel_cofork.of_π` is a limit cone.
-/
def is_colimit.of_π {Z : C} (g : Y ⟶ Z) (eq : f ≫ g = 0)
(desc : Π {Z' : C} (g' : Y ⟶ Z') (eq' : f ≫ g' = 0), Z ⟶ Z')
(fac : ∀ {Z' : C} (g' : Y ⟶ Z') (eq' : f ≫ g' = 0), g ≫ desc g' eq' = g')
(uniq : ∀ {Z' : C} (g' : Y ⟶ Z') (eq' : f ≫ g' = 0) (m : Z ⟶ Z') (w : g ≫ m = g'), m = desc g' eq') :
is_colimit (cokernel_cofork.of_π g eq) :=
is_colimit_aux _ (λ s, desc s.π s.condition) (λ s, fac s.π s.condition) (λ s, uniq s.π s.condition)
end
section
variables [has_cokernel f]
/-- The cokernel of a morphism, expressed as the coequalizer with the 0 morphism. -/
abbreviation cokernel : C := coequalizer f 0
/-- The map from the target of `f` to `cokernel f`. -/
abbreviation cokernel.π : Y ⟶ cokernel f := coequalizer.π f 0
@[simp] lemma coequalizer_as_cokernel : coequalizer.π f 0 = cokernel.π f := rfl
@[simp, reassoc] lemma cokernel.condition : f ≫ cokernel.π f = 0 :=
cokernel_cofork.condition _
/-- Given any morphism `k : Y ⟶ W` such that `f ≫ k = 0`, `k` factors through `cokernel.π f`
via `cokernel.desc : cokernel f ⟶ W`. -/
abbreviation cokernel.desc {W : C} (k : Y ⟶ W) (h : f ≫ k = 0) : cokernel f ⟶ W :=
colimit.desc (parallel_pair f 0) (cokernel_cofork.of_π k h)
@[simp, reassoc]
lemma cokernel.π_desc {W : C} (k : Y ⟶ W) (h : f ≫ k = 0) :
cokernel.π f ≫ cokernel.desc f k h = k :=
colimit.ι_desc _ _
@[simp]
lemma cokernel.desc_zero {W : C} {h} : cokernel.desc f (0 : Y ⟶ W) h = 0 :=
by { ext, simp, }
instance cokernel.desc_epi {W : C} (k : Y ⟶ W) (h : f ≫ k = 0) [epi k] : epi (cokernel.desc f k h) :=
⟨λ Z g g' w,
begin
replace w := cokernel.π f ≫= w,
simp only [cokernel.π_desc_assoc] at w,
exact (cancel_epi k).1 w,
end⟩
/-- Any morphism `k : Y ⟶ W` satisfying `f ≫ k = 0` induces `l : cokernel f ⟶ W` such that
`cokernel.π f ≫ l = k`. -/
def cokernel.desc' {W : C} (k : Y ⟶ W) (h : f ≫ k = 0) :
{l : cokernel f ⟶ W // cokernel.π f ≫ l = k} :=
⟨cokernel.desc f k h, cokernel.π_desc _ _ _⟩
/-- The cokernel of the zero morphism is an isomorphism -/
instance cokernel.π_zero_is_iso :
is_iso (cokernel.π (0 : X ⟶ Y)) :=
coequalizer.π_of_self _
lemma eq_zero_of_mono_cokernel [mono (cokernel.π f)] : f = 0 :=
(cancel_mono (cokernel.π f)).1 (by simp)
/-- The cokernel of a zero morphism is isomorphic to the target. -/
def cokernel_zero_iso_target : cokernel (0 : X ⟶ Y) ≅ Y :=
coequalizer.iso_target_of_self 0
@[simp] lemma cokernel_zero_iso_target_hom :
cokernel_zero_iso_target.hom = cokernel.desc (0 : X ⟶ Y) (𝟙 Y) (by simp) := rfl
@[simp] lemma cokernel_zero_iso_target_inv :
cokernel_zero_iso_target.inv = cokernel.π (0 : X ⟶ Y) := rfl
/-- If two morphisms are known to be equal, then their cokernels are isomorphic. -/
def cokernel_iso_of_eq {f g : X ⟶ Y} [has_cokernel f] [has_cokernel g] (h : f = g) :
cokernel f ≅ cokernel g :=
has_colimit.iso_of_nat_iso (by simp[h])
@[simp]
lemma cokernel_iso_of_eq_refl {h : f = f} : cokernel_iso_of_eq h = iso.refl (cokernel f) :=
by { ext, simp [cokernel_iso_of_eq], }
@[simp]
lemma cokernel_iso_of_eq_trans {f g h : X ⟶ Y} [has_cokernel f] [has_cokernel g] [has_cokernel h]
(w₁ : f = g) (w₂ : g = h) :
cokernel_iso_of_eq w₁ ≪≫ cokernel_iso_of_eq w₂ = cokernel_iso_of_eq (w₁.trans w₂) :=
by { unfreezingI { induction w₁, induction w₂, }, ext, simp [cokernel_iso_of_eq], }
variables {f}
lemma cokernel_not_mono_of_nonzero (w : f ≠ 0) : ¬mono (cokernel.π f) :=
λ I, by exactI w (eq_zero_of_mono_cokernel f)
lemma cokernel_not_iso_of_nonzero (w : f ≠ 0) : (is_iso (cokernel.π f)) → false :=
λ I, cokernel_not_mono_of_nonzero w $ by { resetI, apply_instance }
/--
When `g` is an isomorphism, the cokernel of `f ≫ g` is isomorphic to the cokernel of `f`.
-/
def cokernel_comp_is_iso {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z)
[has_cokernel (f ≫ g)] [has_cokernel f] [is_iso g] :
cokernel (f ≫ g) ≅ cokernel f :=
{ hom := cokernel.desc _ (inv g ≫ cokernel.π f) (by simp),
inv := cokernel.desc _ (g ≫ cokernel.π (f ≫ g)) (by rw [←category.assoc, cokernel.condition]), }
@[simp]
lemma cokernel_π_comp_cokernel_comp_is_iso_hom {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z)
[has_cokernel (f ≫ g)] [has_cokernel f] [is_iso g] :
cokernel.π (f ≫ g) ≫ (cokernel_comp_is_iso f g).hom = inv g ≫ cokernel.π f :=
by simp [cokernel_comp_is_iso]
@[simp]
lemma cokernel_π_comp_cokernel_comp_is_iso_inv {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z)
[has_cokernel (f ≫ g)] [has_cokernel f] [is_iso g] :
cokernel.π f ≫ (cokernel_comp_is_iso f g).inv = g ≫ cokernel.π (f ≫ g) :=
by simp [cokernel_comp_is_iso]
/--
When `f` is an isomorphism, the cokernel of `f ≫ g` is isomorphic to the cokernel of `g`.
-/
def cokernel_is_iso_comp {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z)
[has_cokernel (f ≫ g)] [is_iso f] [has_cokernel g] :
cokernel (f ≫ g) ≅ cokernel g :=
{ hom := cokernel.desc _ (cokernel.π g) (by simp),
inv := cokernel.desc _ (cokernel.π (f ≫ g)) (by { rw [←cancel_epi f, ←category.assoc], simp, }), }
@[simp]
lemma cokernel_π_comp_cokernel_is_iso_comp_hom {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z)
[has_cokernel (f ≫ g)] [is_iso f] [has_cokernel g] :
cokernel.π (f ≫ g) ≫ (cokernel_is_iso_comp f g).hom = cokernel.π g :=
by simp [cokernel_is_iso_comp]
@[simp]
lemma cokernel_π_comp_cokernel_is_iso_comp_inv {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z)
[has_cokernel (f ≫ g)] [is_iso f] [has_cokernel g] :
cokernel.π g ≫ (cokernel_is_iso_comp f g).inv = cokernel.π (f ≫ g) :=
by simp [cokernel_is_iso_comp]
end
section has_zero_object
variables [has_zero_object C]
local attribute [instance] has_zero_object.has_zero
/-- The morphism to the zero object determines a cocone on a cokernel diagram -/
def cokernel.zero_cocone : cocone (parallel_pair f 0) :=
{ X := 0,
ι := { app := λ j, 0 } }
/-- The morphism to the zero object is a cokernel of an epimorphism -/
def cokernel.is_colimit_cocone_zero_cocone [epi f] : is_colimit (cokernel.zero_cocone f) :=
cofork.is_colimit.mk _ (λ s, 0)
(λ s, by { erw zero_comp,
convert (zero_of_epi_comp f _).symm,
exact cokernel_cofork.condition _ })
(λ _ _ _, zero_of_from_zero _)
/-- The cokernel of an epimorphism is isomorphic to the zero object -/
def cokernel.of_epi [has_cokernel f] [epi f] : cokernel f ≅ 0 :=
functor.map_iso (cocones.forget _) $ is_colimit.unique_up_to_iso
(colimit.is_colimit (parallel_pair f 0)) (cokernel.is_colimit_cocone_zero_cocone f)
/-- The cokernel morphism of an epimorphism is a zero morphism -/
lemma cokernel.π_of_epi [has_cokernel f] [epi f] : cokernel.π f = 0 :=
zero_of_target_iso_zero _ (cokernel.of_epi f)
end has_zero_object
section has_image
/--
The cokernel of the image inclusion of a morphism `f` is isomorphic to the cokernel of `f`.
(This result requires that the factorisation through the image is an epimorphism.
This holds in any category with equalizers.)
-/
@[simps]
def cokernel_image_ι {X Y : C} (f : X ⟶ Y)
[has_image f] [has_cokernel (image.ι f)] [has_cokernel f] [epi (factor_thru_image f)] :
cokernel (image.ι f) ≅ cokernel f :=
{ hom := cokernel.desc _ (cokernel.π f)
begin
have w := cokernel.condition f,
conv at w { to_lhs, congr, rw ←image.fac f, },
rw [←has_zero_morphisms.comp_zero (limits.factor_thru_image f), category.assoc, cancel_epi] at w,
exact w,
end,
inv := cokernel.desc _ (cokernel.π _)
begin
conv { to_lhs, congr, rw ←image.fac f, },
rw [category.assoc, cokernel.condition, has_zero_morphisms.comp_zero],
end, }
end has_image
section
variables (X Y)
/-- The cokernel of a zero morphism is an isomorphism -/
def cokernel.π_of_zero :
is_iso (cokernel.π (0 : X ⟶ Y)) :=
coequalizer.π_of_self _
end
section has_zero_object
variables [has_zero_object C]
local attribute [instance] has_zero_object.has_zero
/-- The kernel of the cokernel of an epimorphism is an isomorphism -/
instance kernel.of_cokernel_of_epi [has_cokernel f]
[has_kernel (cokernel.π f)] [epi f] : is_iso (kernel.ι (cokernel.π f)) :=
equalizer.ι_of_eq $ cokernel.π_of_epi f
/-- The cokernel of the kernel of a monomorphism is an isomorphism -/
instance cokernel.of_kernel_of_mono [has_kernel f]
[has_cokernel (kernel.ι f)] [mono f] : is_iso (cokernel.π (kernel.ι f)) :=
coequalizer.π_of_eq $ kernel.ι_of_mono f
end has_zero_object
section transport
/-- If `i` is an isomorphism such that `i.hom ≫ l = f`, then any cokernel of `f` is a cokernel of
`l`. -/
def is_cokernel.of_iso_comp {Z : C} (l : Z ⟶ Y) (i : X ≅ Z) (h : i.hom ≫ l = f)
{s : cokernel_cofork f} (hs : is_colimit s) : is_colimit (cokernel_cofork.of_π (cofork.π s) $
show l ≫ cofork.π s = 0, by simp [i.eq_inv_comp.2 h]) :=
cofork.is_colimit.mk _
(λ s, hs.desc $ cokernel_cofork.of_π (cofork.π s) $ by simp [←h])
(λ s, by simp)
(λ s m h, by { apply cofork.is_colimit.hom_ext hs, simpa using h walking_parallel_pair.one })
/-- If `i` is an isomorphism such that `i.hom ≫ l = f`, then the cokernel of `f` is a cokernel of
`l`. -/
def cokernel.of_iso_comp [has_cokernel f]
{Z : C} (l : Z ⟶ Y) (i : X ≅ Z) (h : i.hom ≫ l = f) :
is_colimit (cokernel_cofork.of_π (cokernel.π f) $
show l ≫ cokernel.π f = 0, by simp [i.eq_inv_comp.2 h]) :=
is_cokernel.of_iso_comp f l i h $ colimit.is_colimit _
/-- If `s` is any colimit cokernel cocone over `f` and `i` is an isomorphism such that
`s.π ≫ i.hom = l`, then `l` is a cokernel of `f`. -/
def is_cokernel.cokernel_iso {Z : C} (l : Y ⟶ Z) {s : cokernel_cofork f} (hs : is_colimit s)
(i : s.X ≅ Z) (h : cofork.π s ≫ i.hom = l) : is_colimit (cokernel_cofork.of_π l $
show f ≫ l = 0, by simp [←h]) :=
is_colimit.of_iso_colimit hs $ cocones.ext i $ λ j, by { cases j, { simp }, { exact h } }
/-- If `i` is an isomorphism such that `cokernel.π f ≫ i.hom = l`, then `l` is a cokernel of `f`. -/
def cokernel.cokernel_iso [has_cokernel f]
{Z : C} (l : Y ⟶ Z) (i : cokernel f ≅ Z) (h : cokernel.π f ≫ i.hom = l) :
is_colimit (cokernel_cofork.of_π l $ by simp [←h]) :=
is_cokernel.cokernel_iso f l (colimit.is_colimit _) i h
end transport
end category_theory.limits
namespace category_theory.limits
variables (C : Type u) [category.{v} C]
variables [has_zero_morphisms C]
/-- `has_kernels` represents the existence of kernels for every morphism. -/
class has_kernels : Prop :=
(has_limit : Π {X Y : C} (f : X ⟶ Y), has_kernel f)
/-- `has_cokernels` represents the existence of cokernels for every morphism. -/
class has_cokernels : Prop :=
(has_colimit : Π {X Y : C} (f : X ⟶ Y), has_cokernel f)
attribute [instance, priority 100] has_kernels.has_limit has_cokernels.has_colimit
@[priority 100]
instance has_kernels_of_has_equalizers [has_equalizers C] : has_kernels C :=
{ has_limit := by apply_instance }
@[priority 100]
instance has_cokernels_of_has_coequalizers [has_coequalizers C] : has_cokernels C :=
{ has_colimit := by apply_instance }
end category_theory.limits
|
c334c14e7919bb4f5105c591a834d1d995f90c57 | bab2ace2b909818f20ac125499a8dd88ce812721 | /src/2020/relations/partition_challenge_xena.lean | 560a200554d772061ae3f17ae4508debf97b473d | [] | no_license | LaplaceKorea/M40001_lean | 8a3cd411fb821a7665132c09e436f02f674cc666 | 116e9ed1fadf59dc2e78376fca92026859a03bf2 | refs/heads/master | 1,693,347,195,820 | 1,635,517,507,000 | 1,635,517,507,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,011 | lean | import tactic
/-!
# The partition challenge!
Prove that equivalence relations on α are the same as partitions of α.
Three sections:
1) partitions
2) equivalence classes
3) the challenge
## Overview
Say `α` is a type, and `R` is a binary relation on `α`.
The following things are already in Lean:
reflexive R := ∀ (x : α), R x x
symmetric R := ∀ ⦃x y : α⦄, R x y → R y x
transitive R := ∀ ⦃x y z : α⦄, R x y → R y z → R x z
equivalence R := reflexive R ∧ symmetric R ∧ transitive R
In the file below, we will define partitions of `α` and "build some
interface" (i.e. prove some propositions). We will define
equivalence classes and do the same thing.
Finally, we will prove that there's a bijection between
equivalence relations on `α` and partitions of `α`.
-/
/-
# 1) Partitions
We define a partition, and prove some easy lemmas.
-/
/-
## Definition of a partition
Let `α` be a type. A *partition* on `α` is defined to be
the following data:
1) A set C of subsets of α, called "blocks".
2) A hypothesis (i.e. a proof!) that all the blocks are non-empty.
3) A hypothesis that every term of type α is in one of the blocks.
4) A hypothesis that two blocks with non-empty intersection are equal.
-/
/-- The structure of a partition on a Type α. -/
@[ext] structure partition (α : Type) :=
(C : set (set α))
(Hnonempty : ∀ X ∈ C, (X : set α).nonempty)
(Hcover : ∀ (a : α), ∃ X ∈ C, a ∈ X)
(Hdisjoint : ∀ X Y ∈ C, (X ∩ Y : set α).nonempty → X = Y)
/-
## Basic interface for partitions
-/
namespace partition
-- let α be a type, and fix a partition P on α. Let X and Y be subsets of α.
variables {α : Type} {P : partition α} {X Y : set α}
/-- If X and Y are blocks, and a is in X and Y, then X = Y. -/
theorem eq_of_mem (hX : X ∈ P.C) (hY : Y ∈ P.C) {a : α}
(haX : a ∈ X)
(haY : a ∈ Y) : X = Y :=
begin
have h := P.Hdisjoint X Y hX hY,
apply h,
use a,
split;
assumption,
end
/-- If a is in two blocks X and Y, and if b is in X,
then b is in Y (as X=Y) -/
theorem mem_of_mem (hX : X ∈ P.C) (hY : Y ∈ P.C) {a b : α}
(haX : a ∈ X) (haY : a ∈ Y) (hbX : b ∈ X) : b ∈ Y :=
begin
convert hbX,
exact (eq_of_mem hX hY haX haY).symm,
end
/-- Every term of type `α` is in one of the blocks for a partition `P`. -/
theorem mem_block (a : α) : ∃ X : set α, X ∈ P.C ∧ a ∈ X :=
begin
rcases P.Hcover a with ⟨X, hXC, haX⟩,
use X,
split; assumption,
end
end partition
/-
# 2) Equivalence classes.
We define equivalence classes and prove a few basic results about them.
-/
section equivalence_classes
/-!
## Definition of equivalence classes
-/
-- Notation and variables for the equivalence class section:
-- let α be a type, and let R be a binary relation on R.
variables {α : Type} (R : α → α → Prop)
/-- The equivalence class of `a` is the set of `b` related to `a`. -/
def cl (a : α) :=
{b : α | R b a}
/-!
## Basic lemmas about equivalence classes
-/
/-- Useful for rewriting -- `b` is in the equivalence class of `a` iff
`b` is related to `a`. True by definition. -/
theorem cl_def {a b : α} : b ∈ cl R a ↔ R b a := iff.rfl
-- Assume now that R is an equivalence relation.
variables {R} (hR : equivalence R)
include hR
/-- x is in cl_R(x) -/
lemma mem_cl_self (a : α) :
a ∈ cl R a :=
begin
rw cl_def,
rcases hR with ⟨hrefl, hsymm, htrans⟩,
unfold reflexive at hrefl,
apply hrefl,
end
/-- if a is in cl(b) then cl(a) ⊆ cl(b) -/
lemma cl_sub_cl_of_mem_cl {a b : α} :
a ∈ cl R b →
cl R a ⊆ cl R b :=
begin
intro hab,
rw set.subset_def,
intro x,
intro hxa,
rw cl_def at *,
rcases hR with ⟨hrefl, hsymm, htrans⟩,
exact htrans hxa hab,
end
lemma cl_eq_cl_of_mem_cl {a b : α} :
a ∈ cl R b →
cl R a = cl R b :=
begin
intro hab,
apply set.subset.antisymm,
{ apply cl_sub_cl_of_mem_cl hR hab },
{ apply cl_sub_cl_of_mem_cl hR,
rw cl_def at *,
rcases hR with ⟨hrefl, hsymm, htrans⟩,
apply hsymm,
exact hab }
end
end equivalence_classes -- section
/-!
# 3) The challenge!
Let `α` be a type (i.e. a collection of stucff).
There is a bijection between equivalence relations on `α` and
partitions of `α`.
We prove this by writing down constructions in each direction
and proving that the constructions are two-sided inverses of one another.
-/
open partition
example (α : Type) : {R : α → α → Prop // equivalence R} ≃ partition α :=
-- We define constructions (functions!) in both directions and prove that
-- one is a two-sided inverse of the other
{ -- Here is the first construction, from equivalence
-- relations to partitions.
-- Let R be an equivalence relation.
to_fun := λ R, {
-- Let C be the set of equivalence classes for R.
C := { B : set α | ∃ x : α, B = cl R.1 x},
-- I claim that C is a partition. We need to check the three
-- hypotheses for a partition (`Hnonempty`, `Hcover` and `Hdisjoint`),
-- so we need to supply three proofs.
Hnonempty := begin
cases R with R hR,
-- If X is an equivalence class then X is nonempty.
show ∀ (X : set α), (∃ (a : α), X = cl R a) → X.nonempty,
sorry,
end,
Hcover := begin
cases R with R hR,
-- The equivalence classes cover α
show ∀ (a : α), ∃ (X : set α) (H : ∃ (b : α), X = cl R b), a ∈ X,
sorry,
end,
Hdisjoint := begin
cases R with R hR,
-- If two equivalence classes overlap, they are equal.
show ∀ (X Y : set α), (∃ (a : α), X = cl R a) →
(∃ (b : α), Y = cl R b) → (X ∩ Y).nonempty → X = Y,
sorry,
end },
-- Conversely, say P is an partition.
inv_fun := λ P,
-- Let's define a binary relation `R` thus:
-- `R a b` iff *every* block containing `a` also contains `b`.
-- Because only one block contains a, this will work,
-- and it turns out to be a nice way of thinking about it.
⟨λ a b, ∀ X ∈ P.C, a ∈ X → b ∈ X, begin
-- I claim this is an equivalence relation.
split,
{ -- It's reflexive
show ∀ (a : α)
(X : set α), X ∈ P.C → a ∈ X → a ∈ X,
sorry,
},
split,
{ -- it's symmetric
show ∀ (a b : α),
(∀ (X : set α), X ∈ P.C → a ∈ X → b ∈ X) →
∀ (X : set α), X ∈ P.C → b ∈ X → a ∈ X,
sorry,
},
{ -- it's transitive
unfold transitive,
show ∀ (a b c : α),
(∀ (X : set α), X ∈ P.C → a ∈ X → b ∈ X) →
(∀ (X : set α), X ∈ P.C → b ∈ X → c ∈ X) →
∀ (X : set α), X ∈ P.C → a ∈ X → c ∈ X,
sorry,
}
end⟩,
-- If you start with the equivalence relation, and then make the partition
-- and a new equivalence relation, you get back to where you started.
left_inv := begin
rintro ⟨R, hR⟩,
-- Tidying up the mess...
suffices : (λ (a b : α), ∀ (c : α), a ∈ cl R c → b ∈ cl R c) = R,
simpa,
-- ... you have to prove two binary relations are equal.
ext a b,
-- so you have to prove an if and only if.
show (∀ (c : α), a ∈ cl R c → b ∈ cl R c) ↔ R a b,
sorry,
end,
-- Similarly, if you start with the partition, and then make the
-- equivalence relation, and then construct the corresponding partition
-- into equivalence classes, you have the same partition you started with.
right_inv := begin
-- Let P be a partition
intro P,
-- It suffices to prove that a subset X is in the original partition
-- if and only if it's in the one made from the equivalence relation.
ext X,
show (∃ (a : α), X = cl _ a) ↔ X ∈ P.C,
dsimp only,
sorry,
end }
/-
-- get these files with
leanproject get ImperialCollegeLondon/M40001_lean
leave this channel and go to a workgroup channel and try
folling in the sorrys.
I will come around to help.
-/ |
9792692896b19b37a26388c36e48c6d0c48d0518 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /stage0/src/Init/Lean/Meta/FunInfo.lean | 4797ce08725f1ff24b8720821ff67398040f396f | [
"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 | 3,210 | 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
import Init.Lean.Meta.InferType
namespace Lean
namespace Meta
@[inline] private def checkFunInfoCache (fn : Expr) (maxArgs? : Option Nat) (k : MetaM FunInfo) : MetaM FunInfo := do
s ← get;
t ← getTransparency;
match s.cache.funInfo.find? ⟨t, fn, maxArgs?⟩ with
| some finfo => pure finfo
| none => do
finfo ← k;
modify $ fun s => { cache := { funInfo := s.cache.funInfo.insert ⟨t, fn, maxArgs?⟩ finfo, .. s.cache }, .. s };
pure finfo
@[inline] private def whenHasVar {α} (e : Expr) (deps : α) (k : α → α) : α :=
if e.hasFVar then k deps else deps
private def collectDepsAux (fvars : Array Expr) : Expr → Array Nat → Array Nat
| e@(Expr.app f a _), deps => whenHasVar e deps (collectDepsAux a ∘ collectDepsAux f)
| e@(Expr.forallE _ d b _), deps => whenHasVar e deps (collectDepsAux b ∘ collectDepsAux d)
| e@(Expr.lam _ d b _), deps => whenHasVar e deps (collectDepsAux b ∘ collectDepsAux d)
| e@(Expr.letE _ t v b _), deps => whenHasVar e deps (collectDepsAux b ∘ collectDepsAux v ∘ collectDepsAux t)
| Expr.proj _ _ e _, deps => collectDepsAux e deps
| Expr.mdata _ e _, deps => collectDepsAux e deps
| e@(Expr.fvar _ _), deps =>
match fvars.indexOf e with
| none => deps
| some i => if deps.contains i.val then deps else deps.push i.val
| _, deps => deps
private def collectDeps (fvars : Array Expr) (e : Expr) : Array Nat :=
let deps := collectDepsAux fvars e #[];
deps.qsort (fun i j => i < j)
/-- Update `hasFwdDeps` fields using new `backDeps` -/
private def updateHasFwdDeps (pinfo : Array ParamInfo) (backDeps : Array Nat) : Array ParamInfo :=
if backDeps.size == 0 then
pinfo
else
-- update hasFwdDeps fields
pinfo.mapIdx $ fun i info =>
if info.hasFwdDeps then info
else if backDeps.contains i then
{ hasFwdDeps := true, .. info }
else
info
private def getFunInfoAux (fn : Expr) (maxArgs? : Option Nat) : MetaM FunInfo :=
checkFunInfoCache fn maxArgs? $ do
fnType ← inferType fn;
withTransparency TransparencyMode.default $
forallBoundedTelescope fnType maxArgs? $ fun fvars type => do
pinfo ← fvars.size.foldM
(fun (i : Nat) (pinfo : Array ParamInfo) => do
let fvar := fvars.get! i;
decl ← getFVarLocalDecl fvar;
let backDeps := collectDeps fvars decl.type;
let pinfo := updateHasFwdDeps pinfo backDeps;
pure $ pinfo.push {
backDeps := backDeps,
implicit := decl.binderInfo == BinderInfo.implicit,
instImplicit := decl.binderInfo == BinderInfo.instImplicit })
#[];
let resultDeps := collectDeps fvars type;
let pinfo := updateHasFwdDeps pinfo resultDeps;
pure { resultDeps := resultDeps, paramInfo := pinfo }
def getFunInfo (fn : Expr) : MetaM FunInfo :=
getFunInfoAux fn none
def getFunInfoNArgs (fn : Expr) (nargs : Nat) : MetaM FunInfo :=
getFunInfoAux fn (some nargs)
end Meta
end Lean
|
c54cf4cdfbbb4041424315a8cebb443e7a8e18dd | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/finsupp/order.lean | ca2d3b3d1f3a5e20144f1be758bb9710f97d90e9 | [
"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 | 7,464 | lean | /-
Copyright (c) 2021 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Aaron Anderson
-/
import data.finsupp.basic
/-!
# Pointwise order on finitely supported functions
This file lifts order structures on `α` to `ι →₀ α`.
## Main declarations
* `finsupp.order_embedding_to_fun`: The order embedding from finitely supported functions to
functions.
* `finsupp.order_iso_multiset`: The order isomorphism between `ℕ`-valued finitely supported
functions and multisets.
-/
noncomputable theory
open_locale classical big_operators
open finset
variables {ι α : Type*}
namespace finsupp
/-! ### Order structures -/
section has_zero
variables [has_zero α]
section has_le
variables [has_le α]
instance : has_le (ι →₀ α) := ⟨λ f g, ∀ i, f i ≤ g i⟩
lemma le_def {f g : ι →₀ α} : f ≤ g ↔ ∀ i, f i ≤ g i := iff.rfl
/-- The order on `finsupp`s over a partial order embeds into the order on functions -/
def order_embedding_to_fun : (ι →₀ α) ↪o (ι → α) :=
{ to_fun := λ f, f,
inj' := λ f g h, finsupp.ext $ λ i, by { dsimp at h, rw h },
map_rel_iff' := λ a b, (@le_def _ _ _ _ a b).symm }
@[simp] lemma order_embedding_to_fun_apply {f : ι →₀ α} {i : ι} :
order_embedding_to_fun f i = f i := rfl
end has_le
section preorder
variables [preorder α]
instance : preorder (ι →₀ α) :=
{ le_refl := λ f i, le_rfl,
le_trans := λ f g h hfg hgh i, (hfg i).trans (hgh i),
.. finsupp.has_le }
lemma monotone_to_fun : monotone (finsupp.to_fun : (ι →₀ α) → (ι → α)) := λ f g h a, le_def.1 h a
end preorder
instance [partial_order α] : partial_order (ι →₀ α) :=
{ le_antisymm := λ f g hfg hgf, ext $ λ i, (hfg i).antisymm (hgf i),
.. finsupp.preorder }
instance [semilattice_inf α] : semilattice_inf (ι →₀ α) :=
{ inf := zip_with (⊓) inf_idem,
inf_le_left := λ f g i, inf_le_left,
inf_le_right := λ f g i, inf_le_right,
le_inf := λ f g i h1 h2 s, le_inf (h1 s) (h2 s),
..finsupp.partial_order, }
@[simp] lemma inf_apply [semilattice_inf α] {i : ι} {f g : ι →₀ α} : (f ⊓ g) i = f i ⊓ g i := rfl
instance [semilattice_sup α] : semilattice_sup (ι →₀ α) :=
{ sup := zip_with (⊔) sup_idem,
le_sup_left := λ f g i, le_sup_left,
le_sup_right := λ f g i, le_sup_right,
sup_le := λ f g h hf hg i, sup_le (hf i) (hg i),
..finsupp.partial_order }
@[simp] lemma sup_apply [semilattice_sup α] {i : ι} {f g : ι →₀ α} : (f ⊔ g) i = f i ⊔ g i := rfl
instance lattice [lattice α] : lattice (ι →₀ α) :=
{ .. finsupp.semilattice_inf, .. finsupp.semilattice_sup }
end has_zero
/-! ### Algebraic order structures -/
instance [ordered_add_comm_monoid α] : ordered_add_comm_monoid (ι →₀ α) :=
{ 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 α] : ordered_cancel_add_comm_monoid (ι →₀ α) :=
{ le_of_add_le_add_left := λ f g i h s, le_of_add_le_add_left (h s),
add_left_cancel := λ f g i h, ext $ λ s, add_left_cancel (ext_iff.1 h s),
.. finsupp.ordered_add_comm_monoid }
instance [ordered_add_comm_monoid α] [contravariant_class α α (+) (≤)] :
contravariant_class (ι →₀ α) (ι →₀ α) (+) (≤) :=
⟨λ f g h H x, le_of_add_le_add_left $ H x⟩
section canonically_ordered_add_monoid
variables [canonically_ordered_add_monoid α]
instance : order_bot (ι →₀ α) :=
{ bot := 0,
bot_le := by simp only [le_def, coe_zero, pi.zero_apply, implies_true_iff, zero_le]}
protected lemma bot_eq_zero : (⊥ : ι →₀ α) = 0 := rfl
@[simp] lemma add_eq_zero_iff (f g : ι →₀ α) : f + g = 0 ↔ f = 0 ∧ g = 0 :=
by simp [ext_iff, forall_and_distrib]
lemma le_iff' (f g : ι →₀ α) {s : finset ι} (hf : f.support ⊆ s) : f ≤ g ↔ ∀ i ∈ s, f i ≤ g i :=
⟨λ h s hs, h s,
λ h s, if H : s ∈ f.support then h s (hf H) else (not_mem_support_iff.1 H).symm ▸ zero_le (g s)⟩
lemma le_iff (f g : ι →₀ α) : f ≤ g ↔ ∀ i ∈ f.support, f i ≤ g i := le_iff' f g $ subset.refl _
instance decidable_le [decidable_rel (@has_le.le α _)] : decidable_rel (@has_le.le (ι →₀ α) _) :=
λ f g, decidable_of_iff _ (le_iff f g).symm
@[simp] lemma single_le_iff {i : ι} {x : α} {f : ι →₀ α} : single i x ≤ f ↔ x ≤ f i :=
(le_iff' _ _ support_single_subset).trans $ by simp
variables [has_sub α] [has_ordered_sub α] {f g : ι →₀ α} {i : ι} {a b : α}
/-- This is called `tsub` for truncated subtraction, to distinguish it with subtraction in an
additive group. -/
instance tsub : has_sub (ι →₀ α) := ⟨zip_with (λ m n, m - n) (tsub_self 0)⟩
instance : has_ordered_sub (ι →₀ α) := ⟨λ n m k, forall_congr $ λ x, tsub_le_iff_right⟩
instance : canonically_ordered_add_monoid (ι →₀ α) :=
{ le_iff_exists_add := λ f g, begin
refine ⟨λ h, ⟨g - f, _⟩, _⟩,
{ ext x,
exact (add_tsub_cancel_of_le $ h x).symm },
{ rintro ⟨g, rfl⟩ x,
exact self_le_add_right (f x) (g x) }
end,
.. finsupp.order_bot,
.. finsupp.ordered_add_comm_monoid }
@[simp] lemma coe_tsub (f g : ι →₀ α) : ⇑(f - g) = f - g := rfl
lemma tsub_apply (f g : ι →₀ α) (a : ι) : (f - g) a = f a - g a := rfl
@[simp] lemma single_tsub : single i (a - b) = single i a - single i b :=
begin
ext j,
obtain rfl | h := eq_or_ne i j,
{ rw [tsub_apply, single_eq_same, single_eq_same, single_eq_same] },
{ rw [tsub_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, tsub_self] }
end
lemma support_tsub {f1 f2 : ι →₀ α} : (f1 - f2).support ⊆ f1.support :=
by simp only [subset_iff, tsub_eq_zero_iff_le, mem_support_iff, ne.def, coe_tsub, pi.sub_apply,
not_imp_not, zero_le, implies_true_iff] {contextual := tt}
lemma subset_support_tsub {f1 f2 : ι →₀ α} : f1.support \ f2.support ⊆ (f1 - f2).support :=
by simp [subset_iff] {contextual := tt}
end canonically_ordered_add_monoid
section canonically_linear_ordered_add_monoid
variables [canonically_linear_ordered_add_monoid α] [decidable_eq ι] {f g : ι →₀ α}
@[simp] lemma support_inf : (f ⊓ g).support = f.support ∩ g.support :=
begin
ext,
simp only [inf_apply, mem_support_iff, ne.def,
finset.mem_union, finset.mem_filter, finset.mem_inter],
simp only [inf_eq_min, ←nonpos_iff_eq_zero, min_le_iff, not_or_distrib],
end
@[simp] lemma support_sup : (f ⊔ g).support = f.support ∪ g.support :=
begin
ext,
simp only [finset.mem_union, mem_support_iff, sup_apply, ne.def, ←bot_eq_zero],
rw [_root_.sup_eq_bot_iff, not_and_distrib],
end
lemma disjoint_iff : disjoint f g ↔ disjoint f.support g.support :=
begin
rw [disjoint_iff, disjoint_iff, finsupp.bot_eq_zero, ← finsupp.support_eq_empty,
finsupp.support_inf],
refl,
end
end canonically_linear_ordered_add_monoid
/-! ### Some lemmas about `ℕ` -/
section nat
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
end finsupp
|
042a79fc39878d7a357318ed8766b7377dc483ff | 75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2 | /library/theories/number_theory/bezout.lean | e7a6b24635828d25719d5f95d1f0e20cf6a6970b | [
"Apache-2.0"
] | permissive | jroesch/lean | 30ef0860fa905d35b9ad6f76de1a4f65c9af6871 | 3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2 | refs/heads/master | 1,586,090,835,348 | 1,455,142,203,000 | 1,455,142,277,000 | 51,536,958 | 1 | 0 | null | 1,455,215,811,000 | 1,455,215,811,000 | null | UTF-8 | Lean | false | false | 3,904 | lean | /-
Copyright (c) 2015 William Peterson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: William Peterson, Jeremy Avigad
Extended gcd, Bezout's theorem, chinese remainder theorem.
-/
import data.nat.div data.int .primes
/- Bezout's theorem -/
section Bezout
open nat int
open eq.ops well_founded decidable prod
private definition pair_nat.lt : ℕ × ℕ → ℕ × ℕ → Prop := measure pr₂
private definition pair_nat.lt.wf : well_founded pair_nat.lt := intro_k (measure.wf pr₂) 20
local attribute pair_nat.lt.wf [instance]
local infixl `≺`:50 := pair_nat.lt
private definition gcd.lt.dec (x y₁ : ℕ) : (succ y₁, x % succ y₁) ≺ (x, succ y₁) :=
!nat.mod_lt (succ_pos y₁)
private definition egcd_rec_f (z : ℤ) : ℤ → ℤ → ℤ × ℤ := λ s t, (t, s - t * z)
definition egcd.F : Π (p₁ : ℕ × ℕ), (Π p₂ : ℕ × ℕ, p₂ ≺ p₁ → ℤ × ℤ) → ℤ × ℤ
| (x, y) := nat.cases_on y
(λ f, (1, 0) )
(λ y₁ (f : Π p₂, p₂ ≺ (x, succ y₁) → ℤ × ℤ),
let bz := f (succ y₁, x % succ y₁) !gcd.lt.dec in
prod.cases_on bz (egcd_rec_f (x / succ y₁)))
definition egcd (x y : ℕ) := fix egcd.F (pair x y)
theorem egcd_zero (x : ℕ) : egcd x 0 = (1, 0) :=
well_founded.fix_eq egcd.F (x, 0)
theorem egcd_succ (x y : ℕ) :
egcd x (succ y) = prod.cases_on (egcd (succ y) (x % succ y)) (egcd_rec_f (x / succ y)) :=
well_founded.fix_eq egcd.F (x, succ y)
theorem egcd_of_pos (x : ℕ) {y : ℕ} (ypos : y > 0) :
let erec := egcd y (x % y), u := pr₁ erec, v := pr₂ erec in
egcd x y = (v, u - v * (x / y)) :=
obtain (y' : nat) (yeq : y = succ y'), from exists_eq_succ_of_pos ypos,
begin
rewrite [yeq, egcd_succ, -prod.eta (egcd _ _)],
esimp, unfold egcd_rec_f,
rewrite [of_nat_div]
end
theorem egcd_prop (x y : ℕ) : (pr₁ (egcd x y)) * x + (pr₂ (egcd x y)) * y = gcd x y :=
gcd.induction x y
(take m, by krewrite [egcd_zero, mul_zero, one_mul])
(take m n,
assume npos : 0 < n,
assume IH,
begin
note H := egcd_of_pos m npos, esimp at H,
rewrite H,
esimp,
rewrite [gcd_rec, -IH],
rewrite [add.comm],
rewrite [-of_nat_mod],
rewrite [int.mod_def],
rewrite [+mul_sub_right_distrib],
rewrite [+mul_sub_left_distrib, *left_distrib],
rewrite [*sub_eq_add_neg, {pr₂ (egcd n (m % n)) * of_nat m + - _}add.comm],
rewrite [-add.assoc, mul.assoc]
end)
theorem Bezout_aux (x y : ℕ) : ∃ a b : ℤ, a * x + b * y = gcd x y :=
exists.intro _ (exists.intro _ (egcd_prop x y))
theorem Bezout (x y : ℤ) : ∃ a b : ℤ, a * x + b * y = gcd x y :=
obtain a' b' (H : a' * nat_abs x + b' * nat_abs y = gcd x y), from !Bezout_aux,
begin
existsi (a' * sign x),
existsi (b' * sign y),
rewrite [*mul.assoc, -*abs_eq_sign_mul, -*of_nat_nat_abs],
apply H
end
end Bezout
/-
A sample application of Bezout's theorem, namely, an alternative proof that irreducible
implies prime (dvd_or_dvd_of_prime_of_dvd_mul).
-/
namespace nat
open int
example {p x y : ℕ} (pp : prime p) (H : p ∣ x * y) : p ∣ x ∨ p ∣ y :=
decidable.by_cases
(suppose p ∣ x, or.inl this)
(suppose ¬ p ∣ x,
have cpx : coprime p x, from coprime_of_prime_of_not_dvd pp this,
obtain (a b : ℤ) (Hab : a * p + b * x = gcd p x), from Bezout_aux p x,
assert a * p * y + b * x * y = y,
by rewrite [-right_distrib, Hab, ↑coprime at cpx, cpx, int.one_mul],
have p ∣ y,
begin
apply dvd_of_of_nat_dvd_of_nat,
rewrite [-this],
apply @dvd_add,
{apply dvd_mul_of_dvd_left,
apply dvd_mul_of_dvd_right,
apply dvd.refl},
{rewrite mul.assoc,
apply dvd_mul_of_dvd_right,
apply of_nat_dvd_of_nat_of_dvd H}
end,
or.inr this)
end nat
|
d99de735a8695203caa566738e2602e750ce15d3 | 5fbbd711f9bfc21ee168f46a4be146603ece8835 | /lean/natural_number_game/proposition/8.lean | f4163b1f0328d6921c6f64e1f717d236695ae7ab | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | goedel-gang/maths | 22596f71e3fde9c088e59931f128a3b5efb73a2c | a20a6f6a8ce800427afd595c598a5ad43da1408d | refs/heads/master | 1,623,055,941,960 | 1,621,599,441,000 | 1,621,599,441,000 | 169,335,840 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 85 | lean | lemma contrapositive (P Q : Prop) : (P → Q) → (¬ Q → ¬ P) :=
begin
cc,
end
|
5a23c1970ca848b18d7c4e1ac4365d497ccc43f7 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /hott/homotopy/complex_hopf.hlean | e89308bf61ad4d90ab4f565f2ef82cd16bc0ce57 | [
"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 | 1,650 | hlean | /-
Copyright (c) 2016 Ulrik Buchholtz and Egbert Rijke. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Ulrik Buchholtz, Egbert Rijke, Floris van Doorn
The H-space structure on S¹ and the complex Hopf fibration
(the standard one).
-/
import .hopf .circle types.fin
open eq equiv is_equiv circle is_conn trunc is_trunc sphere susp pointed fiber sphere.ops function
namespace hopf
definition circle_h_space [instance] : h_space S¹ :=
⦃ h_space, one := base, mul := circle_mul,
one_mul := circle_base_mul, mul_one := circle_mul_base ⦄
definition circle_assoc (x y z : S¹) : (x * y) * z = x * (y * z) :=
begin
induction x,
{ reflexivity },
{ apply eq_pathover, induction y,
{ exact natural_square_tr
(λa : S¹, ap (λb : S¹, b * z) (circle_mul_base a))
loop },
{ apply is_prop.elimo, apply is_trunc_square } }
end
open sphere_index
definition complex_hopf : S 3 → S 2 :=
begin
intro x, apply @sigma.pr1 (susp S¹) (hopf S¹),
apply inv (hopf.total S¹), apply inv (join.spheres 1 1), exact x
end
definition complex_phopf [constructor] : S* 3 →* S* 2 :=
proof pmap.mk complex_hopf idp qed
definition pfiber_complex_phopf : pfiber complex_phopf ≃* S* 1 :=
begin
fapply pequiv_of_equiv,
{ esimp, unfold [complex_hopf],
refine fiber.equiv_precompose (sigma.pr1 ∘ (hopf.total S¹)⁻¹ᵉ)
(join.spheres (of_nat 1) (of_nat 1))⁻¹ᵉ _ ⬝e _,
refine fiber.equiv_precompose _ (hopf.total S¹)⁻¹ᵉ _ ⬝e _,
apply fiber_pr1},
{ reflexivity}
end
end hopf
|
405538ecbb191597b4128a03d97968b6266eff09 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/ring_theory/is_tensor_product.lean | 23e7bdcfeb9b84d7259ab270d84ee919fa48e948 | [
"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 | 18,322 | lean | /-
Copyright (c) 2022 Andrew Yang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andrew Yang
-/
import ring_theory.tensor_product
import algebra.module.ulift
/-!
# The characteristice predicate of tensor product
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
## Main definitions
- `is_tensor_product`: A predicate on `f : M₁ →ₗ[R] M₂ →ₗ[R] M` expressing that `f` realizes `M` as
the tensor product of `M₁ ⊗[R] M₂`. This is defined by requiring the lift `M₁ ⊗[R] M₂ → M` to be
bijective.
- `is_base_change`: A predicate on an `R`-algebra `S` and a map `f : M →ₗ[R] N` with `N` being a
`S`-module, expressing that `f` realizes `N` as the base change of `M` along `R → S`.
- `algebra.is_pushout`: A predicate on the following diagram of scalar towers
```
R → S
↓ ↓
R' → S'
```
asserting that is a pushout diagram (i.e. `S' = S ⊗[R] R'`)
## Main results
- `tensor_product.is_base_change`: `S ⊗[R] M` is the base change of `M` along `R → S`.
-/
universes u v₁ v₂ v₃ v₄
open_locale tensor_product
open tensor_product
section is_tensor_product
variables {R : Type*} [comm_ring R]
variables {M₁ M₂ M M' : Type*}
variables [add_comm_monoid M₁] [add_comm_monoid M₂] [add_comm_monoid M] [add_comm_monoid M']
variables [module R M₁] [module R M₂] [module R M] [module R M']
variable (f : M₁ →ₗ[R] M₂ →ₗ[R] M)
variables {N₁ N₂ N : Type*} [add_comm_monoid N₁] [add_comm_monoid N₂] [add_comm_monoid N]
variables [module R N₁] [module R N₂] [module R N]
variable {g : N₁ →ₗ[R] N₂ →ₗ[R] N}
/--
Given a bilinear map `f : M₁ →ₗ[R] M₂ →ₗ[R] M`, `is_tensor_product f` means that
`M` is the tensor product of `M₁` and `M₂` via `f`.
This is defined by requiring the lift `M₁ ⊗[R] M₂ → M` to be bijective.
-/
def is_tensor_product : Prop := function.bijective (tensor_product.lift f)
variables (R M N) {f}
lemma tensor_product.is_tensor_product : is_tensor_product (tensor_product.mk R M N) :=
begin
delta is_tensor_product,
convert_to function.bijective linear_map.id using 2,
{ apply tensor_product.ext', simp },
{ exact function.bijective_id }
end
variables {R M N}
/-- If `M` is the tensor product of `M₁` and `M₂`, it is linearly equivalent to `M₁ ⊗[R] M₂`. -/
@[simps apply] noncomputable
def is_tensor_product.equiv (h : is_tensor_product f) : M₁ ⊗[R] M₂ ≃ₗ[R] M :=
linear_equiv.of_bijective _ h
@[simp] lemma is_tensor_product.equiv_to_linear_map (h : is_tensor_product f) :
h.equiv.to_linear_map = tensor_product.lift f := rfl
@[simp] lemma is_tensor_product.equiv_symm_apply (h : is_tensor_product f) (x₁ : M₁) (x₂ : M₂) :
h.equiv.symm (f x₁ x₂) = x₁ ⊗ₜ x₂ :=
begin
apply h.equiv.injective,
refine (h.equiv.apply_symm_apply _).trans _,
simp
end
/-- If `M` is the tensor product of `M₁` and `M₂`, we may lift a bilinear map `M₁ →ₗ[R] M₂ →ₗ[R] M'`
to a `M →ₗ[R] M'`. -/
noncomputable
def is_tensor_product.lift (h : is_tensor_product f) (f' : M₁ →ₗ[R] M₂ →ₗ[R] M') : M →ₗ[R] M' :=
(tensor_product.lift f').comp h.equiv.symm.to_linear_map
lemma is_tensor_product.lift_eq (h : is_tensor_product f) (f' : M₁ →ₗ[R] M₂ →ₗ[R] M')
(x₁ : M₁) (x₂ : M₂) : h.lift f' (f x₁ x₂) = f' x₁ x₂ :=
begin
delta is_tensor_product.lift,
simp,
end
/-- The tensor product of a pair of linear maps between modules. -/
noncomputable
def is_tensor_product.map (hf : is_tensor_product f) (hg : is_tensor_product g)
(i₁ : M₁ →ₗ[R] N₁) (i₂ : M₂ →ₗ[R] N₂) : M →ₗ[R] N :=
hg.equiv.to_linear_map.comp ((tensor_product.map i₁ i₂).comp hf.equiv.symm.to_linear_map)
lemma is_tensor_product.map_eq (hf : is_tensor_product f) (hg : is_tensor_product g)
(i₁ : M₁ →ₗ[R] N₁) (i₂ : M₂ →ₗ[R] N₂) (x₁ : M₁) (x₂ : M₂) :
hf.map hg i₁ i₂ (f x₁ x₂) = g (i₁ x₁) (i₂ x₂) :=
begin
delta is_tensor_product.map,
simp
end
lemma is_tensor_product.induction_on (h : is_tensor_product f) {C : M → Prop}
(m : M) (h0 : C 0) (htmul : ∀ x y, C (f x y)) (hadd : ∀ x y, C x → C y → C (x + y)) : C m :=
begin
rw ← h.equiv.right_inv m,
generalize : h.equiv.inv_fun m = y,
change C (tensor_product.lift f y),
induction y using tensor_product.induction_on,
{ rwa map_zero },
{ rw tensor_product.lift.tmul, apply htmul },
{ rw map_add, apply hadd; assumption }
end
end is_tensor_product
section is_base_change
variables {R : Type*} {M : Type v₁} {N : Type v₂} (S : Type v₃)
variables [add_comm_monoid M] [add_comm_monoid N] [comm_ring R]
variables [comm_ring S] [algebra R S] [module R M] [module R N] [module S N] [is_scalar_tower R S N]
variables (f : M →ₗ[R] N)
include f
/-- Given an `R`-algebra `S` and an `R`-module `M`, an `S`-module `N` together with a map
`f : M →ₗ[R] N` is the base change of `M` to `S` if the map `S × M → N, (s, m) ↦ s • f m` is the
tensor product. -/
def is_base_change : Prop := is_tensor_product
(((algebra.of_id S $ module.End S (M →ₗ[R] N)).to_linear_map.flip f).restrict_scalars R)
variables {S f} (h : is_base_change S f)
variables {P Q : Type*} [add_comm_monoid P] [module R P]
variables [add_comm_monoid Q] [module S Q]
section
variables [module R Q] [is_scalar_tower R S Q]
/-- Suppose `f : M →ₗ[R] N` is the base change of `M` along `R → S`. Then any `R`-linear map from
`M` to an `S`-module factors thorugh `f`. -/
noncomputable
def is_base_change.lift (g : M →ₗ[R] Q) : N →ₗ[S] Q :=
{ map_smul' := λ r x, begin
let F := ((algebra.of_id S $ module.End S (M →ₗ[R] Q))
.to_linear_map.flip g).restrict_scalars R,
have hF : ∀ (s : S) (m : M), h.lift F (s • f m) = s • g m := h.lift_eq F,
change h.lift F (r • x) = r • h.lift F x,
apply h.induction_on x,
{ rw [smul_zero, map_zero, smul_zero] },
{ intros s m,
change h.lift F (r • s • f m) = r • h.lift F (s • f m),
rw [← mul_smul, hF, hF, mul_smul] },
{ intros x₁ x₂ e₁ e₂, rw [map_add, smul_add, map_add, smul_add, e₁, e₂] }
end,
..(h.lift (((algebra.of_id S $ module.End S (M →ₗ[R] Q))
.to_linear_map.flip g).restrict_scalars R)) }
lemma is_base_change.lift_eq (g : M →ₗ[R] Q) (x : M) : h.lift g (f x) = g x :=
begin
have hF : ∀ (s : S) (m : M), h.lift g (s • f m) = s • g m := h.lift_eq _,
convert hF 1 x; rw one_smul,
end
lemma is_base_change.lift_comp (g : M →ₗ[R] Q) : ((h.lift g).restrict_scalars R).comp f = g :=
linear_map.ext (h.lift_eq g)
end
include h
@[elab_as_eliminator]
lemma is_base_change.induction_on (x : N) (P : N → Prop)
(h₁ : P 0)
(h₂ : ∀ m : M, P (f m))
(h₃ : ∀ (s : S) n, P n → P (s • n))
(h₄ : ∀ n₁ n₂, P n₁ → P n₂ → P (n₁ + n₂)) : P x :=
h.induction_on x h₁ (λ s y, h₃ _ _ (h₂ _)) h₄
lemma is_base_change.alg_hom_ext (g₁ g₂ : N →ₗ[S] Q) (e : ∀ x, g₁ (f x) = g₂ (f x)) :
g₁ = g₂ :=
begin
ext x,
apply h.induction_on x,
{ rw [map_zero, map_zero] },
{ assumption },
{ intros s n e', rw [g₁.map_smul, g₂.map_smul, e'] },
{ intros x y e₁ e₂, rw [map_add, map_add, e₁, e₂] }
end
lemma is_base_change.alg_hom_ext' [module R Q] [is_scalar_tower R S Q] (g₁ g₂ : N →ₗ[S] Q)
(e : (g₁.restrict_scalars R).comp f = (g₂.restrict_scalars R).comp f) :
g₁ = g₂ :=
h.alg_hom_ext g₁ g₂ (linear_map.congr_fun e)
variables (R M N S)
omit h f
lemma tensor_product.is_base_change : is_base_change S (tensor_product.mk R S M 1) :=
begin
delta is_base_change,
convert tensor_product.is_tensor_product R S M using 1,
ext s x,
change s • 1 ⊗ₜ x = s ⊗ₜ x,
rw tensor_product.smul_tmul',
congr' 1,
exact mul_one _,
end
variables {R M N S}
/-- The base change of `M` along `R → S` is linearly equivalent to `S ⊗[R] M`. -/
noncomputable
def is_base_change.equiv : S ⊗[R] M ≃ₗ[S] N :=
{ map_smul' := λ r x, begin
change h.equiv (r • x) = r • h.equiv x,
apply tensor_product.induction_on x,
{ rw [smul_zero, map_zero, smul_zero] },
{ intros x y, simp [smul_tmul', algebra.of_id_apply] },
{ intros x y hx hy, rw [map_add, smul_add, map_add, smul_add, hx, hy] },
end,
..h.equiv }
lemma is_base_change.equiv_tmul (s : S) (m : M) : h.equiv (s ⊗ₜ m) = s • (f m) :=
tensor_product.lift.tmul s m
lemma is_base_change.equiv_symm_apply (m : M) : h.equiv.symm (f m) = 1 ⊗ₜ m :=
by rw [h.equiv.symm_apply_eq, h.equiv_tmul, one_smul]
variable (f)
lemma is_base_change.of_lift_unique
(h : ∀ (Q : Type (max v₁ v₂ v₃)) [add_comm_monoid Q], by exactI ∀ [module R Q] [module S Q],
by exactI ∀ [is_scalar_tower R S Q], by exactI ∀ (g : M →ₗ[R] Q),
∃! (g' : N →ₗ[S] Q), (g'.restrict_scalars R).comp f = g) : is_base_change S f :=
begin
obtain ⟨g, hg, -⟩ := h (ulift.{v₂} $ S ⊗[R] M)
(ulift.module_equiv.symm.to_linear_map.comp $ tensor_product.mk R S M 1),
let f' : S ⊗[R] M →ₗ[R] N := _, change function.bijective f',
let f'' : S ⊗[R] M →ₗ[S] N,
{ refine { to_fun := f', map_smul' := λ s x,
tensor_product.induction_on x _ (λ s' y, smul_assoc s s' _) (λ x y hx hy, _), .. f' },
{ rw [map_zero, smul_zero, map_zero, smul_zero] },
{ rw [smul_add, map_add, map_add, smul_add, hx, hy] } },
simp_rw [fun_like.ext_iff, linear_map.comp_apply, linear_map.restrict_scalars_apply] at hg,
let fe : S ⊗[R] M ≃ₗ[S] N :=
linear_equiv.of_linear f'' (ulift.module_equiv.to_linear_map.comp g) _ _,
{ exact fe.bijective },
{ rw ← (linear_map.cancel_left (ulift.module_equiv : ulift.{max v₁ v₃} N ≃ₗ[S] N).symm.injective),
refine (h (ulift.{max v₁ v₃} N) $ ulift.module_equiv.symm.to_linear_map.comp f).unique _ rfl,
{ apply_instance },
ext x,
simp only [linear_map.comp_apply, linear_map.restrict_scalars_apply, hg],
apply one_smul },
{ ext x, change (g $ (1 : S) • f x).down = _, rw [one_smul, hg], refl },
end
variable {f}
lemma is_base_change.iff_lift_unique :
is_base_change S f ↔
∀ (Q : Type (max v₁ v₂ v₃)) [add_comm_monoid Q], by exactI ∀ [module R Q] [module S Q],
by exactI ∀ [is_scalar_tower R S Q], by exactI ∀ (g : M →ₗ[R] Q),
∃! (g' : N →ₗ[S] Q), (g'.restrict_scalars R).comp f = g :=
⟨λ h, by { introsI,
exact ⟨h.lift g, h.lift_comp g, λ g' e, h.alg_hom_ext' _ _ (e.trans (h.lift_comp g).symm)⟩ },
is_base_change.of_lift_unique f⟩
lemma is_base_change.of_equiv (e : M ≃ₗ[R] N) : is_base_change R e.to_linear_map :=
begin
apply is_base_change.of_lift_unique,
introsI Q I₁ I₂ I₃ I₄ g,
have : I₂ = I₃,
{ ext r q,
rw [← one_smul R q, smul_smul, ← smul_assoc, smul_eq_mul, mul_one] },
unfreezingI { cases this },
refine ⟨g.comp e.symm.to_linear_map, by { ext, simp }, _⟩,
rintros y (rfl : _ = _),
ext,
simp,
end
variables {T O : Type*} [comm_ring T] [algebra R T] [algebra S T] [is_scalar_tower R S T]
variables [add_comm_monoid O] [module R O] [module S O] [module T O] [is_scalar_tower S T O]
variables [is_scalar_tower R S O] [is_scalar_tower R T O]
lemma is_base_change.comp {f : M →ₗ[R] N} (hf : is_base_change S f) {g : N →ₗ[S] O}
(hg : is_base_change T g) : is_base_change T ((g.restrict_scalars R).comp f) :=
begin
apply is_base_change.of_lift_unique,
introsI Q _ _ _ _ i,
letI := module.comp_hom Q (algebra_map S T),
haveI : is_scalar_tower S T Q := ⟨λ x y z, by { rw [algebra.smul_def, mul_smul], refl }⟩,
haveI : is_scalar_tower R S Q,
{ refine ⟨λ x y z, _⟩,
change (is_scalar_tower.to_alg_hom R S T) (x • y) • z = x • (algebra_map S T y • z),
rw [alg_hom.map_smul, smul_assoc],
refl },
refine ⟨hg.lift (hf.lift i), by { ext, simp [is_base_change.lift_eq] }, _⟩,
rintros g' (e : _ = _),
refine hg.alg_hom_ext' _ _ (hf.alg_hom_ext' _ _ _),
rw [is_base_change.lift_comp, is_base_change.lift_comp, ← e],
ext,
refl
end
variables {R' S' : Type*} [comm_ring R'] [comm_ring S']
variables [algebra R R'] [algebra S S'] [algebra R' S'] [algebra R S']
variables [is_scalar_tower R R' S'] [is_scalar_tower R S S']
open is_scalar_tower (to_alg_hom)
variables (R S R' S')
/--
A type-class stating that the following diagram of scalar towers
R → S
↓ ↓
R' → S'
is a pushout diagram (i.e. `S' = S ⊗[R] R'`)
-/
@[mk_iff]
class algebra.is_pushout : Prop :=
(out : is_base_change S (to_alg_hom R R' S').to_linear_map)
variables {R S R' S'}
lemma algebra.is_pushout.symm
(h : algebra.is_pushout R S R' S') :
algebra.is_pushout R R' S S' :=
begin
letI := (algebra.tensor_product.include_right : R' →ₐ[R] S ⊗ R').to_ring_hom.to_algebra,
let e : R' ⊗[R] S ≃ₗ[R'] S',
{ refine { map_smul' := _, ..(tensor_product.comm R R' S).trans $ h.1.equiv.restrict_scalars R },
intros r x,
change
h.1.equiv (tensor_product.comm R R' S (r • x)) = r • h.1.equiv (tensor_product.comm R R' S x),
apply tensor_product.induction_on x,
{ simp only [smul_zero, map_zero] },
{ intros x y,
simp [smul_tmul', algebra.smul_def, ring_hom.algebra_map_to_algebra, h.1.equiv_tmul],
ring },
{ intros x y hx hy, simp only [map_add, smul_add, hx, hy] } },
have : (to_alg_hom R S S').to_linear_map
= (e.to_linear_map.restrict_scalars R).comp (tensor_product.mk R R' S 1),
{ ext, simp [e, h.1.equiv_tmul, algebra.smul_def] },
constructor,
rw this,
exact (tensor_product.is_base_change R S R').comp (is_base_change.of_equiv e),
end
variables (R S R' S')
lemma algebra.is_pushout.comm :
algebra.is_pushout R S R' S' ↔ algebra.is_pushout R R' S S' :=
⟨algebra.is_pushout.symm, algebra.is_pushout.symm⟩
variables {R S R'}
local attribute [instance] algebra.tensor_product.right_algebra
instance tensor_product.is_pushout {R S T : Type*} [comm_ring R] [comm_ring S] [comm_ring T]
[algebra R S] [algebra R T] :
algebra.is_pushout R S T (tensor_product R S T) :=
⟨tensor_product.is_base_change R T S⟩
instance tensor_product.is_pushout' {R S T : Type*} [comm_ring R] [comm_ring S] [comm_ring T]
[algebra R S] [algebra R T] :
algebra.is_pushout R T S (tensor_product R S T) :=
algebra.is_pushout.symm infer_instance
/--
If `S' = S ⊗[R] R'`, then any pair of `R`-algebra homomorphisms `f : S → A` and `g : R' → A`
such that `f x` and `g y` commutes for all `x, y` descends to a (unique) homomoprhism `S' → A`.
-/
@[simps apply (lemmas_only)] noncomputable
def algebra.pushout_desc [H : algebra.is_pushout R S R' S']
{A : Type*} [semiring A] [algebra R A] (f : S →ₐ[R] A) (g : R' →ₐ[R] A)
(hf : ∀ x y, f x * g y = g y * f x) : S' →ₐ[R] A :=
begin
letI := module.comp_hom A f.to_ring_hom,
haveI : is_scalar_tower R S A :=
{ smul_assoc := λ r s a, show f (r • s) * a = r • (f s * a), by rw [f.map_smul, smul_mul_assoc] },
haveI : is_scalar_tower S A A :=
{ smul_assoc := λ r a b, mul_assoc _ _ _ },
have : ∀ x, H.out.lift g.to_linear_map (algebra_map R' S' x) = g x := H.out.lift_eq _,
refine alg_hom.of_linear_map ((H.out.lift g.to_linear_map).restrict_scalars R) _ _,
{ dsimp only [linear_map.restrict_scalars_apply],
rw [← (algebra_map R' S').map_one, this, g.map_one] },
{ intros x y,
apply H.out.induction_on x,
{ rw [zero_mul, map_zero, zero_mul] },
rotate,
{ intros s s' e, dsimp only [linear_map.restrict_scalars_apply] at e ⊢,
rw [linear_map.map_smul, smul_mul_assoc, linear_map.map_smul, e, smul_mul_assoc] },
{ intros s s' e₁ e₂, dsimp only [linear_map.restrict_scalars_apply] at e₁ e₂ ⊢,
rw [add_mul, map_add, map_add, add_mul, e₁, e₂] },
intro x, dsimp, rw this, apply H.out.induction_on y,
{ rw [mul_zero, map_zero, mul_zero] },
{ intro y, dsimp, rw [← _root_.map_mul, this, this, _root_.map_mul] },
{ intros s s' e,
rw [mul_comm, smul_mul_assoc, linear_map.map_smul, linear_map.map_smul, mul_comm, e],
change f s * (g x * _) = g x * (f s * _),
rw [← mul_assoc, ← mul_assoc, hf] },
{ intros s s' e₁ e₂, rw [mul_add, map_add, map_add, mul_add, e₁, e₂] }, }
end
@[simp]
lemma algebra.pushout_desc_left [H : algebra.is_pushout R S R' S']
{A : Type*} [semiring A] [algebra R A] (f : S →ₐ[R] A) (g : R' →ₐ[R] A) (H) (x : S) :
algebra.pushout_desc S' f g H (algebra_map S S' x) = f x :=
begin
rw [algebra.pushout_desc_apply, algebra.algebra_map_eq_smul_one, linear_map.map_smul,
← algebra.pushout_desc_apply S' f g H, _root_.map_one],
exact mul_one (f x)
end
lemma algebra.lift_alg_hom_comp_left [H : algebra.is_pushout R S R' S']
{A : Type*} [semiring A] [algebra R A] (f : S →ₐ[R] A) (g : R' →ₐ[R] A) (H) :
(algebra.pushout_desc S' f g H).comp (to_alg_hom R S S') = f :=
alg_hom.ext (λ x, (algebra.pushout_desc_left S' f g H x : _))
@[simp]
lemma algebra.pushout_desc_right [H : algebra.is_pushout R S R' S']
{A : Type*} [semiring A] [algebra R A] (f : S →ₐ[R] A) (g : R' →ₐ[R] A) (H) (x : R') :
algebra.pushout_desc S' f g H (algebra_map R' S' x) = g x :=
begin
apply_with @@is_base_change.lift_eq { instances := ff },
end
lemma algebra.lift_alg_hom_comp_right [H : algebra.is_pushout R S R' S']
{A : Type*} [semiring A] [algebra R A] (f : S →ₐ[R] A) (g : R' →ₐ[R] A) (H) :
(algebra.pushout_desc S' f g H).comp (to_alg_hom R R' S') = g :=
alg_hom.ext (λ x, (algebra.pushout_desc_right S' f g H x : _))
@[ext]
lemma algebra.is_pushout.alg_hom_ext [H : algebra.is_pushout R S R' S']
{A : Type*} [semiring A] [algebra R A] {f g : S' →ₐ[R] A}
(h₁ : f.comp (to_alg_hom R R' S') = g.comp (to_alg_hom R R' S'))
(h₂ : f.comp (to_alg_hom R S S') = g.comp (to_alg_hom R S S')) : f = g :=
begin
ext x,
apply H.1.induction_on x,
{ simp only [map_zero] },
{ exact alg_hom.congr_fun h₁ },
{ intros s s' e, rw [algebra.smul_def, f.map_mul, g.map_mul, e],
congr' 1, exact (alg_hom.congr_fun h₂ s : _) },
{ intros s₁ s₂ e₁ e₂, rw [map_add, map_add, e₁, e₂] }
end
end is_base_change
|
e2cddde3cf0b8e843d8e214372679e7c9cc196df | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/hott/777.hlean | 803afd309ee1bfceb3b276905a281543e3e68f62 | [
"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 | 239 | hlean | namespace sum
definition code.{u v} {A : Type.{u}} {B : Type.{v}} : A + B → A + B → Type.{max u v}
| code (inl a) (inl a') := lift (a = a')
| code (inr b) (inr b') := lift (b = b')
| code _ _ := lift empty
end sum
|
057143df1d8de82785bd21ae6a8951ac6eab284c | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/category_theory/monoidal/subcategory.lean | a1d995d799d5b6d912eb19deaaf233ed24a5ee9d | [
"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,302 | lean | /-
Copyright (c) 2022 Antoine Labelle. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Antoine Labelle
-/
import category_theory.monoidal.braided
import category_theory.monoidal.linear
import category_theory.preadditive.additive_functor
import category_theory.linear.linear_functor
import category_theory.closed.monoidal
/-!
# Full monoidal subcategories
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Given a monidal category `C` and a monoidal predicate on `C`, that is a function `P : C → Prop`
closed under `𝟙_` and `⊗`, we can put a monoidal structure on `{X : C // P X}` (the category
structure is defined in `category_theory.full_subcategory`).
When `C` is also braided/symmetric, the full monoidal subcategory also inherits the
braided/symmetric structure.
## TODO
* Add monoidal/braided versions of `category_theory.full_subcategory.lift`
-/
universes u v
namespace category_theory
namespace monoidal_category
open iso
variables {C : Type u} [category.{v} C] [monoidal_category C] (P : C → Prop)
/--
A property `C → Prop` is a monoidal predicate if it is closed under `𝟙_` and `⊗`.
-/
class monoidal_predicate : Prop :=
(prop_id' : P (𝟙_ C) . obviously)
(prop_tensor' : ∀ {X Y}, P X → P Y → P (X ⊗ Y) . obviously)
restate_axiom monoidal_predicate.prop_id'
restate_axiom monoidal_predicate.prop_tensor'
open monoidal_predicate
variables [monoidal_predicate P]
/--
When `P` is a monoidal predicate, the full subcategory for `P` inherits the monoidal structure of
`C`.
-/
instance full_monoidal_subcategory : monoidal_category (full_subcategory P) :=
{ tensor_obj := λ X Y, ⟨X.1 ⊗ Y.1, prop_tensor X.2 Y.2⟩,
tensor_hom := λ X₁ Y₁ X₂ Y₂ f g, by { change X₁.1 ⊗ X₂.1 ⟶ Y₁.1 ⊗ Y₂.1,
change X₁.1 ⟶ Y₁.1 at f, change X₂.1 ⟶ Y₂.1 at g, exact f ⊗ g },
tensor_unit := ⟨𝟙_ C, prop_id⟩,
associator := λ X Y Z,
⟨(α_ X.1 Y.1 Z.1).hom, (α_ X.1 Y.1 Z.1).inv,
hom_inv_id (α_ X.1 Y.1 Z.1), inv_hom_id (α_ X.1 Y.1 Z.1)⟩,
left_unitor := λ X, ⟨(λ_ X.1).hom, (λ_ X.1).inv, hom_inv_id (λ_ X.1), inv_hom_id (λ_ X.1)⟩,
right_unitor := λ X, ⟨(ρ_ X.1).hom, (ρ_ X.1).inv, hom_inv_id (ρ_ X.1), inv_hom_id (ρ_ X.1)⟩,
tensor_id' := λ X Y, tensor_id X.1 Y.1,
tensor_comp' := λ X₁ Y₁ Z₁ X₂ Y₂ Z₂ f₁ f₂ g₁ g₂, tensor_comp f₁ f₂ g₁ g₂,
associator_naturality' := λ X₁ X₂ X₃ Y₁ Y₂ Y₃ f₁ f₂ f₃, associator_naturality f₁ f₂ f₃,
left_unitor_naturality' := λ X Y f, left_unitor_naturality f,
right_unitor_naturality' := λ X Y f, right_unitor_naturality f,
pentagon' := λ W X Y Z, pentagon W.1 X.1 Y.1 Z.1,
triangle' := λ X Y, triangle X.1 Y.1 }
/--
The forgetful monoidal functor from a full monoidal subcategory into the original category
("forgetting" the condition).
-/
@[simps]
def full_monoidal_subcategory_inclusion : monoidal_functor (full_subcategory P) C :=
{ to_functor := full_subcategory_inclusion P,
ε := 𝟙 _,
μ := λ X Y, 𝟙 _ }
instance full_monoidal_subcategory.full :
full (full_monoidal_subcategory_inclusion P).to_functor := full_subcategory.full P
instance full_monoidal_subcategory.faithful :
faithful (full_monoidal_subcategory_inclusion P).to_functor := full_subcategory.faithful P
section
variables [preadditive C]
instance full_monoidal_subcategory_inclusion_additive :
(full_monoidal_subcategory_inclusion P).to_functor.additive :=
functor.full_subcategory_inclusion_additive _
instance [monoidal_preadditive C] : monoidal_preadditive (full_subcategory P) :=
monoidal_preadditive_of_faithful (full_monoidal_subcategory_inclusion P)
variables (R : Type*) [ring R] [linear R C]
instance full_monoidal_subcategory_inclusion_linear :
(full_monoidal_subcategory_inclusion P).to_functor.linear R :=
functor.full_subcategory_inclusion_linear R _
instance [monoidal_preadditive C] [monoidal_linear R C] : monoidal_linear R (full_subcategory P) :=
monoidal_linear_of_faithful R (full_monoidal_subcategory_inclusion P)
end
variables {P} {P' : C → Prop} [monoidal_predicate P']
/-- An implication of predicates `P → P'` induces a monoidal functor between full monoidal
subcategories. -/
@[simps]
def full_monoidal_subcategory.map (h : ∀ ⦃X⦄, P X → P' X) :
monoidal_functor (full_subcategory P) (full_subcategory P') :=
{ to_functor := full_subcategory.map h,
ε := 𝟙 _,
μ := λ X Y, 𝟙 _ }
instance full_monoidal_subcategory.map_full (h : ∀ ⦃X⦄, P X → P' X) :
full (full_monoidal_subcategory.map h).to_functor := { preimage := λ X Y f, f }
instance full_monoidal_subcategory.map_faithful (h : ∀ ⦃X⦄, P X → P' X) :
faithful (full_monoidal_subcategory.map h).to_functor := {}
section braided
variables (P) [braided_category C]
/--
The braided structure on a full subcategory inherited by the braided structure on `C`.
-/
instance full_braided_subcategory : braided_category (full_subcategory P) :=
braided_category_of_faithful (full_monoidal_subcategory_inclusion P)
(λ X Y, ⟨(β_ X.1 Y.1).hom, (β_ X.1 Y.1).inv, (β_ X.1 Y.1).hom_inv_id, (β_ X.1 Y.1).inv_hom_id⟩)
(λ X Y, by tidy)
/--
The forgetful braided functor from a full braided subcategory into the original category
("forgetting" the condition).
-/
@[simps]
def full_braided_subcategory_inclusion : braided_functor (full_subcategory P) C :=
{ to_monoidal_functor := full_monoidal_subcategory_inclusion P,
braided' := λ X Y, by { rw [is_iso.eq_inv_comp], tidy } }
instance full_braided_subcategory.full :
full (full_braided_subcategory_inclusion P).to_functor := full_monoidal_subcategory.full P
instance full_braided_subcategory.faithful :
faithful (full_braided_subcategory_inclusion P).to_functor := full_monoidal_subcategory.faithful P
variables {P}
/-- An implication of predicates `P → P'` induces a braided functor between full braided
subcategories. -/
@[simps]
def full_braided_subcategory.map (h : ∀ ⦃X⦄, P X → P' X) :
braided_functor (full_subcategory P) (full_subcategory P') :=
{ to_monoidal_functor := full_monoidal_subcategory.map h,
braided' := λ X Y, by { rw [is_iso.eq_inv_comp], tidy } }
instance full_braided_subcategory.map_full (h : ∀ ⦃X⦄, P X → P' X) :
full (full_braided_subcategory.map h).to_functor := full_monoidal_subcategory.map_full h
instance full_braided_subcategory.map_faithful (h : ∀ ⦃X⦄, P X → P' X) :
faithful (full_braided_subcategory.map h).to_functor := full_monoidal_subcategory.map_faithful h
end braided
section symmetric
variables (P) [symmetric_category C]
instance full_symmetric_subcategory : symmetric_category (full_subcategory P) :=
symmetric_category_of_faithful (full_braided_subcategory_inclusion P)
end symmetric
section closed
variables (P) [monoidal_closed C]
/--
A property `C → Prop` is a closed predicate if it is closed under taking internal homs
-/
class closed_predicate : Prop :=
(prop_ihom' : ∀ {X Y}, P X → P Y → P ((ihom X).obj Y) . obviously)
restate_axiom closed_predicate.prop_ihom'
open closed_predicate
variable [closed_predicate P]
instance full_monoidal_closed_subcategory : monoidal_closed (full_subcategory P) :=
{ closed' := λ X,
{ is_adj :=
{ right := full_subcategory.lift P (full_subcategory_inclusion P ⋙ (ihom X.1))
(λ Y, prop_ihom X.2 Y.2),
adj := adjunction.mk_of_unit_counit
{ unit := { app := λ Y, (ihom.coev X.1).app Y.1,
naturality' := λ Y Z f, ihom.coev_naturality X.1 f },
counit := { app := λ Y, (ihom.ev X.1).app Y.1,
naturality' := λ Y Z f, ihom.ev_naturality X.1 f },
left_triangle' := by { ext Y, simp, exact ihom.ev_coev X.1 Y.1 },
right_triangle' := by { ext Y, simp, exact ihom.coev_ev X.1 Y.1 } } } } }
@[simp] lemma full_monoidal_closed_subcategory_ihom_obj (X Y : full_subcategory P) :
((ihom X).obj Y).obj = (ihom (X.obj)).obj Y.obj := rfl
@[simp] lemma full_monoidal_closed_subcategory_ihom_map (X : full_subcategory P)
{Y Z : full_subcategory P}
(f : Y ⟶ Z) : (ihom X).map f = (ihom (X.obj)).map f := rfl
end closed
end monoidal_category
end category_theory
|
a1e46bf7fcd1851e73eedeccfa5204c4f7af8583 | ec62863c729b7eedee77b86d974f2c529fa79d25 | /3/b.lean | ba977f97df137d8e649dc410484240cc3d92811a | [] | no_license | rwbarton/advent-of-lean-4 | 2ac9b17ba708f66051e3d8cd694b0249bc433b65 | 417c7e2718253ba7148c0279fcb251b6fc291477 | refs/heads/main | 1,675,917,092,057 | 1,609,864,581,000 | 1,609,864,581,000 | 317,700,289 | 24 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 415 | lean | def solve (num denom : Nat) (xs : List String) : Int :=
let f n x :=
Nat.mod n denom == 0 &&
x.get (Nat.mod (num * n.div denom) x.length) == '#';
((List.zipWith f (List.range xs.length) xs).filter id).length
def main : IO Unit :=
do let input ← IO.FS.lines "a.in"
let xs := input.toList
let result := solve 1 1 xs * solve 3 1 xs * solve 5 1 xs * solve 7 1 xs * solve 1 2 xs
IO.print s!"{result}\n"
|
dde266ba95b01855b95f21ff7365ad2e93420d66 | 4950bf76e5ae40ba9f8491647d0b6f228ddce173 | /src/linear_algebra/tensor_product.lean | c85418bb450f8b178b90880379abcb3e44487ab7 | [
"Apache-2.0"
] | permissive | ntzwq/mathlib | ca50b21079b0a7c6781c34b62199a396dd00cee2 | 36eec1a98f22df82eaccd354a758ef8576af2a7f | refs/heads/master | 1,675,193,391,478 | 1,607,822,996,000 | 1,607,822,996,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 30,675 | 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
-/
import group_theory.congruence
import linear_algebra.basic
/-!
# Tensor product of semimodules over commutative semirings.
This file constructs the tensor product of semimodules over commutative semirings. Given a semiring
`R` and semimodules over it `M` and `N`, the standard construction of the tensor product is
`tensor_product R M N`. It is also a semimodule over `R`.
It comes with a canonical bilinear map `M → N → tensor_product R M N`.
Given any bilinear map `M → N → P`, there is a unique linear map `tensor_product R M N → P` whose
composition with the canonical bilinear map `M → N → tensor_product R M N` is the given bilinear
map `M → N → P`.
We start by proving basic lemmas about bilinear maps.
## Notations
This file uses the localized notation `M ⊗ N` and `M ⊗[R] N` for `tensor_product R M N`, as well
as `m ⊗ₜ n` and `m ⊗ₜ[R] n` for `tensor_product.tmul R m n`.
## Tags
bilinear, tensor, tensor product
-/
namespace linear_map
variables {R : Type*} [comm_semiring R]
variables {M : Type*} {N : Type*} {P : Type*} {Q : Type*} {S : Type*}
variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q]
[add_comm_monoid S]
variables [semimodule R M] [semimodule R N] [semimodule R P] [semimodule R Q] [semimodule R S]
include R
variables (R)
/-- Create a bilinear map from a function that is linear in each component. -/
def mk₂ (f : M → N → P)
(H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n)
(H2 : ∀ (c:R) m n, f (c • m) n = c • f m n)
(H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂)
(H4 : ∀ (c:R) m n, f m (c • n) = c • f m n) : M →ₗ N →ₗ P :=
⟨λ m, ⟨f m, H3 m, λ c, H4 c m⟩,
λ m₁ m₂, linear_map.ext $ H1 m₁ m₂,
λ c m, linear_map.ext $ H2 c m⟩
variables {R}
@[simp] theorem mk₂_apply
(f : M → N → P) {H1 H2 H3 H4} (m : M) (n : N) :
(mk₂ R f H1 H2 H3 H4 : M →ₗ[R] N →ₗ P) m n = f m n := rfl
theorem ext₂ {f g : M →ₗ[R] N →ₗ[R] P}
(H : ∀ m n, f m n = g m n) : f = g :=
linear_map.ext (λ m, linear_map.ext $ λ n, H m n)
/-- Given a linear map from `M` to linear maps from `N` to `P`, i.e., a bilinear map from `M × N` to
`P`, change the order of variables and get a linear map from `N` to linear maps from `M` to `P`. -/
def flip (f : M →ₗ[R] N →ₗ[R] P) : N →ₗ M →ₗ P :=
mk₂ R (λ n m, f m n)
(λ n₁ n₂ m, (f m).map_add _ _)
(λ c n m, (f m).map_smul _ _)
(λ n m₁ m₂, by rw f.map_add; refl)
(λ c n m, by rw f.map_smul; refl)
variable (f : M →ₗ[R] N →ₗ[R] P)
@[simp] theorem flip_apply (m : M) (n : N) : flip f n m = f m n := rfl
variables {R}
theorem flip_inj {f g : M →ₗ[R] N →ₗ P} (H : flip f = flip g) : f = g :=
ext₂ $ λ m n, show flip f n m = flip g n m, by rw H
variables (R M N P)
/-- Given a linear map from `M` to linear maps from `N` to `P`, i.e., a bilinear map `M → N → P`,
change the order of variables and get a linear map from `N` to linear maps from `M` to `P`. -/
def lflip : (M →ₗ[R] N →ₗ P) →ₗ[R] N →ₗ M →ₗ P :=
⟨flip, λ _ _, rfl, λ _ _, rfl⟩
variables {R M N P}
@[simp] theorem lflip_apply (m : M) (n : N) : lflip R M N P f n m = f m n := rfl
theorem map_zero₂ (y) : f 0 y = 0 := (flip f y).map_zero
theorem map_neg₂ {R : Type*} [comm_semiring R] {M N P : Type*}
[add_comm_group M] [add_comm_group N] [add_comm_group P]
[semimodule R M] [semimodule R N] [semimodule R P] (f : M →ₗ[R] N →ₗ[R] P) (x y) :
f (-x) y = -f x y :=
(flip f y).map_neg _
theorem map_add₂ (x₁ x₂ y) : f (x₁ + x₂) y = f x₁ y + f x₂ y := (flip f y).map_add _ _
theorem map_smul₂ (r:R) (x y) : f (r • x) y = r • f x y := (flip f y).map_smul _ _
variables (R P)
/-- Composing a linear map `M → N` and a linear map `N → P` to form a linear map `M → P`. -/
def lcomp (f : M →ₗ[R] N) : (N →ₗ[R] P) →ₗ[R] M →ₗ[R] P :=
flip $ linear_map.comp (flip id) f
variables {R P}
@[simp] theorem lcomp_apply (f : M →ₗ[R] N) (g : N →ₗ P) (x : M) :
lcomp R P f g x = g (f x) := rfl
variables (R M N P)
/-- Composing a linear map `M → N` and a linear map `N → P` to form a linear map `M → P`. -/
def llcomp : (N →ₗ[R] P) →ₗ[R] (M →ₗ[R] N) →ₗ M →ₗ P :=
flip ⟨lcomp R P,
λ f f', ext₂ $ λ g x, g.map_add _ _,
λ c f, ext₂ $ λ g x, g.map_smul _ _⟩
variables {R M N P}
section
@[simp] theorem llcomp_apply (f : N →ₗ[R] P) (g : M →ₗ[R] N) (x : M) :
llcomp R M N P f g x = f (g x) := rfl
end
/-- Composing a linear map `Q → N` and a bilinear map `M → N → P` to
form a bilinear map `M → Q → P`. -/
def compl₂ (g : Q →ₗ N) : M →ₗ Q →ₗ P := (lcomp R _ g).comp f
@[simp] theorem compl₂_apply (g : Q →ₗ[R] N) (m : M) (q : Q) :
f.compl₂ g m q = f m (g q) := rfl
/-- Composing a linear map `P → Q` and a bilinear map `M × N → P` to
form a bilinear map `M → N → Q`. -/
def compr₂ (g : P →ₗ Q) : M →ₗ N →ₗ Q :=
linear_map.comp (llcomp R N P Q g) f
@[simp] theorem compr₂_apply (g : P →ₗ[R] Q) (m : M) (n : N) :
f.compr₂ g m n = g (f m n) := rfl
variables (R M)
/-- Scalar multiplication as a bilinear map `R → M → M`. -/
def lsmul : R →ₗ M →ₗ M :=
mk₂ R (•) add_smul (λ _ _ _, mul_smul _ _ _) smul_add
(λ r s m, by simp only [smul_smul, smul_eq_mul, mul_comm])
variables {R M}
@[simp] theorem lsmul_apply (r : R) (m : M) : lsmul R M r m = r • m := rfl
end linear_map
section semiring
variables {R : Type*} [comm_semiring R]
variables {M : Type*} {N : Type*} {P : Type*} {Q : Type*} {S : Type*}
variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q]
[add_comm_monoid S]
variables [semimodule R M] [semimodule R N] [semimodule R P] [semimodule R Q] [semimodule R S]
include R
variables (M N)
namespace tensor_product
section
-- open free_add_monoid
variables (R)
/-- The relation on `free_add_monoid (M × N)` that generates a congruence whose quotient is
the tensor product. -/
inductive eqv : free_add_monoid (M × N) → free_add_monoid (M × N) → Prop
| of_zero_left : ∀ n : N, eqv (free_add_monoid.of (0, n)) 0
| of_zero_right : ∀ m : M, eqv (free_add_monoid.of (m, 0)) 0
| of_add_left : ∀ (m₁ m₂ : M) (n : N), eqv
(free_add_monoid.of (m₁, n) + free_add_monoid.of (m₂, n)) (free_add_monoid.of (m₁ + m₂, n))
| of_add_right : ∀ (m : M) (n₁ n₂ : N), eqv
(free_add_monoid.of (m, n₁) + free_add_monoid.of (m, n₂)) (free_add_monoid.of (m, n₁ + n₂))
| of_smul : ∀ (r : R) (m : M) (n : N), eqv
(free_add_monoid.of (r • m, n)) (free_add_monoid.of (m, r • n))
| add_comm : ∀ x y, eqv (x + y) (y + x)
end
end tensor_product
variables (R)
/-- The tensor product of two semimodules `M` and `N` over the same commutative semiring `R`.
The localized notations are `M ⊗ N` and `M ⊗[R] N`, accessed by `open_locale tensor_product`. -/
def tensor_product : Type* :=
(add_con_gen (tensor_product.eqv R M N)).quotient
variables {R}
localized "infix ` ⊗ `:100 := tensor_product _" in tensor_product
localized "notation M ` ⊗[`:100 R `] ` N:100 := tensor_product R M N" in tensor_product
namespace tensor_product
section module
instance : add_comm_monoid (M ⊗[R] N) :=
{ add_comm := λ x y, add_con.induction_on₂ x y $ λ x y, quotient.sound' $
add_con_gen.rel.of _ _ $ eqv.add_comm _ _,
.. (add_con_gen (tensor_product.eqv R M N)).add_monoid }
instance : inhabited (M ⊗[R] N) := ⟨0⟩
variables (R) {M N}
/-- The canonical function `M → N → M ⊗ N`. The localized notations are `m ⊗ₜ n` and `m ⊗ₜ[R] n`,
accessed by `open_locale tensor_product`. -/
def tmul (m : M) (n : N) : M ⊗[R] N := add_con.mk' _ $ free_add_monoid.of (m, n)
variables {R}
infix ` ⊗ₜ `:100 := tmul _
notation x ` ⊗ₜ[`:100 R `] ` y := tmul R x y
@[elab_as_eliminator]
protected theorem induction_on
{C : (M ⊗[R] N) → Prop}
(z : M ⊗[R] N)
(C0 : C 0)
(C1 : ∀ {x y}, C $ x ⊗ₜ[R] y)
(Cp : ∀ {x y}, C x → C y → C (x + y)) : C z :=
add_con.induction_on z $ λ x, free_add_monoid.rec_on x C0 $ λ ⟨m, n⟩ y ih,
by { rw add_con.coe_add, exact Cp C1 ih }
variables (M)
@[simp] lemma zero_tmul (n : N) : (0 ⊗ₜ n : M ⊗[R] N) = 0 :=
quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_zero_left _
variables {M}
lemma add_tmul (m₁ m₂ : M) (n : N) : (m₁ + m₂) ⊗ₜ n = m₁ ⊗ₜ n + m₂ ⊗ₜ[R] n :=
eq.symm $ quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_add_left _ _ _
variables (N)
@[simp] lemma tmul_zero (m : M) : (m ⊗ₜ 0 : M ⊗[R] N) = 0 :=
quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_zero_right _
variables {N}
lemma tmul_add (m : M) (n₁ n₂ : N) : m ⊗ₜ (n₁ + n₂) = m ⊗ₜ n₁ + m ⊗ₜ[R] n₂ :=
eq.symm $ quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_add_right _ _ _
lemma smul_tmul (r : R) (m : M) (n : N) : (r • m) ⊗ₜ n = m ⊗ₜ[R] (r • n) :=
quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_smul _ _ _
/-- Auxiliary function to defining scalar multiplication on tensor product. -/
def smul.aux (r : R) : free_add_monoid (M × N) →+ M ⊗[R] N :=
free_add_monoid.lift $ λ p : M × N, (r • p.1) ⊗ₜ p.2
theorem smul.aux_of (r : R) (m : M) (n : N) :
smul.aux r (free_add_monoid.of (m, n)) = (r • m) ⊗ₜ n :=
rfl
instance : has_scalar R (M ⊗[R] N) :=
⟨λ r, (add_con_gen (tensor_product.eqv R M N)).lift (smul.aux r) $ add_con.add_con_gen_le $
λ x y hxy, match x, y, hxy with
| _, _, (eqv.of_zero_left n) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_zero, smul.aux_of, smul_zero, zero_tmul]
| _, _, (eqv.of_zero_right m) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_zero, smul.aux_of, tmul_zero]
| _, _, (eqv.of_add_left m₁ m₂ n) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_add, smul.aux_of, smul_add, add_tmul]
| _, _, (eqv.of_add_right m n₁ n₂) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_add, smul.aux_of, tmul_add]
| _, _, (eqv.of_smul s m n) := (add_con.ker_rel _).2 $
by simp_rw [smul.aux_of, smul_tmul, smul_smul, mul_comm]
| _, _, (eqv.add_comm x y) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_add, add_comm]
end⟩
protected theorem smul_zero (r : R) : (r • 0 : M ⊗[R] N) = 0 :=
add_monoid_hom.map_zero _
protected theorem smul_add (r : R) (x y : M ⊗[R] N) :
r • (x + y) = r • x + r • y :=
add_monoid_hom.map_add _ _ _
theorem smul_tmul' (r : R) (m : M) (n : N) :
r • (m ⊗ₜ n : M ⊗[R] N) = (r • m) ⊗ₜ n :=
rfl
instance : semimodule R (M ⊗[R] N) :=
{ smul := (•),
smul_add := λ r x y, tensor_product.smul_add r x y,
mul_smul := λ r s x, tensor_product.induction_on x
(by simp_rw tensor_product.smul_zero)
(λ m n, by simp_rw [smul_tmul', mul_smul])
(λ x y ihx ihy, by { simp_rw tensor_product.smul_add, rw [ihx, ihy] }),
one_smul := λ x, tensor_product.induction_on x
(by rw tensor_product.smul_zero)
(λ m n, by rw [smul_tmul', one_smul])
(λ x y ihx ihy, by rw [tensor_product.smul_add, ihx, ihy]),
add_smul := λ r s x, tensor_product.induction_on x
(by simp_rw [tensor_product.smul_zero, add_zero])
(λ m n, by simp_rw [smul_tmul', add_smul, add_tmul])
(λ x y ihx ihy, by { simp_rw tensor_product.smul_add, rw [ihx, ihy, add_add_add_comm] }),
smul_zero := λ r, tensor_product.smul_zero r,
zero_smul := λ x, tensor_product.induction_on x
(by rw tensor_product.smul_zero)
(λ m n, by rw [smul_tmul', zero_smul, zero_tmul])
(λ x y ihx ihy, by rw [tensor_product.smul_add, ihx, ihy, add_zero]) }
@[simp] lemma tmul_smul (r : R) (x : M) (y : N) : x ⊗ₜ (r • y) = r • (x ⊗ₜ[R] y) :=
(smul_tmul _ _ _).symm
variables (R M N)
/-- The canonical bilinear map `M → N → M ⊗[R] N`. -/
def mk : M →ₗ N →ₗ M ⊗[R] N :=
linear_map.mk₂ R (⊗ₜ) add_tmul (λ c m n, by rw [smul_tmul, tmul_smul]) tmul_add tmul_smul
variables {R M N}
@[simp] lemma mk_apply (m : M) (n : N) : mk R M N m n = m ⊗ₜ n := rfl
lemma ite_tmul (x₁ : M) (x₂ : N) (P : Prop) [decidable P] :
((if P then x₁ else 0) ⊗ₜ[R] x₂) = if P then (x₁ ⊗ₜ x₂) else 0 :=
by { split_ifs; simp }
lemma tmul_ite (x₁ : M) (x₂ : N) (P : Prop) [decidable P] :
(x₁ ⊗ₜ[R] (if P then x₂ else 0)) = if P then (x₁ ⊗ₜ x₂) else 0 :=
by { split_ifs; simp }
section
open_locale big_operators
lemma sum_tmul {α : Type*} (s : finset α) (m : α → M) (n : N) :
((∑ a in s, m a) ⊗ₜ[R] n) = ∑ a in s, m a ⊗ₜ[R] n :=
begin
classical,
induction s using finset.induction with a s has ih h,
{ simp, },
{ simp [finset.sum_insert has, add_tmul, ih], },
end
lemma tmul_sum (m : M) {α : Type*} (s : finset α) (n : α → N) :
(m ⊗ₜ[R] (∑ a in s, n a)) = ∑ a in s, m ⊗ₜ[R] n a :=
begin
classical,
induction s using finset.induction with a s has ih h,
{ simp, },
{ simp [finset.sum_insert has, tmul_add, ih], },
end
end
end module
section UMP
variables {M N P Q}
variables (f : M →ₗ[R] N →ₗ[R] P)
/-- Auxiliary function to constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P`
with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is
the given bilinear map `M → N → P`. -/
def lift_aux : (M ⊗[R] N) →+ P :=
(add_con_gen (tensor_product.eqv R M N)).lift (free_add_monoid.lift $ λ p : M × N, f p.1 p.2) $
add_con.add_con_gen_le $ λ x y hxy, match x, y, hxy with
| _, _, (eqv.of_zero_left n) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_zero, free_add_monoid.lift_eval_of, f.map_zero₂]
| _, _, (eqv.of_zero_right m) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_zero, free_add_monoid.lift_eval_of, (f m).map_zero]
| _, _, (eqv.of_add_left m₁ m₂ n) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_add, free_add_monoid.lift_eval_of, f.map_add₂]
| _, _, (eqv.of_add_right m n₁ n₂) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_add, free_add_monoid.lift_eval_of, (f m).map_add]
| _, _, (eqv.of_smul r m n) := (add_con.ker_rel _).2 $
by simp_rw [free_add_monoid.lift_eval_of, f.map_smul₂, (f m).map_smul]
| _, _, (eqv.add_comm x y) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_add, add_comm]
end
lemma lift_aux_tmul (m n) : lift_aux f (m ⊗ₜ n) = f m n :=
zero_add _
variable {f}
@[simp] lemma lift_aux.smul (r : R) (x) : lift_aux f (r • x) = r • lift_aux f x :=
tensor_product.induction_on x (smul_zero _).symm
(λ p q, by rw [← tmul_smul, lift_aux_tmul, lift_aux_tmul, (f p).map_smul])
(λ p q ih1 ih2, by rw [smul_add, (lift_aux f).map_add, ih1, ih2, (lift_aux f).map_add, smul_add])
variable (f)
/-- Constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that
its composition with the canonical bilinear map `M → N → M ⊗ N` is
the given bilinear map `M → N → P`. -/
def lift : M ⊗ N →ₗ P :=
{ map_smul' := lift_aux.smul,
.. lift_aux f }
variable {f}
@[simp] lemma lift.tmul (x y) : lift f (x ⊗ₜ y) = f x y :=
zero_add _
@[simp] lemma lift.tmul' (x y) : (lift f).1 (x ⊗ₜ y) = f x y :=
lift.tmul _ _
@[ext]
theorem ext {g h : (M ⊗[R] N) →ₗ[R] P}
(H : ∀ x y, g (x ⊗ₜ y) = h (x ⊗ₜ y)) : g = h :=
linear_map.ext $ λ z, tensor_product.induction_on z (by simp_rw linear_map.map_zero) H $
λ x y ihx ihy, by rw [g.map_add, h.map_add, ihx, ihy]
theorem lift.unique {g : (M ⊗[R] N) →ₗ[R] P} (H : ∀ x y, g (x ⊗ₜ y) = f x y) :
g = lift f :=
ext $ λ m n, by rw [H, lift.tmul]
theorem lift_mk : lift (mk R M N) = linear_map.id :=
eq.symm $ lift.unique $ λ x y, rfl
theorem lift_compr₂ (g : P →ₗ Q) : lift (f.compr₂ g) = g.comp (lift f) :=
eq.symm $ lift.unique $ λ x y, by simp
theorem lift_mk_compr₂ (f : M ⊗ N →ₗ P) : lift ((mk R M N).compr₂ f) = f :=
by rw [lift_compr₂ f, lift_mk, linear_map.comp_id]
theorem mk_compr₂_inj {g h : M ⊗ N →ₗ P}
(H : (mk R M N).compr₂ g = (mk R M N).compr₂ h) : g = h :=
by rw [← lift_mk_compr₂ g, H, lift_mk_compr₂]
example : M → N → (M → N → P) → P :=
λ m, flip $ λ f, f m
variables (R M N P)
/-- Linearly constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P`
with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is
the given bilinear map `M → N → P`. -/
def uncurry : (M →ₗ[R] N →ₗ[R] P) →ₗ[R] M ⊗[R] N →ₗ[R] P :=
linear_map.flip $ lift $ (linear_map.lflip _ _ _ _).comp (linear_map.flip linear_map.id)
variables {R M N P}
@[simp] theorem uncurry_apply (f : M →ₗ[R] N →ₗ[R] P) (m : M) (n : N) :
uncurry R M N P f (m ⊗ₜ n) = f m n :=
by rw [uncurry, linear_map.flip_apply, lift.tmul]; refl
variables (R M N P)
/-- A linear equivalence constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P`
with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is
the given bilinear map `M → N → P`. -/
def lift.equiv : (M →ₗ N →ₗ P) ≃ₗ (M ⊗ N →ₗ P) :=
{ inv_fun := λ f, (mk R M N).compr₂ f,
left_inv := λ f, linear_map.ext₂ $ λ m n, lift.tmul _ _,
right_inv := λ f, ext $ λ m n, lift.tmul _ _,
.. uncurry R M N P }
/-- Given a linear map `M ⊗ N → P`, compose it with the canonical bilinear map `M → N → M ⊗ N` to
form a bilinear map `M → N → P`. -/
def lcurry : (M ⊗[R] N →ₗ[R] P) →ₗ[R] M →ₗ[R] N →ₗ[R] P :=
(lift.equiv R M N P).symm
variables {R M N P}
@[simp] theorem lcurry_apply (f : M ⊗[R] N →ₗ[R] P) (m : M) (n : N) :
lcurry R M N P f m n = f (m ⊗ₜ n) := rfl
/-- Given a linear map `M ⊗ N → P`, compose it with the canonical bilinear map `M → N → M ⊗ N` to
form a bilinear map `M → N → P`. -/
def curry (f : M ⊗ N →ₗ P) : M →ₗ N →ₗ P := lcurry R M N P f
@[simp] theorem curry_apply (f : M ⊗ N →ₗ[R] P) (m : M) (n : N) :
curry f m n = f (m ⊗ₜ n) := rfl
theorem ext_threefold {g h : (M ⊗[R] N) ⊗[R] P →ₗ[R] Q}
(H : ∀ x y z, g ((x ⊗ₜ y) ⊗ₜ z) = h ((x ⊗ₜ y) ⊗ₜ z)) : g = h :=
begin
let e := linear_equiv.to_equiv (lift.equiv R (M ⊗[R] N) P Q),
apply e.symm.injective,
refine ext _,
intros x y,
ext z,
exact H x y z
end
-- We'll need this one for checking the pentagon identity!
theorem ext_fourfold {g h : ((M ⊗[R] N) ⊗[R] P) ⊗[R] Q →ₗ[R] S}
(H : ∀ w x y z, g (((w ⊗ₜ x) ⊗ₜ y) ⊗ₜ z) = h (((w ⊗ₜ x) ⊗ₜ y) ⊗ₜ z)) : g = h :=
begin
let e := linear_equiv.to_equiv (lift.equiv R ((M ⊗[R] N) ⊗[R] P) Q S),
apply e.symm.injective,
refine ext_threefold _,
intros x y z,
ext w,
exact H x y z w,
end
end UMP
variables {M N}
section
variables (R M)
/--
The base ring is a left identity for the tensor product of modules, up to linear equivalence.
-/
protected def lid : R ⊗ M ≃ₗ M :=
linear_equiv.of_linear (lift $ linear_map.lsmul R M) (mk R R M 1)
(linear_map.ext $ λ _, by simp)
(ext $ λ r m, by simp; rw [← tmul_smul, ← smul_tmul, smul_eq_mul, mul_one])
end
@[simp] theorem lid_tmul (m : M) (r : R) :
((tensor_product.lid R M) : (R ⊗ M → M)) (r ⊗ₜ m) = r • m :=
begin
dsimp [tensor_product.lid],
simp,
end
@[simp] lemma lid_symm_apply (m : M) :
(tensor_product.lid R M).symm m = 1 ⊗ₜ m := rfl
section
variables (R M N)
/--
The tensor product of modules is commutative, up to linear equivalence.
-/
protected def comm : M ⊗ N ≃ₗ N ⊗ M :=
linear_equiv.of_linear (lift (mk R N M).flip) (lift (mk R M N).flip)
(ext $ λ m n, rfl)
(ext $ λ m n, rfl)
@[simp] theorem comm_tmul (m : M) (n : N) :
(tensor_product.comm R M N) (m ⊗ₜ n) = n ⊗ₜ m := rfl
@[simp] theorem comm_symm_tmul (m : M) (n : N) :
(tensor_product.comm R M N).symm (n ⊗ₜ m) = m ⊗ₜ n := rfl
end
section
variables (R M)
/--
The base ring is a right identity for the tensor product of modules, up to linear equivalence.
-/
protected def rid : M ⊗[R] R ≃ₗ M :=
linear_equiv.trans (tensor_product.comm R M R) (tensor_product.lid R M)
end
@[simp] theorem rid_tmul (m : M) (r : R) :
(tensor_product.rid R M) (m ⊗ₜ r) = r • m :=
begin
dsimp [tensor_product.rid, tensor_product.comm, tensor_product.lid],
simp,
end
@[simp] lemma rid_symm_apply (m : M) :
(tensor_product.rid R M).symm m = m ⊗ₜ 1 := rfl
open linear_map
section
variables (R M N P)
/-- The associator for tensor product of R-modules, as a linear equivalence. -/
protected def assoc : (M ⊗[R] N) ⊗[R] P ≃ₗ[R] M ⊗[R] (N ⊗[R] P) :=
begin
refine linear_equiv.of_linear
(lift $ lift $ comp (lcurry R _ _ _) $ mk _ _ _)
(lift $ comp (uncurry R _ _ _) $ curry $ mk _ _ _)
(mk_compr₂_inj $ linear_map.ext $ λ m, ext $ λ n p, _)
(mk_compr₂_inj $ flip_inj $ linear_map.ext $ λ p, ext $ λ m n, _);
repeat { rw lift.tmul <|> rw compr₂_apply <|> rw comp_apply <|>
rw mk_apply <|> rw flip_apply <|> rw lcurry_apply <|>
rw uncurry_apply <|> rw curry_apply <|> rw id_apply }
end
end
@[simp] theorem assoc_tmul (m : M) (n : N) (p : P) :
(tensor_product.assoc R M N P) ((m ⊗ₜ n) ⊗ₜ p) = m ⊗ₜ (n ⊗ₜ p) := rfl
@[simp] theorem assoc_symm_tmul (m : M) (n : N) (p : P) :
(tensor_product.assoc R M N P).symm (m ⊗ₜ (n ⊗ₜ p)) = (m ⊗ₜ n) ⊗ₜ p := rfl
/-- The tensor product of a pair of linear maps between modules. -/
def map (f : M →ₗ[R] P) (g : N →ₗ Q) : M ⊗ N →ₗ[R] P ⊗ Q :=
lift $ comp (compl₂ (mk _ _ _) g) f
@[simp] theorem map_tmul (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (m : M) (n : N) :
map f g (m ⊗ₜ n) = f m ⊗ₜ g n :=
rfl
section
variables {P' Q' : Type*}
variables [add_comm_monoid P'] [semimodule R P']
variables [add_comm_monoid Q'] [semimodule R Q']
lemma map_comp (f₂ : P →ₗ[R] P') (f₁ : M →ₗ[R] P) (g₂ : Q →ₗ[R] Q') (g₁ : N →ₗ[R] Q) :
map (f₂.comp f₁) (g₂.comp g₁) = (map f₂ g₂).comp (map f₁ g₁) :=
by { ext1, simp only [linear_map.comp_apply, map_tmul] }
lemma lift_comp_map (i : P →ₗ[R] Q →ₗ[R] Q') (f : M →ₗ[R] P) (g : N →ₗ[R] Q) :
(lift i).comp (map f g) = lift ((i.comp f).compl₂ g) :=
by { ext1, simp only [lift.tmul, map_tmul, linear_map.compl₂_apply, linear_map.comp_apply] }
end
/-- If `M` and `P` are linearly equivalent and `N` and `Q` are linearly equivalent
then `M ⊗ N` and `P ⊗ Q` are linearly equivalent. -/
def congr (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) : M ⊗ N ≃ₗ[R] P ⊗ Q :=
linear_equiv.of_linear (map f g) (map f.symm g.symm)
(ext $ λ m n, by simp; simp only [linear_equiv.apply_symm_apply])
(ext $ λ m n, by simp; simp only [linear_equiv.symm_apply_apply])
@[simp] theorem congr_tmul (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) (m : M) (n : N) :
congr f g (m ⊗ₜ n) = f m ⊗ₜ g n :=
rfl
@[simp] theorem congr_symm_tmul (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) (p : P) (q : Q) :
(congr f g).symm (p ⊗ₜ q) = f.symm p ⊗ₜ g.symm q :=
rfl
end tensor_product
namespace linear_map
variables {R} (M) {N P Q}
/-- `ltensor M f : M ⊗ N →ₗ M ⊗ P` is the natural linear map induced by `f : N →ₗ P`. -/
def ltensor (f : N →ₗ[R] P) : M ⊗ N →ₗ[R] M ⊗ P :=
tensor_product.map id f
/-- `rtensor f M : N₁ ⊗ M →ₗ N₂ ⊗ M` is the natural linear map induced by `f : N₁ →ₗ N₂`. -/
def rtensor (f : N →ₗ[R] P) : N ⊗ M →ₗ[R] P ⊗ M :=
tensor_product.map f id
variables (g : P →ₗ[R] Q) (f : N →ₗ[R] P)
@[simp] lemma ltensor_tmul (m : M) (n : N) : f.ltensor M (m ⊗ₜ n) = m ⊗ₜ (f n) := rfl
@[simp] lemma rtensor_tmul (m : M) (n : N) : f.rtensor M (n ⊗ₜ m) = (f n) ⊗ₜ m := rfl
open tensor_product
/-- `ltensor_hom M` is the natural linear map that sends a linear map `f : N →ₗ P` to `M ⊗ f`. -/
def ltensor_hom : (N →ₗ[R] P) →ₗ[R] (M ⊗[R] N →ₗ[R] M ⊗[R] P) :=
{ to_fun := ltensor M,
map_add' := λ f g, by { ext x y, simp only [add_apply, ltensor_tmul, tmul_add] },
map_smul' := λ r f, by { ext x y, simp only [tmul_smul, smul_apply, ltensor_tmul] } }
/-- `rtensor_hom M` is the natural linear map that sends a linear map `f : N →ₗ P` to `M ⊗ f`. -/
def rtensor_hom : (N →ₗ[R] P) →ₗ[R] (N ⊗[R] M →ₗ[R] P ⊗[R] M) :=
{ to_fun := λ f, f.rtensor M,
map_add' := λ f g, by { ext x y, simp only [add_apply, rtensor_tmul, add_tmul] },
map_smul' := λ r f, by { ext x y, simp only [smul_tmul, tmul_smul, smul_apply, rtensor_tmul] } }
@[simp] lemma coe_ltensor_hom :
(ltensor_hom M : (N →ₗ[R] P) → (M ⊗[R] N →ₗ[R] M ⊗[R] P)) = ltensor M := rfl
@[simp] lemma coe_rtensor_hom :
(rtensor_hom M : (N →ₗ[R] P) → (N ⊗[R] M →ₗ[R] P ⊗[R] M)) = rtensor M := rfl
@[simp] lemma ltensor_add (f g : N →ₗ[R] P) : (f + g).ltensor M = f.ltensor M + g.ltensor M :=
(ltensor_hom M).map_add f g
@[simp] lemma rtensor_add (f g : N →ₗ[R] P) : (f + g).rtensor M = f.rtensor M + g.rtensor M :=
(rtensor_hom M).map_add f g
@[simp] lemma ltensor_zero : ltensor M (0 : N →ₗ[R] P) = 0 :=
(ltensor_hom M).map_zero
@[simp] lemma rtensor_zero : rtensor M (0 : N →ₗ[R] P) = 0 :=
(rtensor_hom M).map_zero
@[simp] lemma ltensor_smul (r : R) (f : N →ₗ[R] P) : (r • f).ltensor M = r • (f.ltensor M) :=
(ltensor_hom M).map_smul r f
@[simp] lemma rtensor_smul (r : R) (f : N →ₗ[R] P) : (r • f).rtensor M = r • (f.rtensor M) :=
(rtensor_hom M).map_smul r f
lemma ltensor_comp : (g.comp f).ltensor M = (g.ltensor M).comp (f.ltensor M) :=
by { ext m n, simp only [comp_apply, ltensor_tmul] }
lemma rtensor_comp : (g.comp f).rtensor M = (g.rtensor M).comp (f.rtensor M) :=
by { ext m n, simp only [comp_apply, rtensor_tmul] }
variables (N)
@[simp] lemma ltensor_id : (id : N →ₗ[R] N).ltensor M = id :=
by { ext m n, simp only [id_coe, id.def, ltensor_tmul] }
@[simp] lemma rtensor_id : (id : N →ₗ[R] N).rtensor M = id :=
by { ext m n, simp only [id_coe, id.def, rtensor_tmul] }
variables {N}
@[simp] lemma ltensor_comp_rtensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) :
(g.ltensor P).comp (f.rtensor N) = map f g :=
by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id]
@[simp] lemma rtensor_comp_ltensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) :
(f.rtensor Q).comp (g.ltensor M) = map f g :=
by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id]
@[simp] lemma map_comp_rtensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (f' : S →ₗ[R] M) :
(map f g).comp (f'.rtensor _) = map (f.comp f') g :=
by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id]
@[simp] lemma map_comp_ltensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (g' : S →ₗ[R] N) :
(map f g).comp (g'.ltensor _) = map f (g.comp g') :=
by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id]
@[simp] lemma rtensor_comp_map (f' : P →ₗ[R] S) (f : M →ₗ[R] P) (g : N →ₗ[R] Q) :
(f'.rtensor _).comp (map f g) = map (f'.comp f) g :=
by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id]
@[simp] lemma ltensor_comp_map (g' : Q →ₗ[R] S) (f : M →ₗ[R] P) (g : N →ₗ[R] Q) :
(g'.ltensor _).comp (map f g) = map f (g'.comp g) :=
by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id]
end linear_map
end semiring
section ring
variables {R : Type*} [comm_semiring R]
variables {M : Type*} {N : Type*} {P : Type*} {Q : Type*} {S : Type*}
variables [add_comm_group M] [add_comm_group N] [add_comm_group P] [add_comm_group Q]
[add_comm_group S]
variables [semimodule R M] [semimodule R N] [semimodule R P] [semimodule R Q] [semimodule R S]
namespace tensor_product
open_locale tensor_product
open linear_map
variables (R)
/-- Auxiliary function to defining negation multiplication on tensor product. -/
def neg.aux : free_add_monoid (M × N) →+ M ⊗[R] N :=
free_add_monoid.lift $ λ p : M × N, (-p.1) ⊗ₜ p.2
variables {R}
theorem neg.aux_of (m : M) (n : N) :
neg.aux R (free_add_monoid.of (m, n)) = (-m) ⊗ₜ[R] n :=
rfl
instance : has_neg (M ⊗[R] N) :=
{ neg := (add_con_gen (tensor_product.eqv R M N)).lift (neg.aux R) $ add_con.add_con_gen_le $
λ x y hxy, match x, y, hxy with
| _, _, (eqv.of_zero_left n) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_zero, neg.aux_of, neg_zero, zero_tmul]
| _, _, (eqv.of_zero_right m) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_zero, neg.aux_of, tmul_zero]
| _, _, (eqv.of_add_left m₁ m₂ n) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_add, neg.aux_of, neg_add, add_tmul]
| _, _, (eqv.of_add_right m n₁ n₂) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_add, neg.aux_of, tmul_add]
| _, _, (eqv.of_smul s m n) := (add_con.ker_rel _).2 $
by simp_rw [neg.aux_of, tmul_smul s, smul_tmul', smul_neg]
| _, _, (eqv.add_comm x y) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_add, add_comm]
end }
lemma neg_tmul (m : M) (n : N) : (-m) ⊗ₜ n = -(m ⊗ₜ[R] n) := rfl
instance : add_comm_group (M ⊗[R] N) :=
{ neg := has_neg.neg,
add_left_neg := λ x, tensor_product.induction_on x
(by { rw [add_zero], apply (neg.aux R).map_zero, })
(λ x y, by { convert (add_tmul (-x) x y).symm, rw [add_left_neg, zero_tmul], })
(λ x y hx hy, by {
unfold has_neg.neg,
rw add_monoid_hom.map_add,
ac_change (-x + x) + (-y + y) = 0,
rw [hx, hy, add_zero], }),
..(infer_instance : add_comm_monoid (M ⊗[R] N)) }
lemma tmul_neg (m : M) (n : N) : m ⊗ₜ (-n) = -(m ⊗ₜ[R] n) := (mk R M N _).map_neg _
end tensor_product
namespace linear_map
@[simp] lemma ltensor_sub (f g : N →ₗ[R] P) : (f - g).ltensor M = f.ltensor M - g.ltensor M :=
by simp only [← coe_ltensor_hom, map_sub]
@[simp] lemma rtensor_sub (f g : N →ₗ[R] P) : (f - g).rtensor M = f.rtensor M - g.rtensor M :=
by simp only [← coe_rtensor_hom, map_sub]
@[simp] lemma ltensor_neg (f : N →ₗ[R] P) : (-f).ltensor M = -(f.ltensor M) :=
by simp only [← coe_ltensor_hom, map_neg]
@[simp] lemma rtensor_neg (f : N →ₗ[R] P) : (-f).rtensor M = -(f.rtensor M) :=
by simp only [← coe_rtensor_hom, map_neg]
end linear_map
end ring
|
45e4463fb21a2588fb264e56be50fc186527e89e | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/private_structure.lean | 91adb48d1a99007f55a2a14d21aae6c15e8c6d37 | [
"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 | 622 | lean | namespace foo
private structure point :=
(x : nat) (y : nat)
definition bla := point
definition mk : bla := point.mk 10 10
#check bla
#check point
#check point.mk
#check point.rec
#check point.rec_on
#check point.cases_on
#check point.x
#check point.y
#check (⟨1, 2⟩ : bla)
#check ({x := 1, y := 2} : bla)
end foo
open foo
-- point is not visible anymore
#check bla
#check point
#check point.mk
#check point.rec
#check point.rec_on
#check point.cases_on
#check point.no_confusion
#check point.x
#check point.y
set_option pp.all true
#print bla
#check (⟨1, 2⟩ : bla)
#check ({x := 1, y := 2} : bla)
#check mk
|
8e1d329c6ce43f57a89e47828bca7b9ebc51c84e | 19cc34575500ee2e3d4586c15544632aa07a8e66 | /src/data/polynomial/eval.lean | 2acea3509585c8dcb43c49fc3832dcc2ea148515 | [
"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 | 19,055 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker
-/
import data.polynomial.induction
import data.polynomial.degree.basic
import deprecated.ring
/-!
# Theory of univariate polynomials
The main defs here are `eval₂`, `eval`, and `map`.
We give several lemmas about their interaction with each other and with module operations.
-/
noncomputable theory
open finsupp finset add_monoid_algebra
open_locale big_operators
namespace polynomial
universes u v w y
variables {R : Type u} {S : Type v} {T : Type w} {ι : Type y} {a b : R} {m n : ℕ}
section semiring
variables [semiring R] {p q r : polynomial R}
section
variables [semiring S]
variables (f : R →+* S) (x : S)
/-- Evaluate a polynomial `p` given a ring hom `f` from the scalar ring
to the target and a value `x` for the variable in the target -/
def eval₂ (p : polynomial R) : S :=
p.sum (λ e a, f a * x ^ e)
lemma eval₂_eq_sum {f : R →+* S} {x : S} : p.eval₂ f x = p.sum (λ e a, f a * x ^ e) := rfl
@[simp] lemma eval₂_zero : (0 : polynomial R).eval₂ f x = 0 :=
finsupp.sum_zero_index
@[simp] lemma eval₂_C : (C a).eval₂ f x = f a :=
(sum_single_index $ by rw [f.map_zero, zero_mul]).trans $ by simp [pow_zero, mul_one]
@[simp] lemma eval₂_X : X.eval₂ f x = x :=
(sum_single_index $ by rw [f.map_zero, zero_mul]).trans $ by rw [f.map_one, one_mul, pow_one]
@[simp] lemma eval₂_monomial {n : ℕ} {r : R} : (monomial n r).eval₂ f x = (f r) * x^n :=
begin
apply sum_single_index,
simp,
end
@[simp] lemma eval₂_X_pow {n : ℕ} : (X^n).eval₂ f x = x^n :=
begin
rw ←monomial_one_eq_X_pow,
convert eval₂_monomial f x,
simp,
end
@[simp] lemma eval₂_add : (p + q).eval₂ f x = p.eval₂ f x + q.eval₂ f x :=
finsupp.sum_add_index
(λ _, by rw [f.map_zero, zero_mul])
(λ _ _ _, by rw [f.map_add, add_mul])
@[simp] lemma eval₂_one : (1 : polynomial R).eval₂ f x = 1 :=
by rw [← C_1, eval₂_C, f.map_one]
@[simp] lemma eval₂_bit0 : (bit0 p).eval₂ f x = bit0 (p.eval₂ f x) :=
by rw [bit0, eval₂_add, bit0]
@[simp] lemma eval₂_bit1 : (bit1 p).eval₂ f x = bit1 (p.eval₂ f x) :=
by rw [bit1, eval₂_add, eval₂_bit0, eval₂_one, bit1]
@[simp] lemma eval₂_smul (g : R →+* S) (p : polynomial R) (x : S) {s : R} :
eval₂ g x (s • p) = g s • eval₂ g x p :=
begin
simp only [eval₂, sum_smul_index, forall_const, zero_mul, g.map_zero, g.map_mul, mul_assoc],
-- Why doesn't `rw [←finsupp.mul_sum]` work?
convert (@finsupp.mul_sum _ _ _ _ _ (g s) p (λ i a, (g a * x ^ i))).symm,
end
instance eval₂.is_add_monoid_hom : is_add_monoid_hom (eval₂ f x) :=
{ map_zero := eval₂_zero _ _, map_add := λ _ _, eval₂_add _ _ }
@[simp] lemma eval₂_nat_cast (n : ℕ) : (n : polynomial R).eval₂ f x = n :=
nat.rec_on n rfl $ λ n ih, by rw [n.cast_succ, eval₂_add, ih, eval₂_one, n.cast_succ]
variables [semiring T]
lemma eval₂_sum (p : polynomial T) (g : ℕ → T → polynomial R) (x : S) :
(p.sum g).eval₂ f x = p.sum (λ n a, (g n a).eval₂ f x) :=
finsupp.sum_sum_index (by simp [is_add_monoid_hom.map_zero f])
(by intros; simp [right_distrib, is_add_monoid_hom.map_add f])
lemma eval₂_finset_sum (s : finset ι) (g : ι → polynomial R) (x : S) :
(∑ i in s, g i).eval₂ f x = ∑ i in s, (g i).eval₂ f x :=
begin
classical,
induction s using finset.induction with p hp s hs, simp,
rw [sum_insert, eval₂_add, hs, sum_insert]; assumption,
end
lemma eval₂_mul_noncomm (hf : ∀ b a, f b * a = a * f b) :
(p * q).eval₂ f x = p.eval₂ f x * q.eval₂ f x :=
begin
have f_zero : ∀ (a : ℕ), f 0 * x ^ a = 0,
{ intro, simp },
have f_add : ∀ (a : ℕ) (b₁ b₂ : R), f (b₁ + b₂) * x ^ a = f b₁ * x ^ a + f b₂ * x ^ a,
{ intros, rw [f.map_add, add_mul] },
simp_rw [eval₂, add_monoid_algebra.mul_def, finsupp.sum_mul _ p, finsupp.mul_sum _ q],
rw sum_sum_index; try { assumption },
apply sum_congr rfl, assume i hi, dsimp only,
rw sum_sum_index; try { assumption },
apply sum_congr rfl, assume j hj, dsimp only,
rw [sum_single_index, is_semiring_hom.map_mul f, pow_add],
{ rw [mul_assoc, ←mul_assoc _ (x ^ i), hf _ (x ^ i), mul_assoc, mul_assoc] },
{ apply f_zero }
end
lemma eval₂_list_prod_noncomm (ps : list (polynomial R)) (hf : ∀ b a, f b * a = a * f b):
ps.prod.eval₂ f x = (ps.map (polynomial.eval₂ f x)).prod :=
begin
induction ps,
{ simp },
{ simp [eval₂_mul_noncomm _ _ hf, ps_ih] {contextual := tt} }
end
/-- `eval₂` as a `ring_hom` for noncommutative rings -/
def eval₂_ring_hom' (f : R →+* S) (hf : ∀ b a, f b * a = a * f b) (x : S) : polynomial R →+* S :=
{ to_fun := eval₂ f x,
map_add' := λ _ _, eval₂_add _ _,
map_zero' := eval₂_zero _ _,
map_mul' := λ _ _, eval₂_mul_noncomm _ _ hf,
map_one' := eval₂_one _ _ }
end
/-!
We next prove that eval₂ is multiplicative
as long as target ring is commutative
(even if the source ring is not).
-/
section eval₂
variables [comm_semiring S]
variables (f : R →+* S) (x : S)
@[simp] lemma eval₂_mul : (p * q).eval₂ f x = p.eval₂ f x * q.eval₂ f x :=
begin
apply eval₂_mul_noncomm,
simp [mul_comm]
end
lemma eval₂_mul_eq_zero_of_left (q : polynomial R) (hp : p.eval₂ f x = 0) :
(p * q).eval₂ f x = 0 :=
begin
rw eval₂_mul f x,
exact mul_eq_zero_of_left hp (q.eval₂ f x)
end
lemma eval₂_mul_eq_zero_of_right (p : polynomial R) (hq : q.eval₂ f x = 0) :
(p * q).eval₂ f x = 0 :=
begin
rw eval₂_mul f x,
exact mul_eq_zero_of_right (p.eval₂ f x) hq
end
instance eval₂.is_semiring_hom : is_semiring_hom (eval₂ f x) :=
⟨eval₂_zero _ _, eval₂_one _ _, λ _ _, eval₂_add _ _, λ _ _, eval₂_mul _ _⟩
/-- `eval₂` as a `ring_hom` -/
def eval₂_ring_hom (f : R →+* S) (x) : polynomial R →+* S :=
ring_hom.of (eval₂ f x)
@[simp] lemma coe_eval₂_ring_hom (f : R →+* S) (x) : ⇑(eval₂_ring_hom f x) = eval₂ f x := rfl
lemma eval₂_pow (n : ℕ) : (p ^ n).eval₂ f x = p.eval₂ f x ^ n := (eval₂_ring_hom _ _).map_pow _ _
lemma eval₂_eq_sum_range :
p.eval₂ f x = ∑ i in finset.range (p.nat_degree + 1), f (p.coeff i) * x^i :=
trans (congr_arg _ p.as_sum_range) (trans (eval₂_finset_sum f _ _ x) (congr_arg _ (by simp)))
end eval₂
section eval
variables {x : R}
/-- `eval x p` is the evaluation of the polynomial `p` at `x` -/
def eval : R → polynomial R → R := eval₂ (ring_hom.id _)
lemma eval_eq_sum : p.eval x = sum p (λ e a, a * x ^ e) :=
rfl
@[simp] lemma eval_C : (C a).eval x = a := eval₂_C _ _
@[simp] lemma eval_nat_cast {n : ℕ} : (n : polynomial R).eval x = n :=
by simp only [←C_eq_nat_cast, eval_C]
@[simp] lemma eval_X : X.eval x = x := eval₂_X _ _
@[simp] lemma eval_monomial {n a} : (monomial n a).eval x = a * x^n :=
eval₂_monomial _ _
@[simp] lemma eval_zero : (0 : polynomial R).eval x = 0 := eval₂_zero _ _
@[simp] lemma eval_add : (p + q).eval x = p.eval x + q.eval x := eval₂_add _ _
@[simp] lemma eval_one : (1 : polynomial R).eval x = 1 := eval₂_one _ _
@[simp] lemma eval_bit0 : (bit0 p).eval x = bit0 (p.eval x) := eval₂_bit0 _ _
@[simp] lemma eval_bit1 : (bit1 p).eval x = bit1 (p.eval x) := eval₂_bit1 _ _
@[simp] lemma eval_smul (p : polynomial R) (x : R) {s : R} :
(s • p).eval x = s • p.eval x :=
eval₂_smul (ring_hom.id _) _ _
lemma eval_sum (p : polynomial R) (f : ℕ → R → polynomial R) (x : R) :
(p.sum f).eval x = p.sum (λ n a, (f n a).eval x) :=
eval₂_sum _ _ _ _
lemma eval_finset_sum (s : finset ι) (g : ι → polynomial R) (x : R) :
(∑ i in s, g i).eval x = ∑ i in s, (g i).eval x := eval₂_finset_sum _ _ _ _
/-- `is_root p x` implies `x` is a root of `p`. The evaluation of `p` at `x` is zero -/
def is_root (p : polynomial R) (a : R) : Prop := p.eval a = 0
instance [decidable_eq R] : 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 coeff_zero_eq_eval_zero (p : polynomial R) :
coeff p 0 = p.eval 0 :=
calc coeff p 0 = coeff p 0 * 0 ^ 0 : by simp
... = p.eval 0 : eq.symm $
finset.sum_eq_single _ (λ b _ hb, by simp [zero_pow (nat.pos_of_ne_zero hb)]) (by simp)
lemma zero_is_root_of_coeff_zero_eq_zero {p : polynomial R} (hp : p.coeff 0 = 0) :
is_root p 0 :=
by rwa coeff_zero_eq_eval_zero at hp
end eval
section comp
/-- The composition of polynomials as a polynomial. -/
def comp (p q : polynomial R) : polynomial R := p.eval₂ C q
lemma comp_eq_sum_left : p.comp q = p.sum (λ e a, C a * q ^ e) :=
rfl
@[simp] lemma comp_X : p.comp X = p :=
begin
refine ext (λ n, _),
rw [comp, eval₂],
conv in (C _ * _) { rw ← single_eq_C_mul_X },
congr,
convert finsupp.sum_single _,
end
@[simp] lemma X_comp : X.comp p = p := eval₂_X _ _
@[simp] lemma comp_C : p.comp (C a) = C (p.eval a) :=
begin
dsimp [comp, eval₂, eval, finsupp.sum],
rw [← p.support.sum_hom (@C R _)],
apply finset.sum_congr rfl; simp
end
@[simp] lemma C_comp : (C a).comp p = C a := eval₂_C _ _
@[simp] lemma comp_zero : p.comp (0 : polynomial R) = C (p.eval 0) :=
by rw [← C_0, comp_C]
@[simp] lemma zero_comp : comp (0 : polynomial R) p = 0 :=
by rw [← C_0, C_comp]
@[simp] lemma comp_one : p.comp 1 = C (p.eval 1) :=
by rw [← C_1, comp_C]
@[simp] lemma one_comp : comp (1 : polynomial R) p = 1 :=
by rw [← C_1, C_comp]
@[simp] lemma add_comp : (p + q).comp r = p.comp r + q.comp r := eval₂_add _ _
end comp
section map
variables [semiring S]
variables (f : R →+* S)
/-- `map f p` maps a polynomial `p` across a ring hom `f` -/
def map : polynomial R → polynomial S := eval₂ (C.comp f) X
instance is_semiring_hom_C_f : is_semiring_hom (C ∘ f) :=
is_semiring_hom.comp _ _
@[simp] lemma map_C : (C a).map f = C (f a) := eval₂_C _ _
@[simp] lemma map_X : X.map f = X := eval₂_X _ _
@[simp] lemma map_monomial {n a} : (monomial n a).map f = monomial n (f a) :=
begin
dsimp only [map],
rw [eval₂_monomial, single_eq_C_mul_X], refl,
end
@[simp] lemma map_zero : (0 : polynomial R).map f = 0 := eval₂_zero _ _
@[simp] lemma map_add : (p + q).map f = p.map f + q.map f := eval₂_add _ _
@[simp] lemma map_one : (1 : polynomial R).map f = 1 := eval₂_one _ _
@[simp] theorem map_nat_cast (n : ℕ) : (n : polynomial R).map f = n :=
nat.rec_on n rfl $ λ n ih, by rw [n.cast_succ, map_add, ih, map_one, n.cast_succ]
@[simp]
lemma coeff_map (n : ℕ) : coeff (p.map f) n = f (coeff p n) :=
begin
rw [map, eval₂, coeff_sum],
conv_rhs { rw [← sum_C_mul_X_eq p, coeff_sum, finsupp.sum,
← p.support.sum_hom f], },
refine finset.sum_congr rfl (λ x hx, _),
simp [function.comp, coeff_C_mul_X, f.map_mul],
split_ifs; simp [is_semiring_hom.map_zero f],
end
lemma map_map [semiring T] (g : S →+* T)
(p : polynomial R) : (p.map f).map g = p.map (g.comp f) :=
ext (by simp [coeff_map])
@[simp] lemma map_id : p.map (ring_hom.id _) = p := by simp [polynomial.ext_iff, coeff_map]
lemma eval₂_eq_eval_map {x : S} : p.eval₂ f x = (p.map f).eval x :=
begin
apply polynomial.induction_on' p,
{ intros p q hp hq, simp [hp, hq], },
{ intros n r, simp, }
end
lemma map_injective (hf : function.injective f): function.injective (map f) :=
λ p q h, ext $ λ m, hf $ by rw [← coeff_map f, ← coeff_map f, h]
variables {f}
lemma map_monic_eq_zero_iff (hp : p.monic) : p.map f = 0 ↔ ∀ x, f x = 0 :=
⟨ λ hfp x, calc f x = f x * f p.leading_coeff : by simp [hp]
... = f x * (p.map f).coeff p.nat_degree : by { congr, apply (coeff_map _ _).symm }
... = 0 : by simp [hfp],
λ h, ext (λ n, trans (coeff_map f n) (h _)) ⟩
lemma map_monic_ne_zero (hp : p.monic) [nontrivial S] : p.map f ≠ 0 :=
λ h, f.map_one_ne_zero ((map_monic_eq_zero_iff hp).mp h _)
variables (f)
open is_semiring_hom
-- If the rings were commutative, we could prove this just using `eval₂_mul`.
-- TODO this proof is just a hack job on the proof of `eval₂_mul`,
-- using that `X` is central. It should probably be golfed!
@[simp] lemma map_mul : (p * q).map f = p.map f * q.map f :=
begin
dunfold map,
dunfold eval₂,
rw [add_monoid_algebra.mul_def, finsupp.sum_mul _ p], simp only [finsupp.mul_sum _ q],
rw [sum_sum_index],
{ apply sum_congr rfl, assume i hi, dsimp only, rw [sum_sum_index],
{ apply sum_congr rfl, assume j hj, dsimp only,
rw [sum_single_index, (C.comp f).map_mul, pow_add],
{ simp [←mul_assoc], conv_lhs { rw ←@X_pow_mul_assoc _ _ _ _ i }, },
{ simp, } },
{ intro, simp, },
{ intros, simp [add_mul], } },
{ intro, simp, },
{ intros, simp [add_mul], }
end
instance map.is_semiring_hom : is_semiring_hom (map f) :=
{ map_zero := eval₂_zero _ _,
map_one := eval₂_one _ _,
map_add := λ _ _, eval₂_add _ _,
map_mul := λ _ _, map_mul f, }
lemma map_list_prod (L : list (polynomial R)) : L.prod.map f = (L.map $ map f).prod :=
eq.symm $ list.prod_hom _ (monoid_hom.of (map f))
@[simp] lemma map_pow (n : ℕ) : (p ^ n).map f = p.map f ^ n := is_monoid_hom.map_pow (map f) _ _
lemma mem_map_range {p : polynomial S} :
p ∈ set.range (map f) ↔ ∀ n, p.coeff n ∈ (set.range f) :=
begin
split,
{ rintro ⟨p, rfl⟩ n, rw coeff_map, exact set.mem_range_self _ },
{ intro h, rw p.as_sum_range,
apply is_add_submonoid.finset_sum_mem,
intros i hi,
rcases h i with ⟨c, hc⟩,
use [C c * X^i],
rw [map_mul, map_C, hc, map_pow, map_X] }
end
lemma eval₂_map [semiring T] (g : S →+* T) (x : T) :
(p.map f).eval₂ g x = p.eval₂ (g.comp f) x :=
begin
convert finsupp.sum_map_range_index _,
{ change map f p = map_range f _ p,
ext,
rw map_range_apply,
exact coeff_map f a, },
{ exact f.map_zero, },
{ intro a, simp only [ring_hom.map_zero, zero_mul], },
end
lemma eval_map (x : S) : (p.map f).eval x = p.eval₂ f x :=
eval₂_map f (ring_hom.id _) x
end map
/-!
After having set up the basic theory of `eval₂`, `eval`, `comp`, and `map`,
we make `eval₂` irreducible.
Perhaps we can make the others irreducible too?
-/
attribute [irreducible] polynomial.eval₂
section hom_eval₂
-- TODO: Here we need commutativity in both `S` and `T`?
variables [comm_semiring S] [comm_semiring T]
variables (f : R →+* S) (g : S →+* T) (p)
lemma hom_eval₂ (x : S) : g (p.eval₂ f x) = p.eval₂ (g.comp f) (g x) :=
begin
apply polynomial.induction_on p; clear p,
{ intros a, rw [eval₂_C, eval₂_C], refl, },
{ intros p q hp hq, simp only [hp, hq, eval₂_add, g.map_add] },
{ intros n a ih,
simp only [eval₂_mul, eval₂_C, eval₂_X_pow, g.map_mul, g.map_pow],
refl, }
end
end hom_eval₂
end semiring
section comm_semiring
section eval
variables [comm_semiring R] {p q : polynomial R} {x : R}
@[simp] lemma eval_mul : (p * q).eval x = p.eval x * q.eval x := eval₂_mul _ _
instance eval.is_semiring_hom : is_semiring_hom (eval x) := eval₂.is_semiring_hom _ _
@[simp] lemma eval_pow (n : ℕ) : (p ^ n).eval x = p.eval x ^ n := eval₂_pow _ _ _
lemma eval₂_hom [comm_semiring S] (f : R →+* S) (x : R) :
p.eval₂ f (f x) = f (p.eval x) :=
(ring_hom.comp_id f) ▸ (hom_eval₂ p (ring_hom.id R) f x).symm
lemma root_mul_left_of_is_root (p : polynomial R) {q : polynomial R} :
is_root q a → is_root (p * q) a :=
λ H, by rw [is_root, eval_mul, is_root.def.1 H, mul_zero]
lemma root_mul_right_of_is_root {p : polynomial R} (q : polynomial R) :
is_root p a → is_root (p * q) a :=
λ H, by rw [is_root, eval_mul, is_root.def.1 H, zero_mul]
/--
Polynomial evaluation commutes with finset.prod
-/
lemma eval_prod {ι : Type*} (s : finset ι) (p : ι → polynomial R) (x : R) :
eval x (∏ j in s, p j) = ∏ j in s, eval x (p j) :=
begin
classical,
apply finset.induction_on s,
{ simp only [finset.prod_empty, eval_one] },
{ intros j s hj hpj,
have h0 : ∏ i in insert j s, eval x (p i) = (eval x (p j)) * ∏ i in s, eval x (p i),
{ apply finset.prod_insert hj },
rw [h0, ← hpj, finset.prod_insert hj, eval_mul] },
end
end eval
section map
variables [comm_semiring R] [comm_semiring S] (f : R →+* S)
lemma map_multiset_prod (m : multiset (polynomial R)) : m.prod.map f = (m.map $ map f).prod :=
eq.symm $ multiset.prod_hom _ (monoid_hom.of (map f))
lemma map_prod {ι : Type*} (g : ι → polynomial R) (s : finset ι) :
(∏ i in s, g i).map f = ∏ i in s, (g i).map f :=
eq.symm $ prod_hom _ _
lemma map_sum {ι : Type*} (g : ι → polynomial R) (s : finset ι) :
(∑ i in s, g i).map f = ∑ i in s, (g i).map f :=
eq.symm $ sum_hom _ _
lemma support_map_subset (p : polynomial R) : (map f p).support ⊆ p.support :=
begin
intros x,
simp only [mem_support_iff],
contrapose!,
change p.coeff x = 0 → (map f p).coeff x = 0,
rw coeff_map,
intro hx,
rw hx,
exact ring_hom.map_zero f,
end
lemma map_comp (p q : polynomial R) : map f (p.comp q) = (map f p).comp (map f q) :=
polynomial.induction_on p
(by simp)
(by simp {contextual := tt})
(by simp [pow_succ', ← mul_assoc, polynomial.comp] {contextual := tt})
end map
end comm_semiring
section ring
variables [ring R] {p q : polynomial R}
-- @[simp]
-- lemma C_eq_int_cast (n : ℤ) : C ↑n = (n : polynomial R) :=
-- (C : R →+* _).map_int_cast n
lemma C_neg : C (-a) = -C a := ring_hom.map_neg C a
lemma C_sub : C (a - b) = C a - C b := ring_hom.map_sub C a b
instance map.is_ring_hom {S} [ring S] (f : R →+* S) : is_ring_hom (map f) :=
by apply is_ring_hom.of_semiring
@[simp] lemma map_sub {S} [comm_ring S] (f : R →+* S) :
(p - q).map f = p.map f - q.map f :=
is_ring_hom.map_sub _
@[simp] lemma map_neg {S} [comm_ring S] (f : R →+* S) :
(-p).map f = -(p.map f) :=
is_ring_hom.map_neg _
@[simp] lemma eval_int_cast {n : ℤ} {x : R} : (n : polynomial R).eval x = n :=
by simp only [←C_eq_int_cast, eval_C]
@[simp] lemma eval₂_neg {S} [ring S] (f : R →+* S) {x : S} :
(-p).eval₂ f x = -p.eval₂ f x :=
by rw [eq_neg_iff_add_eq_zero, ←eval₂_add, add_left_neg, eval₂_zero]
@[simp] lemma eval₂_sub {S} [ring S] (f : R →+* S) {x : S} :
(p - q).eval₂ f x = p.eval₂ f x - q.eval₂ f x :=
by rw [sub_eq_add_neg, eval₂_add, eval₂_neg, sub_eq_add_neg]
@[simp] lemma eval_neg (p : polynomial R) (x : R) : (-p).eval x = -p.eval x :=
eval₂_neg _
@[simp] lemma eval_sub (p q : polynomial R) (x : R) : (p - q).eval x = p.eval x - q.eval x :=
eval₂_sub _
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]
end ring
section comm_ring
variables [comm_ring R] {p q : polynomial R}
instance eval₂.is_ring_hom {S} [comm_ring S]
(f : R →+* S) {x : S} : is_ring_hom (eval₂ f x) :=
by apply is_ring_hom.of_semiring
instance eval.is_ring_hom {x : R} : is_ring_hom (eval x) := eval₂.is_ring_hom _
end comm_ring
end polynomial
|
bf1265f27177706da31ec478fc18897909c08fe3 | ef47cc39429c8f578004338bf040c9c309b26766 | /src/exercises_sources/thursday/afternoon/category_theory/exercise11.lean | 4ca60e76a45a0db87f2912474b3c628cb2341e53 | [] | no_license | farmanb/lftcm2020 | 29f1c646437a8f8b00ee2e07c8b663ca04bfa16f | 1948bfaf58e3b340b39cd9b8366aa4f13e5ffa7d | refs/heads/master | 1,669,697,152,764 | 1,595,275,412,000 | 1,595,275,412,000 | 285,654,242 | 0 | 0 | null | 1,596,742,086,000 | 1,596,742,085,000 | null | UTF-8 | Lean | false | false | 979 | lean | import algebra.category.Group.limits
import algebra.category.Group.colimits
import algebra.category.Group.preadditive
import category_theory.abelian.basic
/-!
Let's prove that the category of abelian groups is abelian!
This is currently missing in mathlib.
The only things remaining are
"every mono is the kernel of its cokernel" and "every epi is the cokernel of its kernel"
and these should be easy consequences of statements in the non-categorical group theory library.
-/
open category_theory
open category_theory.limits
instance : abelian AddCommGroup :=
{ normal_mono := λ X Y f f_mono,
-- If you're actually going to attempt this, write `by extract_goal` here
-- and prove this as a preliminary lemma.
{ Z := cokernel f,
g := cokernel.π f,
w := by tidy,
is_limit :=
begin
fapply kernel_fork.is_limit.of_ι,
-- now look in group_theory/quotient_group.lean!
sorry,
sorry,
sorry,
end, },
normal_epi := sorry, }
|
695e00b4fdc41776181809a6dc1d6fcbf829bd04 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/data/int/interval.lean | eba687e82273633151272e6dc3d0072aa8cff007 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 6,924 | lean | /-
Copyright (c) 2021 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import algebra.char_zero.lemmas
import order.locally_finite
import data.finset.locally_finite
/-!
# Finite intervals of integers
This file proves that `ℤ` is a `locally_finite_order` and calculates the cardinality of its
intervals as finsets and fintypes.
-/
open finset int
instance : locally_finite_order ℤ :=
{ finset_Icc := λ a b, (finset.range (b + 1 - a).to_nat).map $
nat.cast_embedding.trans $ add_left_embedding a,
finset_Ico := λ a b, (finset.range (b - a).to_nat).map $
nat.cast_embedding.trans $ add_left_embedding a,
finset_Ioc := λ a b, (finset.range (b - a).to_nat).map $
nat.cast_embedding.trans $ add_left_embedding (a + 1),
finset_Ioo := λ a b, (finset.range (b - a - 1).to_nat).map $
nat.cast_embedding.trans $ add_left_embedding (a + 1),
finset_mem_Icc := λ a b x, begin
simp_rw [mem_map, exists_prop, mem_range, int.lt_to_nat, function.embedding.trans_apply,
nat.cast_embedding_apply, add_left_embedding_apply],
split,
{ rintro ⟨a, h, rfl⟩,
rw [lt_sub_iff_add_lt, int.lt_add_one_iff, add_comm] at h,
exact ⟨int.le.intro rfl, h⟩ },
{ rintro ⟨ha, hb⟩,
use (x - a).to_nat,
rw ←lt_add_one_iff at hb,
rw to_nat_sub_of_le ha,
exact ⟨sub_lt_sub_right hb _, add_sub_cancel'_right _ _⟩ }
end,
finset_mem_Ico := λ a b x, begin
simp_rw [mem_map, exists_prop, mem_range, int.lt_to_nat, function.embedding.trans_apply,
nat.cast_embedding_apply, add_left_embedding_apply],
split,
{ rintro ⟨a, h, rfl⟩,
exact ⟨int.le.intro rfl, lt_sub_iff_add_lt'.mp h⟩ },
{ rintro ⟨ha, hb⟩,
use (x - a).to_nat,
rw to_nat_sub_of_le ha,
exact ⟨sub_lt_sub_right hb _, add_sub_cancel'_right _ _⟩ }
end,
finset_mem_Ioc := λ a b x, begin
simp_rw [mem_map, exists_prop, mem_range, int.lt_to_nat, function.embedding.trans_apply,
nat.cast_embedding_apply, add_left_embedding_apply],
split,
{ rintro ⟨a, h, rfl⟩,
rw [←add_one_le_iff, le_sub_iff_add_le', add_comm _ (1 : ℤ), ←add_assoc] at h,
exact ⟨int.le.intro rfl, h⟩ },
{ rintro ⟨ha, hb⟩,
use (x - (a + 1)).to_nat,
rw [to_nat_sub_of_le ha, ←add_one_le_iff, sub_add, add_sub_cancel],
exact ⟨sub_le_sub_right hb _, add_sub_cancel'_right _ _⟩ }
end,
finset_mem_Ioo := λ a b x, begin
simp_rw [mem_map, exists_prop, mem_range, int.lt_to_nat, function.embedding.trans_apply,
nat.cast_embedding_apply, add_left_embedding_apply],
split,
{ rintro ⟨a, h, rfl⟩,
rw [sub_sub, lt_sub_iff_add_lt'] at h,
exact ⟨int.le.intro rfl, h⟩ },
{ rintro ⟨ha, hb⟩,
use (x - (a + 1)).to_nat,
rw [to_nat_sub_of_le ha, sub_sub],
exact ⟨sub_lt_sub_right hb _, add_sub_cancel'_right _ _⟩ }
end }
namespace int
variables (a b : ℤ)
lemma Icc_eq_finset_map :
Icc a b = (finset.range (b + 1 - a).to_nat).map
(nat.cast_embedding.trans $ add_left_embedding a) := rfl
lemma Ico_eq_finset_map :
Ico a b = (finset.range (b - a).to_nat).map
(nat.cast_embedding.trans $ add_left_embedding a) := rfl
lemma Ioc_eq_finset_map :
Ioc a b = (finset.range (b - a).to_nat).map
(nat.cast_embedding.trans $ add_left_embedding (a + 1)) := rfl
lemma Ioo_eq_finset_map :
Ioo a b = (finset.range (b - a - 1).to_nat).map
(nat.cast_embedding.trans $ add_left_embedding (a + 1)) := rfl
@[simp] lemma card_Icc : (Icc a b).card = (b + 1 - a).to_nat :=
by { change (finset.map _ _).card = _, rw [finset.card_map, finset.card_range] }
@[simp] lemma card_Ico : (Ico a b).card = (b - a).to_nat :=
by { change (finset.map _ _).card = _, rw [finset.card_map, finset.card_range] }
@[simp] lemma card_Ioc : (Ioc a b).card = (b - a).to_nat :=
by { change (finset.map _ _).card = _, rw [finset.card_map, finset.card_range] }
@[simp] lemma card_Ioo : (Ioo a b).card = (b - a - 1).to_nat :=
by { change (finset.map _ _).card = _, rw [finset.card_map, finset.card_range] }
lemma card_Icc_of_le (h : a ≤ b + 1) : ((Icc a b).card : ℤ) = b + 1 - a :=
by rw [card_Icc, to_nat_sub_of_le h]
lemma card_Ico_of_le (h : a ≤ b) : ((Ico a b).card : ℤ) = b - a :=
by rw [card_Ico, to_nat_sub_of_le h]
lemma card_Ioc_of_le (h : a ≤ b) : ((Ioc a b).card : ℤ) = b - a :=
by rw [card_Ioc, to_nat_sub_of_le h]
lemma card_Ioo_of_lt (h : a < b) : ((Ioo a b).card : ℤ) = b - a - 1 :=
by rw [card_Ioo, sub_sub, to_nat_sub_of_le h]
@[simp] lemma card_fintype_Icc : fintype.card (set.Icc a b) = (b + 1 - a).to_nat :=
by rw [←card_Icc, fintype.card_of_finset]
@[simp] lemma card_fintype_Ico : fintype.card (set.Ico a b) = (b - a).to_nat :=
by rw [←card_Ico, fintype.card_of_finset]
@[simp] lemma card_fintype_Ioc : fintype.card (set.Ioc a b) = (b - a).to_nat :=
by rw [←card_Ioc, fintype.card_of_finset]
@[simp] lemma card_fintype_Ioo : fintype.card (set.Ioo a b) = (b - a - 1).to_nat :=
by rw [←card_Ioo, fintype.card_of_finset]
lemma card_fintype_Icc_of_le (h : a ≤ b + 1) : (fintype.card (set.Icc a b) : ℤ) = b + 1 - a :=
by rw [card_fintype_Icc, to_nat_sub_of_le h]
lemma card_fintype_Ico_of_le (h : a ≤ b) : (fintype.card (set.Ico a b) : ℤ) = b - a :=
by rw [card_fintype_Ico, to_nat_sub_of_le h]
lemma card_fintype_Ioc_of_le (h : a ≤ b) : (fintype.card (set.Ioc a b) : ℤ) = b - a :=
by rw [card_fintype_Ioc, to_nat_sub_of_le h]
lemma card_fintype_Ioo_of_lt (h : a < b) : (fintype.card (set.Ioo a b) : ℤ) = b - a - 1 :=
by rw [card_fintype_Ioo, sub_sub, to_nat_sub_of_le h]
lemma image_Ico_mod (n a : ℤ) (h : 0 ≤ a) :
(Ico n (n+a)).image (% a) = Ico 0 a :=
begin
obtain rfl | ha := eq_or_lt_of_le h,
{ simp, },
ext i,
simp only [mem_image, exists_prop, mem_range, mem_Ico],
split,
{ rintro ⟨i, h, rfl⟩, exact ⟨mod_nonneg i (ne_of_gt ha), mod_lt_of_pos i ha⟩, },
intro hia,
have hn := int.mod_add_div n a,
obtain hi | hi := lt_or_le i (n % a),
{ refine ⟨i + a * (n/a + 1), ⟨_, _⟩, _⟩,
{ rw [add_comm (n/a), mul_add, mul_one, ← add_assoc],
refine hn.symm.le.trans (add_le_add_right _ _),
simpa only [zero_add] using add_le_add (hia.left) (int.mod_lt_of_pos n ha).le, },
{ refine lt_of_lt_of_le (add_lt_add_right hi (a * (n/a + 1))) _,
rw [mul_add, mul_one, ← add_assoc, hn], },
{ rw [int.add_mul_mod_self_left, int.mod_eq_of_lt hia.left hia.right], } },
{ refine ⟨i + a * (n/a), ⟨_, _⟩, _⟩,
{ exact hn.symm.le.trans (add_le_add_right hi _), },
{ rw [add_comm n a],
refine add_lt_add_of_lt_of_le hia.right (le_trans _ hn.le),
simp only [zero_le, le_add_iff_nonneg_left],
exact int.mod_nonneg n (ne_of_gt ha), },
{ rw [int.add_mul_mod_self_left, int.mod_eq_of_lt hia.left hia.right], } },
end
end int
|
719200a22a375739532b2d1082c30855b1a17ba7 | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/topology/metric_space/isometry.lean | cf19e0196875f0a8ae0560da8c1a0ed1d81caf66 | [
"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 | 15,690 | lean | /-
Copyright (c) 2018 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Isometries of emetric and metric spaces
Authors: Sébastien Gouëzel
-/
import analysis.normed_space.basic
/-!
# Isometries
We define isometries, i.e., maps between emetric spaces that preserve
the edistance (on metric spaces, these are exactly the maps that preserve distances),
and prove their basic properties. We also introduce isometric bijections.
Since a lot of elementary properties don't require `eq_of_dist_eq_zero` we start setting up the
theory for `pseudo_metric_space` and we specialize to `metric_space` when needed.
-/
noncomputable theory
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
open function set
/-- An isometry (also known as isometric embedding) is a map preserving the edistance
between pseudoemetric spaces, or equivalently the distance between pseudometric space. -/
def isometry [pseudo_emetric_space α] [pseudo_emetric_space β] (f : α → β) : Prop :=
∀x1 x2 : α, edist (f x1) (f x2) = edist x1 x2
/-- On pseudometric spaces, a map is an isometry if and only if it preserves distances. -/
lemma isometry_emetric_iff_metric [pseudo_metric_space α] [pseudo_metric_space β] {f : α → β} :
isometry f ↔ (∀x y, dist (f x) (f y) = dist x y) :=
⟨assume H x y, by simp [dist_edist, H x y],
assume H x y, by simp [edist_dist, H x y]⟩
/-- An isometry preserves edistances. -/
theorem isometry.edist_eq [pseudo_emetric_space α] [pseudo_emetric_space β] {f : α → β}
(hf : isometry f) (x y : α) : edist (f x) (f y) = edist x y :=
hf x y
/-- An isometry preserves distances. -/
theorem isometry.dist_eq [pseudo_metric_space α] [pseudo_metric_space β] {f : α → β}
(hf : isometry f) (x y : α) : dist (f x) (f y) = dist x y :=
by rw [dist_edist, dist_edist, hf]
section emetric_isometry
variables [pseudo_emetric_space α] [pseudo_emetric_space β] [pseudo_emetric_space γ]
variables {f : α → β} {x y z : α} {s : set α}
lemma isometry.lipschitz (h : isometry f) : lipschitz_with 1 f :=
lipschitz_with.of_edist_le $ λ x y, le_of_eq (h x y)
lemma isometry.antilipschitz (h : isometry f) : antilipschitz_with 1 f :=
λ x y, by simp only [h x y, ennreal.coe_one, one_mul, le_refl]
/-- An isometry from an emetric space is injective -/
lemma isometry.injective {α : Type u} [emetric_space α] {f : α → β} (h : isometry f) :
injective f := h.antilipschitz.injective
/-- Any map on a subsingleton is an isometry -/
theorem isometry_subsingleton [subsingleton α] : isometry f :=
λx y, by rw subsingleton.elim x y; simp
/-- The identity is an isometry -/
lemma isometry_id : isometry (id : α → α) :=
λx y, rfl
/-- The composition of isometries is an isometry -/
theorem isometry.comp {g : β → γ} {f : α → β} (hg : isometry g) (hf : isometry f) :
isometry (g ∘ f) :=
assume x y, calc
edist ((g ∘ f) x) ((g ∘ f) y) = edist (f x) (f y) : hg _ _
... = edist x y : hf _ _
/-- An isometry from a metric space is a uniform embedding -/
theorem isometry.uniform_embedding {α : Type u} {β : Type v} [emetric_space α]
[pseudo_emetric_space β] {f : α → β} (hf : isometry f) :
uniform_embedding f :=
hf.antilipschitz.uniform_embedding hf.lipschitz.uniform_continuous
/-- An isometry from a complete emetric space is a closed embedding -/
theorem isometry.closed_embedding {α : Type u} {β : Type v} [emetric_space α] [complete_space α]
[emetric_space β] {f : α → β} (hf : isometry f) : closed_embedding f :=
hf.antilipschitz.closed_embedding hf.lipschitz.uniform_continuous
/-- An isometry is continuous. -/
lemma isometry.continuous (hf : isometry f) : continuous f :=
hf.lipschitz.continuous
/-- The right inverse of an isometry is an isometry. -/
lemma isometry.right_inv {f : α → β} {g : β → α} (h : isometry f) (hg : right_inverse g f) :
isometry g :=
λ x y, by rw [← h, hg _, hg _]
/-- Isometries preserve the diameter in pseudoemetric spaces. -/
lemma isometry.ediam_image (hf : isometry f) (s : set α) :
emetric.diam (f '' s) = emetric.diam s :=
eq_of_forall_ge_iff $ λ d,
by simp only [emetric.diam_le_iff, ball_image_iff, hf.edist_eq]
lemma isometry.ediam_range (hf : isometry f) :
emetric.diam (range f) = emetric.diam (univ : set α) :=
by { rw ← image_univ, exact hf.ediam_image univ }
/-- The injection from a subtype is an isometry -/
lemma isometry_subtype_coe {s : set α} : isometry (coe : s → α) :=
λx y, rfl
lemma isometry.comp_continuous_on_iff {α : Type u} [emetric_space α] {f : α → β} {γ}
[topological_space γ] (hf : isometry f) {g : γ → α} {s : set γ} :
continuous_on (f ∘ g) s ↔ continuous_on g s :=
hf.uniform_embedding.to_uniform_inducing.inducing.continuous_on_iff.symm
lemma isometry.comp_continuous_iff {α : Type u} [emetric_space α] {f : α → β} {γ}
[topological_space γ] (hf : isometry f) {g : γ → α} :
continuous (f ∘ g) ↔ continuous g :=
hf.uniform_embedding.to_uniform_inducing.inducing.continuous_iff.symm
end emetric_isometry --section
/-- An isometry preserves the diameter in pseudometric spaces. -/
lemma isometry.diam_image [pseudo_metric_space α] [pseudo_metric_space β]
{f : α → β} (hf : isometry f) (s : set α) : metric.diam (f '' s) = metric.diam s :=
by rw [metric.diam, metric.diam, hf.ediam_image]
lemma isometry.diam_range [pseudo_metric_space α] [pseudo_metric_space β] {f : α → β}
(hf : isometry f) : metric.diam (range f) = metric.diam (univ : set α) :=
by { rw ← image_univ, exact hf.diam_image univ }
namespace add_monoid_hom
variables {E F : Type*} [semi_normed_group E] [semi_normed_group F]
lemma isometry_iff_norm (f : E →+ F) : isometry f ↔ ∀ x, ∥f x∥ = ∥x∥ :=
begin
simp only [isometry_emetric_iff_metric, dist_eq_norm, ← f.map_sub],
refine ⟨λ h x, _, λ h x y, h _⟩,
simpa using h x 0
end
lemma isometry_of_norm (f : E →+ F) (hf : ∀ x, ∥f x∥ = ∥x∥) : isometry f :=
f.isometry_iff_norm.2 hf
end add_monoid_hom
/-- `α` and `β` are isometric if there is an isometric bijection between them. -/
@[nolint has_inhabited_instance] -- such a bijection need not exist
structure isometric (α : Type*) (β : Type*) [pseudo_emetric_space α] [pseudo_emetric_space β]
extends α ≃ β :=
(isometry_to_fun : isometry to_fun)
infix ` ≃ᵢ `:25 := isometric
namespace isometric
variables [pseudo_emetric_space α] [pseudo_emetric_space β] [pseudo_emetric_space γ]
instance : has_coe_to_fun (α ≃ᵢ β) := ⟨λ_, α → β, λe, e.to_equiv⟩
lemma coe_eq_to_equiv (h : α ≃ᵢ β) (a : α) : h a = h.to_equiv a := rfl
@[simp] lemma coe_to_equiv (h : α ≃ᵢ β) : ⇑h.to_equiv = h := rfl
protected lemma isometry (h : α ≃ᵢ β) : isometry h := h.isometry_to_fun
protected lemma bijective (h : α ≃ᵢ β) : bijective h := h.to_equiv.bijective
protected lemma injective (h : α ≃ᵢ β) : injective h := h.to_equiv.injective
protected lemma surjective (h : α ≃ᵢ β) : surjective h := h.to_equiv.surjective
protected lemma edist_eq (h : α ≃ᵢ β) (x y : α) : edist (h x) (h y) = edist x y :=
h.isometry.edist_eq x y
protected lemma dist_eq {α β : Type*} [pseudo_metric_space α] [pseudo_metric_space β] (h : α ≃ᵢ β)
(x y : α) : dist (h x) (h y) = dist x y :=
h.isometry.dist_eq x y
protected lemma continuous (h : α ≃ᵢ β) : continuous h := h.isometry.continuous
@[simp] lemma ediam_image (h : α ≃ᵢ β) (s : set α) : emetric.diam (h '' s) = emetric.diam s :=
h.isometry.ediam_image s
lemma to_equiv_inj : ∀ ⦃h₁ h₂ : α ≃ᵢ β⦄, (h₁.to_equiv = h₂.to_equiv) → h₁ = h₂
| ⟨e₁, h₁⟩ ⟨e₂, h₂⟩ H := by { dsimp at H, subst e₁ }
@[ext] lemma ext ⦃h₁ h₂ : α ≃ᵢ β⦄ (H : ∀ x, h₁ x = h₂ x) : h₁ = h₂ :=
to_equiv_inj $ equiv.ext H
/-- Alternative constructor for isometric bijections,
taking as input an isometry, and a right inverse. -/
def mk' {α : Type u} [emetric_space α] (f : α → β) (g : β → α) (hfg : ∀ x, f (g x) = x)
(hf : isometry f) : α ≃ᵢ β :=
{ to_fun := f,
inv_fun := g,
left_inv := λ x, hf.injective $ hfg _,
right_inv := hfg,
isometry_to_fun := hf }
/-- The identity isometry of a space. -/
protected def refl (α : Type*) [pseudo_emetric_space α] : α ≃ᵢ α :=
{ isometry_to_fun := isometry_id, .. equiv.refl α }
/-- The composition of two isometric isomorphisms, as an isometric isomorphism. -/
protected def trans (h₁ : α ≃ᵢ β) (h₂ : β ≃ᵢ γ) : α ≃ᵢ γ :=
{ isometry_to_fun := h₂.isometry_to_fun.comp h₁.isometry_to_fun,
.. equiv.trans h₁.to_equiv h₂.to_equiv }
@[simp] lemma trans_apply (h₁ : α ≃ᵢ β) (h₂ : β ≃ᵢ γ) (x : α) : h₁.trans h₂ x = h₂ (h₁ x) := rfl
/-- The inverse of an isometric isomorphism, as an isometric isomorphism. -/
protected def symm (h : α ≃ᵢ β) : β ≃ᵢ α :=
{ isometry_to_fun := h.isometry.right_inv h.right_inv,
to_equiv := h.to_equiv.symm }
@[simp] lemma symm_symm (h : α ≃ᵢ β) : h.symm.symm = h := to_equiv_inj h.to_equiv.symm_symm
@[simp] lemma apply_symm_apply (h : α ≃ᵢ β) (y : β) : h (h.symm y) = y :=
h.to_equiv.apply_symm_apply y
@[simp] lemma symm_apply_apply (h : α ≃ᵢ β) (x : α) : h.symm (h x) = x :=
h.to_equiv.symm_apply_apply x
lemma symm_apply_eq (h : α ≃ᵢ β) {x : α} {y : β} :
h.symm y = x ↔ y = h x :=
h.to_equiv.symm_apply_eq
lemma eq_symm_apply (h : α ≃ᵢ β) {x : α} {y : β} :
x = h.symm y ↔ h x = y :=
h.to_equiv.eq_symm_apply
lemma symm_comp_self (h : α ≃ᵢ β) : ⇑h.symm ∘ ⇑h = id :=
funext $ assume a, h.to_equiv.left_inv a
lemma self_comp_symm (h : α ≃ᵢ β) : ⇑h ∘ ⇑h.symm = id :=
funext $ assume a, h.to_equiv.right_inv a
@[simp] lemma range_eq_univ (h : α ≃ᵢ β) : range h = univ :=
h.to_equiv.range_eq_univ
lemma image_symm (h : α ≃ᵢ β) : image h.symm = preimage h :=
image_eq_preimage_of_inverse h.symm.to_equiv.left_inv h.symm.to_equiv.right_inv
lemma preimage_symm (h : α ≃ᵢ β) : preimage h.symm = image h :=
(image_eq_preimage_of_inverse h.to_equiv.left_inv h.to_equiv.right_inv).symm
@[simp] lemma symm_trans_apply (h₁ : α ≃ᵢ β) (h₂ : β ≃ᵢ γ) (x : γ) :
(h₁.trans h₂).symm x = h₁.symm (h₂.symm x) := rfl
lemma ediam_univ (h : α ≃ᵢ β) : emetric.diam (univ : set α) = emetric.diam (univ : set β) :=
by rw [← h.range_eq_univ, h.isometry.ediam_range]
@[simp] lemma ediam_preimage (h : α ≃ᵢ β) (s : set β) : emetric.diam (h ⁻¹' s) = emetric.diam s :=
by rw [← image_symm, ediam_image]
/-- The (bundled) homeomorphism associated to an isometric isomorphism. -/
protected def to_homeomorph (h : α ≃ᵢ β) : α ≃ₜ β :=
{ continuous_to_fun := h.continuous,
continuous_inv_fun := h.symm.continuous,
to_equiv := h.to_equiv }
@[simp] lemma coe_to_homeomorph (h : α ≃ᵢ β) : ⇑(h.to_homeomorph) = h := rfl
@[simp] lemma coe_to_homeomorph_symm (h : α ≃ᵢ β) : ⇑(h.to_homeomorph.symm) = h.symm := rfl
@[simp] lemma to_homeomorph_to_equiv (h : α ≃ᵢ β) :
h.to_homeomorph.to_equiv = h.to_equiv :=
rfl
@[simp] lemma comp_continuous_on_iff {γ} [topological_space γ] (h : α ≃ᵢ β)
{f : γ → α} {s : set γ} :
continuous_on (h ∘ f) s ↔ continuous_on f s :=
h.to_homeomorph.comp_continuous_on_iff _ _
@[simp] lemma comp_continuous_iff {γ} [topological_space γ] (h : α ≃ᵢ β) {f : γ → α} :
continuous (h ∘ f) ↔ continuous f :=
h.to_homeomorph.comp_continuous_iff
@[simp] lemma comp_continuous_iff' {γ} [topological_space γ] (h : α ≃ᵢ β) {f : β → γ} :
continuous (f ∘ h) ↔ continuous f :=
h.to_homeomorph.comp_continuous_iff'
/-- The group of isometries. -/
instance : group (α ≃ᵢ α) :=
{ one := isometric.refl _,
mul := λ e₁ e₂, e₂.trans e₁,
inv := isometric.symm,
mul_assoc := λ e₁ e₂ e₃, rfl,
one_mul := λ e, ext $ λ _, rfl,
mul_one := λ e, ext $ λ _, rfl,
mul_left_inv := λ e, ext e.symm_apply_apply }
@[simp] lemma coe_one : ⇑(1 : α ≃ᵢ α) = id := rfl
@[simp] lemma coe_mul (e₁ e₂ : α ≃ᵢ α) : ⇑(e₁ * e₂) = e₁ ∘ e₂ := rfl
lemma mul_apply (e₁ e₂ : α ≃ᵢ α) (x : α) : (e₁ * e₂) x = e₁ (e₂ x) := rfl
@[simp] lemma inv_apply_self (e : α ≃ᵢ α) (x: α) : e⁻¹ (e x) = x := e.symm_apply_apply x
@[simp] lemma apply_inv_self (e : α ≃ᵢ α) (x: α) : e (e⁻¹ x) = x := e.apply_symm_apply x
section normed_group
variables {G : Type*} [semi_normed_group G]
/-- Addition `y ↦ y + x` as an `isometry`. -/
protected def add_right (x : G) : G ≃ᵢ G :=
{ isometry_to_fun := isometry_emetric_iff_metric.2 $ λ y z, dist_add_right _ _ _,
.. equiv.add_right x }
@[simp] lemma add_right_to_equiv (x : G) :
(isometric.add_right x).to_equiv = equiv.add_right x := rfl
@[simp] lemma coe_add_right (x : G) : (isometric.add_right x : G → G) = λ y, y + x := rfl
lemma add_right_apply (x y : G) : (isometric.add_right x : G → G) y = y + x := rfl
@[simp] lemma add_right_symm (x : G) :
(isometric.add_right x).symm = isometric.add_right (-x) :=
ext $ λ y, rfl
/-- Addition `y ↦ x + y` as an `isometry`. -/
protected def add_left (x : G) : G ≃ᵢ G :=
{ isometry_to_fun := isometry_emetric_iff_metric.2 $ λ y z, dist_add_left _ _ _,
to_equiv := equiv.add_left x }
@[simp] lemma add_left_to_equiv (x : G) :
(isometric.add_left x).to_equiv = equiv.add_left x := rfl
@[simp] lemma coe_add_left (x : G) : ⇑(isometric.add_left x) = (+) x := rfl
@[simp] lemma add_left_symm (x : G) :
(isometric.add_left x).symm = isometric.add_left (-x) :=
ext $ λ y, rfl
variable (G)
/-- Negation `x ↦ -x` as an `isometry`. -/
protected def neg : G ≃ᵢ G :=
{ isometry_to_fun := isometry_emetric_iff_metric.2 $ λ x y, dist_neg_neg _ _,
to_equiv := equiv.neg G }
variable {G}
@[simp] lemma neg_symm : (isometric.neg G).symm = isometric.neg G := rfl
@[simp] lemma neg_to_equiv : (isometric.neg G).to_equiv = equiv.neg G := rfl
@[simp] lemma coe_neg : ⇑(isometric.neg G) = has_neg.neg := rfl
end normed_group
end isometric
namespace isometric
variables [pseudo_metric_space α] [pseudo_metric_space β] (h : α ≃ᵢ β)
@[simp] lemma diam_image (s : set α) : metric.diam (h '' s) = metric.diam s :=
h.isometry.diam_image s
@[simp] lemma diam_preimage (s : set β) : metric.diam (h ⁻¹' s) = metric.diam s :=
by rw [← image_symm, diam_image]
lemma diam_univ : metric.diam (univ : set α) = metric.diam (univ : set β) :=
congr_arg ennreal.to_real h.ediam_univ
end isometric
/-- An isometry induces an isometric isomorphism between the source space and the
range of the isometry. -/
def isometry.isometric_on_range [emetric_space α] [pseudo_emetric_space β] {f : α → β}
(h : isometry f) : α ≃ᵢ range f :=
{ isometry_to_fun := λx y, by simpa [subtype.edist_eq] using h x y,
.. equiv.of_injective f h.injective }
@[simp] lemma isometry.isometric_on_range_apply [emetric_space α] [pseudo_emetric_space β]
{f : α → β} (h : isometry f) (x : α) : h.isometric_on_range x = ⟨f x, mem_range_self _⟩ :=
rfl
/-- In a normed algebra, the inclusion of the base field in the extended field is an isometry. -/
lemma algebra_map_isometry (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [semi_normed_ring 𝕜']
[semi_normed_algebra 𝕜 𝕜'] : isometry (algebra_map 𝕜 𝕜') :=
begin
refine isometry_emetric_iff_metric.2 (λx y, _),
rw [dist_eq_norm, dist_eq_norm, ← ring_hom.map_sub, norm_algebra_map_eq],
end
|
1f30a33e34e69fb17653f326aee0994ed2d98bff | 367134ba5a65885e863bdc4507601606690974c1 | /src/data/list/zip.lean | 37fb51ba8df7d72f59dff1c94627164496f32536 | [
"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 | 11,721 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Kenny Lau
-/
import data.list.basic
universes u v w z
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type z}
open nat
namespace list
/- zip & unzip -/
@[simp] theorem zip_with_cons_cons (f : α → β → γ) (a : α) (b : β) (l₁ : list α) (l₂ : list β) :
zip_with f (a :: l₁) (b :: l₂) = f a b :: zip_with f l₁ l₂ := rfl
@[simp] theorem zip_cons_cons (a : α) (b : β) (l₁ : list α) (l₂ : list β) :
zip (a :: l₁) (b :: l₂) = (a, b) :: zip l₁ l₂ := rfl
@[simp] theorem zip_with_nil_left (f : α → β → γ) (l) : zip_with f [] l = [] := rfl
@[simp] theorem zip_with_nil_right (f : α → β → γ) (l) : zip_with f l [] = [] :=
by cases l; refl
@[simp] theorem zip_nil_left (l : list α) : zip ([] : list β) l = [] := rfl
@[simp] theorem zip_nil_right (l : list α) : zip l ([] : list β) = [] :=
zip_with_nil_right _ l
@[simp] theorem zip_swap : ∀ (l₁ : list α) (l₂ : list β),
(zip l₁ l₂).map prod.swap = zip l₂ l₁
| [] l₂ := (zip_nil_right _).symm
| l₁ [] := by rw zip_nil_right; refl
| (a::l₁) (b::l₂) := by simp only [zip_cons_cons, map_cons, zip_swap l₁ l₂, prod.swap_prod_mk];
split; refl
@[simp] theorem length_zip_with (f : α → β → γ) : ∀ (l₁ : list α) (l₂ : list β),
length (zip_with f l₁ l₂) = min (length l₁) (length l₂)
| [] l₂ := rfl
| l₁ [] := by simp only [length, min_zero, zip_with_nil_right]
| (a::l₁) (b::l₂) := by by simp [length, zip_cons_cons, length_zip_with l₁ l₂, min_add_add_right]
@[simp] theorem length_zip : ∀ (l₁ : list α) (l₂ : list β),
length (zip l₁ l₂) = min (length l₁) (length l₂) :=
length_zip_with _
lemma lt_length_left_of_zip_with {f : α → β → γ} {i : ℕ} {l : list α} {l' : list β}
(h : i < (zip_with f l l').length) :
i < l.length :=
by { rw [length_zip_with, lt_min_iff] at h, exact h.left }
lemma lt_length_right_of_zip_with {f : α → β → γ} {i : ℕ} {l : list α} {l' : list β}
(h : i < (zip_with f l l').length) :
i < l'.length :=
by { rw [length_zip_with, lt_min_iff] at h, exact h.right }
lemma lt_length_left_of_zip {i : ℕ} {l : list α} {l' : list β} (h : i < (zip l l').length) :
i < l.length :=
lt_length_left_of_zip_with h
lemma lt_length_right_of_zip {i : ℕ} {l : list α} {l' : list β} (h : i < (zip l l').length) :
i < l'.length :=
lt_length_right_of_zip_with h
theorem zip_append : ∀ {l₁ r₁ : list α} {l₂ r₂ : list β} (h : length l₁ = length l₂),
zip (l₁ ++ r₁) (l₂ ++ r₂) = zip l₁ l₂ ++ zip r₁ r₂
| [] r₁ l₂ r₂ h := by simp only [eq_nil_of_length_eq_zero h.symm]; refl
| l₁ r₁ [] r₂ h := by simp only [eq_nil_of_length_eq_zero h]; refl
| (a::l₁) r₁ (b::l₂) r₂ h := by simp only [cons_append, zip_cons_cons, zip_append (succ.inj h)];
split; refl
theorem zip_map (f : α → γ) (g : β → δ) : ∀ (l₁ : list α) (l₂ : list β),
zip (l₁.map f) (l₂.map g) = (zip l₁ l₂).map (prod.map f g)
| [] l₂ := rfl
| l₁ [] := by simp only [map, zip_nil_right]
| (a::l₁) (b::l₂) := by simp only [map, zip_cons_cons, zip_map l₁ l₂, prod.map]; split; refl
theorem zip_map_left (f : α → γ) (l₁ : list α) (l₂ : list β) :
zip (l₁.map f) l₂ = (zip l₁ l₂).map (prod.map f id) :=
by rw [← zip_map, map_id]
theorem zip_map_right (f : β → γ) (l₁ : list α) (l₂ : list β) :
zip l₁ (l₂.map f) = (zip l₁ l₂).map (prod.map id f) :=
by rw [← zip_map, map_id]
@[simp] lemma zip_with_map {μ}
(f : γ → δ → μ) (g : α → γ) (h : β → δ) (as : list α) (bs : list β) :
zip_with f (as.map g) (bs.map h) =
zip_with (λ a b, f (g a) (h b)) as bs :=
begin
induction as generalizing bs,
{ simp },
{ cases bs; simp * }
end
lemma zip_with_map_left
(f : α → β → γ) (g : δ → α) (l : list δ) (l' : list β) :
zip_with f (l.map g) l' = zip_with (f ∘ g) l l' :=
by { convert (zip_with_map f g id l l'), exact eq.symm (list.map_id _) }
lemma zip_with_map_right
(f : α → β → γ) (l : list α) (g : δ → β) (l' : list δ) :
zip_with f l (l'.map g) = zip_with (λ x, f x ∘ g) l l' :=
by { convert (list.zip_with_map f id g l l'), exact eq.symm (list.map_id _) }
theorem zip_map' (f : α → β) (g : α → γ) : ∀ (l : list α),
zip (l.map f) (l.map g) = l.map (λ a, (f a, g a))
| [] := rfl
| (a::l) := by simp only [map, zip_cons_cons, zip_map' l]; split; refl
theorem mem_zip {a b} : ∀ {l₁ : list α} {l₂ : list β},
(a, b) ∈ zip l₁ l₂ → a ∈ l₁ ∧ b ∈ l₂
| (_::l₁) (_::l₂) (or.inl rfl) := ⟨or.inl rfl, or.inl rfl⟩
| (a'::l₁) (b'::l₂) (or.inr h) := by split; simp only [mem_cons_iff, or_true, mem_zip h]
theorem map_fst_zip : ∀ (l₁ : list α) (l₂ : list β),
l₁.length ≤ l₂.length →
map prod.fst (zip l₁ l₂) = l₁
| [] bs _ := rfl
| (a :: as) (b :: bs) h := by { simp at h, simp! * }
| (a :: as) [] h := by { simp at h, contradiction }
theorem map_snd_zip : ∀ (l₁ : list α) (l₂ : list β),
l₂.length ≤ l₁.length →
map prod.snd (zip l₁ l₂) = l₂
| _ [] _ := by { rw zip_nil_right, refl }
| [] (b :: bs) h := by { simp at h, contradiction }
| (a :: as) (b :: bs) h := by { simp at h, simp! * }
@[simp] theorem unzip_nil : unzip (@nil (α × β)) = ([], []) := rfl
@[simp] theorem unzip_cons (a : α) (b : β) (l : list (α × β)) :
unzip ((a, b) :: l) = (a :: (unzip l).1, b :: (unzip l).2) :=
by rw unzip; cases unzip l; refl
theorem unzip_eq_map : ∀ (l : list (α × β)), unzip l = (l.map prod.fst, l.map prod.snd)
| [] := rfl
| ((a, b) :: l) := by simp only [unzip_cons, map_cons, unzip_eq_map l]
theorem unzip_left (l : list (α × β)) : (unzip l).1 = l.map prod.fst :=
by simp only [unzip_eq_map]
theorem unzip_right (l : list (α × β)) : (unzip l).2 = l.map prod.snd :=
by simp only [unzip_eq_map]
theorem unzip_swap (l : list (α × β)) : unzip (l.map prod.swap) = (unzip l).swap :=
by simp only [unzip_eq_map, map_map]; split; refl
theorem zip_unzip : ∀ (l : list (α × β)), zip (unzip l).1 (unzip l).2 = l
| [] := rfl
| ((a, b) :: l) := by simp only [unzip_cons, zip_cons_cons, zip_unzip l]; split; refl
theorem unzip_zip_left : ∀ {l₁ : list α} {l₂ : list β}, length l₁ ≤ length l₂ →
(unzip (zip l₁ l₂)).1 = l₁
| [] l₂ h := rfl
| l₁ [] h := by rw eq_nil_of_length_eq_zero (eq_zero_of_le_zero h); refl
| (a::l₁) (b::l₂) h := by simp only [zip_cons_cons, unzip_cons,
unzip_zip_left (le_of_succ_le_succ h)]; split; refl
theorem unzip_zip_right {l₁ : list α} {l₂ : list β} (h : length l₂ ≤ length l₁) :
(unzip (zip l₁ l₂)).2 = l₂ :=
by rw [← zip_swap, unzip_swap]; exact unzip_zip_left h
theorem unzip_zip {l₁ : list α} {l₂ : list β} (h : length l₁ = length l₂) :
unzip (zip l₁ l₂) = (l₁, l₂) :=
by rw [← @prod.mk.eta _ _ (unzip (zip l₁ l₂)),
unzip_zip_left (le_of_eq h), unzip_zip_right (ge_of_eq h)]
lemma zip_of_prod {l : list α} {l' : list β} {lp : list (α × β)}
(hl : lp.map prod.fst = l) (hr : lp.map prod.snd = l') :
lp = l.zip l' :=
by rw [←hl, ←hr, ←zip_unzip lp, ←unzip_left, ←unzip_right, zip_unzip, zip_unzip]
lemma map_prod_left_eq_zip {l : list α} (f : α → β) : l.map (λ x, (x, f x)) = l.zip (l.map f) :=
by { rw ←zip_map', congr, exact map_id _ }
lemma map_prod_right_eq_zip {l : list α} (f : α → β) : l.map (λ x, (f x, x)) = (l.map f).zip l :=
by { rw ←zip_map', congr, exact map_id _ }
@[simp] theorem length_revzip (l : list α) : length (revzip l) = length l :=
by simp only [revzip, length_zip, length_reverse, min_self]
@[simp] theorem unzip_revzip (l : list α) : (revzip l).unzip = (l, l.reverse) :=
unzip_zip (length_reverse l).symm
@[simp] theorem revzip_map_fst (l : list α) : (revzip l).map prod.fst = l :=
by rw [← unzip_left, unzip_revzip]
@[simp] theorem revzip_map_snd (l : list α) : (revzip l).map prod.snd = l.reverse :=
by rw [← unzip_right, unzip_revzip]
theorem reverse_revzip (l : list α) : reverse l.revzip = revzip l.reverse :=
by rw [← zip_unzip.{u u} (revzip l).reverse, unzip_eq_map]; simp; simp [revzip]
theorem revzip_swap (l : list α) : (revzip l).map prod.swap = revzip l.reverse :=
by simp [revzip]
lemma nth_zip_with {α β γ} (f : α → β → γ) (l₁ : list α) (l₂ : list β) (i : ℕ) :
(zip_with f l₁ l₂).nth i = f <$> l₁.nth i <*> l₂.nth i :=
begin
induction l₁ generalizing l₂ i,
{ simp [zip_with, (<*>)] },
{ cases l₂; simp only [zip_with, has_seq.seq, functor.map, nth, option.map_none'],
{ cases ((l₁_hd :: l₁_tl).nth i); refl },
{ cases i; simp only [option.map_some', nth, option.some_bind', *],
refl } },
end
lemma nth_zip_with_eq_some {α β γ} (f : α → β → γ) (l₁ : list α) (l₂ : list β) (z : γ) (i : ℕ) :
(zip_with f l₁ l₂).nth i = some z ↔ ∃ x y, l₁.nth i = some x ∧ l₂.nth i = some y ∧ f x y = z :=
begin
induction l₁ generalizing l₂ i,
{ simp [zip_with] },
{ cases l₂; simp only [zip_with, nth, exists_false, and_false, false_and],
cases i; simp *, },
end
lemma nth_zip_eq_some (l₁ : list α) (l₂ : list β) (z : α × β) (i : ℕ) :
(zip l₁ l₂).nth i = some z ↔ l₁.nth i = some z.1 ∧ l₂.nth i = some z.2 :=
begin
cases z,
rw [zip, nth_zip_with_eq_some], split,
{ rintro ⟨x, y, h₀, h₁, h₂⟩, cc },
{ rintro ⟨h₀, h₁⟩, exact ⟨_,_,h₀,h₁,rfl⟩ }
end
@[simp] lemma nth_le_zip_with {f : α → β → γ} {l : list α} {l' : list β} {i : ℕ}
{h : i < (zip_with f l l').length} :
(zip_with f l l').nth_le i h =
f (l.nth_le i (lt_length_left_of_zip_with h)) (l'.nth_le i (lt_length_right_of_zip_with h)) :=
begin
rw [←option.some_inj, ←nth_le_nth, nth_zip_with_eq_some],
refine ⟨l.nth_le i (lt_length_left_of_zip_with h), l'.nth_le i (lt_length_right_of_zip_with h),
nth_le_nth _, _⟩,
simp only [←nth_le_nth, eq_self_iff_true, and_self]
end
@[simp] lemma nth_le_zip {l : list α} {l' : list β} {i : ℕ} {h : i < (zip l l').length} :
(zip l l').nth_le i h =
(l.nth_le i (lt_length_left_of_zip h), l'.nth_le i (lt_length_right_of_zip h)) :=
nth_le_zip_with
lemma mem_zip_inits_tails {l : list α} {init tail : list α} :
(init, tail) ∈ zip l.inits l.tails ↔ init ++ tail = l :=
begin
induction l generalizing init tail;
simp_rw [tails, inits, zip_cons_cons],
{ simp },
{ split; rw [mem_cons_iff, zip_map_left, mem_map, prod.exists],
{ rintros (⟨rfl, rfl⟩ | ⟨_, _, h, rfl, rfl⟩),
{ simp },
{ simp [l_ih.mp h], }, },
{ cases init,
{ simp },
{ intro h,
right,
use [init_tl, tail],
simp * at *, }, }, },
end
lemma map_uncurry_zip_eq_zip_with
(f : α → β → γ) (l : list α) (l' : list β) :
map (function.uncurry f) (l.zip l') = zip_with f l l' :=
begin
induction l with hd tl hl generalizing l',
{ simp },
{ cases l' with hd' tl',
{ simp },
{ simp [hl] } }
end
@[simp] lemma sum_zip_with_distrib_left {γ : Type*} [semiring γ]
(f : α → β → γ) (n : γ) (l : list α) (l' : list β) :
(l.zip_with (λ x y, n * f x y) l').sum = n * (l.zip_with f l').sum :=
begin
induction l with hd tl hl generalizing f n l',
{ simp },
{ cases l' with hd' tl',
{ simp, },
{ simp [hl, mul_add] } }
end
end list
|
fd80d9fd5ef47d2ca74b46223020594f58403e28 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /test/induction.lean | 91c7afa2411f12e857a3211a208b1e5c30631957 | [
"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 | 38,041 | lean | import data.list.basic
import topology.basic
import tactic.induction
import tactic.linarith
universes u v w
--------------------------------------------------------------------------------
-- Setup: Some Inductive Types
--------------------------------------------------------------------------------
inductive le : ℕ → ℕ → Type
| zero {n} : le 0 n
| succ {n m} : le n m → le (n + 1) (m + 1)
inductive lt : ℕ → ℕ → Type
| zero {n} : lt 0 (n + 1)
| succ {n m} : lt n m → lt (n + 1) (m + 1)
inductive Fin : ℕ → Type
| zero {n} : Fin (n + 1)
| succ {n} : Fin n → Fin (n + 1)
inductive List (α : Sort*) : Sort*
| nil {} : List
| cons {} (x : α) (xs : List) : List
namespace List
def append {α} : List α → List α → List α
| nil ys := ys
| (cons x xs) ys := cons x (append xs ys)
end List
inductive Vec (α : Sort u) : ℕ → Sort (max 1 u)
| nil : Vec 0
| cons {n} : α → Vec n → Vec (n + 1)
namespace Vec
inductive eq {α} : ∀ n m, Vec α n → Vec α m → Prop
| nil : eq 0 0 nil nil
| cons {n m} {xs : Vec α n} {ys : Vec α m} {x y : α} :
x = y →
eq n m xs ys →
eq (n + 1) (m + 1) (cons x xs) (cons y ys)
end Vec
inductive Two : Type | zero | one
inductive ℕ' : Type
| intro : ℕ → ℕ'
--------------------------------------------------------------------------------
-- Unit Tests
--------------------------------------------------------------------------------
example (k) : 0 + k = k :=
begin
induction' k,
{ refl },
{ simp }
end
example {k} (fk : Fin k) : Fin (k + 1) :=
begin
induction' fk,
{ exact Fin.zero },
{ exact Fin.succ ih }
end
example {α} (l : List α) : l.append List.nil = l :=
begin
induction' l,
{ refl },
{ dsimp only [List.append],
exact (congr_arg _ ih) }
end
example {k l} (h : lt k l) : le k l :=
begin
induction' h,
{ exact le.zero },
{ exact le.succ ih }
end
example {k l} : lt k l → le k l :=
begin
induction' k; induction' l; intro hlt,
{ cases' hlt },
{ exact le.zero },
{ cases' hlt },
{ cases' hlt,
exact le.succ (@ih m hlt), }
end
example {α n m} {xs : Vec α n} {ys : Vec α m} (h : Vec.eq n m xs ys) : n = m :=
begin
induction' h,
case nil {
refl },
case cons {
exact congr_arg nat.succ ih, }
end
-- A simple induction with complex index arguments.
example {k} (h : lt (k + 1) k) : false :=
begin
induction' h,
{ exact ih }
end
-- A more complex induction with complex index arguments. Note the dependencies
-- between index arguments.
example {α : Sort u} {x y n m} {xs : Vec α n} {ys : Vec α m}
: Vec.eq (n + 1) (m + 1) (Vec.cons x xs) (Vec.cons y ys)
→ Vec.eq n m xs ys :=
begin
intro h,
induction' h,
exact h_1
end
-- It also works with cases'.
example {α : Sort u} {x y n m} {xs : Vec α n} {ys : Vec α m}
: Vec.eq (n + 1) (m + 1) (Vec.cons x xs) (Vec.cons y ys)
→ Vec.eq n m xs ys :=
begin
intro h,
cases' h,
exact h_1
end
-- This example requires elimination of cyclic generalised index equations.
example (n : ℕ) (h : n = n + 3) : false :=
begin
success_if_fail { cases h },
induction' h
end
-- It also works with cases'.
example (n : ℕ) (h : n = n + 3) : false :=
begin
success_if_fail { cases h },
cases' h
end
-- This example used to fail because it involves a nested inductive as a complex
-- index.
inductive rose₁ : Type
| tip : rose₁
| node : list rose₁ → rose₁
example (rs) (h : rose₁.tip = rose₁.node rs) : false :=
begin
cases' h
end
-- This example checks whether we can deal with infinitely branching inductive
-- types.
inductive inf_tree (α : Type) : Type
| tip : inf_tree
| node (a : α) (f : ∀ (n : ℕ), inf_tree) : inf_tree
namespace inf_tree
inductive all {α} (P : α → Prop) : inf_tree α → Prop
| tip : all tip
| node {a} {f : ℕ → inf_tree α} : P a → (∀ n, all (f n)) → all (node a f)
example {α} (t : inf_tree α) : all (λ _, true) t :=
begin
induction' t,
{ exact all.tip },
{ exact all.node trivial ih }
end
end inf_tree
-- This example tests type-based naming.
example (k : ℕ') (i : ℕ') : ℕ :=
begin
induction' k,
induction' i,
exact (n + m)
end
-- For constructor arguments that are propositions, the default name is "h".
-- For non-propositions, it is "x".
inductive nat_or_positive
| nat : ℕ' → nat_or_positive
| positive (n : ℕ) : n > 0 → nat_or_positive
example (n : nat_or_positive) : unit :=
begin
cases' n,
case nat {
guard_hyp x : ℕ',
exact () },
case positive {
guard_hyp n : ℕ,
guard_hyp h : n > 0,
exact () }
end
-- By default, induction' generates the most general possible induction
-- hypothesis.
example {n m : ℕ} : n + m = m + n :=
begin
induction' m,
case zero { simp },
case succ : k IH {
guard_hyp k : ℕ,
guard_hyp n : ℕ,
guard_hyp IH : ∀ {n}, n + k = k + n,
ac_refl }
end
-- Here's an example where this is more useful.
example {n m : ℕ} (h : n + n = m + m) : n = m :=
begin
induction' n with n ih,
case zero {
cases' m,
{ refl },
{ cases' h } },
case succ {
cases' m,
{ cases' h },
{ rw @ih m,
simp only [nat.succ_eq_add_one] at h,
replace h : n + n + 2 = m + m + 2 := by linarith,
injections } }
end
-- If we don't want a hypothesis to be generalised, we can say so with a
-- "fixing" clause.
example {n m : ℕ} : n + m = m + n :=
begin
induction' m fixing n,
case zero { simp },
case succ : k IH {
guard_hyp k : ℕ,
guard_hyp n : ℕ,
guard_hyp IH : n + k = k + n,
ac_refl }
end
-- We can also fix all hypotheses. This gives us the behaviour of stock
-- `induction`. Hypotheses which depend on the major premise (or its index
-- arguments) still get generalised.
example {n m k : ℕ} (h : n + m = k) : n + m = k :=
begin
induction' n fixing *,
case zero { simp [*] },
case succ : n IH {
guard_hyp n : ℕ,
guard_hyp m : ℕ,
guard_hyp k : ℕ,
guard_hyp h : n.succ + m = k,
guard_hyp IH : n + m = k → n + m = k,
-- Neither m nor k were generalised.
exact h }
end
-- We can also generalise only certain hypotheses using a `generalizing`
-- clause. This gives us the behaviour of stock `induction ... generalizing`.
-- Hypotheses which depend on the major premise get generalised even if they are
-- not mentioned in the `generalizing` clause.
example {n m k : ℕ} (h : n + m = k) : n + m = k :=
begin
induction' n generalizing k,
case zero { simp [*] },
case succ : n IH {
guard_hyp n : ℕ,
guard_hyp m : ℕ,
guard_hyp k : ℕ,
guard_hyp h : n.succ + m = k,
guard_hyp IH : ∀ {k}, n + m = k → n + m = k,
-- k was generalised, but m was not.
exact h }
end
-- Sometimes generalising a hypothesis H does not give us a more general
-- induction hypothesis. In such cases, induction' should not generalise H. The
-- following example is not realistic, but situations like this can occur in
-- practice; see accufact_1_eq_fact below.
example (n m k : ℕ) : m + k = k + m :=
begin
induction' m,
case zero { simp },
case succ {
guard_hyp ih : ∀ k, m + k = k + m,
-- k was generalised because this makes the IH more general.
-- n was not generalised -- if it had been, the IH would be
--
-- ∀ n k, m + k = k + m
--
-- with one useless additional argument.
ac_refl }
end
-- This example checks that constructor arguments don't 'steal' the names of
-- generalised hypotheses.
example (n : list ℕ) (n : ℕ) : list ℕ :=
begin
-- this performs induction on (n : ℕ)
induction' n,
{ exact n },
{ guard_hyp n : list ℕ,
guard_hyp n_1 : ℕ,
-- n is the list, which was automatically generalized and keeps its name.
-- n_1 is the recursive argument of `nat.succ`. It would be called `n` if
-- there wasn't already an `n` in the context.
exact (n_1 :: n) }
end
-- This example tests whether `induction'` gets confused when there are
-- additional cases around.
example (k : ℕ) (t : Two) : 0 + k = k :=
begin
cases t,
induction' k,
{ refl },
{ simp },
induction' k,
{ refl },
{ simp }
end
-- The type of the induction premise can be a complex expression so long as it
-- normalises to an inductive (possibly applied to params/indexes).
example (n) : 0 + n = n :=
begin
let T := ℕ,
change T at n,
induction' n; simp
end
-- Fail if the type of the induction premise is not an inductive type
example {α} (x : α) (f : α → α) : unit :=
begin
success_if_fail { induction' x },
success_if_fail { induction' f },
exact ()
end
-- The following example used to trigger a bug where eliminate would generate
-- hypotheses with duplicate names.
structure fraction : Type :=
(num : ℤ)
(denom : ℤ)
(denom_ne_zero : denom ≠ 0)
lemma fraction.ext (a b : fraction) (hnum : fraction.num a = fraction.num b)
(hdenom : fraction.denom a = fraction.denom b) :
a = b :=
begin
cases' a,
cases' b,
guard_hyp num : ℤ,
guard_hyp denom : ℤ,
guard_hyp num_1 : ℤ,
guard_hyp denom_1 : ℤ,
rw fraction.mk.inj_eq,
exact and.intro hnum hdenom
end
-- A "with" clause can be used to give the names of constructor arguments (as
-- for `cases`, `induction` etc).
example (x : ℕ × ℕ) (y : Vec ℕ 2) (z : List ℕ) : unit :=
begin
cases' x with i j k l,
guard_hyp i : ℕ,
guard_hyp j : ℕ,
clear i j,
cases' y with i j k l,
-- Note that i is 'skipped' because it is used to name the (n : ℕ)
-- argument of `cons`, but that argument is cleared by index unification. I
-- find this a little strange, but `cases` also behaves like this.
guard_hyp j : ℕ,
guard_hyp k : Vec ℕ 1,
clear j k,
cases' z with i j k l,
case nil { exact () },
case cons {
guard_hyp i : ℕ,
guard_hyp j : List ℕ,
exact () }
end
-- "with" also works with induction'.
example (x : List ℕ) : unit :=
begin
induction' x with i j k l,
case nil { exact () },
case cons {
guard_hyp i : ℕ,
guard_hyp j : List ℕ,
guard_hyp k : unit,
exact () }
end
-- An underscore in a "with" clause means "use the auto-generated name for this
-- argument".
example (x : List ℕ) : unit :=
begin
induction' x with _ j _ l,
case nil { exact () },
case cons {
guard_hyp x : ℕ,
guard_hyp j : List ℕ,
guard_hyp ih : unit,
exact () }
end
namespace with_tests
inductive test
| intro (n) (f : fin n) (m) (g : fin m)
-- A hyphen in a "with" clause means "clear this hypothesis and its reverse
-- dependencies".
example (h : test) : unit :=
begin
cases' h with - F M G,
guard_hyp M : ℕ,
guard_hyp G : fin M,
success_if_fail { guard_hyp n },
success_if_fail { guard_hyp F },
exact ()
end
-- Names given in a "with" clause are used verbatim, even if this results in
-- shadowing.
example (x : ℕ) (h : test) : unit :=
begin
cases' h with x y y -,
/-
Expected goal:
x x : ℕ,
y : fin x,
y : ℕ
⊢ unit
It's hard to give a good test case here because we would need a variant of
`guard_hyp` that is sensitive to shadowing. But we can at least check that the
hyps don't have the names they would get if we avoided shadowing.
-/
success_if_fail { guard_hyp x_1 },
success_if_fail { guard_hyp y_1 },
exact ()
end
end with_tests
-- induction' and cases' can be used to perform induction/case analysis on
-- arbitrary expressions (not just hypotheses). A very synthetic example:
example {α} : α ∨ ¬ α :=
begin
cases' classical.em α with a nota,
{ exact (or.inl a) },
{ exact (or.inr nota) }
end
-- Cases'/induction' can add an equation witnessing the case split it
-- performed. Again, a highly synthetic example:
example {α} (xs : list α)
: xs.reverse.length = 0 ∨ ∃ m, xs.reverse.length = m + 1 :=
begin
cases' eq : xs.length,
case zero {
left,
rw list.length_reverse,
exact eq },
case succ : l {
right,
rw list.length_reverse,
use l,
exact eq }
end
-- Index equation simplification can deal with equations that aren't in normal
-- form.
example {α} (x : α) (xs) : list.take 1 (x :: xs) ≠ [] :=
begin
intro contra,
cases' contra
end
-- Index generalisation should leave early occurrences of complex index terms
-- alone. This means that given the major premise `e : E (f y) y` where `y` is a
-- complex term, index generalisation should give us
--
-- e : E (f y) i,
--
-- *not*
--
-- e : E (f i) i.
--
-- Otherwise we get problems with examples like this:
inductive ℕ₂ : Type
| zero
| succ (n : ℕ₂) : ℕ₂
namespace ℕ₂
def plus : ℕ₂ → ℕ₂ → ℕ₂
| zero y := y
| (succ x) y := succ (plus x y)
example (x : ℕ₂) (h : plus zero x = zero) : x = zero :=
begin
cases' h,
guard_target zero = plus zero zero,
refl
-- If index generalisation blindly replaced all occurrences of zero, we would
-- get
--
-- index = zero → plus index x = index → x = index
--
-- and after applying the recursor
--
-- plus index x = zero → x = plus index x
--
-- This leaves the goal provable, but very confusing.
end
-- TODO Here's a test case (due to Floris van Doorn) where index generalisation
-- is over-eager: it replaces the complex index `zero` everywhere in the goal,
-- which makes the goal type-incorrect. `cases` does not exhibit this problem.
example (x : ℕ₂) (h : plus zero x = zero) :
(⟨x, h⟩ : ∃ x, plus zero x = zero) = ⟨zero, rfl⟩ :=
begin
success_if_fail { cases' h },
cases h,
refl
end
end ℕ₂
-- For whatever reason, the eliminator for `false` has an explicit argument
-- where all other eliminators have an implicit one. `eliminate_hyp` has to
-- work around this to ensure that we can eliminate a `false` hyp.
example {α} (h : false) : α :=
begin
cases' h
end
-- Index equation simplification also works with nested datatypes.
inductive rose (α : Type) : Type
| leaf : rose
| node (val : α) (children : list rose) : rose
namespace rose
inductive nonempty {α} : rose α → Prop
| node (v c cs) : nonempty (node v (c :: cs))
lemma nonempty_node_elim {α} {v : α} {cs} (h : nonempty (node v cs)) : ¬ cs.empty :=
begin
induction' h,
finish
end
end rose
-- The following test cases, provided by Patrick Massot, test interactions with
-- several 'advanced' Lean features.
namespace topological_space_tests
class topological_space (X : Type) :=
(is_open : set X → Prop)
(univ_mem : is_open set.univ)
(union : ∀ (B : set (set X)) (h : ∀ b ∈ B, is_open b), is_open (⋃₀ B))
(inter : ∀ (A B : set X) (hA : is_open A) (hB : is_open B), is_open (A ∩ B))
open topological_space (is_open)
inductive generated_open (X : Type) (g : set (set X)) : set X → Prop
| generator : ∀ A ∈ g, generated_open A
| inter : ∀ A B, generated_open A → generated_open B → generated_open (A ∩ B)
| union : ∀ (B : set (set X)), (∀ b ∈ B, generated_open b) → generated_open (⋃₀ B)
| univ : generated_open set.univ
def generate_from (X : Type) (g : set (set X)) : topological_space X :=
{ is_open := generated_open X g,
univ_mem := generated_open.univ,
inter := generated_open.inter,
union := generated_open.union }
inductive generated_filter {X : Type*} (g : set (set X)) : set X → Prop
| generator {A} : A ∈ g → generated_filter A
| inter {A B} : generated_filter A → generated_filter B → generated_filter (A ∩ B)
| subset {A B} : generated_filter A → A ⊆ B → generated_filter B
| univ : generated_filter set.univ
def neighbourhood {X : Type} [topological_space X] (x : X) (V : set X) : Prop :=
∃ (U : set X), is_open U ∧ x ∈ U ∧ U ⊆ V
axiom nhd_inter {X : Type*} [topological_space X] {x : X} {U V : set X}
(hU : neighbourhood x U) (hV : neighbourhood x V) : neighbourhood x (U ∩ V)
axiom nhd_superset {X : Type*} [topological_space X] {x : X} {U V : set X}
(hU : neighbourhood x U) (hUV : U ⊆ V) : neighbourhood x V
axiom nhd_univ {X : Type*} [topological_space X] {x : X} : neighbourhood x set.univ
-- This example fails if auto-generalisation refuses to revert before
-- frozen local instances.
example {X : Type} [T : topological_space X] {s : set (set X)}
(h : T = generate_from X s) {U x} :
generated_filter {V | V ∈ s ∧ x ∈ V} U → neighbourhood x U :=
begin
rw h,
intro U_in,
induction' U_in fixing T h with U hU U V U_gen V_gen hU hV U V U_gen hUV hU,
{ exact ⟨U, generated_open.generator U hU.1, hU.2, set.subset.refl U⟩ },
{ exact @nhd_inter _ (generate_from X s) _ _ _ hU hV },
{ exact @nhd_superset _ (generate_from X s) _ _ _ hU hUV },
{ apply nhd_univ }
end
-- This example fails if auto-generalisation tries to generalise `let`
-- hypotheses.
example {X : Type} [T : topological_space X] {s : set (set X)}
(h : T = generate_from X s) {U x} :
generated_filter {V | V ∈ s ∧ x ∈ V} U → neighbourhood x U :=
begin
rw h,
letI := generate_from X s,
intro U_in,
induction' U_in fixing T h with U hU U V U_gen V_gen hU hV U V U_gen hUV hU,
{ exact ⟨U, generated_open.generator U hU.1, hU.2, set.subset.refl U⟩ },
{ exact nhd_inter hU hV },
{ exact nhd_superset hU hUV },
{ apply nhd_univ }
end
-- This example fails if infinitely branching inductive types like
-- `generated_open` are not handled properly. In particular, it tests the
-- interaction of infinitely branching types with complex indices.
example {X : Type*} [T : topological_space X] {s : set (set X)}
(h : T = generate_from X s) {U : set X} {x : X} :
neighbourhood x U → generated_filter {V | V ∈ s ∧ x ∈ V} U :=
begin
rw h, letI := generate_from X s,
clear h,
rintros ⟨V, V_op, x_in, hUV⟩,
apply generated_filter.subset _ hUV,
clear hUV,
induction' V_op fixing _inst T s U,
{ apply generated_filter.generator,
split ; assumption },
{ cases x_in,
apply generated_filter.inter ; tauto },
{ rw set.mem_sUnion at x_in,
rcases x_in with ⟨W, hW, hxW⟩,
exact generated_filter.subset (ih W hW hxW) (set.subset_sUnion_of_mem hW)},
{ apply generated_filter.univ }
end
end topological_space_tests
--------------------------------------------------------------------------------
-- Logical Verification Use Cases
--------------------------------------------------------------------------------
-- The following examples were provided by Jasmin Blanchette. They are taken
-- from his course 'Logical Verification'.
/- Head induction for transitive closure -/
inductive star {α : Sort*} (r : α → α → Prop) (a : α) : α → Prop
| refl {} : star a
| tail {b c} : star b → r b c → star c
namespace star
variables {α : Sort*} {r : α → α → Prop} {a b c d : α}
lemma head (hab : r a b) (hbc : star r b c) :
star r a c :=
begin
induction' hbc fixing hab,
case refl {
exact refl.tail hab },
case tail : c d hbc hcd hac {
exact hac.tail hcd }
end
-- In this example, induction' must apply the dependent recursor for star; the
-- nondependent one doesn't apply.
lemma head_induction_on {b} {P : ∀a : α, star r a b → Prop} {a} (h : star r a b)
(refl : P b refl)
(head : ∀{a c} (h' : r a c) (h : star r c b), P c h → P a (h.head h')) :
P a h :=
begin
induction' h,
case refl {
exact refl },
case tail : b c hab hbc ih {
apply ih,
{ exact head hbc _ refl, },
{ intros _ _ hab _, exact head hab _} }
end
end star
/- Factorial -/
def accufact : ℕ → ℕ → ℕ
| a 0 := a
| a (n + 1) := accufact ((n + 1) * a) n
lemma accufact_1_eq_fact (n : ℕ) :
accufact 1 n = nat.factorial n :=
have accufact_eq_fact_mul : ∀m a, accufact a m = nat.factorial m * a :=
begin
intros m a,
induction' m,
case zero {
simp [nat.factorial, accufact] },
case succ {
simp [nat.factorial, accufact, ih, nat.succ_eq_add_one],
cc }
end,
by simp [accufact_eq_fact_mul n 1]
/- Substitution -/
namespace expressions
inductive exp : Type
| Var : string → exp
| Num : ℤ → exp
| Plus : exp → exp → exp
export exp
def subst (ρ : string → exp) : exp → exp
| (Var y) := ρ y
| (Num i) := Num i
| (Plus e₁ e₂) := Plus (subst e₁) (subst e₂)
lemma subst_Var (e : exp) :
subst (λx, Var x) e = e :=
begin
induction' e,
case Var {
guard_hyp s : string,
rw [subst] },
case Num {
guard_hyp n : ℤ,
rw [subst] },
case Plus {
guard_hyp e : exp,
guard_hyp e_1 : exp,
guard_hyp ih_e,
guard_hyp ih_e_1,
rw [subst],
rw ih_e,
rw ih_e_1 }
end
end expressions
/- Less-than -/
namespace less_than
inductive lt : nat → nat → Type
| zero_succ (n : nat) : lt 0 (1 + n)
| succ_succ {n m : nat} : lt n m → lt (1 + n) (1 + m)
inductive lte : nat → nat → Type
| zero (n : nat) : lte 0 n
| succ {n m : nat} : lte n m → lte (1 + n) (1 + m)
def lt_lte {n m} : lt n m → lte n m :=
begin
intro lt_n_m,
induction' lt_n_m,
case zero_succ : i {
constructor },
case succ_succ : i j lt_i_j ih {
constructor,
apply ih }
end
end less_than
/- Sortedness -/
inductive sorted : list ℕ → Prop
| nil : sorted []
| single {x : ℕ} : sorted [x]
| two_or_more {x y : ℕ} {zs : list ℕ} (hle : x ≤ y)
(hsorted : sorted (y :: zs)) :
sorted (x :: y :: zs)
/- In this example it's important that cases' *doesn't* normalise the values of
indexes when simplifying index equations. -/
lemma not_sorted_17_13 :
¬ sorted [17, 13] :=
begin
intro h,
cases' h,
guard_hyp hle : 17 ≤ 13,
linarith
end
/- Palindromes -/
namespace palindrome
inductive palindrome {α : Type} : list α → Prop
| nil : palindrome []
| single (x : α) : palindrome [x]
| sandwich (x : α) (xs : list α) (hpal : palindrome xs) :
palindrome ([x] ++ xs ++ [x])
axiom reverse_append_sandwich {α : Type} (x : α) (ys : list α) :
list.reverse ([x] ++ ys ++ [x]) = [x] ++ list.reverse ys ++ [x]
lemma rev_palindrome {α : Type} (xs : list α) (hpal : palindrome xs) :
palindrome (list.reverse xs) :=
begin
induction' hpal,
case nil {
exact palindrome.nil },
case single {
exact palindrome.single _ },
case sandwich {
rw reverse_append_sandwich,
apply palindrome.sandwich,
apply ih }
end
end palindrome
/- Transitive Closure -/
namespace transitive_closure
inductive tc {α : Type} (r : α → α → Prop) : α → α → Prop
| base (x y : α) (hr : r x y) : tc x y
| step (x y z : α) (hr : r x y) (ht : tc y z) : tc x z
/- The transitive closure is a nice example with lots of variables to keep track
of. We start with a lemma where the variable names do not collide with those
appearing in the definition of the inductive predicate. -/
lemma tc_pets₁ {α : Type} (r : α → α → Prop) (c : α) :
∀a b, tc r a b → r b c → tc r a c :=
begin
intros a b htab hrbc,
induction' htab fixing c,
case base : _ _ hrab {
exact tc.step _ _ _ hrab (tc.base _ _ hrbc) },
case step : _ x _ hrax {
exact tc.step _ _ _ hrax (ih hrbc) }
end
/- The same proof, but this time the variable names clash. Also, this time we
let `induction'` generalize `z`. -/
lemma tc_pets₂ {α : Type} (r : α → α → Prop) (z : α) :
∀x y, tc r x y → r y z → tc r x z :=
begin
intros x y htxy hryz,
induction' htxy,
case base : _ _ hrxy {
exact tc.step _ _ _ hrxy (tc.base _ _ hryz) },
case step : _ x' y hrxx' htx'y ih {
exact tc.step _ _ _ hrxx' (ih _ hryz) }
end
/- Another proof along the same lines. -/
lemma tc_trans {α : Type} (r : α → α → Prop) (c : α) :
∀a b : α, tc r a b → tc r b c → tc r a c :=
begin
intros a b htab htbc,
induction' htab,
case base {
exact tc.step _ _ _ hr htbc },
case step {
exact tc.step _ _ _ hr (ih _ htbc) }
end
/- ... and with clashing variable names: -/
lemma tc_trans' {α : Type} (r : α → α → Prop) {x y z} :
tc r x y → tc r y z → tc r x z :=
begin
intros h₁ h₂,
induction' h₁,
case base {
exact tc.step _ _ _ hr h₂ },
case step {
exact tc.step _ _ _ hr (ih h₂) }
end
end transitive_closure
/- Evenness -/
inductive Even : ℕ → Prop
| zero : Even 0
| add_two : ∀k : ℕ, Even k → Even (k + 2)
lemma not_even_2_mul_add_1 (n : ℕ) :
¬ Even (2 * n + 1) :=
begin
intro h,
induction' h,
-- No case tag since there's only one goal. I don't really like this, but
-- this is the behaviour of induction/cases.
{
apply ih (n - 1),
cases' n,
case zero {
linarith },
case succ {
simp [nat.succ_eq_add_one] at *,
linarith } }
end
/- Big-Step Semantics -/
namespace semantics
def state :=
string → ℕ
def state.update (name : string) (val : ℕ) (s : state) : state :=
λname', if name' = name then val else s name'
notation s `{` name ` ↦ ` val `}` := state.update name val s
inductive stmt : Type
| skip : stmt
| assign : string → (state → ℕ) → stmt
| seq : stmt → stmt → stmt
| ite : (state → Prop) → stmt → stmt → stmt
| while : (state → Prop) → stmt → stmt
export stmt
infixr ` ;; ` : 90 := stmt.seq
/- Our first version is partly uncurried, like in the Logical Verification
course, and also like in Concrete Semantics. This makes the binary infix
notation possible. -/
inductive big_step : stmt × state → state → Prop
| skip {s} :
big_step (skip, s) s
| assign {x a s} :
big_step (assign x a, s) (s{x ↦ a s})
| seq {S T s t u} (hS : big_step (S, s) t)
(hT : big_step (T, t) u) :
big_step (seq S T, s) u
| ite_true {b : state → Prop} {S T s t} (hcond : b s)
(hbody : big_step (S, s) t) :
big_step (ite b S T, s) t
| ite_false {b : state → Prop} {S T s t} (hcond : ¬ b s)
(hbody : big_step (T, s) t) :
big_step (ite b S T, s) t
| while_true {b : state → Prop} {S s t u} (hcond : b s)
(hbody : big_step (S, s) t)
(hrest : big_step (while b S, t) u) :
big_step (while b S, s) u
| while_false {b : state → Prop} {S s} (hcond : ¬ b s) :
big_step (while b S, s) s
infix ` ⟹ `:110 := big_step
open big_step
lemma not_big_step_while_true {S s t} :
¬ (while (λ_, true) S, s) ⟹ t :=
begin
intro hw,
induction' hw,
case while_true {
exact ih_hw_1 },
case while_false {
exact hcond trivial }
end
/- The same with a curried version of the predicate. It should make no
difference whether a predicate is curried or uncurried. -/
inductive curried_big_step : stmt → state → state → Prop
| skip {s} :
curried_big_step skip s s
| assign {x a s} :
curried_big_step (assign x a) s (s{x ↦ a s})
| seq {S T s t u} (hS : curried_big_step S s t)
(hT : curried_big_step T t u) :
curried_big_step (seq S T) s u
| ite_true {b : state → Prop} {S T s t} (hcond : b s)
(hbody : curried_big_step S s t) :
curried_big_step (ite b S T) s t
| ite_false {b : state → Prop} {S T s t} (hcond : ¬ b s)
(hbody : curried_big_step T s t) :
curried_big_step (ite b S T) s t
| while_true {b : state → Prop} {S s t u} (hcond : b s)
(hbody : curried_big_step S s t)
(hrest : curried_big_step (while b S) t u) :
curried_big_step (while b S) s u
| while_false {b : state → Prop} {S s} (hcond : ¬ b s) :
curried_big_step (while b S) s s
lemma not_curried_big_step_while_true {S s t} :
¬ curried_big_step (while (λ_, true) S) s t :=
begin
intro hw,
induction' hw,
case while_true {
exact ih_hw_1, },
case while_false {
exact hcond trivial }
end
end semantics
/- Small-Step Semantics -/
namespace semantics
inductive small_step : stmt × state → stmt × state → Prop
| assign {x a s} :
small_step (assign x a, s) (skip, s{x ↦ a s})
| seq_step {S S' T s s'} (hS : small_step (S, s) (S', s')) :
small_step (seq S T, s) (seq S' T, s')
| seq_skip {T s} :
small_step (seq skip T, s) (T, s)
| ite_true {b : state → Prop} {S T s} (hcond : b s) :
small_step (ite b S T, s) (S, s)
| ite_false {b : state → Prop} {S T s} (hcond : ¬ b s) :
small_step (ite b S T, s) (T, s)
| while {b : state → Prop} {S s} :
small_step (while b S, s) (ite b (seq S (while b S)) skip, s)
lemma small_step_if_equal_states {S T s t s' t'}
(hstep : small_step (S, s) (T, t)) (hs : s' = s) (ht : t' = t) :
small_step (S, s') (T, t') :=
begin
induction' hstep,
{ rw [hs, ht],
exact small_step.assign, },
{ apply small_step.seq_step,
exact ih hs ht, },
{ rw [hs, ht],
exact small_step.seq_skip, },
{ rw [hs, ht],
exact small_step.ite_true hcond, },
{ rw [hs, ht],
exact small_step.ite_false hcond, },
{ rw [hs, ht],
exact small_step.while, }
end
infixr (name := small_step) ` ⇒ ` := small_step
infixr (name := small_step.star) ` ⇒* ` : 100 := star small_step
/- More lemmas about big-step and small-step semantics. These are taken from the
Logical Verification course materials. They provide lots of good test cases for
cases'/induction'. -/
namespace star
variables {α : Sort*} {r : α → α → Prop} {a b c d : α}
attribute [refl] star.refl
@[trans] lemma trans (hab : star r a b) (hbc : star r b c) :
star r a c :=
begin
induction' hbc,
case refl {
assumption },
case tail : c d hbc hcd hac {
exact (star.tail (hac hab)) hcd }
end
lemma single (hab : r a b) :
star r a b :=
star.refl.tail hab
lemma trans_induction_on {α : Sort*} {r : α → α → Prop}
{p : ∀{a b : α}, star r a b → Prop} {a b : α} (h : star r a b)
(ih₁ : ∀a, @p a a star.refl) (ih₂ : ∀{a b} (h : r a b), p (single h))
(ih₃ : ∀{a b c} (h₁ : star r a b) (h₂ : star r b c), p h₁ →
p h₂ → p (trans h₁ h₂)) :
p h :=
begin
induction' h,
case refl {
exact ih₁ a },
case tail : b c hab hbc ih {
exact ih₃ hab (single hbc) (ih ih₁ @ih₂ @ih₃) (ih₂ hbc) }
end
lemma lift {β : Sort*} {s : β → β → Prop} (f : α → β)
(h : ∀a b, r a b → s (f a) (f b)) (hab : star r a b) :
star s (f a) (f b) :=
begin
apply trans_induction_on hab,
exact (λ a, star.refl),
exact (λ a b, star.single ∘ h _ _),
exact (λ a b c _ _, star.trans)
end
end star
lemma big_step_deterministic {S s l r} (hl : (S, s) ⟹ l)
(hr : (S, s) ⟹ r) :
l = r :=
begin
induction' hl,
case skip : t {
cases' hr,
refl },
case assign : x a s {
cases' hr,
refl },
case seq : S T s t l hS hT ihS ihT {
cases' hr with _ _ _ _ _ _ _ t' _ hS' hT',
cases' ihS hS',
cases' ihT hT',
refl },
case ite_true : b S T s t hb hS ih {
cases' hr,
{ apply ih,
assumption },
{ apply ih,
cc } },
case ite_false : b S T s t hb hT ih {
cases' hr,
{ apply ih,
cc },
{ apply ih,
assumption } },
case while_true : b S s t u hb hS hw ihS ihw {
cases' hr,
{ cases' ihS hr,
cases' ihw hr_1,
refl },
{ cc } },
{ cases' hr,
{ cc },
{ refl } }
end
@[simp] lemma big_step_skip_iff {s t} :
(stmt.skip, s) ⟹ t ↔ t = s :=
begin
apply iff.intro,
{ intro h,
cases' h,
refl },
{ intro h,
rw h,
exact big_step.skip }
end
@[simp] lemma big_step_assign_iff {x a s t} :
(stmt.assign x a, s) ⟹ t ↔ t = s{x ↦ a s} :=
begin
apply iff.intro,
{ intro h,
cases' h,
refl },
{ intro h,
rw h,
exact big_step.assign }
end
@[simp] lemma big_step_seq_iff {S T s t} :
(S ;; T, s) ⟹ t ↔ (∃u, (S, s) ⟹ u ∧ (T, u) ⟹ t) :=
begin
apply iff.intro,
{ intro h,
cases' h,
apply exists.intro,
apply and.intro; assumption },
{ intro h,
cases' h,
cases' h,
apply big_step.seq; assumption }
end
@[simp] lemma big_step_ite_iff {b S T s t} :
(stmt.ite b S T, s) ⟹ t ↔
(b s ∧ (S, s) ⟹ t) ∨ (¬ b s ∧ (T, s) ⟹ t) :=
begin
apply iff.intro,
{ intro h,
cases' h,
{ apply or.intro_left,
cc },
{ apply or.intro_right,
cc } },
{ intro h,
cases' h; cases' h,
{ apply big_step.ite_true; assumption },
{ apply big_step.ite_false; assumption } }
end
lemma big_step_while_iff {b S s u} :
(stmt.while b S, s) ⟹ u ↔
(∃t, b s ∧ (S, s) ⟹ t ∧ (stmt.while b S, t) ⟹ u)
∨ (¬ b s ∧ u = s) :=
begin
apply iff.intro,
{ intro h,
cases' h,
{ apply or.intro_left,
apply exists.intro t,
cc },
{ apply or.intro_right,
cc } },
{ intro h,
cases' h,
case or.inl {
cases' h with t h,
cases' h with hb h,
cases' h with hS hwhile,
exact big_step.while_true hb hS hwhile },
case or.inr {
cases' h with hb hus,
rw hus,
exact big_step.while_false hb } }
end
lemma big_step_while_true_iff {b : state → Prop} {S s u}
(hcond : b s) :
(stmt.while b S, s) ⟹ u ↔
(∃t, (S, s) ⟹ t ∧ (stmt.while b S, t) ⟹ u) :=
by rw big_step_while_iff; simp [hcond]
@[simp] lemma big_step_while_false_iff {b : state → Prop}
{S s t} (hcond : ¬ b s) :
(stmt.while b S, s) ⟹ t ↔ t = s :=
by rw big_step_while_iff; simp [hcond]
lemma small_step_final (S s) :
(¬ ∃T t, (S, s) ⇒ (T, t)) ↔ S = stmt.skip :=
begin
induction' S,
case skip {
simp,
intros T t hstep,
cases' hstep },
case assign : x a {
simp,
apply exists.intro stmt.skip,
apply exists.intro (s{x ↦ a s}),
exact small_step.assign },
case seq : S T ihS ihT {
simp,
cases' classical.em (S = stmt.skip),
case inl {
rw h,
apply exists.intro T,
apply exists.intro s,
exact small_step.seq_skip },
case inr {
simp [h, not_forall, not_not] at ihS,
cases' ihS s with S' hS',
cases' hS' with s' hs',
apply exists.intro (S' ;; T),
apply exists.intro s',
exact small_step.seq_step hs' } },
case ite : b S T ihS ihT {
simp,
cases' classical.em (b s),
case inl {
apply exists.intro S,
apply exists.intro s,
exact small_step.ite_true h },
case inr {
apply exists.intro T,
apply exists.intro s,
exact small_step.ite_false h } },
case while : b S ih {
simp,
apply exists.intro (stmt.ite b (S ;; stmt.while b S) stmt.skip),
apply exists.intro s,
exact small_step.while }
end
lemma small_step_deterministic {S s Ll Rr}
(hl : (S, s) ⇒ Ll) (hr : (S, s) ⇒ Rr) :
Ll = Rr :=
begin
induction' hl,
case assign : x a s {
cases' hr,
refl },
case seq_step : S S₁ T s s₁ hS₁ ih {
cases' hr,
case seq_step : S S₂ _ _ s₂ hS₂ {
have hSs₁₂ := ih hS₂,
cc },
case seq_skip {
cases' hS₁ } },
case seq_skip : T s {
cases' hr,
{ cases' hr },
{ refl } },
case ite_true : b S T s hcond {
cases' hr,
case ite_true {
refl },
case ite_false {
cc } },
case ite_false : b S T s hcond {
cases' hr,
case ite_true {
cc },
case ite_false {
refl } },
case while : b S s {
cases' hr,
refl }
end
lemma small_step_skip {S s t} :
¬ ((stmt.skip, s) ⇒ (S, t)) :=
by intro h; cases' h
@[simp] lemma small_step_seq_iff {S T s Ut} :
(S ;; T, s) ⇒ Ut ↔
(∃S' t, (S, s) ⇒ (S', t) ∧ Ut = (S' ;; T, t))
∨ (S = stmt.skip ∧ Ut = (T, s)) :=
begin
apply iff.intro,
{ intro h,
cases' h,
{ apply or.intro_left,
apply exists.intro S',
apply exists.intro s',
cc },
{ apply or.intro_right,
cc } },
{ intro h,
cases' h,
{ cases' h,
cases' h,
cases' h,
rw right,
apply small_step.seq_step,
assumption },
{ cases' h,
rw left,
rw right,
apply small_step.seq_skip } }
end
@[simp] lemma small_step_ite_iff {b S T s Us} :
(stmt.ite b S T, s) ⇒ Us ↔
(b s ∧ Us = (S, s)) ∨ (¬ b s ∧ Us = (T, s)) :=
begin
apply iff.intro,
{ intro h,
cases' h,
{ apply or.intro_left,
cc },
{ apply or.intro_right,
cc } },
{ intro h,
cases' h,
{ cases' h,
rw right,
apply small_step.ite_true,
assumption },
{ cases' h,
rw right,
apply small_step.ite_false,
assumption } }
end
lemma star_small_step_seq {S T s u}
(h : (S, s) ⇒* (stmt.skip, u)) :
(S ;; T, s) ⇒* (stmt.skip ;; T, u) :=
begin
apply star.lift (λSs, (prod.fst Ss ;; T, prod.snd Ss)) _ h,
intros Ss Ss' h,
cases' Ss,
cases' Ss',
apply small_step.seq_step,
assumption
end
lemma star_small_step_of_big_step {S s t} (h : (S, s) ⟹ t) :
(S, s) ⇒* (stmt.skip, t) :=
begin
induction' h,
case skip {
refl },
case assign {
exact star.single small_step.assign },
case seq : S T s t u hS hT ihS ihT {
transitivity,
exact star_small_step_seq ihS,
apply star.head small_step.seq_skip ihT },
case ite_true : b S T s t hs hst ih {
exact star.head (small_step.ite_true hs) ih },
case ite_false : b S T s t hs hst ih {
exact star.head (small_step.ite_false hs) ih },
case while_true : b S s t u hb hS hw ihS ihw {
exact (star.head small_step.while
(star.head (small_step.ite_true hb)
(star.trans (star_small_step_seq ihS)
(star.head small_step.seq_skip ihw)))) },
case while_false : b S s hb {
exact star.tail (star.single small_step.while)
(small_step.ite_false hb) }
end
lemma big_step_of_small_step_of_big_step {S₀ S₁ s₀ s₁ s₂}
(h₁ : (S₀, s₀) ⇒ (S₁, s₁)) :
(S₁, s₁) ⟹ s₂ → (S₀, s₀) ⟹ s₂ :=
begin
induction' h₁;
simp [*, big_step_while_true_iff, or_imp_distrib] {contextual := tt},
case seq_step {
intros u hS' hT,
apply exists.intro u,
exact and.intro (ih hS') hT },
end
lemma big_step_of_star_small_step {S s t} :
(S, s) ⇒* (stmt.skip, t) → (S, s) ⟹ t :=
begin
generalize hSs : (S, s) = Ss,
intro h,
induction h
using star.head_induction_on
with _ S's' h h' ih
generalizing S s;
cases' hSs,
{ exact big_step.skip },
{ cases' S's' with S' s',
apply big_step_of_small_step_of_big_step h,
apply ih,
refl }
end
end semantics
|
efcc42c2f24aaddbdd2c3276ea6436f9d164e828 | bb31430994044506fa42fd667e2d556327e18dfe | /src/analysis/normed_space/linear_isometry.lean | f23d83eb76925b693caf61317f08da3a39f6437c | [
"Apache-2.0"
] | permissive | sgouezel/mathlib | 0cb4e5335a2ba189fa7af96d83a377f83270e503 | 00638177efd1b2534fc5269363ebf42a7871df9a | refs/heads/master | 1,674,527,483,042 | 1,673,665,568,000 | 1,673,665,568,000 | 119,598,202 | 0 | 0 | null | 1,517,348,647,000 | 1,517,348,646,000 | null | UTF-8 | Lean | false | false | 37,649 | lean | /-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, Frédéric Dupuis, Heather Macbeth
-/
import analysis.normed.group.basic
import topology.algebra.module.basic
import linear_algebra.basis
/-!
# (Semi-)linear isometries
In this file we define `linear_isometry σ₁₂ E E₂` (notation: `E →ₛₗᵢ[σ₁₂] E₂`) to be a semilinear
isometric embedding of `E` into `E₂` and `linear_isometry_equiv` (notation: `E ≃ₛₗᵢ[σ₁₂] E₂`) to be
a semilinear isometric equivalence between `E` and `E₂`. The notation for the associated purely
linear concepts is `E →ₗᵢ[R] E₂`, `E ≃ₗᵢ[R] E₂`, and `E →ₗᵢ⋆[R] E₂`, `E ≃ₗᵢ⋆[R] E₂` for
the star-linear versions.
We also prove some trivial lemmas and provide convenience constructors.
Since a lot of elementary properties don't require `‖x‖ = 0 → x = 0` we start setting up the
theory for `seminormed_add_comm_group` and we specialize to `normed_add_comm_group` when needed.
-/
open function set
variables {R R₂ R₃ R₄ E E₂ E₃ E₄ F 𝓕 : Type*} [semiring R] [semiring R₂] [semiring R₃] [semiring R₄]
{σ₁₂ : R →+* R₂} {σ₂₁ : R₂ →+* R} {σ₁₃ : R →+* R₃} {σ₃₁ : R₃ →+* R} {σ₁₄ : R →+* R₄}
{σ₄₁ : R₄ →+* R} {σ₂₃ : R₂ →+* R₃} {σ₃₂ : R₃ →+* R₂} {σ₂₄ : R₂ →+* R₄} {σ₄₂ : R₄ →+* R₂}
{σ₃₄ : R₃ →+* R₄} {σ₄₃ : R₄ →+* R₃}
[ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂]
[ring_hom_inv_pair σ₁₃ σ₃₁] [ring_hom_inv_pair σ₃₁ σ₁₃]
[ring_hom_inv_pair σ₂₃ σ₃₂] [ring_hom_inv_pair σ₃₂ σ₂₃]
[ring_hom_inv_pair σ₁₄ σ₄₁] [ring_hom_inv_pair σ₄₁ σ₁₄]
[ring_hom_inv_pair σ₂₄ σ₄₂] [ring_hom_inv_pair σ₄₂ σ₂₄]
[ring_hom_inv_pair σ₃₄ σ₄₃] [ring_hom_inv_pair σ₄₃ σ₃₄]
[ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] [ring_hom_comp_triple σ₁₂ σ₂₄ σ₁₄]
[ring_hom_comp_triple σ₂₃ σ₃₄ σ₂₄] [ring_hom_comp_triple σ₁₃ σ₃₄ σ₁₄]
[ring_hom_comp_triple σ₃₂ σ₂₁ σ₃₁] [ring_hom_comp_triple σ₄₂ σ₂₁ σ₄₁]
[ring_hom_comp_triple σ₄₃ σ₃₂ σ₄₂] [ring_hom_comp_triple σ₄₃ σ₃₁ σ₄₁]
[seminormed_add_comm_group E] [seminormed_add_comm_group E₂] [seminormed_add_comm_group E₃]
[seminormed_add_comm_group E₄] [module R E] [module R₂ E₂] [module R₃ E₃] [module R₄ E₄]
[normed_add_comm_group F] [module R F]
/-- A `σ₁₂`-semilinear isometric embedding of a normed `R`-module into an `R₂`-module. -/
structure linear_isometry (σ₁₂ : R →+* R₂) (E E₂ : Type*) [seminormed_add_comm_group E]
[seminormed_add_comm_group E₂] [module R E] [module R₂ E₂] extends E →ₛₗ[σ₁₂] E₂ :=
(norm_map' : ∀ x, ‖to_linear_map x‖ = ‖x‖)
notation E ` →ₛₗᵢ[`:25 σ₁₂:25 `] `:0 E₂:0 := linear_isometry σ₁₂ E E₂
notation E ` →ₗᵢ[`:25 R:25 `] `:0 E₂:0 := linear_isometry (ring_hom.id R) E E₂
notation E ` →ₗᵢ⋆[`:25 R:25 `] `:0 E₂:0 := linear_isometry (star_ring_end R) E E₂
set_option old_structure_cmd true
/-- `semilinear_isometry_class F σ E E₂` asserts `F` is a type of bundled `σ`-semilinear isometries
`E → E₂`.
See also `linear_isometry_class F R E E₂` for the case where `σ` is the identity map on `R`.
A map `f` between an `R`-module and an `S`-module over a ring homomorphism `σ : R →+* S`
is semilinear if it satisfies the two properties `f (x + y) = f x + f y` and
`f (c • x) = (σ c) • f x`. -/
class semilinear_isometry_class (𝓕 : Type*) {R R₂ : out_param Type*} [semiring R] [semiring R₂]
(σ₁₂ : out_param $ R →+* R₂) (E E₂ : out_param Type*) [seminormed_add_comm_group E]
[seminormed_add_comm_group E₂] [module R E] [module R₂ E₂]
extends semilinear_map_class 𝓕 σ₁₂ E E₂ :=
(norm_map : ∀ (f : 𝓕) (x : E), ‖f x‖ = ‖x‖)
/-- `linear_isometry_class F R E E₂` asserts `F` is a type of bundled `R`-linear isometries
`M → M₂`.
This is an abbreviation for `semilinear_isometry_class F (ring_hom.id R) E E₂`.
-/
abbreviation linear_isometry_class (𝓕 : Type*) (R E E₂ : out_param Type*) [semiring R]
[seminormed_add_comm_group E] [seminormed_add_comm_group E₂] [module R E] [module R E₂] :=
semilinear_isometry_class 𝓕 (ring_hom.id R) E E₂
set_option old_structure_cmd false
namespace semilinear_isometry_class
protected lemma isometry [semilinear_isometry_class 𝓕 σ₁₂ E E₂] (f : 𝓕) : isometry f :=
add_monoid_hom_class.isometry_of_norm _ (norm_map _)
@[continuity] protected lemma continuous [semilinear_isometry_class 𝓕 σ₁₂ E E₂] (f : 𝓕) :
continuous f :=
(semilinear_isometry_class.isometry f).continuous
@[simp] lemma nnnorm_map [semilinear_isometry_class 𝓕 σ₁₂ E E₂] (f : 𝓕) (x : E) :
‖f x‖₊ = ‖x‖₊ :=
nnreal.eq $ norm_map f x
protected lemma lipschitz [semilinear_isometry_class 𝓕 σ₁₂ E E₂] (f : 𝓕) :
lipschitz_with 1 f :=
(semilinear_isometry_class.isometry f).lipschitz
protected lemma antilipschitz [semilinear_isometry_class 𝓕 σ₁₂ E E₂] (f : 𝓕) :
antilipschitz_with 1 f :=
(semilinear_isometry_class.isometry f).antilipschitz
lemma ediam_image [semilinear_isometry_class 𝓕 σ₁₂ E E₂] (f : 𝓕) (s : set E) :
emetric.diam (f '' s) = emetric.diam s :=
(semilinear_isometry_class.isometry f).ediam_image s
lemma ediam_range [semilinear_isometry_class 𝓕 σ₁₂ E E₂] (f : 𝓕) :
emetric.diam (range f) = emetric.diam (univ : set E) :=
(semilinear_isometry_class.isometry f).ediam_range
lemma diam_image [semilinear_isometry_class 𝓕 σ₁₂ E E₂] (f : 𝓕) (s : set E) :
metric.diam (f '' s) = metric.diam s :=
(semilinear_isometry_class.isometry f).diam_image s
lemma diam_range [semilinear_isometry_class 𝓕 σ₁₂ E E₂] (f : 𝓕) :
metric.diam (range f) = metric.diam (univ : set E) :=
(semilinear_isometry_class.isometry f).diam_range
@[priority 100]
instance [s : semilinear_isometry_class 𝓕 σ₁₂ E E₂] : continuous_semilinear_map_class 𝓕 σ₁₂ E E₂ :=
{ map_continuous := semilinear_isometry_class.continuous,
..s }
end semilinear_isometry_class
namespace linear_isometry
/-- We use `f₁` when we need the domain to be a `normed_space`. -/
variables (f : E →ₛₗᵢ[σ₁₂] E₂) (f₁ : F →ₛₗᵢ[σ₁₂] E₂)
lemma to_linear_map_injective : injective (to_linear_map : (E →ₛₗᵢ[σ₁₂] E₂) → (E →ₛₗ[σ₁₂] E₂))
| ⟨f, _⟩ ⟨g, _⟩ rfl := rfl
@[simp] lemma to_linear_map_inj {f g : E →ₛₗᵢ[σ₁₂] E₂} :
f.to_linear_map = g.to_linear_map ↔ f = g := to_linear_map_injective.eq_iff
instance : semilinear_isometry_class (E →ₛₗᵢ[σ₁₂] E₂) σ₁₂ E E₂ :=
{ coe := λ f, f.to_fun,
coe_injective' := λ f g h, to_linear_map_injective (fun_like.coe_injective h),
map_add := λ f, map_add f.to_linear_map,
map_smulₛₗ := λ f, map_smulₛₗ f.to_linear_map,
norm_map := λ f, f.norm_map' }
/-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun`
directly.
-/
instance : has_coe_to_fun (E →ₛₗᵢ[σ₁₂] E₂) (λ _, E → E₂) := ⟨λ f, f.to_fun⟩
@[simp] lemma coe_to_linear_map : ⇑f.to_linear_map = f := rfl
@[simp] lemma coe_mk (f : E →ₛₗ[σ₁₂] E₂) (hf) : ⇑(mk f hf) = f := rfl
lemma coe_injective : @injective (E →ₛₗᵢ[σ₁₂] E₂) (E → E₂) coe_fn :=
fun_like.coe_injective
/-- 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 (σ₁₂ : R →+* R₂) (E E₂ : Type*) [seminormed_add_comm_group E]
[seminormed_add_comm_group E₂] [module R E] [module R₂ E₂] (h : E →ₛₗᵢ[σ₁₂] E₂) : E → E₂ := h
initialize_simps_projections linear_isometry (to_linear_map_to_fun → apply)
@[ext] lemma ext {f g : E →ₛₗᵢ[σ₁₂] E₂} (h : ∀ x, f x = g x) : f = g :=
coe_injective $ funext h
protected lemma congr_arg [semilinear_isometry_class 𝓕 σ₁₂ E E₂] {f : 𝓕} :
Π {x x' : E}, x = x' → f x = f x'
| _ _ rfl := rfl
protected lemma congr_fun [semilinear_isometry_class 𝓕 σ₁₂ E E₂] {f g : 𝓕} (h : f = g) (x : E) :
f x = g x := h ▸ rfl
@[simp] protected lemma map_zero : f 0 = 0 := f.to_linear_map.map_zero
@[simp] protected lemma map_add (x y : E) : f (x + y) = f x + f y := f.to_linear_map.map_add x y
@[simp] protected lemma map_neg (x : E) : f (- x) = - f x := f.to_linear_map.map_neg x
@[simp] protected lemma map_sub (x y : E) : f (x - y) = f x - f y := f.to_linear_map.map_sub x y
@[simp] protected lemma map_smulₛₗ (c : R) (x : E) : f (c • x) = σ₁₂ c • f x :=
f.to_linear_map.map_smulₛₗ c x
@[simp] protected lemma map_smul [module R E₂] (f : E →ₗᵢ[R] E₂) (c : R) (x : E) :
f (c • x) = c • f x :=
f.to_linear_map.map_smul c x
@[simp] lemma norm_map (x : E) : ‖f x‖ = ‖x‖ := semilinear_isometry_class.norm_map f x
@[simp] lemma nnnorm_map (x : E) : ‖f x‖₊ = ‖x‖₊ := nnreal.eq $ norm_map f x
protected lemma isometry : isometry f := add_monoid_hom_class.isometry_of_norm _ (norm_map _)
@[simp] lemma is_complete_image_iff [semilinear_isometry_class 𝓕 σ₁₂ E E₂] (f : 𝓕) {s : set E} :
is_complete (f '' s) ↔ is_complete s :=
is_complete_image_iff (semilinear_isometry_class.isometry f).uniform_inducing
lemma is_complete_map_iff [ring_hom_surjective σ₁₂] {p : submodule R E} :
is_complete (p.map f.to_linear_map : set E₂) ↔ is_complete (p : set E) :=
f.is_complete_image_iff
lemma is_complete_map_iff' [semilinear_isometry_class 𝓕 σ₁₂ E E₂] (f : 𝓕) [ring_hom_surjective σ₁₂]
{p : submodule R E} : is_complete (p.map f : set E₂) ↔ is_complete (p : set E) :=
is_complete_image_iff f
instance complete_space_map [semilinear_isometry_class 𝓕 σ₁₂ E E₂] (f : 𝓕) [ring_hom_surjective σ₁₂]
(p : submodule R E) [complete_space p] : complete_space (p.map f) :=
((is_complete_map_iff' f).2 $ complete_space_coe_iff_is_complete.1 ‹_›).complete_space_coe
instance complete_space_map' [ring_hom_surjective σ₁₂] (p : submodule R E) [complete_space p] :
complete_space (p.map f.to_linear_map) :=
(f.is_complete_map_iff.2 $ complete_space_coe_iff_is_complete.1 ‹_›).complete_space_coe
@[simp] lemma dist_map (x y : E) : dist (f x) (f y) = dist x y := f.isometry.dist_eq x y
@[simp] lemma edist_map (x y : E) : edist (f x) (f y) = edist x y := f.isometry.edist_eq x y
protected lemma injective : injective f₁ := isometry.injective (linear_isometry.isometry f₁)
@[simp] lemma map_eq_iff {x y : F} : f₁ x = f₁ y ↔ x = y := f₁.injective.eq_iff
lemma map_ne {x y : F} (h : x ≠ y) : f₁ x ≠ f₁ y := f₁.injective.ne h
protected lemma lipschitz : lipschitz_with 1 f := f.isometry.lipschitz
protected lemma antilipschitz : antilipschitz_with 1 f := f.isometry.antilipschitz
@[continuity] protected lemma continuous : continuous f := f.isometry.continuous
@[simp] lemma preimage_ball (x : E) (r : ℝ) :
f ⁻¹' (metric.ball (f x) r) = metric.ball x r :=
f.isometry.preimage_ball x r
@[simp] lemma preimage_sphere (x : E) (r : ℝ) :
f ⁻¹' (metric.sphere (f x) r) = metric.sphere x r :=
f.isometry.preimage_sphere x r
@[simp] lemma preimage_closed_ball (x : E) (r : ℝ) :
f ⁻¹' (metric.closed_ball (f x) r) = metric.closed_ball x r :=
f.isometry.preimage_closed_ball x r
lemma ediam_image (s : set E) : emetric.diam (f '' s) = emetric.diam s :=
f.isometry.ediam_image s
lemma ediam_range : emetric.diam (range f) = emetric.diam (univ : set E) :=
f.isometry.ediam_range
lemma diam_image (s : set E) : metric.diam (f '' s) = metric.diam s :=
isometry.diam_image (linear_isometry.isometry f) s
lemma diam_range : metric.diam (range f) = metric.diam (univ : set E) :=
isometry.diam_range (linear_isometry.isometry f)
/-- Interpret a linear isometry as a continuous linear map. -/
def to_continuous_linear_map : E →SL[σ₁₂] E₂ := ⟨f.to_linear_map, f.continuous⟩
lemma to_continuous_linear_map_injective :
function.injective (to_continuous_linear_map : _ → E →SL[σ₁₂] E₂) :=
λ x y h, coe_injective (congr_arg _ h : ⇑x.to_continuous_linear_map = _)
@[simp] lemma to_continuous_linear_map_inj {f g : E →ₛₗᵢ[σ₁₂] E₂} :
f.to_continuous_linear_map = g.to_continuous_linear_map ↔ f = g :=
to_continuous_linear_map_injective.eq_iff
@[simp] lemma coe_to_continuous_linear_map : ⇑f.to_continuous_linear_map = f := rfl
@[simp] lemma comp_continuous_iff {α : Type*} [topological_space α] {g : α → E} :
continuous (f ∘ g) ↔ continuous g :=
f.isometry.comp_continuous_iff
/-- The identity linear isometry. -/
def id : E →ₗᵢ[R] E := ⟨linear_map.id, λ x, rfl⟩
@[simp] lemma coe_id : ((id : E →ₗᵢ[R] E) : E → E) = _root_.id := rfl
@[simp] lemma id_apply (x : E) : (id : E →ₗᵢ[R] E) x = x := rfl
@[simp] lemma id_to_linear_map : (id.to_linear_map : E →ₗ[R] E) = linear_map.id := rfl
@[simp] lemma id_to_continuous_linear_map :
id.to_continuous_linear_map = continuous_linear_map.id R E := rfl
instance : inhabited (E →ₗᵢ[R] E) := ⟨id⟩
/-- Composition of linear isometries. -/
def comp (g : E₂ →ₛₗᵢ[σ₂₃] E₃) (f : E →ₛₗᵢ[σ₁₂] E₂) : E →ₛₗᵢ[σ₁₃] E₃ :=
⟨g.to_linear_map.comp f.to_linear_map, λ x, (norm_map g _).trans (norm_map f _)⟩
include σ₁₃
@[simp] lemma coe_comp (g : E₂ →ₛₗᵢ[σ₂₃] E₃) (f : E →ₛₗᵢ[σ₁₂] E₂) :
⇑(g.comp f) = g ∘ f :=
rfl
omit σ₁₃
@[simp] lemma id_comp : (id : E₂ →ₗᵢ[R₂] E₂).comp f = f := ext $ λ x, rfl
@[simp] lemma comp_id : f.comp id = f := ext $ λ x, rfl
include σ₁₃ σ₂₄ σ₁₄
lemma comp_assoc (f : E₃ →ₛₗᵢ[σ₃₄] E₄) (g : E₂ →ₛₗᵢ[σ₂₃] E₃) (h : E →ₛₗᵢ[σ₁₂] E₂) :
(f.comp g).comp h = f.comp (g.comp h) :=
rfl
omit σ₁₃ σ₂₄ σ₁₄
instance : monoid (E →ₗᵢ[R] E) :=
{ one := id,
mul := comp,
mul_assoc := comp_assoc,
one_mul := id_comp,
mul_one := comp_id }
@[simp] lemma coe_one : ((1 : E →ₗᵢ[R] E) : E → E) = _root_.id := rfl
@[simp] lemma coe_mul (f g : E →ₗᵢ[R] E) : ⇑(f * g) = f ∘ g := rfl
lemma one_def : (1 : E →ₗᵢ[R] E) = id := rfl
lemma mul_def (f g : E →ₗᵢ[R] E) : (f * g : E →ₗᵢ[R] E) = f.comp g := rfl
end linear_isometry
/-- Construct a `linear_isometry` from a `linear_map` satisfying `isometry`. -/
def linear_map.to_linear_isometry (f : E →ₛₗ[σ₁₂] E₂) (hf : isometry f) : E →ₛₗᵢ[σ₁₂] E₂ :=
{ norm_map' := by { simp_rw [←dist_zero_right, ←f.map_zero], exact λ x, hf.dist_eq x _ },
.. f }
namespace submodule
variables {R' : Type*} [ring R'] [module R' E] (p : submodule R' E)
/-- `submodule.subtype` as a `linear_isometry`. -/
def subtypeₗᵢ : p →ₗᵢ[R'] E := ⟨p.subtype, λ x, rfl⟩
@[simp] lemma coe_subtypeₗᵢ : ⇑p.subtypeₗᵢ = p.subtype := rfl
@[simp] lemma subtypeₗᵢ_to_linear_map : p.subtypeₗᵢ.to_linear_map = p.subtype := rfl
@[simp] lemma subtypeₗᵢ_to_continuous_linear_map :
p.subtypeₗᵢ.to_continuous_linear_map = p.subtypeL := rfl
end submodule
/-- A semilinear isometric equivalence between two normed vector spaces. -/
structure linear_isometry_equiv (σ₁₂ : R →+* R₂) {σ₂₁ : R₂ →+* R} [ring_hom_inv_pair σ₁₂ σ₂₁]
[ring_hom_inv_pair σ₂₁ σ₁₂] (E E₂ : Type*) [seminormed_add_comm_group E]
[seminormed_add_comm_group E₂] [module R E] [module R₂ E₂] extends E ≃ₛₗ[σ₁₂] E₂ :=
(norm_map' : ∀ x, ‖to_linear_equiv x‖ = ‖x‖)
notation E ` ≃ₛₗᵢ[`:25 σ₁₂:25 `] `:0 E₂:0 := linear_isometry_equiv σ₁₂ E E₂
notation E ` ≃ₗᵢ[`:25 R:25 `] `:0 E₂:0 := linear_isometry_equiv (ring_hom.id R) E E₂
notation E ` ≃ₗᵢ⋆[`:25 R:25 `] `:0 E₂:0 :=
linear_isometry_equiv (star_ring_end R) E E₂
set_option old_structure_cmd true
/-- `semilinear_isometry_equiv_class F σ E E₂` asserts `F` is a type of bundled `σ`-semilinear
isometric equivs `E → E₂`.
See also `linear_isometry_equiv_class F R E E₂` for the case where `σ` is the identity map on `R`.
A map `f` between an `R`-module and an `S`-module over a ring homomorphism `σ : R →+* S`
is semilinear if it satisfies the two properties `f (x + y) = f x + f y` and
`f (c • x) = (σ c) • f x`. -/
class semilinear_isometry_equiv_class (𝓕 : Type*) {R R₂ : out_param Type*}
[semiring R] [semiring R₂] (σ₁₂ : out_param $ R →+* R₂) {σ₂₁ : out_param $ R₂ →+* R}
[ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] (E E₂ : out_param Type*)
[seminormed_add_comm_group E] [seminormed_add_comm_group E₂] [module R E] [module R₂ E₂]
extends semilinear_equiv_class 𝓕 σ₁₂ E E₂ :=
(norm_map : ∀ (f : 𝓕) (x : E), ‖f x‖ = ‖x‖)
/-- `linear_isometry_equiv_class F R E E₂` asserts `F` is a type of bundled `R`-linear isometries
`M → M₂`.
This is an abbreviation for `semilinear_isometry_equiv_class F (ring_hom.id R) E E₂`.
-/
abbreviation linear_isometry_equiv_class (𝓕 : Type*) (R E E₂ : out_param Type*) [semiring R]
[seminormed_add_comm_group E] [seminormed_add_comm_group E₂] [module R E] [module R E₂] :=
semilinear_isometry_equiv_class 𝓕 (ring_hom.id R) E E₂
set_option old_structure_cmd false
namespace semilinear_isometry_equiv_class
variables (𝓕)
include σ₂₁
-- `σ₂₁` becomes a metavariable, but it's OK since it's an outparam
@[priority 100, nolint dangerous_instance]
instance [s : semilinear_isometry_equiv_class 𝓕 σ₁₂ E E₂] : semilinear_isometry_class 𝓕 σ₁₂ E E₂ :=
{ coe := (coe : 𝓕 → E → E₂),
coe_injective' := @fun_like.coe_injective 𝓕 _ _ _,
..s }
omit σ₂₁
end semilinear_isometry_equiv_class
namespace linear_isometry_equiv
variables (e : E ≃ₛₗᵢ[σ₁₂] E₂)
include σ₂₁
lemma to_linear_equiv_injective : injective (to_linear_equiv : (E ≃ₛₗᵢ[σ₁₂] E₂) → (E ≃ₛₗ[σ₁₂] E₂))
| ⟨e, _⟩ ⟨_, _⟩ rfl := rfl
@[simp] lemma to_linear_equiv_inj {f g : E ≃ₛₗᵢ[σ₁₂] E₂} :
f.to_linear_equiv = g.to_linear_equiv ↔ f = g :=
to_linear_equiv_injective.eq_iff
instance : semilinear_isometry_equiv_class (E ≃ₛₗᵢ[σ₁₂] E₂) σ₁₂ E E₂ :=
{ coe := λ e, e.to_fun,
inv := λ e, e.inv_fun,
coe_injective' := λ f g h₁ h₂,
by { cases f with f' _, cases g with g' _, cases f', cases g', congr', },
left_inv := λ e, e.left_inv,
right_inv := λ e, e.right_inv,
map_add := λ f, map_add f.to_linear_equiv,
map_smulₛₗ := λ e, map_smulₛₗ e.to_linear_equiv,
norm_map := λ e, e.norm_map' }
/-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun`
directly.
-/
instance : has_coe_to_fun (E ≃ₛₗᵢ[σ₁₂] E₂) (λ _, E → E₂) := ⟨λ f, f.to_fun⟩
lemma coe_injective : @function.injective (E ≃ₛₗᵢ[σ₁₂] E₂) (E → E₂) coe_fn :=
fun_like.coe_injective
@[simp] lemma coe_mk (e : E ≃ₛₗ[σ₁₂] E₂) (he : ∀ x, ‖e x‖ = ‖x‖) :
⇑(mk e he) = e :=
rfl
@[simp] lemma coe_to_linear_equiv (e : E ≃ₛₗᵢ[σ₁₂] E₂) : ⇑e.to_linear_equiv = e := rfl
@[ext] lemma ext {e e' : E ≃ₛₗᵢ[σ₁₂] E₂} (h : ∀ x, e x = e' x) : e = e' :=
to_linear_equiv_injective $ linear_equiv.ext h
protected lemma congr_arg {f : E ≃ₛₗᵢ[σ₁₂] E₂} : Π {x x' : E}, x = x' → f x = f x'
| _ _ rfl := rfl
protected lemma congr_fun {f g : E ≃ₛₗᵢ[σ₁₂] E₂} (h : f = g) (x : E) : f x = g x := h ▸ rfl
/-- Construct a `linear_isometry_equiv` from a `linear_equiv` and two inequalities:
`∀ x, ‖e x‖ ≤ ‖x‖` and `∀ y, ‖e.symm y‖ ≤ ‖y‖`. -/
def of_bounds (e : E ≃ₛₗ[σ₁₂] E₂) (h₁ : ∀ x, ‖e x‖ ≤ ‖x‖) (h₂ : ∀ y, ‖e.symm y‖ ≤ ‖y‖) :
E ≃ₛₗᵢ[σ₁₂] E₂ :=
⟨e, λ x, le_antisymm (h₁ x) $ by simpa only [e.symm_apply_apply] using h₂ (e x)⟩
@[simp] lemma norm_map (x : E) : ‖e x‖ = ‖x‖ := e.norm_map' x
/-- Reinterpret a `linear_isometry_equiv` as a `linear_isometry`. -/
def to_linear_isometry : E →ₛₗᵢ[σ₁₂] E₂ := ⟨e.1, e.2⟩
lemma to_linear_isometry_injective :
function.injective (to_linear_isometry : _ → E →ₛₗᵢ[σ₁₂] E₂) :=
λ x y h, coe_injective (congr_arg _ h : ⇑x.to_linear_isometry = _)
@[simp] lemma to_linear_isometry_inj {f g : E ≃ₛₗᵢ[σ₁₂] E₂} :
f.to_linear_isometry = g.to_linear_isometry ↔ f = g :=
to_linear_isometry_injective.eq_iff
@[simp] lemma coe_to_linear_isometry : ⇑e.to_linear_isometry = e := rfl
protected lemma isometry : isometry e := e.to_linear_isometry.isometry
/-- Reinterpret a `linear_isometry_equiv` as an `isometric`. -/
def to_isometric : E ≃ᵢ E₂ := ⟨e.to_linear_equiv.to_equiv, e.isometry⟩
lemma to_isometric_injective :
function.injective (to_isometric : (E ≃ₛₗᵢ[σ₁₂] E₂) → E ≃ᵢ E₂) :=
λ x y h, coe_injective (congr_arg _ h : ⇑x.to_isometric = _)
@[simp] lemma to_isometric_inj {f g : E ≃ₛₗᵢ[σ₁₂] E₂} :
f.to_isometric = g.to_isometric ↔ f = g :=
to_isometric_injective.eq_iff
@[simp] lemma coe_to_isometric : ⇑e.to_isometric = e := rfl
lemma range_eq_univ (e : E ≃ₛₗᵢ[σ₁₂] E₂) : set.range e = set.univ :=
by { rw ← coe_to_isometric, exact isometric.range_eq_univ _, }
/-- Reinterpret a `linear_isometry_equiv` as an `homeomorph`. -/
def to_homeomorph : E ≃ₜ E₂ := e.to_isometric.to_homeomorph
lemma to_homeomorph_injective :
function.injective (to_homeomorph : (E ≃ₛₗᵢ[σ₁₂] E₂) → E ≃ₜ E₂) :=
λ x y h, coe_injective (congr_arg _ h : ⇑x.to_homeomorph = _)
@[simp] lemma to_homeomorph_inj {f g : E ≃ₛₗᵢ[σ₁₂] E₂} :
f.to_homeomorph = g.to_homeomorph ↔ f = g :=
to_homeomorph_injective.eq_iff
@[simp] lemma coe_to_homeomorph : ⇑e.to_homeomorph = e := rfl
protected lemma continuous : continuous e := e.isometry.continuous
protected lemma continuous_at {x} : continuous_at e x := e.continuous.continuous_at
protected lemma continuous_on {s} : continuous_on e s := e.continuous.continuous_on
protected lemma continuous_within_at {s x} : continuous_within_at e s x :=
e.continuous.continuous_within_at
/-- Interpret a `linear_isometry_equiv` as a continuous linear equiv. -/
def to_continuous_linear_equiv : E ≃SL[σ₁₂] E₂ :=
{ .. e.to_linear_isometry.to_continuous_linear_map,
.. e.to_homeomorph }
lemma to_continuous_linear_equiv_injective :
function.injective (to_continuous_linear_equiv : _ → E ≃SL[σ₁₂] E₂) :=
λ x y h, coe_injective (congr_arg _ h : ⇑x.to_continuous_linear_equiv = _)
@[simp] lemma to_continuous_linear_equiv_inj {f g : E ≃ₛₗᵢ[σ₁₂] E₂} :
f.to_continuous_linear_equiv = g.to_continuous_linear_equiv ↔ f = g :=
to_continuous_linear_equiv_injective.eq_iff
@[simp] lemma coe_to_continuous_linear_equiv : ⇑e.to_continuous_linear_equiv = e := rfl
omit σ₂₁
variables (R E)
/-- Identity map as a `linear_isometry_equiv`. -/
def refl : E ≃ₗᵢ[R] E := ⟨linear_equiv.refl R E, λ x, rfl⟩
variables {R E}
instance : inhabited (E ≃ₗᵢ[R] E) := ⟨refl R E⟩
@[simp] lemma coe_refl : ⇑(refl R E) = id := rfl
/-- The inverse `linear_isometry_equiv`. -/
def symm : E₂ ≃ₛₗᵢ[σ₂₁] E :=
⟨e.to_linear_equiv.symm,
λ x, (e.norm_map _).symm.trans $ congr_arg norm $ e.to_linear_equiv.apply_symm_apply x⟩
@[simp] lemma apply_symm_apply (x : E₂) : e (e.symm x) = x := e.to_linear_equiv.apply_symm_apply x
@[simp] lemma symm_apply_apply (x : E) : e.symm (e x) = x := e.to_linear_equiv.symm_apply_apply x
@[simp] lemma map_eq_zero_iff {x : E} : e x = 0 ↔ x = 0 := e.to_linear_equiv.map_eq_zero_iff
@[simp] lemma symm_symm : e.symm.symm = e := ext $ λ x, rfl
@[simp] lemma to_linear_equiv_symm : e.to_linear_equiv.symm = e.symm.to_linear_equiv := rfl
@[simp] lemma to_isometric_symm : e.to_isometric.symm = e.symm.to_isometric := rfl
@[simp] lemma to_homeomorph_symm : e.to_homeomorph.symm = e.symm.to_homeomorph := rfl
/-- 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 (σ₁₂ : R →+* R₂) {σ₂₁ : R₂ →+* R} [ring_hom_inv_pair σ₁₂ σ₂₁]
[ring_hom_inv_pair σ₂₁ σ₁₂] (E E₂ : Type*) [seminormed_add_comm_group E]
[seminormed_add_comm_group E₂] [module R E] [module R₂ E₂] (h : E ≃ₛₗᵢ[σ₁₂] E₂) : E → E₂ := h
/-- See Note [custom simps projection] -/
def simps.symm_apply (σ₁₂ : R →+* R₂) {σ₂₁ : R₂ →+* R} [ring_hom_inv_pair σ₁₂ σ₂₁]
[ring_hom_inv_pair σ₂₁ σ₁₂] (E E₂ : Type*) [seminormed_add_comm_group E]
[seminormed_add_comm_group E₂]
[module R E] [module R₂ E₂] (h : E ≃ₛₗᵢ[σ₁₂] E₂) : E₂ → E := h.symm
initialize_simps_projections linear_isometry_equiv
(to_linear_equiv_to_fun → apply, to_linear_equiv_inv_fun → symm_apply)
include σ₃₁ σ₃₂
/-- Composition of `linear_isometry_equiv`s as a `linear_isometry_equiv`. -/
def trans (e' : E₂ ≃ₛₗᵢ[σ₂₃] E₃) : E ≃ₛₗᵢ[σ₁₃] E₃ :=
⟨e.to_linear_equiv.trans e'.to_linear_equiv, λ x, (e'.norm_map _).trans (e.norm_map _)⟩
include σ₁₃ σ₂₁
@[simp] lemma coe_trans (e₁ : E ≃ₛₗᵢ[σ₁₂] E₂) (e₂ : E₂ ≃ₛₗᵢ[σ₂₃] E₃) : ⇑(e₁.trans e₂) = e₂ ∘ e₁ :=
rfl
@[simp] lemma trans_apply (e₁ : E ≃ₛₗᵢ[σ₁₂] E₂) (e₂ : E₂ ≃ₛₗᵢ[σ₂₃] E₃) (c : E) :
(e₁.trans e₂ : E ≃ₛₗᵢ[σ₁₃] E₃) c = e₂ (e₁ c) :=
rfl
@[simp] lemma to_linear_equiv_trans (e' : E₂ ≃ₛₗᵢ[σ₂₃] E₃) :
(e.trans e').to_linear_equiv = e.to_linear_equiv.trans e'.to_linear_equiv :=
rfl
omit σ₁₃ σ₂₁ σ₃₁ σ₃₂
@[simp] lemma trans_refl : e.trans (refl R₂ E₂) = e := ext $ λ x, rfl
@[simp] lemma refl_trans : (refl R E).trans e = e := ext $ λ x, rfl
@[simp] lemma self_trans_symm : e.trans e.symm = refl R E := ext e.symm_apply_apply
@[simp] lemma symm_trans_self : e.symm.trans e = refl R₂ E₂ := ext e.apply_symm_apply
@[simp] lemma symm_comp_self : e.symm ∘ e = id := funext e.symm_apply_apply
@[simp] lemma self_comp_symm : e ∘ e.symm = id := e.symm.symm_comp_self
include σ₁₃ σ₂₁ σ₃₂ σ₃₁
@[simp] lemma symm_trans (e₁ : E ≃ₛₗᵢ[σ₁₂] E₂) (e₂ : E₂ ≃ₛₗᵢ[σ₂₃] E₃) :
(e₁.trans e₂).symm = e₂.symm.trans e₁.symm :=
rfl
lemma coe_symm_trans (e₁ : E ≃ₛₗᵢ[σ₁₂] E₂) (e₂ : E₂ ≃ₛₗᵢ[σ₂₃] E₃) :
⇑(e₁.trans e₂).symm = e₁.symm ∘ e₂.symm :=
rfl
include σ₁₄ σ₄₁ σ₄₂ σ₄₃ σ₂₄
lemma trans_assoc (eEE₂ : E ≃ₛₗᵢ[σ₁₂] E₂) (eE₂E₃ : E₂ ≃ₛₗᵢ[σ₂₃] E₃) (eE₃E₄ : E₃ ≃ₛₗᵢ[σ₃₄] E₄) :
eEE₂.trans (eE₂E₃.trans eE₃E₄) = (eEE₂.trans eE₂E₃).trans eE₃E₄ :=
rfl
omit σ₂₁ σ₃₁ σ₄₁ σ₃₂ σ₄₂ σ₄₃ σ₁₃ σ₂₄ σ₁₄
instance : group (E ≃ₗᵢ[R] E) :=
{ mul := λ e₁ e₂, e₂.trans e₁,
one := refl _ _,
inv := symm,
one_mul := trans_refl,
mul_one := refl_trans,
mul_assoc := λ _ _ _, trans_assoc _ _ _,
mul_left_inv := self_trans_symm }
@[simp] lemma coe_one : ⇑(1 : E ≃ₗᵢ[R] E) = id := rfl
@[simp] lemma coe_mul (e e' : E ≃ₗᵢ[R] E) : ⇑(e * e') = e ∘ e' := rfl
@[simp] lemma coe_inv (e : E ≃ₗᵢ[R] E) : ⇑(e⁻¹) = e.symm := rfl
lemma one_def : (1 : E ≃ₗᵢ[R] E) = refl _ _ := rfl
lemma mul_def (e e' : E ≃ₗᵢ[R] E) : (e * e' : E ≃ₗᵢ[R] E) = e'.trans e := rfl
lemma inv_def (e : E ≃ₗᵢ[R] E) : (e⁻¹ : E ≃ₗᵢ[R] E) = e.symm := rfl
/-! Lemmas about mixing the group structure with definitions. Because we have multiple ways to
express `linear_isometry_equiv.refl`, `linear_isometry_equiv.symm`, and
`linear_isometry_equiv.trans`, we want simp lemmas for every combination.
The assumption made here is that if you're using the group structure, you want to preserve it
after simp.
This copies the approach used by the lemmas near `equiv.perm.trans_one`. -/
@[simp] lemma trans_one : e.trans (1 : E₂ ≃ₗᵢ[R₂] E₂) = e := trans_refl _
@[simp] lemma one_trans : (1 : E ≃ₗᵢ[R] E).trans e = e := refl_trans _
@[simp] lemma refl_mul (e : E ≃ₗᵢ[R] E) : (refl _ _) * e = e := trans_refl _
@[simp] lemma mul_refl (e : E ≃ₗᵢ[R] E) : e * (refl _ _) = e := refl_trans _
include σ₂₁
/-- Reinterpret a `linear_isometry_equiv` as a `continuous_linear_equiv`. -/
instance : has_coe_t (E ≃ₛₗᵢ[σ₁₂] E₂) (E ≃SL[σ₁₂] E₂) :=
⟨λ e, ⟨e.to_linear_equiv, e.continuous, e.to_isometric.symm.continuous⟩⟩
instance : has_coe_t (E ≃ₛₗᵢ[σ₁₂] E₂) (E →SL[σ₁₂] E₂) := ⟨λ e, ↑(e : E ≃SL[σ₁₂] E₂)⟩
@[simp] lemma coe_coe : ⇑(e : E ≃SL[σ₁₂] E₂) = e := rfl
@[simp] lemma coe_coe' : ((e : E ≃SL[σ₁₂] E₂) : E →SL[σ₁₂] E₂) = e := rfl
@[simp] lemma coe_coe'' : ⇑(e : E →SL[σ₁₂] E₂) = e := rfl
omit σ₂₁
@[simp] lemma map_zero : e 0 = 0 := e.1.map_zero
@[simp] lemma map_add (x y : E) : e (x + y) = e x + e y := e.1.map_add x y
@[simp] lemma map_sub (x y : E) : e (x - y) = e x - e y := e.1.map_sub x y
@[simp] lemma map_smulₛₗ (c : R) (x : E) : e (c • x) = σ₁₂ c • e x := e.1.map_smulₛₗ c x
@[simp] lemma map_smul [module R E₂] {e : E ≃ₗᵢ[R] E₂} (c : R) (x : E) : e (c • x) = c • e x :=
e.1.map_smul c x
@[simp] lemma nnnorm_map (x : E) : ‖e x‖₊ = ‖x‖₊ := semilinear_isometry_class.nnnorm_map e x
@[simp] lemma dist_map (x y : E) : dist (e x) (e y) = dist x y :=
e.to_linear_isometry.dist_map x y
@[simp] lemma edist_map (x y : E) : edist (e x) (e y) = edist x y :=
e.to_linear_isometry.edist_map x y
protected lemma bijective : bijective e := e.1.bijective
protected lemma injective : injective e := e.1.injective
protected lemma surjective : surjective e := e.1.surjective
@[simp] lemma map_eq_iff {x y : E} : e x = e y ↔ x = y := e.injective.eq_iff
lemma map_ne {x y : E} (h : x ≠ y) : e x ≠ e y := e.injective.ne h
protected lemma lipschitz : lipschitz_with 1 e := e.isometry.lipschitz
protected lemma antilipschitz : antilipschitz_with 1 e := e.isometry.antilipschitz
lemma image_eq_preimage (s : set E) : e '' s = e.symm ⁻¹' s :=
e.to_linear_equiv.image_eq_preimage s
@[simp] lemma ediam_image (s : set E) : emetric.diam (e '' s) = emetric.diam s :=
e.isometry.ediam_image s
@[simp] lemma diam_image (s : set E) : metric.diam (e '' s) = metric.diam s :=
e.isometry.diam_image s
@[simp] lemma preimage_ball (x : E₂) (r : ℝ) :
e ⁻¹' (metric.ball x r) = metric.ball (e.symm x) r :=
e.to_isometric.preimage_ball x r
@[simp] lemma preimage_sphere (x : E₂) (r : ℝ) :
e ⁻¹' (metric.sphere x r) = metric.sphere (e.symm x) r :=
e.to_isometric.preimage_sphere x r
@[simp] lemma preimage_closed_ball (x : E₂) (r : ℝ) :
e ⁻¹' (metric.closed_ball x r) = metric.closed_ball (e.symm x) r :=
e.to_isometric.preimage_closed_ball x r
@[simp] lemma image_ball (x : E) (r : ℝ) :
e '' (metric.ball x r) = metric.ball (e x) r :=
e.to_isometric.image_ball x r
@[simp] lemma image_sphere (x : E) (r : ℝ) :
e '' (metric.sphere x r) = metric.sphere (e x) r :=
e.to_isometric.image_sphere x r
@[simp] lemma image_closed_ball (x : E) (r : ℝ) :
e '' (metric.closed_ball x r) = metric.closed_ball (e x) r :=
e.to_isometric.image_closed_ball x r
variables {α : Type*} [topological_space α]
@[simp] lemma comp_continuous_on_iff {f : α → E} {s : set α} :
continuous_on (e ∘ f) s ↔ continuous_on f s :=
e.isometry.comp_continuous_on_iff
@[simp] lemma comp_continuous_iff {f : α → E} :
continuous (e ∘ f) ↔ continuous f :=
e.isometry.comp_continuous_iff
instance complete_space_map (p : submodule R E) [complete_space p] :
complete_space (p.map (e.to_linear_equiv : E →ₛₗ[σ₁₂] E₂)) :=
e.to_linear_isometry.complete_space_map' p
include σ₂₁
/-- Construct a linear isometry equiv from a surjective linear isometry. -/
noncomputable def of_surjective (f : F →ₛₗᵢ[σ₁₂] E₂)
(hfr : function.surjective f) :
F ≃ₛₗᵢ[σ₁₂] E₂ :=
{ norm_map' := f.norm_map,
.. linear_equiv.of_bijective f.to_linear_map ⟨f.injective, hfr⟩ }
@[simp] lemma coe_of_surjective (f : F →ₛₗᵢ[σ₁₂] E₂) (hfr : function.surjective f) :
⇑(linear_isometry_equiv.of_surjective f hfr) = f :=
by { ext, refl }
/-- If a linear isometry has an inverse, it is a linear isometric equivalence. -/
def of_linear_isometry (f : E →ₛₗᵢ[σ₁₂] E₂) (g : E₂ →ₛₗ[σ₂₁] E)
(h₁ : f.to_linear_map.comp g = linear_map.id) (h₂ : g.comp f.to_linear_map = linear_map.id) :
E ≃ₛₗᵢ[σ₁₂] E₂ :=
{ norm_map' := λ x, f.norm_map x,
.. linear_equiv.of_linear f.to_linear_map g h₁ h₂ }
@[simp] lemma coe_of_linear_isometry (f : E →ₛₗᵢ[σ₁₂] E₂) (g : E₂ →ₛₗ[σ₂₁] E)
(h₁ : f.to_linear_map.comp g = linear_map.id) (h₂ : g.comp f.to_linear_map = linear_map.id) :
(of_linear_isometry f g h₁ h₂ : E → E₂) = (f : E → E₂) :=
rfl
@[simp] lemma coe_of_linear_isometry_symm (f : E →ₛₗᵢ[σ₁₂] E₂)
(g : E₂ →ₛₗ[σ₂₁] E) (h₁ : f.to_linear_map.comp g = linear_map.id)
(h₂ : g.comp f.to_linear_map = linear_map.id) :
((of_linear_isometry f g h₁ h₂).symm : E₂ → E) = (g : E₂ → E) :=
rfl
omit σ₂₁
variables (R)
/-- The negation operation on a normed space `E`, considered as a linear isometry equivalence. -/
def neg : E ≃ₗᵢ[R] E :=
{ norm_map' := norm_neg,
.. linear_equiv.neg R }
variables {R}
@[simp] lemma coe_neg : (neg R : E → E) = λ x, -x := rfl
@[simp] lemma symm_neg : (neg R : E ≃ₗᵢ[R] E).symm = neg R := rfl
variables (R E E₂ E₃)
/-- The natural equivalence `(E × E₂) × E₃ ≃ E × (E₂ × E₃)` is a linear isometry. -/
def prod_assoc [module R E₂] [module R E₃] : (E × E₂) × E₃ ≃ₗᵢ[R] E × E₂ × E₃ :=
{ to_fun := equiv.prod_assoc E E₂ E₃,
inv_fun := (equiv.prod_assoc E E₂ E₃).symm,
map_add' := by simp,
map_smul' := by simp,
norm_map' :=
begin
rintros ⟨⟨e, f⟩, g⟩,
simp only [linear_equiv.coe_mk, equiv.prod_assoc_apply, prod.norm_def, max_assoc],
end,
.. equiv.prod_assoc E E₂ E₃, }
@[simp] lemma coe_prod_assoc [module R E₂] [module R E₃] :
(prod_assoc R E E₂ E₃ : (E × E₂) × E₃ → E × E₂ × E₃) = equiv.prod_assoc E E₂ E₃ :=
rfl
@[simp] lemma coe_prod_assoc_symm [module R E₂] [module R E₃] :
((prod_assoc R E E₂ E₃).symm : E × E₂ × E₃ → (E × E₂) × E₃) = (equiv.prod_assoc E E₂ E₃).symm :=
rfl
/-- If `p` is a submodule that is equal to `⊤`, then `linear_isometry_equiv.of_top p hp` is the
"identity" equivalence between `p` and `E`. -/
@[simps to_linear_equiv apply symm_apply_coe]
def of_top {R : Type*} [ring R] [module R E] (p : submodule R E) (hp : p = ⊤) :
p ≃ₗᵢ[R] E :=
{ to_linear_equiv := linear_equiv.of_top p hp, .. p.subtypeₗᵢ }
variables {R E E₂ E₃} {R' : Type*} [ring R'] [module R' E] (p q : submodule R' E)
/-- `linear_equiv.of_eq` as a `linear_isometry_equiv`. -/
def of_eq (hpq : p = q) :
p ≃ₗᵢ[R'] q :=
{ norm_map' := λ x, rfl,
..linear_equiv.of_eq p q hpq }
variables {p q}
@[simp] lemma coe_of_eq_apply (h : p = q) (x : p) : (of_eq p q h x : E) = x := rfl
@[simp] lemma of_eq_symm (h : p = q) : (of_eq p q h).symm = of_eq q p h.symm := rfl
@[simp] lemma of_eq_rfl : of_eq p p rfl = linear_isometry_equiv.refl R' p := by ext; refl
end linear_isometry_equiv
/-- Two linear isometries are equal if they are equal on basis vectors. -/
lemma basis.ext_linear_isometry {ι : Type*} (b : basis ι R E) {f₁ f₂ : E →ₛₗᵢ[σ₁₂] E₂}
(h : ∀ i, f₁ (b i) = f₂ (b i)) : f₁ = f₂ :=
linear_isometry.to_linear_map_injective $ b.ext h
include σ₂₁
/-- Two linear isometric equivalences are equal if they are equal on basis vectors. -/
lemma basis.ext_linear_isometry_equiv {ι : Type*} (b : basis ι R E) {f₁ f₂ : E ≃ₛₗᵢ[σ₁₂] E₂}
(h : ∀ i, f₁ (b i) = f₂ (b i)) : f₁ = f₂ :=
linear_isometry_equiv.to_linear_equiv_injective $ b.ext' h
omit σ₂₁
/-- Reinterpret a `linear_isometry` as a `linear_isometry_equiv` to the range. -/
@[simps to_linear_equiv apply_coe]
noncomputable def linear_isometry.equiv_range {R S : Type*} [semiring R] [ring S] [module S E]
[module R F] {σ₁₂ : R →+* S} {σ₂₁ : S →+* R} [ring_hom_inv_pair σ₁₂ σ₂₁]
[ring_hom_inv_pair σ₂₁ σ₁₂] (f : F →ₛₗᵢ[σ₁₂] E) :
F ≃ₛₗᵢ[σ₁₂] f.to_linear_map.range :=
{ to_linear_equiv := linear_equiv.of_injective f.to_linear_map f.injective, .. f }
|
319273c5edf6e2fab82c1f009bda594eebf92aba | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /12_Axioms.org.13.lean | 3f8e76dc6db95e109a2a8e4dedb1ff30f8ae34d6 | [] | no_license | cjmazey/lean-tutorial | ba559a49f82aa6c5848b9bf17b7389bf7f4ba645 | 381f61c9fcac56d01d959ae0fa6e376f2c4e3b34 | refs/heads/master | 1,610,286,098,832 | 1,447,124,923,000 | 1,447,124,923,000 | 43,082,433 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,032 | lean | import standard
import data.prod
open prod prod.ops quot
private definition eqv {A : Type} (p₁ p₂ : A × A) : Prop :=
(p₁.1 = p₂.1 ∧ p₁.2 = p₂.2) ∨ (p₁.1 = p₂.2 ∧ p₁.2 = p₂.1)
infix `~` := eqv
open eq or
local notation `⟨` H₁ `,` H₂ `⟩` := and.intro H₁ H₂
private theorem eqv.refl {A : Type} : ∀ p : A × A, p ~ p :=
take p, inl ⟨rfl, rfl⟩
private theorem eqv.symm {A : Type} : ∀ p₁ p₂ : A × A, p₁ ~ p₂ → p₂ ~ p₁
| (a₁, a₂) (b₁, b₂) (inl ⟨a₁b₁, a₂b₂⟩) := inl ⟨symm a₁b₁, symm a₂b₂⟩
| (a₁, a₂) (b₁, b₂) (inr ⟨a₁b₂, a₂b₁⟩) := inr ⟨symm a₂b₁, symm a₁b₂⟩
private theorem eqv.trans {A : Type} : ∀ p₁ p₂ p₃ : A × A, p₁ ~ p₂ → p₂ ~ p₃ → p₁ ~ p₃
| (a₁, a₂) (b₁, b₂) (c₁, c₂) (inl ⟨a₁b₁, a₂b₂⟩) (inl ⟨b₁c₁, b₂c₂⟩) :=
inl ⟨trans a₁b₁ b₁c₁, trans a₂b₂ b₂c₂⟩
| (a₁, a₂) (b₁, b₂) (c₁, c₂) (inl ⟨a₁b₁, a₂b₂⟩) (inr ⟨b₁c₂, b₂c₁⟩) :=
inr ⟨trans a₁b₁ b₁c₂, trans a₂b₂ b₂c₁⟩
| (a₁, a₂) (b₁, b₂) (c₁, c₂) (inr ⟨a₁b₂, a₂b₁⟩) (inl ⟨b₁c₁, b₂c₂⟩) :=
inr ⟨trans a₁b₂ b₂c₂, trans a₂b₁ b₁c₁⟩
| (a₁, a₂) (b₁, b₂) (c₁, c₂) (inr ⟨a₁b₂, a₂b₁⟩) (inr ⟨b₁c₂, b₂c₁⟩) :=
inl ⟨trans a₁b₂ b₂c₁, trans a₂b₁ b₁c₂⟩
private theorem is_equivalence (A : Type) : equivalence (@eqv A) :=
mk_equivalence (@eqv A) (@eqv.refl A) (@eqv.symm A) (@eqv.trans A)
definition uprod.setoid [instance] (A : Type) : setoid (A × A) :=
setoid.mk (@eqv A) (is_equivalence A)
definition uprod (A : Type) : Type :=
quot (uprod.setoid A)
namespace uprod
definition mk {A : Type} (a₁ a₂ : A) : uprod A :=
⟦(a₁, a₂)⟧
notation `{` a₁ `,` a₂ `}` := mk a₁ a₂
-- BEGIN
theorem mk_eq_mk {A : Type} (a₁ a₂ : A) : {a₁, a₂} = {a₂, a₁} :=
quot.sound (inr ⟨rfl, rfl⟩)
-- END
end uprod
|
6630bae44d8a55ec04053aebcca33c4e3fe90a36 | de91c42b87530c3bdcc2b138ef1a3c3d9bee0d41 | /expressions/bool_expr.lean | 4a2a72f13bd927215498b4c235df0c2ee68a46c3 | [] | no_license | kevinsullivan/lang | d3e526ba363dc1ddf5ff1c2f36607d7f891806a7 | e9d869bff94fb13ad9262222a6f3c4aafba82d5e | refs/heads/master | 1,687,840,064,795 | 1,628,047,969,000 | 1,628,047,969,000 | 282,210,749 | 0 | 1 | null | 1,608,153,830,000 | 1,595,592,637,000 | Lean | UTF-8 | Lean | false | false | 1,496 | lean | import .scalar_expr
import .time_expr
namespace lang.bool_expr
open lang.time
structure bool_var extends var
inductive bool_expr
| lit (b : bool)
| btrue
| bfalse
| band
| bor
| bnot
| scalar_lt_scalar (s1 : scalar_expr) (s2 : scalar_expr)
| duration_lt_duration {tf : time_frame_expr} {ts : time_space_expr tf}
(d1 : duration_expr ts) (d2 : duration_expr ts) : bool_expr
abbreviation bool_env := bool_var → bool
abbreviation bool_eval :=
bool_env → bool_expr → bool
def default_bool_env
: bool_env :=
λv, tt
def default_bool_eval
: bool_eval :=
λenv_, λexpr_, tt
def static_bool_eval
: bool_eval
| env_ (bool_expr.lit s) := s
| env_ (bool_expr.duration_lt_duration d1 d2) := d1.value.coord < d2.value.coord
| env_ _ := tt
--| duration_lt_duration {tf : time_frame_expr} {ts : time_space_expr tf}
-- (d1 : duration_expr ts) (d2 : duration_expr ts) : bool_expr
def bool_expr.value
(expr_ : bool_expr) : bool :=
static_bool_eval default_bool_env expr_
notation `|`slit`|` := bool_expr.lit slit
notation s1<s2 := bool_expr.scalar_lt_scalar s1 s2
notation d1<d2 := bool_expr.duration_lt_duration d1 d2
inductive bool_sem : ∀ b : bool_expr, Type 1
| bool_eval_true (b : bool_expr) (is_true : b.value = tt) : bool_sem b
| bool_eval_false (b : bool_expr) (is_false : b.value = ff) : bool_sem b
meta def check_bool_true : ∀b : bool_expr, tactic (bool_sem b)
| b := tactic.fail "wrong prop"
--| _ _ := tactic.fail "bad prop"
end lang.bool_expr |
abf21e52b6ad0200acf467e723839f318d9a6f8d | 4950bf76e5ae40ba9f8491647d0b6f228ddce173 | /src/category_theory/sites/canonical.lean | d0ac499eb5bd4727c918778a6a67010628fc297d | [
"Apache-2.0"
] | permissive | ntzwq/mathlib | ca50b21079b0a7c6781c34b62199a396dd00cee2 | 36eec1a98f22df82eaccd354a758ef8576af2a7f | refs/heads/master | 1,675,193,391,478 | 1,607,822,996,000 | 1,607,822,996,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,660 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import category_theory.sites.sheaf
/-!
# The canonical topology on a category
We define the finest (largest) Grothendieck topology for which a given presheaf `P` is a sheaf.
This is well defined since if `P` is a sheaf for a topology `J`, then it is a sheaf for any
coarser (smaller) topology. Nonetheless we define the topology explicitly by specifying its sieves:
A sieve `S` on `X` is covering for `finest_topology_single P` iff
for any `f : Y ⟶ X`, `P` satisfies the sheaf axiom for `S.pullback f`.
Showing that this is a genuine Grothendieck topology (namely that it satisfies the transitivity
axiom) forms the bulk of this file.
This generalises to a set of presheaves, giving the topology `finest_topology Ps` which is the
finest topology for which every presheaf in `Ps` is a sheaf.
Using `Ps` as the set of representable presheaves defines the `canonical_topology`: the finest
topology for which every representable is a sheaf.
A Grothendieck topology is called `subcanonical` if it is smaller than the canonical topology,
equivalently it is subcanonical iff every representable presheaf is a sheaf.
## References
* https://ncatlab.org/nlab/show/canonical+topology
* https://ncatlab.org/nlab/show/subcanonical+coverage
* https://stacks.math.columbia.edu/tag/00Z9
* https://math.stackexchange.com/a/358709/
-/
universes v u
namespace category_theory
open category_theory category limits sieve classical
variables {C : Type u} [category.{v} C]
namespace sheaf
variables {P : Cᵒᵖ ⥤ Type v}
variables {X Y : C} {S : sieve X} {R : presieve X}
variables (J J₂ : grothendieck_topology C)
/--
To show `P` is a sheaf for the binding of `U` with `B`, it suffices to show that `P` is a sheaf for
`U`, that `P` is a sheaf for each sieve in `B`, and that it is separated for any pullback of any
sieve in `B`.
This is mostly an auxiliary lemma to show `is_sheaf_for_trans`.
Adapted from [Elephant], Lemma C2.1.7(i) with suggestions as mentioned in
https://math.stackexchange.com/a/358709/
-/
lemma is_sheaf_for_bind (P : Cᵒᵖ ⥤ Type v) (U : sieve X)
(B : Π ⦃Y⦄ ⦃f : Y ⟶ X⦄, U f → sieve Y)
(hU : presieve.is_sheaf_for P U)
(hB : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄ (hf : U f), presieve.is_sheaf_for P (B hf))
(hB' : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄ (h : U f) ⦃Z⦄ (g : Z ⟶ Y),
presieve.is_separated_for P ((B h).pullback g)) :
presieve.is_sheaf_for P (sieve.bind U B) :=
begin
intros s hs,
let y : Π ⦃Y⦄ ⦃f : Y ⟶ X⦄ (hf : U f), presieve.family_of_elements P (B hf) :=
λ Y f hf Z g hg, s _ (presieve.bind_comp _ _ hg),
have hy : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄ (hf : U f), (y hf).compatible,
{ intros Y f H Y₁ Y₂ Z g₁ g₂ f₁ f₂ hf₁ hf₂ comm,
apply hs,
apply reassoc_of comm },
let t : presieve.family_of_elements P U := λ Y f hf, (hB hf).amalgamate (y hf) (hy hf),
have ht : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄ (hf : U f), (y hf).is_amalgamation (t f hf) :=
λ Y f hf, (hB hf).is_amalgamation _,
have hT : t.compatible,
{ rw presieve.compatible_iff_sieve_compatible,
intros Z W f h hf,
apply (hB (U.downward_closed hf h)).is_separated_for.ext,
intros Y l hl,
apply (hB' hf (l ≫ h)).ext,
intros M m hm,
have : bind U B (m ≫ l ≫ h ≫ f),
{ have : bind U B _ := presieve.bind_comp f hf hm,
simpa using this },
transitivity s (m ≫ l ≫ h ≫ f) this,
{ have := ht (U.downward_closed hf h) _ ((B _).downward_closed hl m),
rw [op_comp, functor_to_types.map_comp_apply] at this,
rw this,
change s _ _ = s _ _,
simp },
{ have : s _ _ = _ := (ht hf _ hm).symm,
simp only [assoc] at this,
rw this,
simp } },
refine ⟨hU.amalgamate t hT, _, _⟩,
{ rintro Z _ ⟨Y, f, g, hg, hf, rfl⟩,
rw [op_comp, functor_to_types.map_comp_apply, presieve.is_sheaf_for.valid_glue _ _ _ hg],
apply ht hg _ hf },
{ intros y hy,
apply hU.is_separated_for.ext,
intros Y f hf,
apply (hB hf).is_separated_for.ext,
intros Z g hg,
rw [←functor_to_types.map_comp_apply, ←op_comp, hy _ (presieve.bind_comp _ _ hg),
hU.valid_glue _ _ hf, ht hf _ hg] }
end
/--
Given two sieves `R` and `S`, to show that `P` is a sheaf for `S`, we can show:
* `P` is a sheaf for `R`
* `P` is a sheaf for the pullback of `S` along any arrow in `R`
* `P` is separated for the pullback of `R` along any arrow in `S`.
This is mostly an auxiliary lemma to construct `finest_topology`.
Adapted from [Elephant], Lemma C2.1.7(ii) with suggestions as mentioned in
https://math.stackexchange.com/a/358709
-/
lemma is_sheaf_for_trans (P : Cᵒᵖ ⥤ Type v) (R S : sieve X)
(hR : presieve.is_sheaf_for P R)
(hR' : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄ (hf : S f), presieve.is_separated_for P (R.pullback f))
(hS : Π ⦃Y⦄ ⦃f : Y ⟶ X⦄ (hf : R f), presieve.is_sheaf_for P (S.pullback f)) :
presieve.is_sheaf_for P S :=
begin
have : (bind R (λ Y f hf, S.pullback f) : presieve X) ≤ S,
{ rintros Z f ⟨W, f, g, hg, (hf : S _), rfl⟩,
apply hf },
apply presieve.is_sheaf_for_subsieve_aux P this,
apply is_sheaf_for_bind _ _ _ hR hS,
{ intros Y f hf Z g,
dsimp,
rw ← pullback_comp,
apply (hS (R.downward_closed hf _)).is_separated_for },
{ intros Y f hf,
have : (sieve.pullback f (bind R (λ T (k : T ⟶ X) (hf : R k), pullback k S))) = R.pullback f,
{ ext Z g,
split,
{ rintro ⟨W, k, l, hl, _, comm⟩,
rw [pullback_apply, ← comm],
simp [hl] },
{ intro a,
refine ⟨Z, 𝟙 Z, _, a, _⟩,
simp [hf] } },
rw this,
apply hR' hf },
end
/--
Construct the finest (largest) Grothendieck topology for which the given presheaf is a sheaf.
This is a special case of https://stacks.math.columbia.edu/tag/00Z9, but following a different
proof (see the comments there).
-/
def finest_topology_single (P : Cᵒᵖ ⥤ Type v) : grothendieck_topology C :=
{ sieves := λ X S, ∀ Y (f : Y ⟶ X), presieve.is_sheaf_for P (S.pullback f),
top_mem' := λ X Y f,
begin
rw sieve.pullback_top,
exact presieve.is_sheaf_for_top_sieve P,
end,
pullback_stable' := λ X Y S f hS Z g,
begin
rw ← pullback_comp,
apply hS,
end,
transitive' := λ X S hS R hR Z g,
begin
-- This is the hard part of the construction, showing that the given set of sieves satisfies
-- the transitivity axiom.
refine is_sheaf_for_trans P (pullback g S) _ (hS Z g) _ _,
{ intros Y f hf,
rw ← pullback_comp,
apply (hS _ _).is_separated_for },
{ intros Y f hf,
have := hR hf _ (𝟙 _),
rw [pullback_id, pullback_comp] at this,
apply this },
end }
/--
Construct the finest (largest) Grothendieck topology for which all the given presheaves are sheaves.
This is equal to the construction of https://stacks.math.columbia.edu/tag/00Z9.
-/
def finest_topology (Ps : set (Cᵒᵖ ⥤ Type v)) : grothendieck_topology C :=
Inf (finest_topology_single '' Ps)
/-- Check that if `P ∈ Ps`, then `P` is indeed a sheaf for the finest topology on `Ps`. -/
lemma sheaf_for_finest_topology (Ps : set (Cᵒᵖ ⥤ Type v)) (h : P ∈ Ps) :
presieve.is_sheaf (finest_topology Ps) P :=
λ X S hS, by simpa using hS _ ⟨⟨_, _, ⟨_, h, rfl⟩, rfl⟩, rfl⟩ _ (𝟙 _)
/--
Check that if each `P ∈ Ps` is a sheaf for `J`, then `J` is a subtopology of `finest_topology Ps`.
-/
lemma le_finest_topology (Ps : set (Cᵒᵖ ⥤ Type v)) (J : grothendieck_topology C)
(hJ : ∀ P ∈ Ps, presieve.is_sheaf J P) : J ≤ finest_topology Ps :=
begin
rintro X S hS _ ⟨⟨_, _, ⟨P, hP, rfl⟩, rfl⟩, rfl⟩,
intros Y f, -- this can't be combined with the previous because the `subst` is applied at the end
exact hJ P hP (S.pullback f) (J.pullback_stable f hS),
end
/--
The `canonical_topology` on a category is the finest (largest) topology for which every
representable presheaf is a sheaf.
See https://stacks.math.columbia.edu/tag/00ZA
-/
def canonical_topology (C : Type u) [category.{v} C] : grothendieck_topology C :=
finest_topology (set.range yoneda.obj)
/-- `yoneda.obj X` is a sheaf for the canonical topology. -/
lemma is_sheaf_yoneda_obj (X : C) : presieve.is_sheaf (canonical_topology C) (yoneda.obj X) :=
λ Y S hS, sheaf_for_finest_topology _ (set.mem_range_self _) _ hS
/-- A representable functor is a sheaf for the canonical topology. -/
lemma is_sheaf_of_representable (P : Cᵒᵖ ⥤ Type v) [representable P] :
presieve.is_sheaf (canonical_topology C) P :=
presieve.is_sheaf_iso (canonical_topology C) representable.w (is_sheaf_yoneda_obj _)
/--
A subcanonical topology is a topology which is smaller than the canonical topology.
Equivalently, a topology is subcanonical iff every representable is a sheaf.
-/
def subcanonical (J : grothendieck_topology C) : Prop :=
J ≤ canonical_topology C
namespace subcanonical
/-- If every functor `yoneda.obj X` is a `J`-sheaf, then `J` is subcanonical. -/
lemma of_yoneda_is_sheaf (J : grothendieck_topology C)
(h : ∀ X, presieve.is_sheaf J (yoneda.obj X)) :
subcanonical J :=
le_finest_topology _ _ (by { rintro P ⟨X, rfl⟩, apply h })
/-- If `J` is subcanonical, then any representable is a `J`-sheaf. -/
lemma is_sheaf_of_representable {J : grothendieck_topology C} (hJ : subcanonical J)
(P : Cᵒᵖ ⥤ Type v) [representable P] :
presieve.is_sheaf J P :=
presieve.is_sheaf_for_coarser_topology _ hJ (is_sheaf_of_representable P)
end subcanonical
end sheaf
end category_theory
|
64ec464e002dc851c491bf2cab6bb06ed19e39be | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/analysis/hofer.lean | d37b8fe886401347f397c3861b963e0fbdb149dd | [
"Apache-2.0"
] | permissive | stjordanis/mathlib | 51e286d19140e3788ef2c470bc7b953e4991f0c9 | 2568d41bca08f5d6bf39d915434c8447e21f42ee | refs/heads/master | 1,631,748,053,501 | 1,627,938,886,000 | 1,627,938,886,000 | 228,728,358 | 0 | 0 | Apache-2.0 | 1,576,630,588,000 | 1,576,630,587,000 | null | UTF-8 | Lean | false | false | 4,597 | lean | /-
Copyright (c) 2020 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot
-/
import analysis.specific_limits
/-!
# Hofer's lemma
This is an elementary lemma about complete metric spaces. It is motivated by an
application to the bubbling-off analysis for holomorphic curves in symplectic topology.
We are *very* far away from having these applications, but the proof here is a nice
example of a proof needing to construct a sequence by induction in the middle of the proof.
## References:
* H. Hofer and C. Viterbo, *The Weinstein conjecture in the presence of holomorphic spheres*
-/
open_locale classical topological_space big_operators
open filter finset
local notation `d` := dist
lemma hofer {X: Type*} [metric_space X] [complete_space X]
(x : X) (ε : ℝ) (ε_pos : 0 < ε)
{ϕ : X → ℝ} (cont : continuous ϕ) (nonneg : ∀ y, 0 ≤ ϕ y) :
∃ (ε' > 0) (x' : X), ε' ≤ ε ∧
d x' x ≤ 2*ε ∧
ε * ϕ(x) ≤ ε' * ϕ x' ∧
∀ y, d x' y ≤ ε' → ϕ y ≤ 2*ϕ x' :=
begin
by_contradiction H,
have reformulation : ∀ x' (k : ℕ), ε * ϕ x ≤ ε / 2 ^ k * ϕ x' ↔ 2^k * ϕ x ≤ ϕ x',
{ intros x' k,
rw [div_mul_eq_mul_div, le_div_iff, mul_assoc, mul_le_mul_left ε_pos, mul_comm],
exact pow_pos (by norm_num) k, },
-- Now let's specialize to `ε/2^k`
replace H : ∀ k : ℕ, ∀ x', d x' x ≤ 2 * ε ∧ 2^k * ϕ x ≤ ϕ x' →
∃ y, d x' y ≤ ε/2^k ∧ 2 * ϕ x' < ϕ y,
{ intros k x',
push_neg at H,
simpa [reformulation] using
H (ε/2^k) (by simp [ε_pos, zero_lt_two]) x' (by simp [ε_pos, zero_lt_two, one_le_two]) },
clear reformulation,
haveI : nonempty X := ⟨x⟩,
choose! F hF using H, -- Use the axiom of choice
-- Now define u by induction starting at x, with u_{n+1} = F(n, u_n)
let u : ℕ → X := λ n, nat.rec_on n x F,
have hu0 : u 0 = x := rfl,
-- The properties of F translate to properties of u
have hu :
∀ n,
d (u n) x ≤ 2 * ε ∧ 2^n * ϕ x ≤ ϕ (u n) →
d (u n) (u $ n + 1) ≤ ε / 2 ^ n ∧ 2 * ϕ (u n) < ϕ (u $ n + 1),
{ intro n,
exact hF n (u n) },
clear hF,
-- Key properties of u, to be proven by induction
have key : ∀ n, d (u n) (u (n + 1)) ≤ ε / 2 ^ n ∧ 2 * ϕ (u n) < ϕ (u (n + 1)),
{ intro n,
induction n using nat.case_strong_induction_on with n IH,
{ specialize hu 0,
simpa [hu0, mul_nonneg_iff, zero_le_one, ε_pos.le, le_refl] using hu },
have A : d (u (n+1)) x ≤ 2 * ε,
{ rw [dist_comm],
let r := range (n+1), -- range (n+1) = {0, ..., n}
calc
d (u 0) (u (n + 1))
≤ ∑ i in r, d (u i) (u $ i+1) : dist_le_range_sum_dist u (n + 1)
... ≤ ∑ i in r, ε/2^i : sum_le_sum (λ i i_in, (IH i $ nat.lt_succ_iff.mp $
finset.mem_range.mp i_in).1)
... = ∑ i in r, (1/2)^i*ε : by { congr' with i, field_simp }
... = (∑ i in r, (1/2)^i)*ε : finset.sum_mul.symm
... ≤ 2*ε : mul_le_mul_of_nonneg_right (sum_geometric_two_le _)
(le_of_lt ε_pos), },
have B : 2^(n+1) * ϕ x ≤ ϕ (u (n + 1)),
{ refine @geom_le (ϕ ∘ u) _ zero_le_two (n + 1) (λ m hm, _),
exact (IH _ $ nat.lt_add_one_iff.1 hm).2.le },
exact hu (n+1) ⟨A, B⟩, },
cases forall_and_distrib.mp key with key₁ key₂,
clear hu key,
-- Hence u is Cauchy
have cauchy_u : cauchy_seq u,
{ refine cauchy_seq_of_le_geometric _ ε one_half_lt_one (λ n, _),
simpa only [one_div, inv_pow'] using key₁ n },
-- So u converges to some y
obtain ⟨y, limy⟩ : ∃ y, tendsto u at_top (𝓝 y),
from complete_space.complete cauchy_u,
-- And ϕ ∘ u goes to +∞
have lim_top : tendsto (ϕ ∘ u) at_top at_top,
{ let v := λ n, (ϕ ∘ u) (n+1),
suffices : tendsto v at_top at_top,
by rwa tendsto_add_at_top_iff_nat at this,
have hv₀ : 0 < v 0,
{ have : 0 ≤ ϕ (u 0) := nonneg x,
calc 0 ≤ 2 * ϕ (u 0) : by linarith
... < ϕ (u (0 + 1)) : key₂ 0 },
apply tendsto_at_top_of_geom_le hv₀ one_lt_two,
exact λ n, (key₂ (n+1)).le },
-- But ϕ ∘ u also needs to go to ϕ(y)
have lim : tendsto (ϕ ∘ u) at_top (𝓝 (ϕ y)),
from tendsto.comp cont.continuous_at limy,
-- So we have our contradiction!
exact not_tendsto_at_top_of_tendsto_nhds lim lim_top,
end
|
81719a3cf30f3de35bf33f7c5d66e465ac732518 | 618003631150032a5676f229d13a079ac875ff77 | /src/algebra/homology/homology.lean | 9491107064e333d30d1964a5e8693495fced3183 | [
"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 | 5,111 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Markus Himmel
-/
import algebra.homology.chain_complex
import category_theory.limits.shapes.images
import category_theory.limits.shapes.kernels
/-!
# Cohomology groups for cochain complexes
We setup that part of the theory of cohomology groups which works in
any category with kernels and images.
We define the cohomology groups themselves, and show that they induce maps on kernels.
Under the additional assumption that our category has equalizers and functorial images, we construct
induced morphisms on images and functorial induced morphisms in cohomology.
-/
universes v u
namespace cochain_complex
open category_theory
open category_theory.limits
variables {V : Type u} [𝒱 : category.{v} V] [has_zero_morphisms.{v} V]
include 𝒱
section
variable [has_kernels.{v} V]
/-- The map induced by a chain map between the kernels of the differentials. -/
def kernel_map {C C' : cochain_complex V} (f : C ⟶ C') (i : ℤ) :
kernel (C.d i) ⟶ kernel (C'.d i) :=
kernel.lift _ (kernel.ι _ ≫ f.f i)
begin
rw [category.assoc, ←comm_at f, ←category.assoc, kernel.condition, has_zero_morphisms.zero_comp],
end
@[simp, reassoc]
lemma kernel_map_condition {C C' : cochain_complex V} (f : C ⟶ C') (i : ℤ) :
kernel_map f i ≫ kernel.ι (C'.d i) = kernel.ι (C.d i) ≫ f.f i :=
by simp [kernel_map]
@[simp]
lemma kernel_map_id (C : cochain_complex.{v} V) (i : ℤ) :
kernel_map (𝟙 C) i = 𝟙 _ :=
(cancel_mono (kernel.ι (C.d i))).1 $ by simp
@[simp]
lemma kernel_map_comp {C C' C'' : cochain_complex.{v} V} (f : C ⟶ C')
(g : C' ⟶ C'') (i : ℤ) :
kernel_map (f ≫ g) i = kernel_map f i ≫ kernel_map g i :=
(cancel_mono (kernel.ι (C''.d i))).1 $ by simp
/-- The kernels of the differentials of a cochain complex form a ℤ-graded object. -/
def kernel_functor : cochain_complex.{v} V ⥤ graded_object ℤ V :=
{ obj := λ C i, kernel (C.d i),
map := λ X Y f i, kernel_map f i }
end
section
variables [has_images.{v} V] [has_image_maps.{v} V]
/-- A morphism of cochain complexes induces a morphism on the images of the differentials in every
degree. -/
abbreviation image_map {C C' : cochain_complex.{v} V} (f : C ⟶ C') (i : ℤ) :
image (C.d i) ⟶ image (C'.d i) :=
image.map (arrow.hom_mk' (cochain_complex.comm_at f i).symm)
@[simp]
lemma image_map_ι {C C' : cochain_complex.{v} V} (f : C ⟶ C') (i : ℤ) :
image_map f i ≫ image.ι (C'.d i) = image.ι (C.d i) ≫ f.f (i + 1) :=
image.map_hom_mk'_ι (cochain_complex.comm_at f i).symm
end
/-!
At this point we assume that we have all images, and all equalizers.
We need to assume all equalizers, not just kernels, so that
`factor_thru_image` is an epimorphism.
-/
variables [has_kernels.{v} V] [has_images.{v} V] [has_equalizers.{v} V]
/--
The connecting morphism from the image of `d i` to the kernel of `d (i+1)`.
-/
def image_to_kernel_map (C : cochain_complex V) (i : ℤ) :
image (C.d i) ⟶ kernel (C.d (i+1)) :=
kernel.lift _ (image.ι (C.d i)) $ (cancel_epi (factor_thru_image (C.d i))).1 $ by simp
@[simp, reassoc]
lemma image_to_kernel_map_condition (C : cochain_complex V) (i : ℤ) :
image_to_kernel_map C i ≫ kernel.ι (C.d (i + 1)) = image.ι (C.d i) :=
by simp [image_to_kernel_map]
@[reassoc]
lemma induced_maps_commute [has_image_maps.{v} V] {C C' : cochain_complex.{v} V} (f : C ⟶ C')
(i : ℤ) :
image_to_kernel_map C i ≫ kernel_map f (i + 1) = image_map f i ≫ image_to_kernel_map C' i :=
by { ext, simp }
variables [has_cokernels.{v} V]
/-- The `i`-th cohomology group of the cochain complex `C`. -/
def cohomology (C : cochain_complex V) (i : ℤ) : V :=
cokernel (image_to_kernel_map C (i-1))
variables [has_image_maps.{v} V]
/-- A morphism of cochain complexes induces a morphism in cohomology at every degree. -/
def cohomology_map {C C' : cochain_complex.{v} V} (f : C ⟶ C') (i : ℤ) :
C.cohomology i ⟶ C'.cohomology i :=
cokernel.desc _ (kernel_map f (i - 1 + 1) ≫ cokernel.π _) $ by simp [induced_maps_commute_assoc]
@[simp, reassoc]
lemma cohomology_map_condition {C C' : cochain_complex.{v} V} (f : C ⟶ C') (i : ℤ) :
cokernel.π (image_to_kernel_map C (i - 1)) ≫ cohomology_map f i =
kernel_map f (i - 1 + 1) ≫ cokernel.π _ :=
by simp [cohomology_map]
@[simp]
lemma cohomology_map_id (C : cochain_complex.{v} V) (i : ℤ) :
cohomology_map (𝟙 C) i = 𝟙 (cohomology C i) :=
begin
ext,
simp only [cohomology_map_condition, kernel_map_id, category.id_comp],
erw [category.comp_id]
end
@[simp]
lemma cohomology_map_comp {C C' C'' : cochain_complex.{v} V} (f : C ⟶ C') (g : C' ⟶ C'') (i : ℤ) :
cohomology_map (f ≫ g) i = cohomology_map f i ≫ cohomology_map g i :=
by { ext, simp }
/-- The cohomology functor from cochain complexes to `ℤ` graded objects in `V`. -/
def cohomology_functor : cochain_complex.{v} V ⥤ graded_object ℤ V :=
{ obj := λ C i, cohomology C i,
map := λ C C' f i, cohomology_map f i }
end cochain_complex
|
053539d9158a0d488a444a494e3a5ad72d11cd0e | 86f6f4f8d827a196a32bfc646234b73328aeb306 | /examples/sets_functions_and_relations/unnamed_128.lean | 1ba46a7d0d04352196f767fd2706c0c2230fba72 | [] | no_license | jamescheuk91/mathematics_in_lean | 09f1f87d2b0dce53464ff0cbe592c568ff59cf5e | 4452499264e2975bca2f42565c0925506ba5dda3 | refs/heads/master | 1,679,716,410,967 | 1,613,957,947,000 | 1,613,957,947,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 241 | lean | variable {α : Type*}
variables (s t u : set α)
-- BEGIN
theorem foo (h : s ⊆ t) : s ∩ u ⊆ t ∩ u :=
λ x ⟨xs, xu⟩, ⟨h xs, xu⟩
example (h : s ⊆ t) : s ∩ u ⊆ t ∩ u :=
by exact λ x ⟨xs, xu⟩, ⟨h xs, xu⟩
-- END |
a46f3a8e38902ad36d053b6a40972c547b879c23 | de91c42b87530c3bdcc2b138ef1a3c3d9bee0d41 | /old/assign/math_assign.lean | 9cfb4a35f5103bd2c4382ca7ebf56cdb958a0986 | [] | no_license | kevinsullivan/lang | d3e526ba363dc1ddf5ff1c2f36607d7f891806a7 | e9d869bff94fb13ad9262222a6f3c4aafba82d5e | refs/heads/master | 1,687,840,064,795 | 1,628,047,969,000 | 1,628,047,969,000 | 282,210,749 | 0 | 1 | null | 1,608,153,830,000 | 1,595,592,637,000 | Lean | UTF-8 | Lean | false | false | 708 | lean | import ..eval.math_eval
variables {K : Type*} [field K] [inhabited K] {f : fm K TIME} (sp : spc K f)
open lang.math
def assign_fm : @env.env K _ _ f sp → fm_var → fm_expr K → env.env K
| i v e :=
{
m := {
f := λve, if v.nm=ve.nm then ((lang.math_eval.fm_eval f ) i.m e) else i.m.f v
..i.m
},
..i
}
--space not inferrable from context, so we need a space to assign a space
def assign_spc {K : Type*} [field K] [inhabited K] {f : fm K TIME} (sp : spc K f) : @env.env K _ _ f sp → sp_var f → sp_expr f → env.env K
| i v e :=
{
m := {
sp := λve, if v.nm=ve.nm then ((lang.math_eval.sp_eval sp) i.m e) else i.m.sp v
..i.m
},
..i
}
|
759ce545dd3b6e0284b6f58e2363335f0126dc18 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Elab/InfoTree/Main.lean | 7dc2dc55302c706f587e36ba0bd42aa2abc601d4 | [
"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 | 15,866 | 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.Meta.PPGoal
namespace Lean.Elab.ContextInfo
variable [Monad m] [MonadEnv m] [MonadMCtx m] [MonadOptions m] [MonadResolveName m] [MonadNameGenerator m]
def saveNoFileMap : m ContextInfo := return {
env := (← getEnv)
fileMap := default
mctx := (← getMCtx)
options := (← getOptions)
currNamespace := (← getCurrNamespace)
openDecls := (← getOpenDecls)
ngen := (← getNGen)
}
def save [MonadFileMap m] : m ContextInfo := do
let ctx ← saveNoFileMap
return { ctx with fileMap := (← getFileMap) }
end ContextInfo
def CompletionInfo.stx : CompletionInfo → Syntax
| dot i .. => i.stx
| id stx .. => stx
| dotId stx .. => stx
| fieldId stx .. => stx
| namespaceId stx => stx
| option stx => stx
| endSection stx .. => stx
| tactic stx .. => stx
def CustomInfo.format : CustomInfo → Format
| i => f!"CustomInfo({i.value.typeName})"
instance : ToFormat CustomInfo := ⟨CustomInfo.format⟩
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
/-- Instantiate the holes on the given `tree` with the assignment table.
(analoguous to instantiating the metavariables in an expression) -/
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)
| 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 }
/-
We must execute `x` using the `ngen` stored in `info`. Otherwise, we may create `MVarId`s and `FVarId`s that
have been used in `lctx` and `info.mctx`.
-/
let ((a, _), _) ←
x.toIO { options := info.options, currNamespace := info.currNamespace, openDecls := info.openDecls, fileName := "<InfoTree>", fileMap := default }
{ env := info.env, ngen := info.ngen }
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⟩ -- HACK: might not be a term
private def formatStxRange (ctx : ContextInfo) (stx : Syntax) : Format :=
let pos := stx.getPos?.getD 0
let endPos := stx.getTailPos?.getD pos
f!"{fmtPos pos stx.getHeadInfo}-{fmtPos endPos stx.getTailInfo}"
where fmtPos pos info :=
let pos := format <| ctx.fileMap.toPosition pos
match info with
| .original .. => pos
| .synthetic (canonical := true) .. => f!"{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
let ty : Format ← try
Meta.ppExpr (← Meta.inferType info.expr)
catch _ =>
pure "<failed-to-infer-type>"
return f!"{← Meta.ppExpr info.expr} {if info.isBinder then "(isBinder := true) " else ""}: {ty} @ {formatElabInfo ctx info.toElabInfo}"
def CompletionInfo.format (ctx : ContextInfo) (info : CompletionInfo) : IO Format :=
match info with
| .dot i (expectedType? := expectedType?) .. => return f!"[.] {← i.format ctx} : {expectedType?}"
| .id stx _ _ lctx expectedType? => ctx.runMetaM lctx do return f!"[.] {← ctx.ppSyntax lctx 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 OptionInfo.format (ctx : ContextInfo) (info : OptionInfo) : IO Format := do
return f!"option {info.optionName} @ {formatStxRange ctx info.stx}"
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 UserWidgetInfo.format (info : UserWidgetInfo) : Format :=
f!"UserWidget {info.widgetId}\n{Std.ToFormat.format info.props}"
def FVarAliasInfo.format (info : FVarAliasInfo) : Format :=
f!"FVarAlias {info.userName.eraseMacroScopes}"
def FieldRedeclInfo.format (ctx : ContextInfo) (info : FieldRedeclInfo) : Format :=
f!"FieldRedecl @ {formatStxRange ctx info.stx}"
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
| ofOptionInfo i => i.format ctx
| ofFieldInfo i => i.format ctx
| ofCompletionInfo i => i.format ctx
| ofUserWidgetInfo i => pure <| i.format
| ofCustomInfo i => pure <| Std.ToFormat.format i
| ofFVarAliasInfo i => pure <| i.format
| ofFieldRedeclInfo i => pure <| 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 _ => none
| ofOptionInfo _ => none
| ofFieldInfo _ => none
| ofCompletionInfo _ => none
| ofUserWidgetInfo _ => none
| ofCustomInfo _ => none
| ofFVarAliasInfo _ => none
| ofFieldRedeclInfo _ => 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
| hole id => return .nestD f!"• ?{toString id.name}"
| 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 .nestD f!"• {fmt}"
else
let ctx? := i.updateContext? ctx?
return .nestD f!"• {fmt}{Std.Format.prefixJoin .line (← 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 }
/-- Returns the current array of InfoTrees and resets it to an empty array. -/
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 addConstInfo [MonadEnv m] [MonadError m]
(stx : Syntax) (n : Name) (expectedType? : Option Expr := none) : m Unit := do
pushInfoLeaf <| .ofTermInfo {
elaborator := .anonymous
lctx := .empty
expr := (← mkConstWithLevelParams n)
stx
expectedType?
}
/-- This does the same job as `resolveGlobalConstNoOverload`; resolving an identifier
syntax to a unique fully resolved name or throwing if there are ambiguities.
But also adds this resolved name to the infotree. This means that when you hover
over a name in the sourcefile you will see the fully resolved name in the hover 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
addConstInfo id n expectedType?
return n
/-- Similar to `resolveGlobalConstNoOverloadWithInfo`, except if there are multiple name resolutions then it returns them as a list. -/
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
addConstInfo id n expectedType?
return ns
/-- Similar to `resolveGlobalName`, but it also adds the resolved name to the info tree. -/
def resolveGlobalNameWithInfos [MonadResolveName m] [MonadEnv m] [MonadError m]
(ref : Syntax) (id : Name) : m (List (Name × List String)) := do
let ns ← resolveGlobalName id
if (← getInfoState).enabled then
for (n, _) in ns do
addConstInfo ref n
return ns
/-- Use this to descend a node on the infotree that is being built.
It saves the current list of trees `t₀` and resets it and then runs `x >>= mkInfo`, producing either an `i : Info` or a hole id.
Running `x >>= mkInfo` will modify the trees state and produce a new list of trees `t₁`.
In the `i : Info` case, `t₁` become the children of a node `node i t₁` that is appended to `t₀`.
-/
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 mvarId => treesSaved.push <| InfoTree.hole mvarId
else
x
/-- Saves the current list of trees `t₀`, runs `x` to produce a new tree list `t₁` and
runs `mkInfoTree t₁` to get `n : InfoTree` and then restores the trees to be `t₀ ++ [n]`.-/
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
/-- Run `x` as a new child infotree node with header given by `mkInfo`. -/
@[inline] def withInfoContext [MonadFinally m] (x : m α) (mkInfo : m Info) : m α := do
withInfoTreeContext x (fun trees => do return InfoTree.node (← mkInfo) trees)
/-- Resets the trees state `t₀`, runs `x` to produce a new trees
state `t₁` and sets the state to be `t₀ ++ (InfoTree.context Γ <$> t₁)`
where `Γ` is the context derived from the monad state. -/
def withSaveInfoContext [MonadNameGenerator m] [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
pure <| InfoTree.context (← ContextInfo.save) 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 _ => modifyInfoState fun s =>
if h : s.trees.size > 0 then
have : s.trees.size - 1 < s.trees.size := Nat.sub_lt h (by decide)
{ 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 withEnableInfoTree [Monad m] [MonadInfoTree m] [MonadFinally m] (flag : Bool) (x : m α) : m α := do
let saved := (← getInfoState).enabled
try
enableInfoTree flag
x
finally
enableInfoTree saved
def getInfoTrees [MonadInfoTree m] [Monad m] : m (PersistentArray InfoTree) :=
return (← getInfoState).trees
end Lean.Elab
|
b2002bd3208fdd1dc7e7a179d6f035503ebe7da1 | e0b0b1648286e442507eb62344760d5cd8d13f2d | /stage0/src/Lean/Elab/Term.lean | 2565efcfff2061821b89ecf6f5f179d589706b5f | [
"Apache-2.0"
] | permissive | MULXCODE/lean4 | 743ed389e05e26e09c6a11d24607ad5a697db39b | 4675817a9e89824eca37192364cd47a4027c6437 | refs/heads/master | 1,682,231,879,857 | 1,620,423,501,000 | 1,620,423,501,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 73,665 | 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.ResolveName
import Lean.Util.Sorry
import Lean.Util.ReplaceExpr
import Lean.Structure
import Lean.Meta.ExprDefEq
import Lean.Meta.AppBuilder
import Lean.Meta.SynthInstance
import Lean.Meta.CollectMVars
import Lean.Meta.Coe
import Lean.Meta.Tactic.Util
import Lean.Hygiene
import Lean.Util.RecDepth
import Lean.Elab.Log
import Lean.Elab.Level
import Lean.Elab.Attributes
import Lean.Elab.AutoBound
import Lean.Elab.InfoTree
import Lean.Elab.Open
import Lean.Elab.SetOption
namespace Lean.Elab.Term
/-
Set isDefEq configuration for the elaborator.
Note that we enable all approximations but `quasiPatternApprox`
In Lean3 and Lean 4, we used to use the quasi-pattern approximation during elaboration.
The example:
```
def ex : StateT δ (StateT σ Id) σ :=
monadLift (get : StateT σ Id σ)
```
demonstrates why it produces counterintuitive behavior.
We have the `Monad-lift` application:
```
@monadLift ?m ?n ?c ?α (get : StateT σ id σ) : ?n ?α
```
It produces the following unification problem when we process the expected type:
```
?n ?α =?= StateT δ (StateT σ id) σ
==> (approximate using first-order unification)
?n := StateT δ (StateT σ id)
?α := σ
```
Then, we need to solve:
```
?m ?α =?= StateT σ id σ
==> instantiate metavars
?m σ =?= StateT σ id σ
==> (approximate since it is a quasi-pattern unification constraint)
?m := fun σ => StateT σ id σ
```
Note that the constraint is not a Milner pattern because σ is in
the local context of `?m`. We are ignoring the other possible solutions:
```
?m := fun σ' => StateT σ id σ
?m := fun σ' => StateT σ' id σ
?m := fun σ' => StateT σ id σ'
```
We need the quasi-pattern approximation for elaborating recursor-like expressions (e.g., dependent `match with` expressions).
If we had use first-order unification, then we would have produced
the right answer: `?m := StateT σ id`
Haskell would work on this example since it always uses
first-order unification.
-/
def setElabConfig (cfg : Meta.Config) : Meta.Config :=
{ cfg with foApprox := true, ctxApprox := true, constApprox := false, quasiPatternApprox := false }
structure Context where
fileName : String
fileMap : FileMap
declName? : Option Name := none
macroStack : MacroStack := []
currMacroScope : MacroScope := firstFrontendMacroScope
/- When `mayPostpone == true`, an elaboration function may interrupt its execution by throwing `Exception.postpone`.
The function `elabTerm` catches this exception and creates fresh synthetic metavariable `?m`, stores `?m` in
the list of pending synthetic metavariables, and returns `?m`. -/
mayPostpone : Bool := true
/- When `errToSorry` is set to true, the method `elabTerm` catches
exceptions and converts them into synthetic `sorry`s.
The implementation of choice nodes and overloaded symbols rely on the fact
that when `errToSorry` is set to false for an elaboration function `F`, then
`errToSorry` remains `false` for all elaboration functions invoked by `F`.
That is, it is safe to transition `errToSorry` from `true` to `false`, but
we must not set `errToSorry` to `true` when it is currently set to `false`. -/
errToSorry : Bool := true
/- When `autoBoundImplicit` is set to true, instead of producing
an "unknown identifier" error for unbound variables, we generate an
internal exception. This exception is caught at `elabBinders` and
`elabTypeWithUnboldImplicit`. Both methods add implicit declarations
for the unbound variable and try again. -/
autoBoundImplicit : Bool := false
autoBoundImplicits : Std.PArray Expr := {}
/-- Map from user name to internal unique name -/
sectionVars : NameMap Name := {}
/-- Map from internal name to fvar -/
sectionFVars : NameMap Expr := {}
/-- Enable/disable implicit lambdas feature. -/
implicitLambda : Bool := true
/-- Saved context for postponed terms and tactics to be executed. -/
structure SavedContext where
declName? : Option Name
options : Options
openDecls : List OpenDecl
macroStack : MacroStack
errToSorry : Bool
/-- We use synthetic metavariables as placeholders for pending elaboration steps. -/
inductive SyntheticMVarKind where
-- typeclass instance search
| typeClass
/- Similar to typeClass, but error messages are different.
if `f?` is `some f`, we produce an application type mismatch error message.
Otherwise, if `header?` is `some header`, we generate the error `(header ++ "has type" ++ eType ++ "but it is expected to have type" ++ expectedType)`
Otherwise, we generate the error `("type mismatch" ++ e ++ "has type" ++ eType ++ "but it is expected to have type" ++ expectedType)` -/
| coe (header? : Option String) (eNew : Expr) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr)
-- tactic block execution
| tactic (tacticCode : Syntax) (ctx : SavedContext)
-- `elabTerm` call that threw `Exception.postpone` (input is stored at `SyntheticMVarDecl.ref`)
| postponed (ctx : SavedContext)
instance : ToString SyntheticMVarKind where
toString
| SyntheticMVarKind.typeClass => "typeclass"
| SyntheticMVarKind.coe .. => "coe"
| SyntheticMVarKind.tactic .. => "tactic"
| SyntheticMVarKind.postponed .. => "postponed"
structure SyntheticMVarDecl where
mvarId : MVarId
stx : Syntax
kind : SyntheticMVarKind
inductive MVarErrorKind where
| implicitArg (ctx : Expr)
| hole
| custom (msgData : MessageData)
instance : ToString MVarErrorKind where
toString
| MVarErrorKind.implicitArg ctx => "implicitArg"
| MVarErrorKind.hole => "hole"
| MVarErrorKind.custom msg => "custom"
structure MVarErrorInfo where
mvarId : MVarId
ref : Syntax
kind : MVarErrorKind
structure LetRecToLift where
ref : Syntax
fvarId : FVarId
attrs : Array Attribute
shortDeclName : Name
declName : Name
lctx : LocalContext
localInstances : LocalInstances
type : Expr
val : Expr
mvarId : MVarId
structure State where
levelNames : List Name := []
syntheticMVars : List SyntheticMVarDecl := []
mvarErrorInfos : List MVarErrorInfo := []
messages : MessageLog := {}
letRecsToLift : List LetRecToLift := []
infoState : InfoState := {}
deriving Inhabited
abbrev TermElabM := ReaderT Context $ StateRefT State MetaM
abbrev TermElab := Syntax → Option Expr → TermElabM Expr
open Meta
instance : Inhabited (TermElabM α) where
default := throw arbitrary
structure SavedState where
meta : Meta.SavedState
«elab» : State
deriving Inhabited
protected def saveState : TermElabM SavedState := do
pure { meta := (← Meta.saveState), «elab» := (← get) }
def SavedState.restore (s : SavedState) (restoreInfo : Bool := false) : TermElabM Unit := do
let traceState ← getTraceState -- We never backtrack trace message
let infoState := (← get).infoState -- We also do not backtrack the info nodes when `restoreInfo == false`
s.meta.restore
set s.elab
setTraceState traceState
unless restoreInfo do
modify fun s => { s with infoState := infoState }
instance : MonadBacktrack SavedState TermElabM where
saveState := Term.saveState
restoreState b := b.restore
abbrev TermElabResult (α : Type) := EStateM.Result Exception SavedState α
instance [Inhabited α] : Inhabited (TermElabResult α) where
default := EStateM.Result.ok arbitrary arbitrary
def setMessageLog (messages : MessageLog) : TermElabM Unit :=
modify fun s => { s with messages := messages }
def resetMessageLog : TermElabM Unit :=
setMessageLog {}
def getMessageLog : TermElabM MessageLog :=
return (← get).messages
/--
Execute `x`, save resulting expression and new state.
We remove any `Info` created by `x`.
The info nodes are committed when we execute `applyResult`.
We use `observing` to implement overloaded notation and decls.
We want to save `Info` nodes for the chosen alternative.
-/
@[inline] def observing (x : TermElabM α) : TermElabM (TermElabResult α) := do
let s ← saveState
try
let e ← x
let sNew ← saveState
s.restore (restoreInfo := true)
pure (EStateM.Result.ok e sNew)
catch
| ex@(Exception.error _ _) =>
let sNew ← saveState
s.restore (restoreInfo := true)
pure (EStateM.Result.error ex sNew)
| ex@(Exception.internal id _) =>
if id == postponeExceptionId then
s.restore (restoreInfo := true)
throw ex
/--
Apply the result/exception and state captured with `observing`.
We use this method to implement overloaded notation and symbols. -/
@[inline] def applyResult (result : TermElabResult α) : TermElabM α :=
match result with
| EStateM.Result.ok a r => do r.restore (restoreInfo := true); pure a
| EStateM.Result.error ex r => do r.restore (restoreInfo := true); throw ex
/--
Execute `x`, but keep state modifications only if `x` did not postpone.
This method is useful to implement elaboration functions that cannot decide whether
they need to postpone or not without updating the state. -/
def commitIfDidNotPostpone (x : TermElabM α) : TermElabM α := do
-- We just reuse the implementation of `observing` and `applyResult`.
let r ← observing x
applyResult r
/--
Execute `x` but discard changes performed at `Term.State` and `Meta.State`.
Recall that the environment is at `Core.State`. Thus, any updates to it will
be preserved. This method is useful for performing computations where all
metavariable must be resolved or discarded. -/
def withoutModifyingElabMetaState (x : TermElabM α) : TermElabM α := do
let s ← get
let sMeta ← getThe Meta.State
try
x
finally
set s
set sMeta
def getLevelNames : TermElabM (List Name) :=
return (← get).levelNames
def getFVarLocalDecl! (fvar : Expr) : TermElabM LocalDecl := do
match (← getLCtx).find? fvar.fvarId! with
| some d => pure d
| none => unreachable!
instance : AddErrorMessageContext TermElabM where
add ref msg := do
let ctx ← read
let ref := getBetterRef ref ctx.macroStack
let msg ← addMessageContext msg
let msg ← addMacroStack msg ctx.macroStack
pure (ref, msg)
instance : MonadLog TermElabM where
getRef := getRef
getFileMap := return (← read).fileMap
getFileName := return (← read).fileName
logMessage msg := do
let ctx ← readThe Core.Context
let msg := { msg with data := MessageData.withNamingContext { currNamespace := ctx.currNamespace, openDecls := ctx.openDecls } msg.data };
modify fun s => { s with messages := s.messages.add msg }
protected def getCurrMacroScope : TermElabM MacroScope := do pure (← read).currMacroScope
protected def getMainModule : TermElabM Name := do pure (← getEnv).mainModule
@[inline] protected def withFreshMacroScope (x : TermElabM α) : TermElabM α := do
let fresh ← modifyGetThe Core.State (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 }))
withReader (fun ctx => { ctx with currMacroScope := fresh }) x
instance : MonadQuotation TermElabM where
getCurrMacroScope := Term.getCurrMacroScope
getMainModule := Term.getMainModule
withFreshMacroScope := Term.withFreshMacroScope
instance : MonadInfoTree TermElabM where
getInfoState := return (← get).infoState
modifyInfoState f := modify fun s => { s with infoState := f s.infoState }
unsafe def mkTermElabAttributeUnsafe : IO (KeyedDeclsAttribute TermElab) :=
mkElabAttribute TermElab `Lean.Elab.Term.termElabAttribute `builtinTermElab `termElab `Lean.Parser.Term `Lean.Elab.Term.TermElab "term"
@[implementedBy mkTermElabAttributeUnsafe]
constant mkTermElabAttribute : IO (KeyedDeclsAttribute TermElab)
builtin_initialize termElabAttribute : KeyedDeclsAttribute TermElab ← mkTermElabAttribute
/--
Auxiliary datatatype for presenting a Lean lvalue modifier.
We represent a unelaborated lvalue as a `Syntax` (or `Expr`) and `List LVal`.
Example: `a.foo[i].1` is represented as the `Syntax` `a` and the list
`[LVal.fieldName "foo", LVal.getOp i, LVal.fieldIdx 1]`.
Recall that the notation `a[i]` is not just for accessing arrays in Lean. -/
inductive LVal where
| fieldIdx (ref : Syntax) (i : Nat)
/- Field `suffix?` is for producing better error messages because `x.y` may be a field access or a hierachical/composite name.
`ref` is the syntax object representing the field. `targetStx` is the target object being accessed. -/
| fieldName (ref : Syntax) (name : String) (suffix? : Option Name) (targetStx : Syntax)
| getOp (ref : Syntax) (idx : Syntax)
def LVal.getRef : LVal → Syntax
| LVal.fieldIdx ref _ => ref
| LVal.fieldName ref .. => ref
| LVal.getOp ref _ => ref
def LVal.isFieldName : LVal → Bool
| LVal.fieldName .. => true
| _ => false
instance : ToString LVal where
toString
| LVal.fieldIdx _ i => toString i
| LVal.fieldName _ n .. => n
| LVal.getOp _ idx => "[" ++ toString idx ++ "]"
def getDeclName? : TermElabM (Option Name) := return (← read).declName?
def getLetRecsToLift : TermElabM (List LetRecToLift) := return (← get).letRecsToLift
def isExprMVarAssigned (mvarId : MVarId) : TermElabM Bool := return (← getMCtx).isExprAssigned mvarId
def getMVarDecl (mvarId : MVarId) : TermElabM MetavarDecl := return (← getMCtx).getDecl mvarId
def assignLevelMVar (mvarId : MVarId) (val : Level) : TermElabM Unit := modifyThe Meta.State fun s => { s with mctx := s.mctx.assignLevel mvarId val }
def withDeclName (name : Name) (x : TermElabM α) : TermElabM α :=
withReader (fun ctx => { ctx with declName? := name }) x
def setLevelNames (levelNames : List Name) : TermElabM Unit :=
modify fun s => { s with levelNames := levelNames }
def withLevelNames (levelNames : List Name) (x : TermElabM α) : TermElabM α := do
let levelNamesSaved ← getLevelNames
setLevelNames levelNames
try x finally setLevelNames levelNamesSaved
def withoutErrToSorry (x : TermElabM α) : TermElabM α :=
withReader (fun ctx => { ctx with errToSorry := false }) x
/-- For testing `TermElabM` methods. The #eval command will sign the error. -/
def throwErrorIfErrors : TermElabM Unit := do
if (← get).messages.hasErrors then
throwError "Error(s)"
@[inline] def traceAtCmdPos (cls : Name) (msg : Unit → MessageData) : TermElabM Unit :=
withRef Syntax.missing $ trace cls msg
def ppGoal (mvarId : MVarId) : TermElabM Format :=
Meta.ppGoal mvarId
open Level (LevelElabM)
def liftLevelM (x : LevelElabM α) : TermElabM α := do
let ctx ← read
let ref ← getRef
let mctx ← getMCtx
let ngen ← getNGen
let lvlCtx : Level.Context := { options := (← getOptions), ref := ref, autoBoundImplicit := ctx.autoBoundImplicit }
match (x lvlCtx).run { ngen := ngen, mctx := mctx, levelNames := (← getLevelNames) } with
| EStateM.Result.ok a newS => setMCtx newS.mctx; setNGen newS.ngen; setLevelNames newS.levelNames; pure a
| EStateM.Result.error ex _ => throw ex
def elabLevel (stx : Syntax) : TermElabM Level :=
liftLevelM $ Level.elabLevel stx
/- Elaborate `x` with `stx` on the macro stack -/
@[inline] def withMacroExpansion (beforeStx afterStx : Syntax) (x : TermElabM α) : TermElabM α :=
withMacroExpansionInfo beforeStx afterStx do
withReader (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x
/-
Add the given metavariable to the list of pending synthetic metavariables.
The method `synthesizeSyntheticMVars` is used to process the metavariables on this list. -/
def registerSyntheticMVar (stx : Syntax) (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do
modify fun s => { s with syntheticMVars := { mvarId := mvarId, stx := stx, kind := kind } :: s.syntheticMVars }
def registerSyntheticMVarWithCurrRef (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do
registerSyntheticMVar (← getRef) mvarId kind
def registerMVarErrorHoleInfo (mvarId : MVarId) (ref : Syntax) : TermElabM Unit := do
modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.hole } :: s.mvarErrorInfos }
def registerMVarErrorImplicitArgInfo (mvarId : MVarId) (ref : Syntax) (app : Expr) : TermElabM Unit := do
modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.implicitArg app } :: s.mvarErrorInfos }
def registerMVarErrorCustomInfo (mvarId : MVarId) (ref : Syntax) (msgData : MessageData) : TermElabM Unit := do
modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.custom msgData } :: s.mvarErrorInfos }
def registerCustomErrorIfMVar (e : Expr) (ref : Syntax) (msgData : MessageData) : TermElabM Unit :=
match e.getAppFn with
| Expr.mvar mvarId _ => registerMVarErrorCustomInfo mvarId ref msgData
| _ => pure ()
/-
Auxiliary method for reporting errors of the form "... contains metavariables ...".
This kind of error is thrown, for example, at `Match.lean` where elaboration
cannot continue if there are metavariables in patterns.
We only want to log it if we haven't logged any error so far. -/
def throwMVarError (m : MessageData) : TermElabM α := do
if (← get).messages.hasErrors then
throwAbortTerm
else
throwError m
def MVarErrorInfo.logError (mvarErrorInfo : MVarErrorInfo) (extraMsg? : Option MessageData) : TermElabM Unit := do
match mvarErrorInfo.kind with
| MVarErrorKind.implicitArg app => do
let app ← instantiateMVars app
let msg : MessageData := m!"don't know how to synthesize implicit argument{indentExpr app.setAppPPExplicitForExposingMVars}"
let msg := msg ++ Format.line ++ "context:" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId
logErrorAt mvarErrorInfo.ref (appendExtra msg)
| MVarErrorKind.hole => do
let msg : MessageData := "don't know how to synthesize placeholder"
let msg := msg ++ Format.line ++ "context:" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId
logErrorAt mvarErrorInfo.ref (MessageData.tagged `Elab.synthPlaceholder <| appendExtra msg)
| MVarErrorKind.custom msg =>
logErrorAt mvarErrorInfo.ref (appendExtra msg)
where
appendExtra (msg : MessageData) : MessageData :=
match extraMsg? with
| none => msg
| some extraMsg => msg ++ extraMsg
/--
Try to log errors for the unassigned metavariables `pendingMVarIds`.
Return `true` if there were "unfilled holes", and we should "abort" declaration.
TODO: try to fill "all" holes using synthetic "sorry's"
Remark: We only log the "unfilled holes" as new errors if no error has been logged so far. -/
def logUnassignedUsingErrorInfos (pendingMVarIds : Array MVarId) (extraMsg? : Option MessageData := none) : TermElabM Bool := do
let s ← get
let hasOtherErrors := s.messages.hasErrors
let mut hasNewErrors := false
let mut alreadyVisited : NameSet := {}
for mvarErrorInfo in s.mvarErrorInfos do
let mvarId := mvarErrorInfo.mvarId
unless alreadyVisited.contains mvarId do
alreadyVisited := alreadyVisited.insert mvarId
let foundError ← withMVarContext mvarId do
/- The metavariable `mvarErrorInfo.mvarId` may have been assigned or
delayed assigned to another metavariable that is unassigned. -/
let mvarDeps ← getMVars (mkMVar mvarId)
if mvarDeps.any pendingMVarIds.contains then do
unless hasOtherErrors do
mvarErrorInfo.logError extraMsg?
pure true
else
pure false
if foundError then
hasNewErrors := true
return hasNewErrors
/-- Ensure metavariables registered using `registerMVarErrorInfos` (and used in the given declaration) have been assigned. -/
def ensureNoUnassignedMVars (decl : Declaration) : TermElabM Unit := do
let pendingMVarIds ← getMVarsAtDecl decl
if (← logUnassignedUsingErrorInfos pendingMVarIds) then
throwAbortCommand
/-
Execute `x` without allowing it to postpone elaboration tasks.
That is, `tryPostpone` is a noop. -/
@[inline] def withoutPostponing (x : TermElabM α) : TermElabM α :=
withReader (fun ctx => { ctx with mayPostpone := false }) x
/-- Creates syntax for `(` <ident> `:` <type> `)` -/
def mkExplicitBinder (ident : Syntax) (type : Syntax) : Syntax :=
mkNode ``Lean.Parser.Term.explicitBinder #[mkAtom "(", mkNullNode #[ident], mkNullNode #[mkAtom ":", type], mkNullNode, mkAtom ")"]
/--
Convert unassigned universe level metavariables into parameters.
The new parameter names are of the form `u_i` where `i >= nextParamIdx`.
The method returns the updated expression and new `nextParamIdx`.
Remark: we make sure the generated parameter names do not clash with the universes at `ctx.levelNames`. -/
def levelMVarToParam (e : Expr) (nextParamIdx : Nat := 1) : TermElabM (Expr × Nat) := do
let mctx ← getMCtx
let levelNames ← getLevelNames
let r := mctx.levelMVarToParam (fun n => levelNames.elem n) e `u nextParamIdx
setMCtx r.mctx
pure (r.expr, r.nextParamIdx)
/-- Variant of `levelMVarToParam` where `nextParamIdx` is stored in a state monad. -/
def levelMVarToParam' (e : Expr) : StateRefT Nat TermElabM Expr := do
let nextParamIdx ← get
let (e, nextParamIdx) ← levelMVarToParam e nextParamIdx
set nextParamIdx
pure e
/--
Auxiliary method for creating fresh binder names.
Do not confuse with the method for creating fresh free/meta variable ids. -/
def mkFreshBinderName [Monad m] [MonadQuotation m] : m Name :=
withFreshMacroScope $ MonadQuotation.addMacroScope `x
/--
Auxiliary method for creating a `Syntax.ident` containing
a fresh name. This method is intended for creating fresh binder names.
It is just a thin layer on top of `mkFreshUserName`. -/
def mkFreshIdent [Monad m] [MonadQuotation m] (ref : Syntax) : m Syntax :=
return mkIdentFrom ref (← mkFreshBinderName)
private def applyAttributesCore
(declName : Name) (attrs : Array Attribute)
(applicationTime? : Option AttributeApplicationTime) : TermElabM Unit :=
for attr in attrs do
let env ← getEnv
match getAttributeImpl env attr.name with
| Except.error errMsg => throwError errMsg
| Except.ok attrImpl =>
match applicationTime? with
| none => attrImpl.add declName attr.stx attr.kind
| some applicationTime =>
if applicationTime == attrImpl.applicationTime then
attrImpl.add declName attr.stx attr.kind
/-- Apply given attributes **at** a given application time -/
def applyAttributesAt (declName : Name) (attrs : Array Attribute) (applicationTime : AttributeApplicationTime) : TermElabM Unit :=
applyAttributesCore declName attrs applicationTime
def applyAttributes (declName : Name) (attrs : Array Attribute) : TermElabM Unit :=
applyAttributesCore declName attrs none
def mkTypeMismatchError (header? : Option String) (e : Expr) (eType : Expr) (expectedType : Expr) : TermElabM MessageData := do
let header : MessageData := match header? with
| some header => m!"{header} "
| none => m!"type mismatch{indentExpr e}\n"
return m!"{header}{← mkHasTypeButIsExpectedMsg eType expectedType}"
def throwTypeMismatchError (header? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr)
(f? : Option Expr := none) (extraMsg? : Option MessageData := none) : TermElabM α := do
/-
We ignore `extraMsg?` for now. In all our tests, it contained no useful information. It was
always of the form:
```
failed to synthesize instance
CoeT <eType> <e> <expectedType>
```
We should revisit this decision in the future and decide whether it may contain useful information
or not. -/
let extraMsg := Format.nil
/-
let extraMsg : MessageData := match extraMsg? with
| none => Format.nil
| some extraMsg => Format.line ++ extraMsg;
-/
match f? with
| none => throwError "{← mkTypeMismatchError header? e eType expectedType}{extraMsg}"
| some f => Meta.throwAppTypeMismatch f e extraMsg
@[inline] def withoutMacroStackAtErr (x : TermElabM α) : TermElabM α :=
withTheReader Core.Context (fun (ctx : Core.Context) => { ctx with options := pp.macroStack.set ctx.options false }) x
/- Try to synthesize metavariable using type class resolution.
This method assumes the local context and local instances of `instMVar` coincide
with the current local context and local instances.
Return `true` if the instance was synthesized successfully, and `false` if
the instance contains unassigned metavariables that are blocking the type class
resolution procedure. Throw an exception if resolution or assignment irrevocably fails. -/
def synthesizeInstMVarCore (instMVar : MVarId) (maxResultSize? : Option Nat := none) : TermElabM Bool := do
let instMVarDecl ← getMVarDecl instMVar
let type := instMVarDecl.type
let type ← instantiateMVars type
let result ← trySynthInstance type maxResultSize?
match result with
| LOption.some val =>
if (← isExprMVarAssigned instMVar) then
let oldVal ← instantiateMVars (mkMVar instMVar)
unless (← isDefEq oldVal val) do
let oldValType ← inferType oldVal
let valType ← inferType val
unless (← isDefEq oldValType valType) do
throwError "synthesized type class instance type is not definitionally equal to expected type, synthesized{indentExpr val}\nhas type{indentExpr valType}\nexpected{indentExpr oldValType}"
throwError "synthesized type class instance is not definitionally equal to expression inferred by typing rules, synthesized{indentExpr val}\ninferred{indentExpr oldVal}"
else
unless (← isDefEq (mkMVar instMVar) val) do
throwError "failed to assign synthesized type class instance{indentExpr val}"
pure true
| LOption.undef => pure false -- we will try later
| LOption.none => throwError "failed to synthesize instance{indentExpr type}"
register_builtin_option autoLift : Bool := {
defValue := true
descr := "insert monadic lifts (i.e., `liftM` and `liftCoeM`) when needed"
}
register_builtin_option maxCoeSize : Nat := {
defValue := 16
descr := "maximum number of instances used to construct an automatic coercion"
}
def synthesizeCoeInstMVarCore (instMVar : MVarId) : TermElabM Bool := do
synthesizeInstMVarCore instMVar (some (maxCoeSize.get (← getOptions)))
/-
The coercion from `α` to `Thunk α` cannot be implemented using an instance because it would
eagerly evaluate `e` -/
def tryCoeThunk? (expectedType : Expr) (eType : Expr) (e : Expr) : TermElabM (Option Expr) := do
match expectedType with
| Expr.app (Expr.const ``Thunk u _) arg _ =>
if (← isDefEq eType arg) then
pure (some (mkApp2 (mkConst ``Thunk.mk u) arg (mkSimpleThunk e)))
else
pure none
| _ =>
pure none
/--
Try to apply coercion to make sure `e` has type `expectedType`.
Relevant definitions:
```
class CoeT (α : Sort u) (a : α) (β : Sort v)
abbrev coe {α : Sort u} {β : Sort v} (a : α) [CoeT α a β] : β
```
-/
private def tryCoe (errorMsgHeader? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := do
if (← isDefEq expectedType eType) then
return e
else match (← tryCoeThunk? expectedType eType e) with
| some r => return r
| none =>
let u ← getLevel eType
let v ← getLevel expectedType
let coeTInstType := mkAppN (mkConst ``CoeT [u, v]) #[eType, e, expectedType]
let mvar ← mkFreshExprMVar coeTInstType MetavarKind.synthetic
let eNew := mkAppN (mkConst ``coe [u, v]) #[eType, expectedType, e, mvar]
let mvarId := mvar.mvarId!
try
withoutMacroStackAtErr do
if (← synthesizeCoeInstMVarCore mvarId) then
expandCoe eNew
else
-- We create an auxiliary metavariable to represent the result, because we need to execute `expandCoe`
-- after we syntheze `mvar`
let mvarAux ← mkFreshExprMVar expectedType MetavarKind.syntheticOpaque
registerSyntheticMVarWithCurrRef mvarAux.mvarId! (SyntheticMVarKind.coe errorMsgHeader? eNew expectedType eType e f?)
return mvarAux
catch
| Exception.error _ msg => throwTypeMismatchError errorMsgHeader? expectedType eType e f? msg
| _ => throwTypeMismatchError errorMsgHeader? expectedType eType e f?
def isTypeApp? (type : Expr) : TermElabM (Option (Expr × Expr)) := do
let type ← withReducible $ whnf type
match type with
| Expr.app m α _ => pure (some ((← instantiateMVars m), (← instantiateMVars α)))
| _ => pure none
def synthesizeInst (type : Expr) : TermElabM Expr := do
let type ← instantiateMVars type
match (← trySynthInstance type) with
| LOption.some val => pure val
| LOption.undef => throwError "failed to synthesize instance{indentExpr type}"
| LOption.none => throwError "failed to synthesize instance{indentExpr type}"
def isMonadApp (type : Expr) : TermElabM Bool := do
let some (m, _) ← isTypeApp? type | pure false
return (← isMonad? m) |>.isSome
/--
Try to coerce `a : α` into `m β` by first coercing `a : α` into ‵β`, and then using `pure`.
The method is only applied if `α` is not monadic (e.g., `Nat → IO Unit`), and the head symbol
of the resulting type is not a metavariable (e.g., `?m Unit` or `Bool → ?m Nat`).
The main limitation of the approach above is polymorphic code. As usual, coercions and polymorphism
do not interact well. In the example above, the lift is successfully applied to `true`, `false` and `!y`
since none of them is polymorphic
```
def f (x : Bool) : IO Bool := do
let y ← if x == 0 then IO.println "hello"; true else false;
!y
```
On the other hand, the following fails since `+` is polymorphic
```
def f (x : Bool) : IO Nat := do
IO.prinln x
x + x -- Error: failed to synthesize `Add (IO Nat)`
```
-/
private def tryPureCoe? (errorMsgHeader? : Option String) (m β α a : Expr) : TermElabM (Option Expr) :=
commitWhenSome? do
let doIt : TermElabM (Option Expr) := do
try
let aNew ← tryCoe errorMsgHeader? β α a none
let aNew ← mkPure m aNew
pure (some aNew)
catch _ =>
pure none
forallTelescope α fun _ α => do
if (← isMonadApp α) then
pure none
else if !α.getAppFn.isMVar then
doIt
else
pure none
/-
Try coercions and monad lifts to make sure `e` has type `expectedType`.
If `expectedType` is of the form `n β`, we try monad lifts and other extensions.
Otherwise, we just use the basic `tryCoe`.
Extensions for monads.
Given an expected type of the form `n β`, if `eType` is of the form `α`, but not `m α`
1 - Try to coerce ‵α` into ‵β`, and use `pure` to lift it to `n α`.
It only works if `n` implements `Pure`
If `eType` is of the form `m α`. We use the following approaches.
1- Try to unify `n` and `m`. If it succeeds, then we use
```
coeM {m : Type u → Type v} {α β : Type u} [∀ a, CoeT α a β] [Monad m] (x : m α) : m β
```
`n` must be a `Monad` to use this one.
2- If there is monad lift from `m` to `n` and we can unify `α` and `β`, we use
```
liftM : ∀ {m : Type u_1 → Type u_2} {n : Type u_1 → Type u_3} [self : MonadLiftT m n] {α : Type u_1}, m α → n α
```
Note that `n` may not be a `Monad` in this case. This happens quite a bit in code such as
```
def g (x : Nat) : IO Nat := do
IO.println x
pure x
def f {m} [MonadLiftT IO m] : m Nat :=
g 10
```
3- If there is a monad lif from `m` to `n` and a coercion from `α` to `β`, we use
```
liftCoeM {m : Type u → Type v} {n : Type u → Type w} {α β : Type u} [MonadLiftT m n] [∀ a, CoeT α a β] [Monad n] (x : m α) : n β
```
Note that approach 3 does not subsume 1 because it is only applicable if there is a coercion from `α` to `β` for all values in `α`.
This is not the case for example for `pure $ x > 0` when the expected type is `IO Bool`. The given type is `IO Prop`, and
we only have a coercion from decidable propositions. Approach 1 works because it constructs the coercion `CoeT (m Prop) (pure $ x > 0) (m Bool)`
using the instance `pureCoeDepProp`.
Note that, approach 2 is more powerful than `tryCoe`.
Recall that type class resolution never assigns metavariables created by other modules.
Now, consider the following scenario
```lean
def g (x : Nat) : IO Nat := ...
deg h (x : Nat) : StateT Nat IO Nat := do
v ← g x;
IO.Println v;
...
```
Let's assume there is no other occurrence of `v` in `h`.
Thus, we have that the expected of `g x` is `StateT Nat IO ?α`,
and the given type is `IO Nat`. So, even if we add a coercion.
```
instance {α m n} [MonadLiftT m n] {α} : Coe (m α) (n α) := ...
```
It is not applicable because TC would have to assign `?α := Nat`.
On the other hand, TC can easily solve `[MonadLiftT IO (StateT Nat IO)]`
since this goal does not contain any metavariables. And then, we
convert `g x` into `liftM $ g x`.
-/
private def tryLiftAndCoe (errorMsgHeader? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := do
let expectedType ← instantiateMVars expectedType
let eType ← instantiateMVars eType
let throwMismatch {α} : TermElabM α := throwTypeMismatchError errorMsgHeader? expectedType eType e f?
let tryCoeSimple : TermElabM Expr :=
tryCoe errorMsgHeader? expectedType eType e f?
let some (n, β) ← isTypeApp? expectedType | tryCoeSimple
let tryPureCoeAndSimple : TermElabM Expr := do
if autoLift.get (← getOptions) then
match (← tryPureCoe? errorMsgHeader? n β eType e) with
| some eNew => pure eNew
| none => tryCoeSimple
else
tryCoeSimple
let some (m, α) ← isTypeApp? eType | tryPureCoeAndSimple
if (← isDefEq m n) then
let some monadInst ← isMonad? n | tryCoeSimple
try expandCoe (← mkAppOptM ``coeM #[m, α, β, none, monadInst, e]) catch _ => throwMismatch
else if autoLift.get (← getOptions) then
try
-- Construct lift from `m` to `n`
let monadLiftType ← mkAppM ``MonadLiftT #[m, n]
let monadLiftVal ← synthesizeInst monadLiftType
let u_1 ← getDecLevel α
let u_2 ← getDecLevel eType
let u_3 ← getDecLevel expectedType
let eNew := mkAppN (Lean.mkConst ``liftM [u_1, u_2, u_3]) #[m, n, monadLiftVal, α, e]
let eNewType ← inferType eNew
if (← isDefEq expectedType eNewType) then
return eNew -- approach 2 worked
else
let some monadInst ← isMonad? n | tryCoeSimple
let u ← getLevel α
let v ← getLevel β
let coeTInstType := Lean.mkForall `a BinderInfo.default α $ mkAppN (mkConst ``CoeT [u, v]) #[α, mkBVar 0, β]
let coeTInstVal ← synthesizeInst coeTInstType
let eNew ← expandCoe (← mkAppN (Lean.mkConst ``liftCoeM [u_1, u_2, u_3]) #[m, n, α, β, monadLiftVal, coeTInstVal, monadInst, e])
let eNewType ← inferType eNew
unless (← isDefEq expectedType eNewType) do throwMismatch
return eNew -- approach 3 worked
catch _ =>
/-
If `m` is not a monad, then we try to use `tryPureCoe?` and then `tryCoe?`.
Otherwise, we just try `tryCoe?`.
-/
match (← isMonad? m) with
| none => tryPureCoeAndSimple
| some _ => tryCoeSimple
else
tryCoeSimple
/--
If `expectedType?` is `some t`, then ensure `t` and `eType` are definitionally equal.
If they are not, then try coercions.
Argument `f?` is used only for generating error messages. -/
def ensureHasTypeAux (expectedType? : Option Expr) (eType : Expr) (e : Expr)
(f? : Option Expr := none) (errorMsgHeader? : Option String := none) : TermElabM Expr := do
match expectedType? with
| none => pure e
| some expectedType =>
if (← isDefEq eType expectedType) then
pure e
else
tryLiftAndCoe errorMsgHeader? expectedType eType e f?
/--
If `expectedType?` is `some t`, then ensure `t` and type of `e` are definitionally equal.
If they are not, then try coercions. -/
def ensureHasType (expectedType? : Option Expr) (e : Expr) (errorMsgHeader? : Option String := none) : TermElabM Expr :=
match expectedType? with
| none => pure e
| _ => do
let eType ← inferType e
ensureHasTypeAux expectedType? eType e none errorMsgHeader?
private def mkSyntheticSorryFor (expectedType? : Option Expr) : TermElabM Expr := do
let expectedType ← match expectedType? with
| none => mkFreshTypeMVar
| some expectedType => pure expectedType
mkSyntheticSorry expectedType
private def exceptionToSorry (ex : Exception) (expectedType? : Option Expr) : TermElabM Expr := do
let syntheticSorry ← mkSyntheticSorryFor expectedType?
logException ex
pure syntheticSorry
/-- If `mayPostpone == true`, throw `Expection.postpone`. -/
def tryPostpone : TermElabM Unit := do
if (← read).mayPostpone then
throwPostpone
/-- If `mayPostpone == true` and `e`'s head is a metavariable, throw `Exception.postpone`. -/
def tryPostponeIfMVar (e : Expr) : TermElabM Unit := do
if e.getAppFn.isMVar then
let e ← instantiateMVars e
if e.getAppFn.isMVar then
tryPostpone
def tryPostponeIfNoneOrMVar (e? : Option Expr) : TermElabM Unit :=
match e? with
| some e => tryPostponeIfMVar e
| none => tryPostpone
def tryPostponeIfHasMVars (expectedType? : Option Expr) (msg : String) : TermElabM Expr := do
tryPostponeIfNoneOrMVar expectedType?
let some expectedType ← pure expectedType? |
throwError "{msg}, expected type must be known"
let expectedType ← instantiateMVars expectedType
if expectedType.hasExprMVar then
tryPostpone
throwError "{msg}, expected type contains metavariables{indentExpr expectedType}"
pure expectedType
private def saveContext : TermElabM SavedContext :=
return {
macroStack := (← read).macroStack
declName? := (← read).declName?
options := (← getOptions)
openDecls := (← getOpenDecls)
errToSorry := (← read).errToSorry
}
def withSavedContext (savedCtx : SavedContext) (x : TermElabM α) : TermElabM α := do
withReader (fun ctx => { ctx with declName? := savedCtx.declName?, macroStack := savedCtx.macroStack, errToSorry := savedCtx.errToSorry }) <|
withTheReader Core.Context (fun ctx => { ctx with options := savedCtx.options, openDecls := savedCtx.openDecls })
x
private def postponeElabTerm (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do
trace[Elab.postpone] "{stx} : {expectedType?}"
let mvar ← mkFreshExprMVar expectedType? MetavarKind.syntheticOpaque
let ctx ← read
registerSyntheticMVar stx mvar.mvarId! (SyntheticMVarKind.postponed (← saveContext))
pure mvar
/-
Helper function for `elabTerm` is tries the registered elaboration functions for `stxNode` kind until it finds one that supports the syntax or
an error is found. -/
private def elabUsingElabFnsAux (s : SavedState) (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool)
: List TermElab → TermElabM Expr
| [] => do throwError "unexpected syntax{indentD stx}"
| (elabFn::elabFns) => do
try
elabFn stx expectedType?
catch ex => match ex with
| Exception.error ref msg =>
if (← read).errToSorry then
exceptionToSorry ex expectedType?
else
throw ex
| Exception.internal id _ =>
if (← read).errToSorry && id == abortTermExceptionId then
exceptionToSorry ex expectedType?
else if id == unsupportedSyntaxExceptionId then
s.restore
elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns
else if catchExPostpone && id == postponeExceptionId then
/- If `elab` threw `Exception.postpone`, we reset any state modifications.
For example, we want to make sure pending synthetic metavariables created by `elab` before
it threw `Exception.postpone` are discarded.
Note that we are also discarding the messages created by `elab`.
For example, consider the expression.
`((f.x a1).x a2).x a3`
Now, suppose the elaboration of `f.x a1` produces an `Exception.postpone`.
Then, a new metavariable `?m` is created. Then, `?m.x a2` also throws `Exception.postpone`
because the type of `?m` is not yet known. Then another, metavariable `?n` is created, and
finally `?n.x a3` also throws `Exception.postpone`. If we did not restore the state, we would
keep "dead" metavariables `?m` and `?n` on the pending synthetic metavariable list. This is
wasteful because when we resume the elaboration of `((f.x a1).x a2).x a3`, we start it from scratch
and new metavariables are created for the nested functions. -/
s.restore
postponeElabTerm stx expectedType?
else
throw ex
private def elabUsingElabFns (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : TermElabM Expr := do
let s ← saveState
let table := termElabAttribute.ext.getState (← getEnv) |>.table
let k := stx.getKind
match table.find? k with
| some elabFns => elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns
| none => throwError "elaboration function for '{k}' has not been implemented{indentD stx}"
instance : MonadMacroAdapter TermElabM where
getCurrMacroScope := getCurrMacroScope
getNextMacroScope := return (← getThe Core.State).nextMacroScope
setNextMacroScope next := modifyThe Core.State fun s => { s with nextMacroScope := next }
private def isExplicit (stx : Syntax) : Bool :=
match stx with
| `(@$f) => true
| _ => false
private def isExplicitApp (stx : Syntax) : Bool :=
stx.getKind == ``Lean.Parser.Term.app && isExplicit stx[0]
/--
Return true if `stx` if a lambda abstraction containing a `{}` or `[]` binder annotation.
Example: `fun {α} (a : α) => a` -/
private def isLambdaWithImplicit (stx : Syntax) : Bool :=
match stx with
| `(fun $binders* => $body) => binders.any fun b => b.isOfKind ``Lean.Parser.Term.implicitBinder || b.isOfKind `Lean.Parser.Term.instBinder
| _ => false
private partial def dropTermParens : Syntax → Syntax := fun stx =>
match stx with
| `(($stx)) => dropTermParens stx
| _ => stx
private def isHole (stx : Syntax) : Bool :=
match stx with
| `(_) => true
| `(? _) => true
| `(? $x:ident) => true
| _ => false
private def isTacticBlock (stx : Syntax) : Bool :=
match stx with
| `(by $x:tacticSeq) => true
| _ => false
private def isNoImplicitLambda (stx : Syntax) : Bool :=
match stx with
| `(noImplicitLambda% $x:term) => true
| _ => false
def mkNoImplicitLambdaAnnotation (type : Expr) : Expr :=
mkAnnotation `noImplicitLambda type
def hasNoImplicitLambdaAnnotation (type : Expr) : Bool :=
annotation? `noImplicitLambda type |>.isSome
/-- Block usage of implicit lambdas if `stx` is `@f` or `@f arg1 ...` or `fun` with an implicit binder annotation. -/
def blockImplicitLambda (stx : Syntax) : Bool :=
let stx := dropTermParens stx
-- TODO: make it extensible
isExplicit stx || isExplicitApp stx || isLambdaWithImplicit stx || isHole stx || isTacticBlock stx || isNoImplicitLambda stx
/--
Return normalized expected type if it is of the form `{a : α} → β` or `[a : α] → β` and
`blockImplicitLambda stx` is not true, else return `none`. -/
private def useImplicitLambda? (stx : Syntax) (expectedType? : Option Expr) : TermElabM (Option Expr) :=
if blockImplicitLambda stx then
pure none
else match expectedType? with
| some expectedType => do
if hasNoImplicitLambdaAnnotation expectedType then
pure none
else
let expectedType ← whnfForall expectedType
match expectedType with
| Expr.forallE _ _ _ c => if c.binderInfo.isExplicit then pure none else pure $ some expectedType
| _ => pure none
| _ => pure none
private def decorateErrorMessageWithLambdaImplicitVars (ex : Exception) (impFVars : Array Expr) : TermElabM Exception := do
match ex with
| Exception.error ref msg =>
if impFVars.isEmpty then
return Exception.error ref msg
else
let mut msg := m!"{msg}\nthe following variables have been introduced by the implicit lamda feature"
for impFVar in impFVars do
let auxMsg := m!"{impFVar} : {← inferType impFVar}"
let auxMsg ← addMessageContext auxMsg
msg := m!"{msg}{indentD auxMsg}"
msg := m!"{msg}\nyou can disable implict lambdas using `@` or writing a lambda expression with `\{}` or `[]` binder annotations."
return Exception.error ref msg
| _ => return ex
private def elabImplicitLambdaAux (stx : Syntax) (catchExPostpone : Bool) (expectedType : Expr) (impFVars : Array Expr) : TermElabM Expr := do
let body ← elabUsingElabFns stx expectedType catchExPostpone
try
let body ← ensureHasType expectedType body
let r ← mkLambdaFVars impFVars body
trace[Elab.implicitForall] r
pure r
catch ex =>
throw (← decorateErrorMessageWithLambdaImplicitVars ex impFVars)
private partial def elabImplicitLambda (stx : Syntax) (catchExPostpone : Bool) (type : Expr) : TermElabM Expr :=
loop type #[]
where
loop
| type@(Expr.forallE n d b c), fvars =>
if c.binderInfo.isExplicit then
elabImplicitLambdaAux stx catchExPostpone type fvars
else withFreshMacroScope do
let n ← MonadQuotation.addMacroScope n
withLocalDecl n c.binderInfo d fun fvar => do
let type ← whnfForall (b.instantiate1 fvar)
loop type (fvars.push fvar)
| type, fvars =>
elabImplicitLambdaAux stx catchExPostpone type fvars
/- Main loop for `elabTerm` -/
private partial def elabTermAux (expectedType? : Option Expr) (catchExPostpone : Bool) (implicitLambda : Bool) : Syntax → TermElabM Expr
| Syntax.missing => mkSyntheticSorryFor expectedType?
| stx => withFreshMacroScope <| withIncRecDepth do
trace[Elab.step] "expected type: {expectedType?}, term\n{stx}"
checkMaxHeartbeats "elaborator"
withNestedTraces do
let env ← getEnv
let stxNew? ← catchInternalId unsupportedSyntaxExceptionId
(do let newStx ← adaptMacro (getMacros env) stx; pure (some newStx))
(fun _ => pure none)
match stxNew? with
| some stxNew => withMacroExpansion stx stxNew <| withRef stxNew <| elabTermAux expectedType? catchExPostpone implicitLambda stxNew
| _ =>
let implicit? ← if implicitLambda && (← read).implicitLambda then useImplicitLambda? stx expectedType? else pure none
match implicit? with
| some expectedType => elabImplicitLambda stx catchExPostpone expectedType
| none => elabUsingElabFns stx expectedType? catchExPostpone
def addTermInfo (stx : Syntax) (e : Expr) : TermElabM Unit := do
if (← getInfoState).enabled then
pushInfoLeaf <| Info.ofTermInfo { lctx := (← getLCtx), expr := e, stx := stx }
def getSyntheticMVarDecl? (mvarId : MVarId) : TermElabM (Option SyntheticMVarDecl) :=
return (← get).syntheticMVars.find? fun d => d.mvarId == mvarId
def mkTermInfo (stx : Syntax) (e : Expr) : TermElabM (Sum Info MVarId) := do
let isHole? : TermElabM (Option MVarId) := do
match e with
| Expr.mvar mvarId _ =>
match (← getSyntheticMVarDecl? mvarId) with
| some { kind := SyntheticMVarKind.tactic .., .. } => return mvarId
| some { kind := SyntheticMVarKind.postponed .., .. } => return mvarId
| _ => return none
| _ => pure none
match (← isHole?) with
| none => return Sum.inl <| Info.ofTermInfo { lctx := (← getLCtx), expr := e, stx := stx }
| some mvarId => return Sum.inr mvarId
/-- Store in the `InfoTree` that `e` is a "dot"-completion target. -/
def addDotCompletionInfo (stx : Syntax) (e : Expr) (expectedType? : Option Expr) (field? : Option Syntax := none) : TermElabM Unit := do
addCompletionInfo <| CompletionInfo.dot { expr := e, stx := stx, lctx := (← getLCtx) } (field? := field?) (expectedType? := expectedType?)
/--
Main function for elaborating terms.
It extracts the elaboration methods from the environment using the node kind.
Recall that the environment has a mapping from `SyntaxNodeKind` to `TermElab` methods.
It creates a fresh macro scope for executing the elaboration method.
All unlogged trace messages produced by the elaboration method are logged using
the position information at `stx`. If the elaboration method throws an `Exception.error` and `errToSorry == true`,
the error is logged and a synthetic sorry expression is returned.
If the elaboration throws `Exception.postpone` and `catchExPostpone == true`,
a new synthetic metavariable of kind `SyntheticMVarKind.postponed` is created, registered,
and returned.
The option `catchExPostpone == false` is used to implement `resumeElabTerm`
to prevent the creation of another synthetic metavariable when resuming the elaboration.
If `implicitLambda == true`, then disable implicit lambdas feature for the given syntax, but not for its subterms.
We use this flag to implement, for example, the `@` modifier. If `Context.implicitLambda == false`, then this parameter has no effect.
-/
def elabTerm (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) : TermElabM Expr :=
withInfoContext' (withRef stx <| elabTermAux expectedType? catchExPostpone implicitLambda stx) (mkTermInfo stx)
def elabTermEnsuringType (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) (errorMsgHeader? : Option String := none) : TermElabM Expr := do
let e ← elabTerm stx expectedType? catchExPostpone implicitLambda
withRef stx <| ensureHasType expectedType? e errorMsgHeader?
/-- Adapt a syntax transformation to a regular, term-producing elaborator. -/
def adaptExpander (exp : Syntax → TermElabM Syntax) : TermElab := fun stx expectedType? => do
let stx' ← exp stx
withMacroExpansion stx stx' $ elabTerm stx' expectedType?
def mkInstMVar (type : Expr) : TermElabM Expr := do
let mvar ← mkFreshExprMVar type MetavarKind.synthetic
let mvarId := mvar.mvarId!
unless (← synthesizeInstMVarCore mvarId) do
registerSyntheticMVarWithCurrRef mvarId SyntheticMVarKind.typeClass
pure mvar
/-
Relevant definitions:
```
class CoeSort (α : Sort u) (β : outParam (Sort v))
abbrev coeSort {α : Sort u} {β : Sort v} (a : α) [CoeSort α β] : β
```
-/
private def tryCoeSort (α : Expr) (a : Expr) : TermElabM Expr := do
let β ← mkFreshTypeMVar
let u ← getLevel α
let v ← getLevel β
let coeSortInstType := mkAppN (Lean.mkConst ``CoeSort [u, v]) #[α, β]
let mvar ← mkFreshExprMVar coeSortInstType MetavarKind.synthetic
let mvarId := mvar.mvarId!
try
withoutMacroStackAtErr do
if (← synthesizeCoeInstMVarCore mvarId) then
expandCoe <| mkAppN (Lean.mkConst ``coeSort [u, v]) #[α, β, a, mvar]
else
throwError "type expected"
catch
| Exception.error _ msg => throwError "type expected\n{msg}"
| _ => throwError "type expected"
/--
Make sure `e` is a type by inferring its type and making sure it is a `Expr.sort`
or is unifiable with `Expr.sort`, or can be coerced into one. -/
def ensureType (e : Expr) : TermElabM Expr := do
if (← isType e) then
pure e
else
let eType ← inferType e
let u ← mkFreshLevelMVar
if (← isDefEq eType (mkSort u)) then
pure e
else
tryCoeSort eType e
/-- Elaborate `stx` and ensure result is a type. -/
def elabType (stx : Syntax) : TermElabM Expr := do
let u ← mkFreshLevelMVar
let type ← elabTerm stx (mkSort u)
withRef stx $ ensureType type
/--
Enable auto-bound implicits, and execute `k` while catching auto bound implicit exceptions. When an exception is caught,
a new local declaration is created, registered, and `k` is tried to be executed again. -/
partial def withAutoBoundImplicit (k : TermElabM α) : TermElabM α := do
let flag := autoBoundImplicitLocal.get (← getOptions)
if flag then
withReader (fun ctx => { ctx with autoBoundImplicit := flag, autoBoundImplicits := {} }) do
let rec loop (s : SavedState) : TermElabM α := do
try
k
catch
| ex => match isAutoBoundImplicitLocalException? ex with
| some n =>
-- Restore state, declare `n`, and try again
s.restore
withLocalDecl n BinderInfo.implicit (← mkFreshTypeMVar) fun x =>
withReader (fun ctx => { ctx with autoBoundImplicits := ctx.autoBoundImplicits.push x } ) do
loop (← saveState)
| none => throw ex
loop (← saveState)
else
k
def withoutAutoBoundImplicit (k : TermElabM α) : TermElabM α := do
withReader (fun ctx => { ctx with autoBoundImplicit := false, autoBoundImplicits := {} }) k
/--
Return `autoBoundImplicits ++ xs.
This methoid throws an error if a variable in `autoBoundImplicits` depends on some `x` in `xs` -/
def addAutoBoundImplicits (xs : Array Expr) : TermElabM (Array Expr) := do
let autoBoundImplicits := (← read).autoBoundImplicits
for auto in autoBoundImplicits do
let localDecl ← getLocalDecl auto.fvarId!
for x in xs do
if (← getMCtx).localDeclDependsOn localDecl x.fvarId! then
throwError "invalid auto implicit argument '{auto}', it depends on explicitly provided argument '{x}'"
return autoBoundImplicits.toArray ++ xs
def mkAuxName (suffix : Name) : TermElabM Name := do
match (← read).declName? with
| none => throwError "auxiliary declaration cannot be created when declaration name is not available"
| some declName => Lean.mkAuxName (declName ++ suffix) 1
builtin_initialize registerTraceClass `Elab.letrec
/- Return true if mvarId is an auxiliary metavariable created for compiling `let rec` or it
is delayed assigned to one. -/
def isLetRecAuxMVar (mvarId : MVarId) : TermElabM Bool := do
trace[Elab.letrec] "mvarId: {mkMVar mvarId} letrecMVars: {(← get).letRecsToLift.map (mkMVar $ ·.mvarId)}"
let mvarId := (← getMCtx).getDelayedRoot mvarId
trace[Elab.letrec] "mvarId root: {mkMVar mvarId}"
return (← get).letRecsToLift.any (·.mvarId == mvarId)
/- =======================================
Builtin elaboration functions
======================================= -/
@[builtinTermElab «prop»] def elabProp : TermElab := fun _ _ =>
return mkSort levelZero
private def elabOptLevel (stx : Syntax) : TermElabM Level :=
if stx.isNone then
pure levelZero
else
elabLevel stx[0]
@[builtinTermElab «sort»] def elabSort : TermElab := fun stx _ =>
return mkSort (← elabOptLevel stx[1])
@[builtinTermElab «type»] def elabTypeStx : TermElab := fun stx _ =>
return mkSort (mkLevelSucc (← elabOptLevel stx[1]))
/-
the method `resolveName` adds a completion point for it using the given
expected type. Thus, we propagate the expected type if `stx[0]` is an identifier.
It doesn't "hurt" if the identifier can be resolved because the expected type is not used in this case.
Recall that if the name resolution fails a synthetic sorry is returned.-/
@[builtinTermElab «pipeCompletion»] def elabPipeCompletion : TermElab := fun stx expectedType? => do
let e ← elabTerm stx[0] none
unless e.isSorry do
addDotCompletionInfo stx e expectedType?
throwErrorAt stx[1] "invalid field notation, identifier or numeral expected"
@[builtinTermElab «completion»] def elabCompletion : TermElab := fun stx expectedType? => do
/- `ident.` is ambiguous in Lean, we may try to be completing a declaration name or access a "field". -/
if stx[0].isIdent then
/- If we can elaborate the identifier successfully, we assume it a dot-completion. Otherwise, we treat it as
identifier completion with a dangling `.`.
Recall that the server falls back to identifier completion when dot-completion fails. -/
let s ← saveState
try
let e ← elabTerm stx[0] none
addDotCompletionInfo stx e expectedType?
catch _ =>
s.restore
addCompletionInfo <| CompletionInfo.id stx stx[0].getId (danglingDot := true) (← getLCtx) expectedType?
throwErrorAt stx[1] "invalid field notation, identifier or numeral expected"
else
elabPipeCompletion stx expectedType?
@[builtinTermElab «hole»] def elabHole : TermElab := fun stx expectedType? => do
let mvar ← mkFreshExprMVar expectedType?
registerMVarErrorHoleInfo mvar.mvarId! stx
pure mvar
@[builtinTermElab «syntheticHole»] def elabSyntheticHole : TermElab := fun stx expectedType? => do
let arg := stx[1]
let userName := if arg.isIdent then arg.getId else Name.anonymous
let mkNewHole : Unit → TermElabM Expr := fun _ => do
let mvar ← mkFreshExprMVar expectedType? MetavarKind.syntheticOpaque userName
registerMVarErrorHoleInfo mvar.mvarId! stx
pure mvar
if userName.isAnonymous then
mkNewHole ()
else
let mctx ← getMCtx
match mctx.findUserName? userName with
| none => mkNewHole ()
| some mvarId =>
let mvar := mkMVar mvarId
let mvarDecl ← getMVarDecl mvarId
let lctx ← getLCtx
if mvarDecl.lctx.isSubPrefixOf lctx then
pure mvar
else match mctx.getExprAssignment? mvarId with
| some val =>
let val ← instantiateMVars val
if mctx.isWellFormed lctx val then
pure val
else
withLCtx mvarDecl.lctx mvarDecl.localInstances do
throwError "synthetic hole has already been defined and assigned to value incompatible with the current context{indentExpr val}"
| none =>
if mctx.isDelayedAssigned mvarId then
-- We can try to improve this case if needed.
throwError "synthetic hole has already beend defined and delayed assigned with an incompatible local context"
else if lctx.isSubPrefixOf mvarDecl.lctx then
let mvarNew ← mkNewHole ()
modifyMCtx fun mctx => mctx.assignExpr mvarId mvarNew
pure mvarNew
else
throwError "synthetic hole has already been defined with an incompatible local context"
private def mkTacticMVar (type : Expr) (tacticCode : Syntax) : TermElabM Expr := do
let mvar ← mkFreshExprMVar type MetavarKind.syntheticOpaque
let mvarId := mvar.mvarId!
let ref ← getRef
let declName? ← getDeclName?
registerSyntheticMVar ref mvarId <| SyntheticMVarKind.tactic tacticCode (← saveContext)
return mvar
@[builtinTermElab byTactic] def elabByTactic : TermElab := fun stx expectedType? =>
match expectedType? with
| some expectedType => mkTacticMVar expectedType stx
| none => throwError ("invalid 'by' tactic, expected type has not been provided")
@[builtinTermElab noImplicitLambda] def elabNoImplicitLambda : TermElab := fun stx expectedType? =>
elabTerm stx[1] (mkNoImplicitLambdaAnnotation <$> expectedType?)
def resolveLocalName (n : Name) : TermElabM (Option (Expr × List String)) := do
let lctx ← getLCtx
let view := extractMacroScopes n
let rec loop (n : Name) (projs : List String) :=
match lctx.findFromUserName? { view with name := n }.review with
| some decl => some (decl.toExpr, projs)
| none => match n with
| Name.str pre s _ => loop pre (s::projs)
| _ => none
return loop view.name []
/- Return true iff `stx` is a `Syntax.ident`, and it is a local variable. -/
def isLocalIdent? (stx : Syntax) : TermElabM (Option Expr) :=
match stx with
| Syntax.ident _ _ val _ => do
let r? ← resolveLocalName val
match r? with
| some (fvar, []) => pure (some fvar)
| _ => pure none
| _ => pure none
/--
Create an `Expr.const` using the given name and explicit levels.
Remark: fresh universe metavariables are created if the constant has more universe
parameters than `explicitLevels`. -/
def mkConst (constName : Name) (explicitLevels : List Level := []) : TermElabM Expr := do
let cinfo ← getConstInfo constName
if explicitLevels.length > cinfo.levelParams.length then
throwError "too many explicit universe levels"
else
let numMissingLevels := cinfo.levelParams.length - explicitLevels.length
let us ← mkFreshLevelMVars numMissingLevels
pure $ Lean.mkConst constName (explicitLevels ++ us)
private def mkConsts (candidates : List (Name × List String)) (explicitLevels : List Level) : TermElabM (List (Expr × List String)) := do
candidates.foldlM (init := []) fun result (constName, projs) => do
-- TODO: better suppor for `mkConst` failure. We may want to cache the failures, and report them if all candidates fail.
let const ← mkConst constName explicitLevels
return (const, projs) :: result
def resolveName (stx : Syntax) (n : Name) (preresolved : List (Name × List String)) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr × List String)) := do
try
if let some (e, projs) ← resolveLocalName n then
unless explicitLevels.isEmpty do
throwError "invalid use of explicit universe parameters, '{e}' is a local"
return [(e, projs)]
-- check for section variable capture by a quotation
let ctx ← read
if let some (e, projs) := preresolved.findSome? fun (n, projs) => ctx.sectionFVars.find? n |>.map (·, projs) then
return [(e, projs)] -- section variables should shadow global decls
if preresolved.isEmpty then
process (← resolveGlobalName n)
else
process preresolved
catch ex =>
if preresolved.isEmpty && explicitLevels.isEmpty then
addCompletionInfo <| CompletionInfo.id stx stx.getId (danglingDot := false) (← getLCtx) expectedType?
throw ex
where process (candidates : List (Name × List String)) : TermElabM (List (Expr × List String)) := do
if candidates.isEmpty then
if (← read).autoBoundImplicit && isValidAutoBoundImplicitName n then
throwAutoBoundImplicitLocal n
else
throwError "unknown identifier '{Lean.mkConst n}'"
if preresolved.isEmpty && explicitLevels.isEmpty then
addCompletionInfo <| CompletionInfo.id stx stx.getId (danglingDot := false) (← getLCtx) expectedType?
mkConsts candidates explicitLevels
/--
Similar to `resolveName`, but creates identifiers for the main part and each projection with position information derived from `ident`.
Example: Assume resolveName `v.head.bla.boo` produces `(v.head, ["bla", "boo"])`, then this method produces
`(v.head, id, [f₁, f₂])` where `id` is an identifier for `v.head`, and `f₁` and `f₂` are identifiers for fields `"bla"` and `"boo"`. -/
def resolveName' (ident : Syntax) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr × Syntax × List Syntax)) := do
match ident with
| Syntax.ident info rawStr n preresolved =>
let r ← resolveName ident n preresolved explicitLevels expectedType?
r.mapM fun (c, fields) => do
let (cSstr, fields) := fields.foldr (init := (rawStr, [])) fun field (restSstr, fs) =>
let fieldSstr := restSstr.takeRightWhile (· ≠ '.')
({ restSstr with stopPos := restSstr.stopPos - (fieldSstr.bsize + 1) }, (field, fieldSstr) :: fs)
let mkIdentFromPos pos rawVal val :=
let info := match info with
| SourceInfo.original .. => SourceInfo.original "".toSubstring pos "".toSubstring
| _ => SourceInfo.synthetic pos (pos + rawVal.bsize)
Syntax.ident info rawVal val []
let id := match c with
| Expr.const id _ _ => id
| Expr.fvar id _ => id
| _ => unreachable!
let id := mkIdentFromPos (ident.getPos?.getD 0) cSstr id
match info.getPos? with
| none =>
return (c, id, fields.map fun (field, _) => mkIdentFrom ident (Name.mkSimple field))
| some pos =>
let mut pos := pos + cSstr.bsize + 1
let mut newFields := #[]
for (field, fieldSstr) in fields do
newFields := newFields.push <| mkIdentFromPos pos fieldSstr (Name.mkSimple field)
pos := pos + fieldSstr.bsize + 1
return (c, id, newFields.toList)
| _ => throwError "identifier expected"
def resolveId? (stx : Syntax) (kind := "term") (withInfo := false) : TermElabM (Option Expr) :=
match stx with
| Syntax.ident _ _ val preresolved => do
let rs ← try resolveName stx val preresolved [] catch _ => pure []
let rs := rs.filter fun ⟨f, projs⟩ => projs.isEmpty
let fs := rs.map fun (f, _) => f
match fs with
| [] => pure none
| [f] =>
if withInfo then
addTermInfo stx f
pure (some f)
| _ => throwError "ambiguous {kind}, use fully qualified name, possible interpretations {fs}"
| _ => throwError "identifier expected"
@[builtinTermElab cdot] def elabBadCDot : TermElab := fun stx _ =>
throwError "invalid occurrence of `·` notation, it must be surrounded by parentheses (e.g. `(· + 1)`)"
@[builtinTermElab strLit] def elabStrLit : TermElab := fun stx _ => do
match stx.isStrLit? with
| some val => pure $ mkStrLit val
| none => throwIllFormedSyntax
private def mkFreshTypeMVarFor (expectedType? : Option Expr) : TermElabM Expr := do
let typeMVar ← mkFreshTypeMVar MetavarKind.synthetic
match expectedType? with
| some expectedType => discard <| isDefEq expectedType typeMVar
| _ => pure ()
return typeMVar
@[builtinTermElab numLit] def elabNumLit : TermElab := fun stx expectedType? => do
let val ← match stx.isNatLit? with
| some val => pure val
| none => throwIllFormedSyntax
let typeMVar ← mkFreshTypeMVarFor expectedType?
let u ← getDecLevel typeMVar
let mvar ← mkInstMVar (mkApp2 (Lean.mkConst ``OfNat [u]) typeMVar (mkNatLit val))
let r := mkApp3 (Lean.mkConst ``OfNat.ofNat [u]) typeMVar (mkNatLit val) mvar
registerMVarErrorImplicitArgInfo mvar.mvarId! stx r
return r
@[builtinTermElab rawNatLit] def elabRawNatLit : TermElab := fun stx expectedType? => do
match stx[1].isNatLit? with
| some val => return mkNatLit val
| none => throwIllFormedSyntax
@[builtinTermElab scientificLit]
def elabScientificLit : TermElab := fun stx expectedType? => do
match stx.isScientificLit? with
| none => throwIllFormedSyntax
| some (m, sign, e) =>
let typeMVar ← mkFreshTypeMVarFor expectedType?
let u ← getDecLevel typeMVar
let mvar ← mkInstMVar (mkApp (Lean.mkConst ``OfScientific [u]) typeMVar)
return mkApp5 (Lean.mkConst ``OfScientific.ofScientific [u]) typeMVar mvar (mkNatLit m) (toExpr sign) (mkNatLit e)
@[builtinTermElab charLit] def elabCharLit : TermElab := fun stx _ => do
match stx.isCharLit? with
| some val => return mkApp (Lean.mkConst ``Char.ofNat) (mkNatLit val.toNat)
| none => throwIllFormedSyntax
@[builtinTermElab quotedName] def elabQuotedName : TermElab := fun stx _ =>
match stx[0].isNameLit? with
| some val => pure $ toExpr val
| none => throwIllFormedSyntax
@[builtinTermElab doubleQuotedName] def elabDoubleQuotedName : TermElab := fun stx _ => do
match stx[1].isNameLit? with
| some val => toExpr (← resolveGlobalConstNoOverloadWithInfo stx[1] val)
| none => throwIllFormedSyntax
@[builtinTermElab typeOf] def elabTypeOf : TermElab := fun stx _ => do
inferType (← elabTerm stx[1] none)
@[builtinTermElab ensureTypeOf] def elabEnsureTypeOf : TermElab := fun stx expectedType? =>
match stx[2].isStrLit? with
| none => throwIllFormedSyntax
| some msg => do
let refTerm ← elabTerm stx[1] none
let refTermType ← inferType refTerm
elabTermEnsuringType stx[3] refTermType (errorMsgHeader? := msg)
@[builtinTermElab ensureExpectedType] def elabEnsureExpectedType : TermElab := fun stx expectedType? =>
match stx[1].isStrLit? with
| none => throwIllFormedSyntax
| some msg => elabTermEnsuringType stx[2] expectedType? (errorMsgHeader? := msg)
@[builtinTermElab «open»] def elabOpen : TermElab := fun stx expectedType? => do
try
pushScope
let openDecls ← elabOpenDecl stx[1]
withTheReader Core.Context (fun ctx => { ctx with openDecls := openDecls }) do
elabTerm stx[3] expectedType?
finally
popScope
@[builtinTermElab «set_option»] def elabSetOption : TermElab := fun stx expectedType? => do
let options ← Elab.elabSetOption stx[1] stx[2]
withTheReader Core.Context (fun ctx => { ctx with maxRecDepth := maxRecDepth.get options, options := options }) do
elabTerm stx[4] expectedType?
private def mkSomeContext : Context := {
fileName := "<TermElabM>"
fileMap := arbitrary
}
@[inline] def TermElabM.run (x : TermElabM α) (ctx : Context := mkSomeContext) (s : State := {}) : MetaM (α × State) :=
withConfig setElabConfig (x ctx |>.run s)
@[inline] def TermElabM.run' (x : TermElabM α) (ctx : Context := mkSomeContext) (s : State := {}) : MetaM α :=
(·.1) <$> x.run ctx s
@[inline] def TermElabM.toIO (x : TermElabM α)
(ctxCore : Core.Context) (sCore : Core.State)
(ctxMeta : Meta.Context) (sMeta : Meta.State)
(ctx : Context) (s : State) : IO (α × Core.State × Meta.State × State) := do
let ((a, s), sCore, sMeta) ← (x.run ctx s).toIO ctxCore sCore ctxMeta sMeta
pure (a, sCore, sMeta, s)
instance [MetaEval α] : MetaEval (TermElabM α) where
eval env opts x _ :=
let x : TermElabM α := do
try x finally
let s ← get
s.messages.forM fun msg => do IO.println (← msg.toString)
MetaEval.eval env opts (hideUnit := true) $ x.run' mkSomeContext
unsafe def evalExpr (α) (typeName : Name) (value : Expr) : TermElabM α :=
withoutModifyingEnv do
let name ← mkFreshUserName `_tmp
let type ← inferType value
let type ← whnfD type
unless type.isConstOf typeName do
throwError "unexpected type at evalExpr{indentExpr type}"
let decl := Declaration.defnDecl {
name := name, levelParams := [], type := type,
value := value, hints := ReducibilityHints.opaque,
safety := DefinitionSafety.unsafe
}
ensureNoUnassignedMVars decl
addAndCompile decl
evalConst α name
private def throwStuckAtUniverseCnstr : TermElabM Unit := do
let entries ← getPostponed
let mut found : Std.HashSet (Level × Level) := {}
let mut uniqueEntries := #[]
for entry in entries do
let mut lhs := entry.lhs
let mut rhs := entry.rhs
if Level.normLt rhs lhs then
(lhs, rhs) := (rhs, lhs)
unless found.contains (lhs, rhs) do
found := found.insert (lhs, rhs)
uniqueEntries := uniqueEntries.push entry
for i in [1:uniqueEntries.size] do
logErrorAt uniqueEntries[i].ref (← mkMessage uniqueEntries[i])
throwErrorAt uniqueEntries[0].ref (← mkMessage uniqueEntries[0])
where
/- Annotate any constant and sort in `e` that satisfies `p` with `pp.universes true` -/
exposeRelevantUniverses (e : Expr) (p : Level → Bool) : Expr :=
e.replace fun e =>
match e with
| Expr.const _ us _ => if us.any p then some (e.setPPUniverses true) else none
| Expr.sort u _ => if p u then some (e.setPPUniverses true) else none
| _ => none
mkMessage (entry : PostponedEntry) : TermElabM MessageData := do
match entry.ctx? with
| none =>
return m!"stuck at solving universe constraints{indentD m!"{entry.lhs} =?= {entry.rhs}"}"
| some ctx =>
withLCtx ctx.lctx ctx.localInstances do
let s := entry.lhs.collectMVars entry.rhs.collectMVars
/- `p u` is true if it contains a universe metavariable in `s` -/
let p (u : Level) := u.any fun | Level.mvar m _ => s.contains m | _ => false
let lhs := exposeRelevantUniverses (← instantiateMVars ctx.lhs) p
let rhs := exposeRelevantUniverses (← instantiateMVars ctx.rhs) p
addMessageContext m!"stuck at solving universe constraints{indentD m!"{entry.lhs} =?= {entry.rhs}"}\nwhile trying to unify{indentD m!"{lhs} : {← inferType lhs}"}\nwith{indentD m!"{rhs} : {← inferType rhs}"}"
@[specialize] def withoutPostponingUniverseConstraints (x : TermElabM α) : TermElabM α := do
let postponed ← getResetPostponed
try
let a ← x
unless (← processPostponed (mayPostpone := false)) do
throwStuckAtUniverseCnstr
setPostponed postponed
return a
catch ex =>
setPostponed postponed
throw ex
end Term
builtin_initialize
registerTraceClass `Elab.postpone
registerTraceClass `Elab.coe
registerTraceClass `Elab.debug
export Term (TermElabM)
end Lean.Elab
|
1c483f2875e8378b2150f1c977c6c192e2aeb370 | 05f637fa14ac28031cb1ea92086a0f4eb23ff2b1 | /tests/lean/sig2.lean | eb46009b69d9b41cfb54823449af60a0409b4a64 | [
"Apache-2.0"
] | permissive | codyroux/lean0.1 | 1ce92751d664aacff0529e139083304a7bbc8a71 | 0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef | refs/heads/master | 1,610,830,535,062 | 1,402,150,480,000 | 1,402,150,480,000 | 19,588,851 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 345 | lean | check sig x : Nat, x > 0
check pair 10 20
check pair 10 true
check pair true 20
check pair true 20 : Bool # Nat
check pair true true
check pair true true : Bool ⨯ Bool
variable a : Nat
axiom Ha : 1 ≤ a
definition NZ : Type := sig x : Nat, 1 ≤ x
check NZ
check pair a Ha : NZ
check pair true 20 : Nat # Nat
check pair true 20 : Bool # Bool
|
62003d082e3e148c65161ac0b81b5971b4e36bd3 | bb31430994044506fa42fd667e2d556327e18dfe | /src/algebra/euclidean_domain/basic.lean | 3f485ba27a7f97bdde735130875f2fbec74b5269 | [
"Apache-2.0"
] | permissive | sgouezel/mathlib | 0cb4e5335a2ba189fa7af96d83a377f83270e503 | 00638177efd1b2534fc5269363ebf42a7871df9a | refs/heads/master | 1,674,527,483,042 | 1,673,665,568,000 | 1,673,665,568,000 | 119,598,202 | 0 | 0 | null | 1,517,348,647,000 | 1,517,348,646,000 | null | UTF-8 | Lean | false | false | 10,054 | lean | /-
Copyright (c) 2018 Louis Carlin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Louis Carlin, Mario Carneiro
-/
import algebra.euclidean_domain.defs
import algebra.ring.divisibility
import algebra.ring.regular
import algebra.group_with_zero.divisibility
import algebra.ring.basic
/-!
# Lemmas about Euclidean domains
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
## Main statements
* `gcd_eq_gcd_ab`: states Bézout's lemma for Euclidean domains.
-/
universe u
namespace euclidean_domain
variable {R : Type u}
variables [euclidean_domain R]
local infix ` ≺ `:50 := euclidean_domain.r
lemma mul_div_cancel_left {a : R} (b) (a0 : a ≠ 0) : a * b / a = b :=
eq.symm $ eq_of_sub_eq_zero $ classical.by_contradiction $ λ h,
begin
have := mul_left_not_lt a h,
rw [mul_sub, sub_eq_iff_eq_add'.2 (div_add_mod (a*b) a).symm] at this,
exact this (mod_lt _ a0)
end
lemma mul_div_cancel (a) {b : R} (b0 : b ≠ 0) : a * b / b = a :=
by { rw mul_comm, exact mul_div_cancel_left a b0 }
@[simp] lemma mod_eq_zero {a b : R} : a % b = 0 ↔ b ∣ a :=
⟨λ h, by { rw [← div_add_mod a b, h, add_zero], exact dvd_mul_right _ _ },
λ ⟨c, e⟩, begin
rw [e, ← add_left_cancel_iff, div_add_mod, add_zero],
haveI := classical.dec,
by_cases b0 : b = 0,
{ simp only [b0, zero_mul] },
{ rw [mul_div_cancel_left _ b0] }
end⟩
@[simp] lemma mod_self (a : R) : a % a = 0 :=
mod_eq_zero.2 dvd_rfl
lemma dvd_mod_iff {a b c : R} (h : c ∣ b) : c ∣ a % b ↔ c ∣ a :=
by rw [dvd_add_iff_right (h.mul_right _), div_add_mod]
@[simp] lemma mod_one (a : R) : a % 1 = 0 :=
mod_eq_zero.2 (one_dvd _)
@[simp] lemma zero_mod (b : R) : 0 % b = 0 :=
mod_eq_zero.2 (dvd_zero _)
@[simp, priority 900] lemma zero_div {a : R} : 0 / a = 0 :=
classical.by_cases
(λ a0 : a = 0, a0.symm ▸ div_zero 0)
(λ a0, by simpa only [zero_mul] using mul_div_cancel 0 a0)
@[simp, priority 900] lemma div_self {a : R} (a0 : a ≠ 0) : a / a = 1 :=
by simpa only [one_mul] using mul_div_cancel 1 a0
lemma eq_div_of_mul_eq_left {a b c : R} (hb : b ≠ 0) (h : a * b = c) : a = c / b :=
by rw [← h, mul_div_cancel _ hb]
lemma eq_div_of_mul_eq_right {a b c : R} (ha : a ≠ 0) (h : a * b = c) : b = c / a :=
by rw [← h, mul_div_cancel_left _ ha]
theorem mul_div_assoc (x : R) {y z : R} (h : z ∣ y) : x * y / z = x * (y / z) :=
begin
classical, by_cases hz : z = 0,
{ subst hz, rw [div_zero, div_zero, mul_zero] },
rcases h with ⟨p, rfl⟩,
rw [mul_div_cancel_left _ hz, mul_left_comm, mul_div_cancel_left _ hz]
end
@[simp, priority 900] -- This generalizes `int.div_one`, see note [simp-normal form]
lemma div_one (p : R) : p / 1 = p :=
(euclidean_domain.eq_div_of_mul_eq_left (one_ne_zero' R) (mul_one p)).symm
lemma div_dvd_of_dvd {p q : R} (hpq : q ∣ p) :
p / q ∣ p :=
begin
by_cases hq : q = 0,
{ rw [hq, zero_dvd_iff] at hpq,
rw hpq,
exact dvd_zero _ },
use q,
rw [mul_comm, ← euclidean_domain.mul_div_assoc _ hpq, mul_comm,
euclidean_domain.mul_div_cancel _ hq]
end
lemma dvd_div_of_mul_dvd {a b c : R} (h : a * b ∣ c) : b ∣ c / a :=
begin
rcases eq_or_ne a 0 with rfl | ha,
{ simp only [div_zero, dvd_zero] },
rcases h with ⟨d, rfl⟩,
refine ⟨d, _⟩,
rw [mul_assoc, mul_div_cancel_left _ ha]
end
section gcd
variable [decidable_eq R]
@[simp] theorem gcd_zero_right (a : R) : gcd a 0 = a :=
by { rw gcd, split_ifs; simp only [h, zero_mod, gcd_zero_left] }
theorem gcd_val (a b : R) : gcd a b = gcd (b % a) a :=
by { rw gcd, split_ifs; [simp only [h, mod_zero, gcd_zero_right], refl]}
theorem gcd_dvd (a b : R) : gcd a b ∣ a ∧ gcd a b ∣ b :=
gcd.induction a b
(λ b, by { rw gcd_zero_left, exact ⟨dvd_zero _, dvd_rfl⟩ })
(λ a b aneq ⟨IH₁, IH₂⟩, by { rw gcd_val,
exact ⟨IH₂, (dvd_mod_iff IH₂).1 IH₁⟩ })
theorem gcd_dvd_left (a b : R) : gcd a b ∣ a := (gcd_dvd a b).left
theorem gcd_dvd_right (a b : R) : gcd a b ∣ b := (gcd_dvd a b).right
protected theorem gcd_eq_zero_iff {a b : R} :
gcd a b = 0 ↔ a = 0 ∧ b = 0 :=
⟨λ h, by simpa [h] using gcd_dvd a b,
by { rintro ⟨rfl, rfl⟩, exact gcd_zero_right _ }⟩
theorem dvd_gcd {a b c : R} : c ∣ a → c ∣ b → c ∣ gcd a b :=
gcd.induction a b
(λ _ _ H, by simpa only [gcd_zero_left] using H)
(λ a b a0 IH ca cb, by { rw gcd_val,
exact IH ((dvd_mod_iff ca).2 cb) ca })
theorem gcd_eq_left {a b : R} : gcd a b = a ↔ a ∣ b :=
⟨λ h, by {rw ← h, apply gcd_dvd_right },
λ h, by rw [gcd_val, mod_eq_zero.2 h, gcd_zero_left]⟩
@[simp] theorem gcd_one_left (a : R) : gcd 1 a = 1 :=
gcd_eq_left.2 (one_dvd _)
@[simp] theorem gcd_self (a : R) : gcd a a = a :=
gcd_eq_left.2 dvd_rfl
@[simp] theorem xgcd_aux_fst (x y : R) : ∀ s t s' t',
(xgcd_aux x s t y s' t').1 = gcd x y :=
gcd.induction x y (by { intros, rw [xgcd_zero_left, gcd_zero_left] })
(λ x y h IH s t s' t', by { simp only [xgcd_aux_rec h, if_neg h, IH], rw ← gcd_val })
theorem xgcd_aux_val (x y : R) : xgcd_aux x 1 0 y 0 1 = (gcd x y, xgcd x y) :=
by rw [xgcd, ← xgcd_aux_fst x y 1 0 0 1, prod.mk.eta]
private def P (a b : R) : R × R × R → Prop | (r, s, t) := (r : R) = a * s + b * t
theorem xgcd_aux_P (a b : R) {r r' : R} : ∀ {s t s' t'}, P a b (r, s, t) →
P a b (r', s', t') → P a b (xgcd_aux r s t r' s' t') :=
gcd.induction r r' (by { intros, simpa only [xgcd_zero_left] }) $ λ x y h IH s t s' t' p p', begin
rw [xgcd_aux_rec h], refine IH _ p, unfold P at p p' ⊢,
rw [mul_sub, mul_sub, add_sub, sub_add_eq_add_sub, ← p', sub_sub,
mul_comm _ s, ← mul_assoc, mul_comm _ t, ← mul_assoc, ← add_mul, ← p,
mod_eq_sub_mul_div]
end
/-- An explicit version of **Bézout's lemma** for Euclidean domains. -/
theorem gcd_eq_gcd_ab (a b : R) : (gcd a b : R) = a * gcd_a a b + b * gcd_b a b :=
by { have := @xgcd_aux_P _ _ _ a b a b 1 0 0 1
(by rw [P, mul_one, mul_zero, add_zero]) (by rw [P, mul_one, mul_zero, zero_add]),
rwa [xgcd_aux_val, xgcd_val] at this }
@[priority 70] -- see Note [lower instance priority]
instance (R : Type*) [e : euclidean_domain R] : no_zero_divisors R :=
by { haveI := classical.dec_eq R, exact
{ eq_zero_or_eq_zero_of_mul_eq_zero :=
λ a b h, (or_iff_not_and_not.2 $ λ h0,
h0.1 $ by rw [← mul_div_cancel a h0.2, h, zero_div]) }}
@[priority 70] -- see Note [lower instance priority]
instance (R : Type*) [e : euclidean_domain R] : is_domain R :=
{ .. e, .. no_zero_divisors.to_is_domain R }
end gcd
section lcm
variables [decidable_eq R]
theorem dvd_lcm_left (x y : R) : x ∣ lcm x y :=
classical.by_cases
(assume hxy : gcd x y = 0, by { rw [lcm, hxy, div_zero], exact dvd_zero _ })
(λ hxy, let ⟨z, hz⟩ := (gcd_dvd x y).2 in ⟨z, eq.symm $ eq_div_of_mul_eq_left hxy $
by rw [mul_right_comm, mul_assoc, ← hz]⟩)
theorem dvd_lcm_right (x y : R) : y ∣ lcm x y :=
classical.by_cases
(assume hxy : gcd x y = 0, by { rw [lcm, hxy, div_zero], exact dvd_zero _ })
(λ hxy, let ⟨z, hz⟩ := (gcd_dvd x y).1 in ⟨z, eq.symm $ eq_div_of_mul_eq_right hxy $
by rw [← mul_assoc, mul_right_comm, ← hz]⟩)
theorem lcm_dvd {x y z : R} (hxz : x ∣ z) (hyz : y ∣ z) : lcm x y ∣ z :=
begin
rw lcm, by_cases hxy : gcd x y = 0,
{ rw [hxy, div_zero], rw euclidean_domain.gcd_eq_zero_iff at hxy, rwa hxy.1 at hxz },
rcases gcd_dvd x y with ⟨⟨r, hr⟩, ⟨s, hs⟩⟩,
suffices : x * y ∣ z * gcd x y,
{ cases this with p hp, use p,
generalize_hyp : gcd x y = g at hxy hs hp ⊢, subst hs,
rw [mul_left_comm, mul_div_cancel_left _ hxy, ← mul_left_inj' hxy, hp],
rw [← mul_assoc], simp only [mul_right_comm] },
rw [gcd_eq_gcd_ab, mul_add], apply dvd_add,
{ rw mul_left_comm, exact mul_dvd_mul_left _ (hyz.mul_right _) },
{ rw [mul_left_comm, mul_comm], exact mul_dvd_mul_left _ (hxz.mul_right _) }
end
@[simp] lemma lcm_dvd_iff {x y z : R} : lcm x y ∣ z ↔ x ∣ z ∧ y ∣ z :=
⟨λ hz, ⟨(dvd_lcm_left _ _).trans hz, (dvd_lcm_right _ _).trans hz⟩,
λ ⟨hxz, hyz⟩, lcm_dvd hxz hyz⟩
@[simp] lemma lcm_zero_left (x : R) : lcm 0 x = 0 :=
by rw [lcm, zero_mul, zero_div]
@[simp] lemma lcm_zero_right (x : R) : lcm x 0 = 0 :=
by rw [lcm, mul_zero, zero_div]
@[simp] lemma lcm_eq_zero_iff {x y : R} : lcm x y = 0 ↔ x = 0 ∨ y = 0 :=
begin
split,
{ intro hxy, rw [lcm, mul_div_assoc _ (gcd_dvd_right _ _), mul_eq_zero] at hxy,
apply or_of_or_of_imp_right hxy, intro hy,
by_cases hgxy : gcd x y = 0,
{ rw euclidean_domain.gcd_eq_zero_iff at hgxy, exact hgxy.2 },
{ rcases gcd_dvd x y with ⟨⟨r, hr⟩, ⟨s, hs⟩⟩,
generalize_hyp : gcd x y = g at hr hs hy hgxy ⊢, subst hs,
rw [mul_div_cancel_left _ hgxy] at hy, rw [hy, mul_zero] } },
rintro (hx | hy),
{ rw [hx, lcm_zero_left] },
{ rw [hy, lcm_zero_right] }
end
@[simp] lemma gcd_mul_lcm (x y : R) : gcd x y * lcm x y = x * y :=
begin
rw lcm, by_cases h : gcd x y = 0,
{ rw [h, zero_mul], rw euclidean_domain.gcd_eq_zero_iff at h, rw [h.1, zero_mul] },
rcases gcd_dvd x y with ⟨⟨r, hr⟩, ⟨s, hs⟩⟩,
generalize_hyp : gcd x y = g at h hr ⊢, subst hr,
rw [mul_assoc, mul_div_cancel_left _ h]
end
end lcm
section div
lemma mul_div_mul_cancel {a b c : R} (ha : a ≠ 0) (hcb : c ∣ b) :
a * b / (a * c) = b / c :=
begin
by_cases hc : c = 0, { simp [hc] },
refine eq_div_of_mul_eq_right hc (mul_left_cancel₀ ha _),
rw [← mul_assoc, ← mul_div_assoc _ (mul_dvd_mul_left a hcb),
mul_div_cancel_left _ (mul_ne_zero ha hc)]
end
lemma mul_div_mul_comm_of_dvd_dvd {a b c d : R} (hac : c ∣ a) (hbd : d ∣ b) :
a * b / (c * d) = a / c * (b / d) :=
begin
rcases eq_or_ne c 0 with rfl | hc0, { simp },
rcases eq_or_ne d 0 with rfl | hd0, { simp },
obtain ⟨k1, rfl⟩ := hac,
obtain ⟨k2, rfl⟩ := hbd,
rw [mul_div_cancel_left _ hc0, mul_div_cancel_left _ hd0, mul_mul_mul_comm,
mul_div_cancel_left _ (mul_ne_zero hc0 hd0)],
end
end div
end euclidean_domain
|
566630647a758ce0462798e2461178880180c449 | bdb33f8b7ea65f7705fc342a178508e2722eb851 | /data/seq/wseq.lean | 708ddf95abcb004ef5d0aea59c948e01f6b1cf39 | [
"Apache-2.0"
] | permissive | rwbarton/mathlib | 939ae09bf8d6eb1331fc2f7e067d39567e10e33d | c13c5ea701bb1eec057e0a242d9f480a079105e9 | refs/heads/master | 1,584,015,335,862 | 1,524,142,167,000 | 1,524,142,167,000 | 130,614,171 | 0 | 0 | Apache-2.0 | 1,548,902,667,000 | 1,524,437,371,000 | Lean | UTF-8 | Lean | false | false | 55,267 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
import data.seq.seq data.seq.computation data.list.basic data.dlist
universes u v w
/-
coinductive wseq (α : Type u) : Type u
| nil : wseq α
| cons : α → wseq α → wseq α
| think : wseq α → wseq α
-/
/-- Weak sequences.
While the `seq` structure allows for lists which may not be finite,
a weak sequence also allows the computation of each element to
involve an indeterminate amount of computation, including possibly
an infinite loop. This is represented as a regular `seq` interspersed
with `none` elements to indicate that computation is ongoing.
This model is appropriate for Haskell style lazy lists, and is closed
under most interesting computation patterns on infinite lists,
but conversely it is difficult to extract elements from it. -/
def wseq (α) := seq (option α)
namespace wseq
variables {α : Type u} {β : Type v} {γ : Type w}
/-- Turn a sequence into a weak sequence -/
def of_seq : seq α → wseq α := (<$>) some
/-- Turn a list into a weak sequence -/
def of_list (l : list α) : wseq α := of_seq l
/-- Turn a stream into a weak sequence -/
def of_stream (l : stream α) : wseq α := of_seq l
instance coe_seq : has_coe (seq α) (wseq α) := ⟨of_seq⟩
instance coe_list : has_coe (list α) (wseq α) := ⟨of_list⟩
instance coe_stream : has_coe (stream α) (wseq α) := ⟨of_stream⟩
/-- The empty weak sequence -/
def nil : wseq α := seq.nil
/-- Prepend an element to a weak sequence -/
def cons (a : α) : wseq α → wseq α := seq.cons (some a)
/-- Compute for one tick, without producing any elements -/
def think : wseq α → wseq α := seq.cons none
/-- Destruct a weak sequence, to (eventually possibly) produce either
`none` for `nil` or `some (a, s)` if an element is produced. -/
def destruct : wseq α → computation (option (α × wseq α)) :=
computation.corec (λs, match seq.destruct s with
| none := sum.inl none
| some (none, s') := sum.inr s'
| some (some a, s') := sum.inl (some (a, s'))
end)
def cases_on {C : wseq α → Sort v} (s : wseq α) (h1 : C nil)
(h2 : ∀ x s, C (cons x s)) (h3 : ∀ s, C (think s)) : C s :=
seq.cases_on s h1 (λ o, option.cases_on o h3 h2)
protected def mem (a : α) (s : wseq α) := seq.mem (some a) s
instance : has_mem α (wseq α) :=
⟨wseq.mem⟩
theorem not_mem_nil (a : α) : a ∉ @nil α := seq.not_mem_nil a
/-- Get the head of a weak sequence. This involves a possibly
infinite computation. -/
def head (s : wseq α) : computation (option α) :=
computation.map ((<$>) prod.fst) (destruct s)
/-- Encode a computation yielding a weak sequence into additional
`think` constructors in a weak sequence -/
def flatten : computation (wseq α) → wseq α :=
seq.corec (λc, match computation.destruct c with
| sum.inl s := seq.omap return (seq.destruct s)
| sum.inr c' := some (none, c')
end)
/-- Get the tail of a weak sequence. This doesn't need a `computation`
wrapper, unlike `head`, because `flatten` allows us to hide this
in the construction of the weak sequence itself. -/
def tail (s : wseq α) : wseq α :=
flatten $ (λo, option.rec_on o nil prod.snd) <$> destruct s
/-- drop the first `n` elements from `s`. -/
def drop (s : wseq α) : ℕ → wseq α
| 0 := s
| (n+1) := tail (drop n)
attribute [simp] drop
/-- Get the nth element of `s`. -/
def nth (s : wseq α) (n : ℕ) : computation (option α) := head (drop s n)
/-- Convert `s` to a list (if it is finite and completes in finite time). -/
def to_list (s : wseq α) : computation (list α) :=
@computation.corec (list α) (list α × wseq α) (λ⟨l, s⟩,
match seq.destruct s with
| none := sum.inl l.reverse
| some (none, s') := sum.inr (l, s')
| some (some a, s') := sum.inr (a::l, s')
end) ([], s)
/-- Get the length of `s` (if it is finite and completes in finite time). -/
def length (s : wseq α) : computation ℕ :=
@computation.corec ℕ (ℕ × wseq α) (λ⟨n, s⟩,
match seq.destruct s with
| none := sum.inl n
| some (none, s') := sum.inr (n, s')
| some (some a, s') := sum.inr (n+1, s')
end) (0, s)
/-- A weak sequence is finite if `to_list s` terminates. Equivalently,
it is a finite number of `think` and `cons` applied to `nil`. -/
@[class] def is_finite (s : wseq α) : Prop := (to_list s).terminates
instance to_list_terminates (s : wseq α) [h : is_finite s] : (to_list s).terminates := h
/-- Get the list corresponding to a finite weak sequence. -/
def get (s : wseq α) [is_finite s] : list α := (to_list s).get
/-- A weak sequence is *productive* if it never stalls forever - there are
always a finite number of `think`s between `cons` constructors.
The sequence itself is allowed to be infinite though. -/
@[class] def productive (s : wseq α) : Prop := ∀ n, (nth s n).terminates
instance nth_terminates (s : wseq α) [h : productive s] : ∀ n, (nth s n).terminates := h
instance head_terminates (s : wseq α) [h : productive s] : (head s).terminates := h 0
/-- Replace the `n`th element of `s` with `a`. -/
def update_nth (s : wseq α) (n : ℕ) (a : α) : wseq α :=
@seq.corec (option α) (ℕ × wseq α) (λ⟨n, s⟩,
match seq.destruct s, n with
| none, n := none
| some (none, s'), n := some (none, n, s')
| some (some a', s'), 0 := some (some a', 0, s')
| some (some a', s'), 1 := some (some a, 0, s')
| some (some a', s'), (n+2) := some (some a', n+1, s')
end) (n+1, s)
/-- Remove the `n`th element of `s`. -/
def remove_nth (s : wseq α) (n : ℕ) : wseq α :=
@seq.corec (option α) (ℕ × wseq α) (λ⟨n, s⟩,
match seq.destruct s, n with
| none, n := none
| some (none, s'), n := some (none, n, s')
| some (some a', s'), 0 := some (some a', 0, s')
| some (some a', s'), 1 := some (none, 0, s')
| some (some a', s'), (n+2) := some (some a', n+1, s')
end) (n+1, s)
/-- Map the elements of `s` over `f`, removing any values that yield `none`. -/
def filter_map (f : α → option β) : wseq α → wseq β :=
seq.corec (λs, match seq.destruct s with
| none := none
| some (none, s') := some (none, s')
| some (some a, s') := some (f a, s')
end)
/-- Select the elements of `s` that satisfy `p`. -/
def filter (p : α → Prop) [decidable_pred p] : wseq α → wseq α :=
filter_map (λa, if p a then some a else none)
-- example of infinite list manipulations
/-- Get the first element of `s` satisfying `p`. -/
def find (p : α → Prop) [decidable_pred p] (s : wseq α) : computation (option α) :=
head $ filter p s
/-- Zip a function over two weak sequences -/
def zip_with (f : α → β → γ) (s1 : wseq α) (s2 : wseq β) : wseq γ :=
@seq.corec (option γ) (wseq α × wseq β) (λ⟨s1, s2⟩,
match seq.destruct s1, seq.destruct s2 with
| some (none, s1'), some (none, s2') := some (none, s1', s2')
| some (some a1, s1'), some (none, s2') := some (none, s1, s2')
| some (none, s1'), some (some a2, s2') := some (none, s1', s2)
| some (some a1, s1'), some (some a2, s2') := some (some (f a1 a2), s1', s2')
| _, _ := none
end) (s1, s2)
/-- Zip two weak sequences into a single sequence of pairs -/
def zip : wseq α → wseq β → wseq (α × β) := zip_with prod.mk
/-- Get the list of indexes of elements of `s` satisfying `p` -/
def find_indexes (p : α → Prop) [decidable_pred p] (s : wseq α) : wseq ℕ :=
(zip s (stream.nats : wseq ℕ)).filter_map
(λ ⟨a, n⟩, if p a then some n else none)
/-- Get the index of the first element of `s` satisfying `p` -/
def find_index (p : α → Prop) [decidable_pred p] (s : wseq α) : computation ℕ :=
(λ o, option.get_or_else o 0) <$> head (find_indexes p s)
/-- Get the index of the first occurrence of `a` in `s` -/
def index_of [decidable_eq α] (a : α) : wseq α → computation ℕ := find_index (eq a)
/-- Get the indexes of occurrences of `a` in `s` -/
def indexes_of [decidable_eq α] (a : α) : wseq α → wseq ℕ := find_indexes (eq a)
/-- `union s1 s2` is a weak sequence which interleaves `s1` and `s2` in
some order (nondeterministically). -/
def union (s1 s2 : wseq α) : wseq α :=
@seq.corec (option α) (wseq α × wseq α) (λ⟨s1, s2⟩,
match seq.destruct s1, seq.destruct s2 with
| none, none := none
| some (a1, s1'), none := some (a1, s1', nil)
| none, some (a2, s2') := some (a2, nil, s2')
| some (none, s1'), some (none, s2') := some (none, s1', s2')
| some (some a1, s1'), some (none, s2') := some (some a1, s1', s2')
| some (none, s1'), some (some a2, s2') := some (some a2, s1', s2')
| some (some a1, s1'), some (some a2, s2') := some (some a1, cons a2 s1', s2')
end) (s1, s2)
/-- Returns `tt` if `s` is `nil` and `ff` if `s` has an element -/
def is_empty (s : wseq α) : computation bool :=
computation.map option.is_none $ head s
/-- Calculate one step of computation -/
def compute (s : wseq α) : wseq α :=
match seq.destruct s with
| some (none, s') := s'
| _ := s
end
/-- Get the first `n` elements of a weak sequence -/
def take (s : wseq α) (n : ℕ) : wseq α :=
@seq.corec (option α) (ℕ × wseq α) (λ⟨n, s⟩,
match n, seq.destruct s with
| 0, _ := none
| m+1, none := none
| m+1, some (none, s') := some (none, m+1, s')
| m+1, some (some a, s') := some (some a, m, s')
end) (n, s)
/-- Split the sequence at position `n` into a finite initial segment
and the weak sequence tail -/
def split_at (s : wseq α) (n : ℕ) : computation (list α × wseq α) :=
@computation.corec (list α × wseq α) (ℕ × list α × wseq α) (λ⟨n, l, s⟩,
match n, seq.destruct s with
| 0, _ := sum.inl (l.reverse, s)
| m+1, none := sum.inl (l.reverse, s)
| m+1, some (none, s') := sum.inr (n, l, s')
| m+1, some (some a, s') := sum.inr (m, a::l, s')
end) (n, [], s)
/-- Returns `tt` if any element of `s` satisfies `p` -/
def any (s : wseq α) (p : α → bool) : computation bool :=
computation.corec (λs : wseq α,
match seq.destruct s with
| none := sum.inl ff
| some (none, s') := sum.inr s'
| some (some a, s') := if p a then sum.inl tt else sum.inr s'
end) s
/-- Returns `tt` if every element of `s` satisfies `p` -/
def all (s : wseq α) (p : α → bool) : computation bool :=
computation.corec (λs : wseq α,
match seq.destruct s with
| none := sum.inl tt
| some (none, s') := sum.inr s'
| some (some a, s') := if p a then sum.inr s' else sum.inl ff
end) s
/-- Apply a function to the elements of the sequence to produce a sequence
of partial results. (There is no `scanr` because this would require
working from the end of the sequence, which may not exist.) -/
def scanl (f : α → β → α) (a : α) (s : wseq β) : wseq α :=
cons a $ @seq.corec (option α) (α × wseq β) (λ⟨a, s⟩,
match seq.destruct s with
| none := none
| some (none, s') := some (none, a, s')
| some (some b, s') := let a' := f a b in some (some a', a', s')
end) (a, s)
/-- Get the weak sequence of initial segments of the input sequence -/
def inits (s : wseq α) : wseq (list α) :=
cons [] $ @seq.corec (option (list α)) (dlist α × wseq α) (λ ⟨l, s⟩,
match seq.destruct s with
| none := none
| some (none, s') := some (none, l, s')
| some (some a, s') := let l' := l.concat a in
some (some l'.to_list, l', s')
end) (dlist.empty, s)
/-- Like take, but does not wait for a result. Calculates `n` steps of
computation and returns the sequence computed so far -/
def collect (s : wseq α) (n : ℕ) : list α :=
(seq.take n s).filter_map id
/-- Append two weak sequences. As with `seq.append`, this may not use
the second sequence if the first one takes forever to compute -/
def append : wseq α → wseq α → wseq α := seq.append
/-- Map a function over a weak sequence -/
def map (f : α → β) : wseq α → wseq β := seq.map (option.map f)
/-- Flatten a sequence of weak sequences. (Note that this allows
empty sequences, unlike `seq.join`.) -/
def join (S : wseq (wseq α)) : wseq α :=
seq.join ((λo : option (wseq α), match o with
| none := seq1.ret none
| some s := (none, s)
end) <$> S)
/-- Monadic bind operator for weak sequences -/
def bind (s : wseq α) (f : α → wseq β) : wseq β :=
join (map f s)
@[simp] def lift_rel_o (R : α → β → Prop) (C : wseq α → wseq β → Prop) :
option (α × wseq α) → option (β × wseq β) → Prop
| none none := true
| (some (a, s)) (some (b, t)) := R a b ∧ C s t
| _ _ := false
theorem lift_rel_o.imp {R S : α → β → Prop} {C D : wseq α → wseq β → Prop}
(H1 : ∀ a b, R a b → S a b) (H2 : ∀ s t, C s t → D s t) :
∀ {o p}, lift_rel_o R C o p → lift_rel_o S D o p
| none none h := trivial
| (some (a, s)) (some (b, t)) h := and.imp (H1 _ _) (H2 _ _) h
| none (some _) h := false.elim h
| (some (_, _)) none h := false.elim h
theorem lift_rel_o.imp_right (R : α → β → Prop) {C D : wseq α → wseq β → Prop}
(H : ∀ s t, C s t → D s t) {o p} : lift_rel_o R C o p → lift_rel_o R D o p :=
lift_rel_o.imp (λ _ _, id) H
@[simp] def bisim_o (R : wseq α → wseq α → Prop) :
option (α × wseq α) → option (α × wseq α) → Prop := lift_rel_o (=) R
theorem bisim_o.imp {R S : wseq α → wseq α → Prop} (H : ∀ s t, R s t → S s t) {o p} :
bisim_o R o p → bisim_o S o p :=
lift_rel_o.imp_right _ H
/-- Two weak sequences are `lift_rel R` related if they are either both empty,
or they are both nonempty and the heads are `R` related and the tails are
`lift_rel R` related. (This is a coinductive definition.) -/
def lift_rel (R : α → β → Prop) (s : wseq α) (t : wseq β) : Prop :=
∃ C : wseq α → wseq β → Prop, C s t ∧
∀ {s t}, C s t → computation.lift_rel (lift_rel_o R C) (destruct s) (destruct t)
/-- If two sequences are equivalent, then they have the same values and
the same computational behavior (i.e. if one loops forever then so does
the other), although they may differ in the number of `think`s needed to
arrive at the answer. -/
def equiv : wseq α → wseq α → Prop := lift_rel (=)
theorem lift_rel_destruct {R : α → β → Prop} {s : wseq α} {t : wseq β} :
lift_rel R s t →
computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t)
| ⟨R, h1, h2⟩ :=
by refine computation.lift_rel.imp _ _ _ (h2 h1);
apply lift_rel_o.imp_right; exact λ s' t' h', ⟨R, h', @h2⟩
theorem lift_rel_destruct_iff {R : α → β → Prop} {s : wseq α} {t : wseq β} :
lift_rel R s t ↔
computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t) :=
⟨lift_rel_destruct, λ h, ⟨λ s t, lift_rel R s t ∨
computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t),
or.inr h, λ s t h, begin
have h : computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t),
{ cases h with h h, exact lift_rel_destruct h, assumption },
apply computation.lift_rel.imp _ _ _ h,
intros a b, apply lift_rel_o.imp_right,
intros s t, apply or.inl
end⟩⟩
infix ~ := equiv
theorem destruct_congr {s t : wseq α} :
s ~ t → computation.lift_rel (bisim_o (~)) (destruct s) (destruct t) :=
lift_rel_destruct
theorem destruct_congr_iff {s t : wseq α} :
s ~ t ↔ computation.lift_rel (bisim_o (~)) (destruct s) (destruct t) :=
lift_rel_destruct_iff
theorem lift_rel.refl (R : α → α → Prop) (H : reflexive R) : reflexive (lift_rel R) :=
λ s, begin
refine ⟨(=), rfl, λ s t (h : s = t), _⟩,
rw ←h, apply computation.lift_rel.refl,
intro a, cases a with a, simp, cases a; simp, apply H
end
theorem lift_rel_o.swap (R : α → β → Prop) (C) :
function.swap (lift_rel_o R C) = lift_rel_o (function.swap R) (function.swap C) :=
by funext x y; cases x with x; [skip, cases x]; { cases y with y; [skip, cases y]; refl }
theorem lift_rel.swap_lem {R : α → β → Prop} {s1 s2} (h : lift_rel R s1 s2) :
lift_rel (function.swap R) s2 s1 :=
begin
refine ⟨function.swap (lift_rel R), h, λ s t (h : lift_rel R t s), _⟩,
rw [←lift_rel_o.swap, computation.lift_rel.swap],
apply lift_rel_destruct h
end
theorem lift_rel.swap (R : α → β → Prop) :
function.swap (lift_rel R) = lift_rel (function.swap R) :=
funext $ λ x, funext $ λ y, propext ⟨lift_rel.swap_lem, lift_rel.swap_lem⟩
theorem lift_rel.symm (R : α → α → Prop) (H : symmetric R) : symmetric (lift_rel R) :=
λ s1 s2 (h : function.swap (lift_rel R) s2 s1),
by rwa [lift_rel.swap, show function.swap R = R, from
funext $ λ a, funext $ λ b, propext $ by constructor; apply H] at h
theorem lift_rel.trans (R : α → α → Prop) (H : transitive R) : transitive (lift_rel R) :=
λ s t u h1 h2, begin
refine ⟨λ s u, ∃ t, lift_rel R s t ∧ lift_rel R t u, ⟨t, h1, h2⟩, λ s u h, _⟩,
cases h with t h, cases h with h1 h2,
have h1 := lift_rel_destruct h1,
have h2 := lift_rel_destruct h2,
refine computation.lift_rel_def.2
⟨(computation.terminates_of_lift_rel h1).trans
(computation.terminates_of_lift_rel h2), λ a c ha hc, _⟩,
cases h1.left ha with b hb, cases hb with hb t1,
have t2 := computation.rel_of_lift_rel h2 hb hc,
cases a with a; cases c with c,
{ trivial },
{ cases b, {cases t2}, {cases t1} },
{ cases a, cases b with b, {cases t1}, {cases b, cases t2} },
{ cases a with a s, cases b with b, {cases t1},
cases b with b t, cases c with c u,
cases t1 with ab st, cases t2 with bc tu,
exact ⟨H ab bc, t, st, tu⟩ }
end
theorem lift_rel.equiv (R : α → α → Prop) : equivalence R → equivalence (lift_rel R)
| ⟨refl, symm, trans⟩ :=
⟨lift_rel.refl R refl, lift_rel.symm R symm, lift_rel.trans R trans⟩
@[refl] theorem equiv.refl : ∀ (s : wseq α), s ~ s :=
lift_rel.refl (=) eq.refl
@[symm] theorem equiv.symm : ∀ {s t : wseq α}, s ~ t → t ~ s :=
lift_rel.symm (=) (@eq.symm _)
@[trans] theorem equiv.trans : ∀ {s t u : wseq α}, s ~ t → t ~ u → s ~ u :=
lift_rel.trans (=) (@eq.trans _)
theorem equiv.equivalence : equivalence (@equiv α) :=
⟨@equiv.refl _, @equiv.symm _, @equiv.trans _⟩
open computation
local notation `return` := computation.return
@[simp] theorem destruct_nil : destruct (nil : wseq α) = return none :=
computation.destruct_eq_ret rfl
@[simp] theorem destruct_cons (a : α) (s) : destruct (cons a s) = return (some (a, s)) :=
computation.destruct_eq_ret $ by simp [destruct, cons, computation.rmap]
@[simp] theorem destruct_think (s : wseq α) : destruct (think s) = (destruct s).think :=
computation.destruct_eq_think $ by simp [destruct, think, computation.rmap]
@[simp] theorem seq_destruct_nil : seq.destruct (nil : wseq α) = none :=
seq.destruct_nil
@[simp] theorem seq_destruct_cons (a : α) (s) : seq.destruct (cons a s) = some (some a, s) :=
seq.destruct_cons _ _
@[simp] theorem seq_destruct_think (s : wseq α) : seq.destruct (think s) = some (none, s) :=
seq.destruct_cons _ _
@[simp] theorem head_nil : head (nil : wseq α) = return none := by simp [head]; refl
@[simp] theorem head_cons (a : α) (s) : head (cons a s) = return (some a) := by simp [head]; refl
@[simp] theorem head_think (s : wseq α) : head (think s) = (head s).think := by simp [head]; refl
@[simp] theorem flatten_ret (s : wseq α) : flatten (return s) = s :=
begin
refine seq.eq_of_bisim (λs1 s2, flatten (return s2) = s1) _ rfl,
intros s' s h, rw ←h, simp [flatten],
cases seq.destruct s, { simp },
{ cases val with o s', simp }
end
@[simp] theorem flatten_think (c : computation (wseq α)) : flatten c.think = think (flatten c) :=
seq.destruct_eq_cons $ by simp [flatten, think]
@[simp] theorem destruct_flatten (c : computation (wseq α)) : destruct (flatten c) = c >>= destruct :=
begin
refine computation.eq_of_bisim (λc1 c2, c1 = c2 ∨
∃ c, c1 = destruct (flatten c) ∧ c2 = computation.bind c destruct) _ (or.inr ⟨c, rfl, rfl⟩),
intros c1 c2 h, exact match c1, c2, h with
| _, _, (or.inl $ eq.refl c) := by cases c.destruct; simp
| _, _, (or.inr ⟨c, rfl, rfl⟩) := begin
apply c.cases_on (λa, _) (λc', _); repeat {simp},
{ cases (destruct a).destruct; simp },
{ exact or.inr ⟨c', rfl, rfl⟩ }
end end
end
theorem head_terminates_iff (s : wseq α) : terminates (head s) ↔ terminates (destruct s) :=
terminates_map_iff _ (destruct s)
@[simp] theorem tail_nil : tail (nil : wseq α) = nil := by simp [tail]
@[simp] theorem tail_cons (a : α) (s) : tail (cons a s) = s := by simp [tail]
@[simp] theorem tail_think (s : wseq α) : tail (think s) = (tail s).think := by simp [tail]
@[simp] theorem dropn_nil (n) :
drop (nil : wseq α) n = nil := by induction n; simp [*, drop]
@[simp] theorem dropn_cons (a : α) (s) (n) :
drop (cons a s) (n+1) = drop s n := by induction n; simp [*, drop]
@[simp] theorem dropn_think (s : wseq α) (n) :
drop (think s) n = (drop s n).think := by induction n; simp [*, drop]
theorem dropn_add (s : wseq α) (m) : ∀ n, drop s (m + n) = drop (drop s m) n
| 0 := rfl
| (n+1) := congr_arg tail (dropn_add n)
theorem dropn_tail (s : wseq α) (n) : drop (tail s) n = drop s (n + 1) :=
by rw add_comm; symmetry; apply dropn_add
theorem nth_add (s : wseq α) (m n) : nth s (m + n) = nth (drop s m) n :=
congr_arg head (dropn_add _ _ _)
theorem nth_tail (s : wseq α) (n) : nth (tail s) n = nth s (n + 1) :=
congr_arg head (dropn_tail _ _)
@[simp] theorem join_nil : join nil = (nil : wseq α) := seq.join_nil
@[simp] theorem join_think (S : wseq (wseq α)) :
join (think S) = think (join S) :=
by { simp [think, join], unfold functor.map, simp [join, seq1.ret] }
@[simp] theorem join_cons (s : wseq α) (S) :
join (cons s S) = think (append s (join S)) :=
by { simp [think, join], unfold functor.map, simp [join, cons, append] }
@[simp] theorem nil_append (s : wseq α) : append nil s = s := seq.nil_append _
@[simp] theorem cons_append (a : α) (s t) :
append (cons a s) t = cons a (append s t) := seq.cons_append _ _ _
@[simp] theorem think_append (s t : wseq α) :
append (think s) t = think (append s t) := seq.cons_append _ _ _
@[simp] theorem append_nil (s : wseq α) : append s nil = s := seq.append_nil _
@[simp] theorem append_assoc (s t u : wseq α) :
append (append s t) u = append s (append t u) := seq.append_assoc _ _ _
@[simp] def tail.aux : option (α × wseq α) → computation (option (α × wseq α))
| none := return none
| (some (a, s)) := destruct s
theorem destruct_tail (s : wseq α) :
destruct (tail s) = destruct s >>= tail.aux :=
begin
dsimp [tail], simp, rw [← bind_pure_comp_eq_map, is_lawful_monad.bind_assoc],
apply congr_arg, funext o,
rcases o with _|⟨a, s⟩;
apply (@pure_bind computation _ _ _ _ _ _).trans _; simp
end
@[simp] def drop.aux : ℕ → option (α × wseq α) → computation (option (α × wseq α))
| 0 := return
| (n+1) := λ a, tail.aux a >>= drop.aux n
theorem drop.aux_none : ∀ n, @drop.aux α n none = return none
| 0 := rfl
| (n+1) := show computation.bind (return none) (drop.aux n) = return none,
by rw [ret_bind, drop.aux_none]
theorem destruct_dropn :
∀ (s : wseq α) n, destruct (drop s n) = destruct s >>= drop.aux n
| s 0 := (bind_ret' _).symm
| s (n+1) := by rw [← dropn_tail, destruct_dropn _ n,
destruct_tail, is_lawful_monad.bind_assoc]; refl
theorem head_terminates_of_head_tail_terminates (s : wseq α) [T : terminates (head (tail s))] :
terminates (head s) :=
(head_terminates_iff _).2 $ begin
cases (head_terminates_iff _).1 T with a h,
simp [tail] at h,
cases exists_of_mem_bind h with s' h1, cases h1 with h1 h2,
unfold functor.map at h1,
exact let ⟨t, h3, h4⟩ := exists_of_mem_map h1 in terminates_of_mem h3
end
theorem destruct_some_of_destruct_tail_some {s : wseq α} {a}
(h : some a ∈ destruct (tail s)) : ∃ a', some a' ∈ destruct s :=
begin
unfold tail functor.map at h, simp at h,
cases exists_of_mem_bind h with t ht, cases ht with tm td, clear h,
cases exists_of_mem_map tm with t' ht', cases ht' with ht' ht2, clear tm,
cases t' with t'; rw ←ht2 at td; simp at td,
{ have := mem_unique td (ret_mem _), contradiction },
{ exact ⟨_, ht'⟩ }
end
theorem head_some_of_head_tail_some {s : wseq α} {a}
(h : some a ∈ head (tail s)) : ∃ a', some a' ∈ head s :=
begin
unfold head at h,
cases exists_of_mem_map h with o ho, cases ho with md e, clear h,
cases o with o; injection e with h', clear e h',
cases destruct_some_of_destruct_tail_some md with a am,
exact ⟨_, mem_map ((<$>) (@prod.fst α (wseq α))) am⟩
end
theorem head_some_of_nth_some {s : wseq α} {a n}
(h : some a ∈ nth s n) : ∃ a', some a' ∈ head s :=
begin
revert a, induction n with n IH; intros,
exacts [⟨_, h⟩, let ⟨a', h'⟩ := head_some_of_head_tail_some h in IH h']
end
instance productive_tail (s : wseq α) [productive s] : productive (tail s) :=
λ n, by rw [nth_tail]; apply_instance
instance productive_dropn (s : wseq α) [productive s] (n) : productive (drop s n) :=
λ m, by rw [←nth_add]; apply_instance
/-- Given a productive weak sequence, we can collapse all the `think`s to
produce a sequence. -/
def to_seq (s : wseq α) [productive s] : seq α :=
⟨λ n, (nth s n).get, λn h,
begin
induction e : computation.get (nth s (n + 1)), {trivial},
have := mem_of_get_eq _ e,
simp [nth] at this h, cases head_some_of_head_tail_some this with a' h',
have := mem_unique h' (@mem_of_get_eq _ _ _ _ h),
contradiction
end⟩
theorem nth_terminates_le {s : wseq α} {m n} (h : m ≤ n) : terminates (nth s n) → terminates (nth s m) :=
by induction h with m' h IH; [exact id,
exact λ T, IH (@head_terminates_of_head_tail_terminates _ _ T)]
theorem head_terminates_of_nth_terminates {s : wseq α} {n} : terminates (nth s n) → terminates (head s) :=
nth_terminates_le (nat.zero_le n)
theorem destruct_terminates_of_nth_terminates {s : wseq α} {n} (T : terminates (nth s n)) : terminates (destruct s) :=
(head_terminates_iff _).1 $ head_terminates_of_nth_terminates T
theorem mem_rec_on {C : wseq α → Prop} {a s} (M : a ∈ s)
(h1 : ∀ b s', (a = b ∨ C s') → C (cons b s'))
(h2 : ∀ s, C s → C (think s)) : C s :=
begin
apply seq.mem_rec_on M,
intros o s' h, cases o with b,
{ apply h2, cases h, {contradiction}, {assumption} },
{ apply h1, apply or.imp_left _ h, intro h, injection h }
end
@[simp] theorem mem_think (s : wseq α) (a) : a ∈ think s ↔ a ∈ s :=
begin
cases s with f al,
change some (some a) ∈ some none :: f ↔ some (some a) ∈ f,
constructor; intro h,
{ apply (stream.eq_or_mem_of_mem_cons h).resolve_left,
intro, injections },
{ apply stream.mem_cons_of_mem _ h }
end
theorem eq_or_mem_iff_mem {s : wseq α} {a a' s'} :
some (a', s') ∈ destruct s → (a ∈ s ↔ a = a' ∨ a ∈ s') :=
begin
generalize e : destruct s = c, intro h,
revert s, apply computation.mem_rec_on h _ (λ c IH, _); intro s;
apply s.cases_on _ (λ x s, _) (λ s, _); intros m;
have := congr_arg computation.destruct m; simp at this;
cases this with i1 i2,
{ rw [i1, i2],
cases s' with f al,
unfold cons has_mem.mem wseq.mem seq.mem seq.cons, simp,
have h_a_eq_a' : a = a' ↔ some (some a) = some (some a'), {simp},
rw [h_a_eq_a'],
refine ⟨stream.eq_or_mem_of_mem_cons, λo, _⟩,
{ cases o with e m,
{ rw e, apply stream.mem_cons },
{ exact stream.mem_cons_of_mem _ m } } },
{ simp, exact IH this }
end
@[simp] theorem mem_cons_iff (s : wseq α) (b) {a} : a ∈ cons b s ↔ a = b ∨ a ∈ s :=
eq_or_mem_iff_mem $ by simp [ret_mem]
theorem mem_cons_of_mem {s : wseq α} (b) {a} (h : a ∈ s) : a ∈ cons b s :=
(mem_cons_iff _ _).2 (or.inr h)
theorem mem_cons (s : wseq α) (a) : a ∈ cons a s :=
(mem_cons_iff _ _).2 (or.inl rfl)
theorem mem_of_mem_tail {s : wseq α} {a} : a ∈ tail s → a ∈ s :=
begin
intro h, have := h, cases h with n e, revert s, simp [stream.nth],
induction n with n IH; intro s; apply s.cases_on _ (λx s, _) (λ s, _);
repeat{simp}; intros m e; injections,
{ exact or.inr m },
{ exact or.inr m },
{ apply IH m, rw e, cases tail s, refl }
end
theorem mem_of_mem_dropn {s : wseq α} {a} : ∀ {n}, a ∈ drop s n → a ∈ s
| 0 h := h
| (n+1) h := @mem_of_mem_dropn n (mem_of_mem_tail h)
theorem nth_mem {s : wseq α} {a n} : some a ∈ nth s n → a ∈ s :=
begin
revert s, induction n with n IH; intros s h,
{ cases exists_of_mem_map h with o h, cases h with h1 h2,
cases o with o; injection h2 with h',
cases o with a' s',
exact (eq_or_mem_iff_mem h1).2 (or.inl h'.symm) },
{ have := @IH (tail s), rw nth_tail at this,
exact mem_of_mem_tail (this h) }
end
theorem exists_nth_of_mem {s : wseq α} {a} (h : a ∈ s) : ∃ n, some a ∈ nth s n :=
begin
apply mem_rec_on h,
{ intros a' s' h, cases h with h h,
{ existsi 0, simp [nth], rw h, apply ret_mem },
{ cases h with n h, existsi n+1,
simp [nth], exact h } },
{ intros s' h, cases h with n h,
existsi n, simp [nth], apply think_mem h }
end
theorem exists_dropn_of_mem {s : wseq α} {a} (h : a ∈ s) :
∃ n s', some (a, s') ∈ destruct (drop s n) :=
let ⟨n, h⟩ := exists_nth_of_mem h in ⟨n, begin
cases (head_terminates_iff _).1 ⟨_, h⟩ with o om,
have := mem_unique (mem_map _ om) h,
cases o with o; injection this with i,
cases o with a' s', dsimp at i,
rw i at om, exact ⟨_, om⟩
end⟩
theorem lift_rel_dropn_destruct {R : α → β → Prop} {s t} (H : lift_rel R s t) :
∀ n, computation.lift_rel (lift_rel_o R (lift_rel R))
(destruct (drop s n)) (destruct (drop t n))
| 0 := lift_rel_destruct H
| (n+1) := begin
simp [destruct_tail],
apply lift_rel_bind,
apply lift_rel_dropn_destruct n,
exact λ a b o, match a, b, o with
| none, none, _ := by simp
| some (a, s), some (b, t), ⟨h1, h2⟩ := by simp [tail.aux]; apply lift_rel_destruct h2
end
end
theorem exists_of_lift_rel_left {R : α → β → Prop} {s t}
(H : lift_rel R s t) {a} (h : a ∈ s) : ∃ {b}, b ∈ t ∧ R a b :=
let ⟨n, h⟩ := exists_nth_of_mem h,
⟨some (._, s'), sd, rfl⟩ := exists_of_mem_map h,
⟨some (b, t'), td, ⟨ab, _⟩⟩ := (lift_rel_dropn_destruct H n).left sd in
⟨b, nth_mem (mem_map ((<$>) prod.fst.{v v}) td), ab⟩
theorem exists_of_lift_rel_right {R : α → β → Prop} {s t}
(H : lift_rel R s t) {b} (h : b ∈ t) : ∃ {a}, a ∈ s ∧ R a b :=
by rw ←lift_rel.swap at H; exact exists_of_lift_rel_left H h
theorem head_terminates_of_mem {s : wseq α} {a} (h : a ∈ s) : terminates (head s) :=
let ⟨n, h⟩ := exists_nth_of_mem h in head_terminates_of_nth_terminates ⟨_, h⟩
theorem of_mem_append {s₁ s₂ : wseq α} {a : α} : a ∈ append s₁ s₂ → a ∈ s₁ ∨ a ∈ s₂ :=
seq.of_mem_append
theorem mem_append_left {s₁ s₂ : wseq α} {a : α} : a ∈ s₁ → a ∈ append s₁ s₂ :=
seq.mem_append_left
theorem exists_of_mem_map {f} {b : β} : ∀ {s : wseq α}, b ∈ map f s → ∃ a, a ∈ s ∧ f a = b
| ⟨g, al⟩ h := let ⟨o, om, oe⟩ := seq.exists_of_mem_map h in
by cases o with a; injection oe with h'; exact ⟨a, om, h'⟩
@[simp] theorem lift_rel_nil (R : α → β → Prop) : lift_rel R nil nil :=
by rw [lift_rel_destruct_iff]; simp
@[simp] theorem lift_rel_cons (R : α → β → Prop) (a b s t) :
lift_rel R (cons a s) (cons b t) ↔ R a b ∧ lift_rel R s t :=
by rw [lift_rel_destruct_iff]; simp
@[simp] theorem lift_rel_think_left (R : α → β → Prop) (s t) :
lift_rel R (think s) t ↔ lift_rel R s t :=
by rw [lift_rel_destruct_iff, lift_rel_destruct_iff]; simp
@[simp] theorem lift_rel_think_right (R : α → β → Prop) (s t) :
lift_rel R s (think t) ↔ lift_rel R s t :=
by rw [lift_rel_destruct_iff, lift_rel_destruct_iff]; simp
theorem cons_congr {s t : wseq α} (a : α) (h : s ~ t) : cons a s ~ cons a t :=
by unfold equiv; simp; exact h
theorem think_equiv (s : wseq α) : think s ~ s :=
by unfold equiv; simp; apply equiv.refl
theorem think_congr {s t : wseq α} (a : α) (h : s ~ t) : think s ~ think t :=
by unfold equiv; simp; exact h
theorem head_congr : ∀ {s t : wseq α}, s ~ t → head s ~ head t :=
suffices ∀ {s t : wseq α}, s ~ t → ∀ {o}, o ∈ head s → o ∈ head t, from
λ s t h o, ⟨this h, this h.symm⟩,
begin
intros s t h o ho,
cases @computation.exists_of_mem_map _ _ _ _ (destruct s) ho with ds dsm,
cases dsm with dsm dse, rw ←dse,
cases destruct_congr h with l r,
cases l dsm with dt dtm, cases dtm with dtm dst,
cases ds with a; cases dt with b,
{ apply mem_map _ dtm },
{ cases b, cases dst },
{ cases a, cases dst },
{ cases a with a s', cases b with b t', rw dst.left,
exact @mem_map _ _ (@functor.map _ _ (α × wseq α) _ prod.fst)
_ (destruct t) dtm }
end
theorem flatten_equiv {c : computation (wseq α)} {s} (h : s ∈ c) : flatten c ~ s :=
begin
apply computation.mem_rec_on h, { simp },
{ intro s', apply equiv.trans, simp [think_equiv] }
end
theorem lift_rel_flatten {R : α → β → Prop} {c1 : computation (wseq α)} {c2 : computation (wseq β)}
(h : c1.lift_rel (lift_rel R) c2) : lift_rel R (flatten c1) (flatten c2) :=
let S := λ s t,
∃ c1 c2, s = flatten c1 ∧ t = flatten c2 ∧ computation.lift_rel (lift_rel R) c1 c2 in
⟨S, ⟨c1, c2, rfl, rfl, h⟩, λ s t h,
match s, t, h with ._, ._, ⟨c1, c2, rfl, rfl, h⟩ := begin
simp, apply lift_rel_bind _ _ h,
intros a b ab, apply computation.lift_rel.imp _ _ _ (lift_rel_destruct ab),
intros a b, apply lift_rel_o.imp_right,
intros s t h, refine ⟨return s, return t, _, _, _⟩; simp [h]
end end⟩
theorem flatten_congr {c1 c2 : computation (wseq α)} :
computation.lift_rel equiv c1 c2 → flatten c1 ~ flatten c2 := lift_rel_flatten
theorem tail_congr {s t : wseq α} (h : s ~ t) : tail s ~ tail t :=
begin
apply flatten_congr,
unfold functor.map, rw [←bind_ret, ←bind_ret],
apply lift_rel_bind _ _ (destruct_congr h),
intros a b h, simp,
cases a with a; cases b with b,
{ trivial },
{ cases h },
{ cases a, cases h },
{ cases a with a s', cases b with b t', exact h.right }
end
theorem dropn_congr {s t : wseq α} (h : s ~ t) (n) : drop s n ~ drop t n :=
by induction n; simp [*, tail_congr]
theorem nth_congr {s t : wseq α} (h : s ~ t) (n) : nth s n ~ nth t n :=
head_congr (dropn_congr h _)
theorem mem_congr {s t : wseq α} (h : s ~ t) (a) : a ∈ s ↔ a ∈ t :=
suffices ∀ {s t : wseq α}, s ~ t → a ∈ s → a ∈ t, from ⟨this h, this h.symm⟩,
λ s t h as, let ⟨n, hn⟩ := exists_nth_of_mem as in
nth_mem ((nth_congr h _ _).1 hn)
theorem productive_congr {s t : wseq α} (h : s ~ t) : productive s ↔ productive t :=
forall_congr $ λn, terminates_congr $ nth_congr h _
theorem equiv.ext {s t : wseq α} (h : ∀ n, nth s n ~ nth t n) : s ~ t :=
⟨λ s t, ∀ n, nth s n ~ nth t n, h, λs t h, begin
refine lift_rel_def.2 ⟨_, _⟩,
{ rw [←head_terminates_iff, ←head_terminates_iff],
exact terminates_congr (h 0) },
{ intros a b ma mb,
cases a with a; cases b with b,
{ trivial },
{ injection mem_unique (mem_map _ ma) ((h 0 _).2 (mem_map _ mb)) },
{ injection mem_unique (mem_map _ ma) ((h 0 _).2 (mem_map _ mb)) },
{ cases a with a s', cases b with b t',
injection mem_unique (mem_map _ ma) ((h 0 _).2 (mem_map _ mb)) with ab,
refine ⟨ab, λ n, _⟩,
refine (nth_congr (flatten_equiv (mem_map _ ma)) n).symm.trans
((_ : nth (tail s) n ~ nth (tail t) n).trans
(nth_congr (flatten_equiv (mem_map _ mb)) n)),
rw [nth_tail, nth_tail], apply h } }
end⟩
theorem length_eq_map (s : wseq α) : length s = computation.map list.length (to_list s) :=
begin
refine eq_of_bisim
(λ c1 c2, ∃ (l : list α) (s : wseq α),
c1 = corec length._match_2 (l.length, s) ∧
c2 = computation.map list.length (corec to_list._match_2 (l, s)))
_ ⟨[], s, rfl, rfl⟩,
intros s1 s2 h, cases h with l h, cases h with s h, rw [h.left, h.right],
apply s.cases_on _ (λ a s, _) (λ s, _);
repeat {simp [to_list, nil, cons, think, length]},
{ refine ⟨a::l, s, _, _⟩; simp },
{ refine ⟨l, s, _, _⟩; simp }
end
@[simp] theorem of_list_nil : of_list [] = (nil : wseq α) := rfl
@[simp] theorem of_list_cons (a : α) (l) :
of_list (a :: l) = cons a (of_list l) :=
show seq.map some (seq.of_list (a :: l)) =
seq.cons (some a) (seq.map some (seq.of_list l)), by simp
@[simp] theorem to_list'_nil (l : list α) :
corec to_list._match_2 (l, nil) = return l.reverse :=
destruct_eq_ret rfl
@[simp] theorem to_list'_cons (l : list α) (s : wseq α) (a : α) :
corec to_list._match_2 (l, cons a s) =
(corec to_list._match_2 (a::l, s)).think :=
destruct_eq_think $ by simp [to_list, cons]
@[simp] theorem to_list'_think (l : list α) (s : wseq α) :
corec to_list._match_2 (l, think s) =
(corec to_list._match_2 (l, s)).think :=
destruct_eq_think $ by simp [to_list, think]
theorem to_list'_map (l : list α) (s : wseq α) :
corec to_list._match_2 (l, s) =
((++) l.reverse) <$> to_list s :=
begin
refine eq_of_bisim
(λ c1 c2, ∃ (l' : list α) (s : wseq α),
c1 = corec to_list._match_2 (l' ++ l, s) ∧
c2 = computation.map ((++) l.reverse) (corec to_list._match_2 (l', s)))
_ ⟨[], s, rfl, rfl⟩,
intros s1 s2 h, cases h with l' h, cases h with s h, rw [h.left, h.right],
apply s.cases_on _ (λ a s, _) (λ s, _);
repeat {simp [to_list, nil, cons, think, length]},
{ refine ⟨a::l', s, _, _⟩; simp },
{ refine ⟨l', s, _, _⟩; simp }
end
@[simp] theorem to_list_cons (a : α) (s) :
to_list (cons a s) = (list.cons a <$> to_list s).think :=
destruct_eq_think $ by unfold to_list; simp; rw to_list'_map; simp; refl
@[simp] theorem to_list_nil : to_list (nil : wseq α) = return [] :=
destruct_eq_ret rfl
theorem to_list_of_list (l : list α) : l ∈ to_list (of_list l) :=
by induction l with a l IH; simp [ret_mem]; exact think_mem (mem_map _ IH)
@[simp] theorem destruct_of_seq (s : seq α) :
destruct (of_seq s) = return (s.head.map $ λ a, (a, of_seq s.tail)) :=
destruct_eq_ret $ begin
simp [of_seq, head, destruct, seq.destruct, seq.head],
rw [show seq.nth (some <$> s) 0 = some <$> seq.nth s 0, by apply seq.map_nth],
cases seq.nth s 0 with a, { refl },
unfold functor.map,
simp [option.map, option.bind, destruct]
end
@[simp] theorem head_of_seq (s : seq α) : head (of_seq s) = return s.head :=
by simp [head]; cases seq.head s; refl
@[simp] theorem tail_of_seq (s : seq α) : tail (of_seq s) = of_seq s.tail :=
begin
simp [tail], apply s.cases_on _ (λ x s, _); simp [of_seq], {refl},
rw [seq.head_cons, seq.tail_cons], refl
end
@[simp] theorem dropn_of_seq (s : seq α) : ∀ n, drop (of_seq s) n = of_seq (s.drop n)
| 0 := rfl
| (n+1) := by dsimp [drop]; rw [dropn_of_seq, tail_of_seq]
theorem nth_of_seq (s : seq α) (n) : nth (of_seq s) n = return (seq.nth s n) :=
by dsimp [nth]; rw [dropn_of_seq, head_of_seq, seq.head_dropn]
instance productive_of_seq (s : seq α) : productive (of_seq s) :=
λ n, by rw nth_of_seq; apply_instance
theorem to_seq_of_seq (s : seq α) : to_seq (of_seq s) = s :=
begin
apply subtype.eq, funext n,
dsimp [to_seq], apply get_eq_of_mem,
rw nth_of_seq, apply ret_mem
end
/-- The monadic `return a` is a singleton list containing `a`. -/
def ret (a : α) : wseq α := of_list [a]
@[simp] theorem map_nil (f : α → β) : map f nil = nil := rfl
@[simp] theorem map_cons (f : α → β) (a s) :
map f (cons a s) = cons (f a) (map f s) := seq.map_cons _ _ _
@[simp] theorem map_think (f : α → β) (s) :
map f (think s) = think (map f s) := seq.map_cons _ _ _
@[simp] theorem map_id (s : wseq α) : map id s = s := by simp [map]
@[simp] theorem map_ret (f : α → β) (a) : map f (ret a) = ret (f a) := by simp [ret]
@[simp] theorem map_append (f : α → β) (s t) : map f (append s t) = append (map f s) (map f t) :=
seq.map_append _ _ _
theorem map_comp (f : α → β) (g : β → γ) (s : wseq α) :
map (g ∘ f) s = map g (map f s) :=
begin
dsimp [map], rw ←seq.map_comp,
apply congr_fun, apply congr_arg,
funext o, cases o; refl
end
theorem mem_map (f : α → β) {a : α} {s : wseq α} : a ∈ s → f a ∈ map f s :=
seq.mem_map (option.map f)
-- The converse is not true without additional assumptions
theorem exists_of_mem_join {a : α} : ∀ {S : wseq (wseq α)}, a ∈ join S → ∃ s, s ∈ S ∧ a ∈ s :=
suffices ∀ ss : wseq α, a ∈ ss → ∀ s S, append s (join S) = ss →
a ∈ append s (join S) → a ∈ s ∨ ∃ s, s ∈ S ∧ a ∈ s, from λ S h,
(this _ h nil S (by simp) (by simp [h])).resolve_left (not_mem_nil _),
begin
intros ss h, apply mem_rec_on h (λ b ss o, _) (λ ss IH, _); intros s S,
{ refine s.cases_on (S.cases_on _ (λ s S, _) (λ S, _)) (λ b' s, _) (λ s, _);
intros ej m; simp at ej;
have := congr_arg seq.destruct ej; simp at this;
try {cases this}; try {contradiction},
substs b' ss,
simp at m ⊢,
cases o with e IH, { simp [e] },
cases m with e m, { simp [e] },
exact or.imp_left or.inr (IH _ _ rfl m) },
{ refine s.cases_on (S.cases_on _ (λ s S, _) (λ S, _)) (λ b' s, _) (λ s, _);
intros ej m; simp at ej;
have := congr_arg seq.destruct ej; simp at this;
try { try {have := this.1}, contradiction }; subst ss,
{ apply or.inr, simp at m ⊢,
cases IH s S rfl m with as ex,
{ exact ⟨s, or.inl rfl, as⟩ },
{ rcases ex with ⟨s', sS, as⟩,
exact ⟨s', or.inr sS, as⟩ } },
{ apply or.inr, simp at m,
rcases (IH nil S (by simp) (by simp [m])).resolve_left (not_mem_nil _) with ⟨s, sS, as⟩,
exact ⟨s, by simp [sS], as⟩ },
{ simp at m IH ⊢, apply IH _ _ rfl m } }
end
theorem exists_of_mem_bind {s : wseq α} {f : α → wseq β} {b}
(h : b ∈ bind s f) : ∃ a ∈ s, b ∈ f a :=
let ⟨t, tm, bt⟩ := exists_of_mem_join h,
⟨a, as, e⟩ := exists_of_mem_map tm in ⟨a, as, by rwa e⟩
theorem destruct_map (f : α → β) (s : wseq α) :
destruct (map f s) = computation.map (option.map (prod.map f (map f))) (destruct s) :=
begin
apply eq_of_bisim (λ c1 c2, ∃ s, c1 = destruct (map f s) ∧
c2 = computation.map (option.map (prod.map f (map f))) (destruct s)),
{ intros c1 c2 h, cases h with s h, rw [h.left, h.right],
apply s.cases_on _ (λ a s, _) (λ s, _); simp; simp,
{ refl }, { refl }, { exact ⟨s, rfl, rfl⟩ } },
{ exact ⟨s, rfl, rfl⟩ }
end
theorem lift_rel_map {δ} (R : α → β → Prop) (S : γ → δ → Prop)
{s1 : wseq α} {s2 : wseq β}
{f1 : α → γ} {f2 : β → δ}
(h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → S (f1 a) (f2 b))
: lift_rel S (map f1 s1) (map f2 s2) :=
⟨λ s1 s2, ∃ s t, s1 = map f1 s ∧ s2 = map f2 t ∧ lift_rel R s t,
⟨s1, s2, rfl, rfl, h1⟩,
λ s1 s2 h, match s1, s2, h with ._, ._, ⟨s, t, rfl, rfl, h⟩ := begin
simp [destruct_map], apply computation.lift_rel_map _ _ (lift_rel_destruct h),
intros o p h,
cases o with a; cases p with b; simp [option.map, option.bind],
{ cases b; cases h },
{ cases a; cases h },
{ cases a with a s; cases b with b t, cases h with r h,
exact ⟨h2 r, s, rfl, t, rfl, h⟩ }
end end⟩
theorem map_congr (f : α → β) {s t : wseq α} (h : s ~ t) : map f s ~ map f t :=
lift_rel_map _ _ h (λ _ _, congr_arg _)
@[simp] def destruct_append.aux (t : wseq α) :
option (α × wseq α) → computation (option (α × wseq α))
| none := destruct t
| (some (a, s)) := return (some (a, append s t))
theorem destruct_append (s t : wseq α) :
destruct (append s t) = (destruct s).bind (destruct_append.aux t) :=
begin
apply eq_of_bisim (λ c1 c2, ∃ s t, c1 = destruct (append s t) ∧
c2 = (destruct s).bind (destruct_append.aux t)) _ ⟨s, t, rfl, rfl⟩,
intros c1 c2 h, cases h with s h, cases h with t h, rw [h.left, h.right],
apply s.cases_on _ (λ a s, _) (λ s, _); simp; simp,
{ apply t.cases_on _ (λ b t, _) (λ t, _); simp; simp,
{ refine ⟨nil, t, _, _⟩; simp } },
{ exact ⟨s, t, rfl, rfl⟩ }
end
@[simp] def destruct_join.aux : option (wseq α × wseq (wseq α)) → computation (option (α × wseq α))
| none := return none
| (some (s, S)) := (destruct (append s (join S))).think
theorem destruct_join (S : wseq (wseq α)) :
destruct (join S) = (destruct S).bind destruct_join.aux :=
begin
apply eq_of_bisim (λ c1 c2, c1 = c2 ∨ ∃ S, c1 = destruct (join S) ∧
c2 = (destruct S).bind destruct_join.aux) _ (or.inr ⟨S, rfl, rfl⟩),
intros c1 c2 h, exact match c1, c2, h with
| _, _, (or.inl $ eq.refl c) := by cases c.destruct; simp
| _, _, or.inr ⟨S, rfl, rfl⟩ := begin
apply S.cases_on _ (λ s S, _) (λ S, _); simp; simp,
{ refine or.inr ⟨S, rfl, rfl⟩ }
end end
end
theorem lift_rel_append (R : α → β → Prop) {s1 s2 : wseq α} {t1 t2 : wseq β}
(h1 : lift_rel R s1 t1) (h2 : lift_rel R s2 t2) :
lift_rel R (append s1 s2) (append t1 t2) :=
⟨λ s t, lift_rel R s t ∨ ∃ s1 t1, s = append s1 s2 ∧ t = append t1 t2 ∧ lift_rel R s1 t1,
or.inr ⟨s1, t1, rfl, rfl, h1⟩,
λ s t h, match s, t, h with
| s, t, or.inl h := begin
apply computation.lift_rel.imp _ _ _ (lift_rel_destruct h),
intros a b, apply lift_rel_o.imp_right,
intros s t, apply or.inl
end
| ._, ._, or.inr ⟨s1, t1, rfl, rfl, h⟩ := begin
simp [destruct_append],
apply computation.lift_rel_bind _ _ (lift_rel_destruct h),
intros o p h,
cases o with a; cases p with b,
{ simp, apply computation.lift_rel.imp _ _ _ (lift_rel_destruct h2),
intros a b, apply lift_rel_o.imp_right,
intros s t, apply or.inl },
{ cases b; cases h },
{ cases a; cases h },
{ cases a with a s; cases b with b t, cases h with r h,
simp, exact ⟨r, or.inr ⟨s, rfl, t, rfl, h⟩⟩ }
end
end⟩
theorem lift_rel_join.lem (R : α → β → Prop) {S T} {U : wseq α → wseq β → Prop}
(ST : lift_rel (lift_rel R) S T) (HU : ∀ s1 s2, (∃ s t S T,
s1 = append s (join S) ∧ s2 = append t (join T) ∧
lift_rel R s t ∧ lift_rel (lift_rel R) S T) → U s1 s2) {a} (ma : a ∈ destruct (join S)) :
∃ {b}, b ∈ destruct (join T) ∧ lift_rel_o R U a b :=
begin
cases exists_results_of_mem ma with n h, clear ma, revert a S T,
apply nat.strong_induction_on n _,
intros n IH a S T ST ra, simp [destruct_join] at ra, exact
let ⟨o, m, k, rs1, rs2, en⟩ := of_results_bind ra,
⟨p, mT, rop⟩ := computation.exists_of_lift_rel_left (lift_rel_destruct ST) rs1.mem in
by exact match o, p, rop, rs1, rs2, mT with
| none, none, _, rs1, rs2, mT := by simp [destruct_join]; exact
⟨none, mem_bind mT (ret_mem _), by rw eq_of_ret_mem rs2.mem; trivial⟩
| some (s, S'), some (t, T'), ⟨st, ST'⟩, rs1, rs2, mT :=
by simp [destruct_append] at rs2; exact
let ⟨k1, rs3, ek⟩ := of_results_think rs2,
⟨o', m1, n1, rs4, rs5, ek1⟩ := of_results_bind rs3,
⟨p', mt, rop'⟩ := computation.exists_of_lift_rel_left (lift_rel_destruct st) rs4.mem in
by exact match o', p', rop', rs4, rs5, mt with
| none, none, _, rs4, rs5', mt :=
have n1 < n, begin
rw [en, ek, ek1],
apply lt_of_lt_of_le _ (nat.le_add_right _ _),
apply nat.lt_succ_of_le (nat.le_add_right _ _)
end,
let ⟨ob, mb, rob⟩ := IH _ this ST' rs5' in by refine ⟨ob, _, rob⟩;
{ simp [destruct_join], apply mem_bind mT, simp [destruct_append],
apply think_mem, apply mem_bind mt, exact mb }
| some (a, s'), some (b, t'), ⟨ab, st'⟩, rs4, rs5, mt := begin
simp at rs5,
refine ⟨some (b, append t' (join T')), _, _⟩,
{ simp [destruct_join], apply mem_bind mT, simp [destruct_append],
apply think_mem, apply mem_bind mt, apply ret_mem },
rw eq_of_ret_mem rs5.mem,
exact ⟨ab, HU _ _ ⟨s', t', S', T', rfl, rfl, st', ST'⟩⟩
end end
end
end
theorem lift_rel_join (R : α → β → Prop) {S : wseq (wseq α)} {T : wseq (wseq β)}
(h : lift_rel (lift_rel R) S T) : lift_rel R (join S) (join T) :=
⟨λ s1 s2, ∃ s t S T,
s1 = append s (join S) ∧ s2 = append t (join T) ∧
lift_rel R s t ∧ lift_rel (lift_rel R) S T,
⟨nil, nil, S, T, by simp, by simp, by simp, h⟩,
λs1 s2 ⟨s, t, S, T, h1, h2, st, ST⟩, begin
clear _fun_match _x,
rw [h1, h2], rw [destruct_append, destruct_append],
apply computation.lift_rel_bind _ _ (lift_rel_destruct st),
exact λ o p h, match o, p, h with
| some (a, s), some (b, t), ⟨h1, h2⟩ :=
by simp; exact ⟨h1, s, t, S, rfl, T, rfl, h2, ST⟩
| none, none, _ := begin
dsimp [destruct_append.aux, computation.lift_rel], constructor,
{ intro, apply lift_rel_join.lem _ ST (λ _ _, id) },
{ intros b mb,
rw [←lift_rel_o.swap], apply lift_rel_join.lem (function.swap R),
{ rw [←lift_rel.swap R, ←lift_rel.swap], apply ST },
{ rw [←lift_rel.swap R, ←lift_rel.swap (lift_rel R)],
exact λ s1 s2 ⟨s, t, S, T, h1, h2, st, ST⟩,
⟨t, s, T, S, h2, h1, st, ST⟩ },
{ exact mb } }
end end
end⟩
theorem join_congr {S T : wseq (wseq α)} (h : lift_rel equiv S T) : join S ~ join T :=
lift_rel_join _ h
theorem lift_rel_bind {δ} (R : α → β → Prop) (S : γ → δ → Prop)
{s1 : wseq α} {s2 : wseq β}
{f1 : α → wseq γ} {f2 : β → wseq δ}
(h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → lift_rel S (f1 a) (f2 b))
: lift_rel S (bind s1 f1) (bind s2 f2) :=
lift_rel_join _ (lift_rel_map _ _ h1 @h2)
theorem bind_congr {s1 s2 : wseq α} {f1 f2 : α → wseq β}
(h1 : s1 ~ s2) (h2 : ∀ a, f1 a ~ f2 a) : bind s1 f1 ~ bind s2 f2 :=
lift_rel_bind _ _ h1 (λ a b h, by rw h; apply h2)
@[simp] theorem join_ret (s : wseq α) : join (ret s) ~ s :=
by simp [ret]; apply think_equiv
@[simp] theorem join_map_ret (s : wseq α) : join (map ret s) ~ s :=
begin
refine ⟨λ s1 s2, join (map ret s2) = s1, rfl, _⟩,
intros s' s h, rw ←h,
apply lift_rel_rec
(λ c1 c2, ∃ s,
c1 = destruct (join (map ret s)) ∧ c2 = destruct s),
{ exact λ c1 c2 h, match c1, c2, h with
| ._, ._, ⟨s, rfl, rfl⟩ := begin
clear h _match,
apply s.cases_on _ (λ a s, _) (λ s, _); simp [ret]; simp [ret],
{ refine ⟨_, ret_mem _, _⟩, simp },
{ exact ⟨s, rfl, rfl⟩ }
end end },
{ exact ⟨s, rfl, rfl⟩ }
end
@[simp] theorem join_append (S T : wseq (wseq α)) :
join (append S T) ~ append (join S) (join T) :=
begin
refine ⟨λ s1 s2, ∃ s S T,
s1 = append s (join (append S T)) ∧
s2 = append s (append (join S) (join T)), ⟨nil, S, T, by simp, by simp⟩, _⟩,
intros s1 s2 h,
apply lift_rel_rec (λ c1 c2, ∃ (s : wseq α) S T,
c1 = destruct (append s (join (append S T))) ∧
c2 = destruct (append s (append (join S) (join T)))) _ _ _
(let ⟨s, S, T, h1, h2⟩ := h in
⟨s, S, T, congr_arg destruct h1, congr_arg destruct h2⟩),
intros c1 c2 h,
exact match c1, c2, h with ._, ._, ⟨s, S, T, rfl, rfl⟩ := begin
clear _match h h,
apply wseq.cases_on s _ (λ a s, _) (λ s, _); simp; simp,
{ apply wseq.cases_on S _ (λ s S, _) (λ S, _); simp; simp,
{ apply wseq.cases_on T _ (λ s T, _) (λ T, _); simp; simp,
{ refine ⟨s, nil, T, _, _⟩; simp },
{ refine ⟨nil, nil, T, _, _⟩; simp } },
{ exact ⟨s, S, T, rfl, rfl⟩ },
{ refine ⟨nil, S, T, _, _⟩; simp } },
{ exact ⟨s, S, T, rfl, rfl⟩ },
{ exact ⟨s, S, T, rfl, rfl⟩ }
end end
end
@[simp] theorem bind_ret (f : α → β) (s) : bind s (ret ∘ f) ~ map f s :=
begin
dsimp [bind], change (λx, ret (f x)) with (ret ∘ f),
rw [map_comp], apply join_map_ret
end
@[simp] theorem ret_bind (a : α) (f : α → wseq β) :
bind (ret a) f ~ f a := by simp [bind]
@[simp] theorem map_join (f : α → β) (S) :
map f (join S) = join (map (map f) S) :=
begin
apply seq.eq_of_bisim (λs1 s2,
∃ s S, s1 = append s (map f (join S)) ∧
s2 = append s (join (map (map f) S))),
{ intros s1 s2 h,
exact match s1, s2, h with ._, ._, ⟨s, S, rfl, rfl⟩ := begin
apply wseq.cases_on s _ (λ a s, _) (λ s, _); simp; simp,
{ apply wseq.cases_on S _ (λ s S, _) (λ S, _); simp; simp,
{ exact ⟨map f s, S, rfl, rfl⟩ },
{ refine ⟨nil, S, _, _⟩; simp } },
{ exact ⟨_, _, rfl, rfl⟩ },
{ exact ⟨_, _, rfl, rfl⟩ }
end end },
{ refine ⟨nil, S, _, _⟩; simp }
end
@[simp] theorem join_join (SS : wseq (wseq (wseq α))) :
join (join SS) ~ join (map join SS) :=
begin
refine ⟨λ s1 s2, ∃ s S SS,
s1 = append s (join (append S (join SS))) ∧
s2 = append s (append (join S) (join (map join SS))),
⟨nil, nil, SS, by simp, by simp⟩, _⟩,
intros s1 s2 h,
apply lift_rel_rec (λ c1 c2, ∃ s S SS,
c1 = destruct (append s (join (append S (join SS)))) ∧
c2 = destruct (append s (append (join S) (join (map join SS)))))
_ (destruct s1) (destruct s2)
(let ⟨s, S, SS, h1, h2⟩ := h in ⟨s, S, SS, by simp [h1], by simp [h2]⟩),
intros c1 c2 h,
exact match c1, c2, h with ._, ._, ⟨s, S, SS, rfl, rfl⟩ := begin
clear _match h h,
apply wseq.cases_on s _ (λ a s, _) (λ s, _); simp; simp,
{ apply wseq.cases_on S _ (λ s S, _) (λ S, _); simp; simp,
{ apply wseq.cases_on SS _ (λ S SS, _) (λ SS, _); simp; simp,
{ refine ⟨nil, S, SS, _, _⟩; simp },
{ refine ⟨nil, nil, SS, _, _⟩; simp } },
{ exact ⟨s, S, SS, rfl, rfl⟩ },
{ refine ⟨nil, S, SS, _, _⟩; simp } },
{ exact ⟨s, S, SS, rfl, rfl⟩ },
{ exact ⟨s, S, SS, rfl, rfl⟩ }
end end
end
@[simp] theorem bind_assoc (s : wseq α) (f : α → wseq β) (g : β → wseq γ) :
bind (bind s f) g ~ bind s (λ (x : α), bind (f x) g) :=
begin
simp [bind], rw [← map_comp f (map g), map_comp (map g ∘ f) join],
apply join_join
end
instance : monad wseq :=
{ map := @map,
pure := @ret,
bind := @bind }
/-
Unfortunately, wseq is not a lawful monad, because it does not satisfy
the monad laws exactly, only up to sequence equivalence.
Furthermore, even quotienting by the equivalence is not sufficient,
because the join operation involves lists of quotient elements,
with a lifted equivalence relation, and pure quotients cannot handle
this type of construction.
instance : is_lawful_monad wseq :=
{ id_map := @map_id,
bind_pure_comp_eq_map := @bind_ret,
pure_bind := @ret_bind,
bind_assoc := @bind_assoc }
-/
end wseq
|
5b5902f61ab420659a0856adb0399868289a817f | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/data/buffer/basic.lean | 0d97e092e4c532de42b4ffd9ad51e772df0c5554 | [
"Apache-2.0"
] | permissive | gebner/mathlib | eab0150cc4f79ec45d2016a8c21750244a2e7ff0 | cc6a6edc397c55118df62831e23bfbd6e6c6b4ab | refs/heads/master | 1,625,574,853,976 | 1,586,712,827,000 | 1,586,712,827,000 | 99,101,412 | 1 | 0 | Apache-2.0 | 1,586,716,389,000 | 1,501,667,958,000 | Lean | UTF-8 | Lean | false | false | 1,901 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
Traversable instance for buffers.
-/
import data.buffer data.array.lemmas
import category.traversable.instances data.equiv.basic
tactic.ext
namespace buffer
open function
variables {α : Type*} {xs : list α}
instance : inhabited (buffer α) := ⟨nil⟩
@[ext]
lemma ext : ∀ {b₁ b₂ : buffer α}, to_list b₁ = to_list b₂ → b₁ = b₂
| ⟨n₁, a₁⟩ ⟨n₂, a₂⟩ h := begin
simp [to_list, to_array] at h,
have e : n₁ = n₂ :=
by rw [←array.to_list_length a₁, ←array.to_list_length a₂, h],
subst e,
have h : a₁ == a₂.to_list.to_array := h ▸ a₁.to_list_to_array.symm,
rw eq_of_heq (h.trans a₂.to_list_to_array)
end
instance (α) [decidable_eq α] : decidable_eq (buffer α) :=
by tactic.mk_dec_eq_instance
@[simp]
lemma to_list_append_list {b : buffer α} :
to_list (append_list b xs) = to_list b ++ xs :=
by induction xs generalizing b; simp! [*]; cases b; simp! [to_list,to_array]
@[simp]
lemma append_list_mk_buffer :
append_list mk_buffer xs = array.to_buffer (list.to_array xs) :=
by ext x : 1; simp [array.to_buffer,to_list,to_list_append_list];
induction xs; [refl,skip]; simp [to_array]; refl
def list_equiv_buffer (α : Type*) : list α ≃ buffer α :=
begin
refine { to_fun := list.to_buffer, inv_fun := buffer.to_list, .. };
simp [left_inverse,function.right_inverse],
{ intro x, induction x, refl,
simp [list.to_buffer,append_list],
rw ← x_ih, refl },
{ intro x, cases x,
simp [to_list,to_array,list.to_buffer],
congr, simp, refl, apply array.to_list_to_array }
end
instance : traversable buffer :=
equiv.traversable list_equiv_buffer
instance : is_lawful_traversable buffer :=
equiv.is_lawful_traversable list_equiv_buffer
end buffer
|
5f82da014c8709a0f5a9dc4046285b813a612f4a | 82e44445c70db0f03e30d7be725775f122d72f3e | /archive/100-theorems-list/42_inverse_triangle_sum.lean | 3e111b0bcfffe2ecc221e67cad68070af5c2cb80 | [
"Apache-2.0"
] | permissive | stjordanis/mathlib | 51e286d19140e3788ef2c470bc7b953e4991f0c9 | 2568d41bca08f5d6bf39d915434c8447e21f42ee | refs/heads/master | 1,631,748,053,501 | 1,627,938,886,000 | 1,627,938,886,000 | 228,728,358 | 0 | 0 | Apache-2.0 | 1,576,630,588,000 | 1,576,630,587,000 | null | UTF-8 | Lean | false | false | 1,058 | lean | /-
Copyright (c) 2020. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jalex Stark, Yury Kudryashov
-/
import data.real.basic
/-!
# Sum of the Reciprocals of the Triangular Numbers
This file proves Theorem 42 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/).
We interpret “triangular numbers” as naturals of the form $\frac{k(k+1)}{2}$ for natural `k`.
We prove that the sum of the first `n` triangular numbers is equal to $2 - \frac2n$.
## Tags
discrete_sum
-/
open_locale big_operators
open finset
/-- **Sum of the Reciprocals of the Triangular Numbers** -/
lemma inverse_triangle_sum :
∀ n, ∑ k in range n, (2 : ℚ) / (k * (k + 1)) = if n = 0 then 0 else 2 - (2 : ℚ) / n :=
begin
refine sum_range_induction _ _ (if_pos rfl) _,
rintro (_|n), { rw [if_neg, if_pos]; norm_num },
simp_rw [if_neg (nat.succ_ne_zero _), nat.succ_eq_add_one],
have A : (n + 1 + 1 : ℚ) ≠ 0, by { norm_cast, norm_num },
push_cast,
field_simp [nat.cast_add_one_ne_zero],
ring
end
|
3f47f3f68c3d18530e61ac7dbdc6bbcdb6a51f49 | 471bedbd023d35c9d078c2f936dd577ace7f5813 | /library/init/meta/interactive.lean | c8765a3568312ac6e2bd4fb28486d20c4a706a25 | [
"Apache-2.0"
] | permissive | lambdaxymox/lean | e06f0fa503666df827edd9867d7f49ca017aae64 | fc13c8c72a15dab71a2c2b31410c2cadc3526bd7 | refs/heads/master | 1,666,785,407,985 | 1,666,153,673,000 | 1,666,153,673,000 | 310,165,986 | 0 | 0 | Apache-2.0 | 1,604,542,096,000 | 1,604,542,095,000 | null | UTF-8 | Lean | false | false | 74,178 | 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, Jannis Limperg
-/
prelude
import init.meta.tactic init.meta.type_context init.meta.rewrite_tactic init.meta.simp_tactic
import init.meta.smt.congruence_closure init.control.combinators
import init.meta.interactive_base init.meta.derive init.meta.match_tactic
import init.meta.congr_tactic init.meta.case_tag
open lean
open lean.parser
open native
precedence `?` : max
local postfix `?`:9001 := optional
local postfix *:9001 := many
namespace tactic
/- allows metavars -/
meta def i_to_expr (q : pexpr) : tactic expr :=
to_expr q tt
/- allow metavars and no subgoals -/
meta def i_to_expr_no_subgoals (q : pexpr) : tactic expr :=
to_expr q tt ff
/- doesn't allows metavars -/
meta def i_to_expr_strict (q : pexpr) : tactic expr :=
to_expr q ff
/- Auxiliary version of i_to_expr for apply-like tactics.
This is a workaround for comment
https://github.com/leanprover/lean/issues/1342#issuecomment-307912291
at issue #1342.
In interactive mode, given a tactic
apply f
we want the apply tactic to create all metavariables. The following
definition will return `@f` for `f`. That is, it will **not** create
metavariables for implicit arguments.
Before we added `i_to_expr_for_apply`, the tactic
apply le_antisymm
would first elaborate `le_antisymm`, and create
@le_antisymm ?m_1 ?m_2 ?m_3 ?m_4
The type class resolution problem
?m_2 : weak_order ?m_1
by the elaborator since ?m_1 is not assigned yet, and the problem is
discarded.
Then, we would invoke `apply_core`, which would create two
new metavariables for the explicit arguments, and try to unify the resulting
type with the current target. After the unification,
the metavariables ?m_1, ?m_3 and ?m_4 are assigned, but we lost
the information about the pending type class resolution problem.
With `i_to_expr_for_apply`, `le_antisymm` is elaborate into `@le_antisymm`,
the apply_core tactic creates all metavariables, and solves the ones that
can be solved by type class resolution.
Another possible fix: we modify the elaborator to return pending
type class resolution problems, and store them in the tactic_state.
-/
meta def i_to_expr_for_apply (q : pexpr) : tactic expr :=
let aux (n : name) : tactic expr := do
p ← resolve_name n,
match p with
| (expr.const c []) := do r ← mk_const c, save_type_info r q, return r
| _ := i_to_expr p
end
in match q with
| (expr.const c []) := aux c
| (expr.local_const c _ _ _) := aux c
| _ := i_to_expr q
end
namespace interactive
open _root_.interactive interactive.types expr
/--
itactic: parse a nested "interactive" tactic. That is, parse
`{` tactic `}`
-/
meta def itactic : Type :=
tactic unit
meta def propagate_tags (tac : itactic) : tactic unit :=
do tag ← get_main_tag,
if tag = [] then tac
else focus1 $ do
tac,
gs ← get_goals,
when (bnot gs.empty) $ do
new_tag ← get_main_tag,
when new_tag.empty $ with_enable_tags (set_main_tag tag)
meta def concat_tags (tac : tactic (list (name × expr))) : tactic unit :=
mcond tags_enabled
(do in_tag ← get_main_tag,
r ← tac,
/- remove assigned metavars -/
r ← r.mfilter $ λ ⟨n, m⟩, bnot <$> is_assigned m,
match r with
| [(_, m)] := set_tag m in_tag /- if there is only new subgoal, we just propagate `in_tag` -/
| _ := r.mmap' (λ ⟨n, m⟩, set_tag m (n::in_tag))
end)
(tac >> skip)
/--
If the current goal is a Pi/forall `∀ x : t, u` (resp. `let x := t in u`) then `intro` puts `x : t` (resp. `x := t`) in the local context. The new subgoal target is `u`.
If the goal is an arrow `t → u`, then it puts `h : t` in the local context and the new goal target is `u`.
If the goal is neither a Pi/forall nor begins with a let binder, the tactic `intro` applies the tactic `whnf` until an introduction can be applied or the goal is not head reducible. In the latter case, the tactic fails.
-/
meta def intro : parse ident_? → tactic unit
| none := propagate_tags (intro1 >> skip)
| (some h) := propagate_tags (tactic.intro h >> skip)
/--
Similar to `intro` tactic. The tactic `intros` will keep introducing new hypotheses until the goal target is not a Pi/forall or let binder.
The variant `intros h₁ ... hₙ` introduces `n` new hypotheses using the given identifiers to name them.
-/
meta def intros : parse ident_* → tactic unit
| [] := propagate_tags (tactic.intros >> skip)
| hs := propagate_tags (intro_lst hs >> skip)
/--
The tactic `introv` allows the user to automatically introduce the variables of a theorem and explicitly name the hypotheses involved. The given names are used to name non-dependent hypotheses.
Examples:
```
example : ∀ a b : nat, a = b → b = a :=
begin
introv h,
exact h.symm
end
```
The state after `introv h` is
```
a b : ℕ,
h : a = b
⊢ b = a
```
```
example : ∀ a b : nat, a = b → ∀ c, b = c → a = c :=
begin
introv h₁ h₂,
exact h₁.trans h₂
end
```
The state after `introv h₁ h₂` is
```
a b : ℕ,
h₁ : a = b,
c : ℕ,
h₂ : b = c
⊢ a = c
```
-/
meta def introv (ns : parse ident_*) : tactic unit :=
propagate_tags (tactic.introv ns >> return ())
/-- Parse a current name and new name for `rename`. -/
private meta def rename_arg_parser : parser (name × name) :=
prod.mk <$> ident <*> (optional (tk "->") *> ident)
/-- Parse the arguments of `rename`. -/
private meta def rename_args_parser : parser (list (name × name)) :=
(functor.map (λ x, [x]) rename_arg_parser)
<|>
(tk "[" *> sep_by (tk ",") rename_arg_parser <* tk "]")
/--
Rename one or more local hypotheses. The renamings are given as follows:
```
rename x y -- rename x to y
rename x → y -- ditto
rename [x y, a b] -- rename x to y and a to b
rename [x → y, a → b] -- ditto
```
Note that if there are multiple hypotheses called `x` in the context, then
`rename x y` will rename *all* of them. If you want to rename only one, use
`dedup` first.
-/
meta def rename (renames : parse rename_args_parser) : tactic unit :=
propagate_tags $ tactic.rename_many $ native.rb_map.of_list renames
/--
The `apply` tactic tries to match the current goal against the conclusion of the type of term. The argument term should be a term well-formed in the local context of the main goal. If it succeeds, then the tactic returns as many subgoals as the number of premises that have not been fixed by type inference or type class resolution. Non-dependent premises are added before dependent ones.
The `apply` tactic uses higher-order pattern matching, type class resolution, and first-order unification with dependent types.
-/
meta def apply (q : parse texpr) : tactic unit :=
concat_tags (do h ← i_to_expr_for_apply q, tactic.apply h)
/--
Similar to the `apply` tactic, but does not reorder goals.
-/
meta def fapply (q : parse texpr) : tactic unit :=
concat_tags (i_to_expr_for_apply q >>= tactic.fapply)
/--
Similar to the `apply` tactic, but only creates subgoals for non-dependent premises that have not been fixed by type inference or type class resolution.
-/
meta def eapply (q : parse texpr) : tactic unit :=
concat_tags (i_to_expr_for_apply q >>= tactic.eapply)
/--
Similar to the `apply` tactic, but allows the user to provide a `apply_cfg` configuration object.
-/
meta def apply_with (q : parse parser.pexpr) (cfg : apply_cfg) : tactic unit :=
concat_tags (do e ← i_to_expr_for_apply q, tactic.apply e cfg)
/--
Similar to the `apply` tactic, but uses matching instead of unification.
`apply_match t` is equivalent to `apply_with t {unify := ff}`
-/
meta def mapply (q : parse texpr) : tactic unit :=
concat_tags (do e ← i_to_expr_for_apply q, tactic.apply e {unify := ff})
/--
This tactic tries to close the main goal `... ⊢ t` by generating a term of type `t` using type class resolution.
-/
meta def apply_instance : tactic unit :=
tactic.apply_instance
/--
This tactic behaves like `exact`, but with a big difference: the user can put underscores `_` in the expression as placeholders for holes that need to be filled, and `refine` will generate as many subgoals as there are holes.
Note that some holes may be implicit. The type of each hole must either be synthesized by the system or declared by an explicit type ascription like `(_ : nat → Prop)`.
-/
meta def refine (q : parse texpr) : tactic unit :=
tactic.refine q
/--
This tactic looks in the local context for a hypothesis whose type is equal to the goal target. If it finds one, it uses it to prove the goal, and otherwise it fails.
-/
meta def assumption : tactic unit :=
tactic.assumption
/-- Try to apply `assumption` to all goals. -/
meta def assumption' : tactic unit :=
tactic.any_goals' tactic.assumption
private meta def change_core (e : expr) : option expr → tactic unit
| none := tactic.change e
| (some h) :=
do num_reverted : ℕ ← revert h,
expr.pi n bi d b ← target,
tactic.change $ expr.pi n bi e b,
intron num_reverted
/--
`change u` replaces the target `t` of the main goal to `u` provided that `t` is well formed with respect to the local context of the main goal and `t` and `u` are definitionally equal.
`change u at h` will change a local hypothesis to `u`.
`change t with u at h1 h2 ...` will replace `t` with `u` in all the supplied hypotheses (or `*`), or in the goal if no `at` clause is specified, provided that `t` and `u` are definitionally equal.
-/
meta def change (q : parse texpr) : parse (tk "with" *> texpr)? → parse location → tactic unit
| none (loc.ns [none]) := do e ← i_to_expr q, change_core e none
| none (loc.ns [some h]) := do eq ← i_to_expr q, eh ← get_local h, change_core eq (some eh)
| none _ := fail "change-at does not support multiple locations"
| (some w) l :=
do u ← mk_meta_univ,
ty ← mk_meta_var (sort u),
eq ← i_to_expr ``(%%q : %%ty),
ew ← i_to_expr ``(%%w : %%ty),
let repl := λe : expr, e.replace (λ a n, if a = eq then some ew else none),
l.try_apply
(λh, do e ← infer_type h, change_core (repl e) (some h))
(do g ← target, change_core (repl g) none)
/--
This tactic provides an exact proof term to solve the main goal. If `t` is the goal and `p` is a term of type `u` then `exact p` succeeds if and only if `t` and `u` can be unified.
-/
meta def exact (q : parse texpr) : tactic unit :=
do tgt : expr ← target,
i_to_expr_strict ``(%%q : %%tgt) >>= tactic.exact
/--
Like `exact`, but takes a list of terms and checks that all goals are discharged after the tactic.
-/
meta def exacts : parse pexpr_list_or_texpr → tactic unit
| [] := done
| (t :: ts) := exact t >> exacts ts
/--
A synonym for `exact` that allows writing `have/suffices/show ..., from ...` in tactic mode.
-/
meta def «from» := exact
/--
`revert h₁ ... hₙ` applies to any goal with hypotheses `h₁` ... `hₙ`. It moves the hypotheses and their dependencies to the target of the goal. This tactic is the inverse of `intro`.
-/
meta def revert (ids : parse ident*) : tactic unit :=
propagate_tags (do hs ← mmap tactic.get_local ids, revert_lst hs, skip)
private meta def resolve_name' (n : name) : tactic expr :=
do {
p ← resolve_name n,
match p with
| expr.const n _ := mk_const n -- create metavars for universe levels
| _ := i_to_expr p
end
}
/- Version of to_expr that tries to bypass the elaborator if `p` is just a constant or local constant.
This is not an optimization, by skipping the elaborator we make sure that no unwanted resolution is used.
Example: the elaborator will force any unassigned ?A that must have be an instance of (has_one ?A) to nat.
Remark: another benefit is that auxiliary temporary metavariables do not appear in error messages. -/
meta def to_expr' (p : pexpr) : tactic expr :=
match p with
| (const c []) := do new_e ← resolve_name' c, save_type_info new_e p, return new_e
| (local_const c _ _ _) := do new_e ← resolve_name' c, save_type_info new_e p, return new_e
| _ := i_to_expr p
end
@[derive has_reflect]
meta structure rw_rule :=
(pos : pos)
(symm : bool)
(rule : pexpr)
meta def get_rule_eqn_lemmas (r : rw_rule) : tactic (list name) :=
let aux (n : name) : tactic (list name) := do {
p ← resolve_name n,
-- unpack local refs
let e := p.erase_annotations.get_app_fn.erase_annotations,
match e with
| const n _ := get_eqn_lemmas_for tt n
| _ := return []
end } <|> return [] in
match r.rule with
| const n _ := aux n
| local_const n _ _ _ := aux n
| _ := return []
end
private meta def rw_goal (cfg : rewrite_cfg) (rs : list rw_rule) : tactic unit :=
rs.mmap' $ λ r, do
save_info r.pos,
eq_lemmas ← get_rule_eqn_lemmas r,
orelse'
(do e ← to_expr' r.rule, rewrite_target e {symm := r.symm, ..cfg})
(eq_lemmas.mfirst $ λ n, do e ← mk_const n, rewrite_target e {symm := r.symm, ..cfg})
(eq_lemmas.empty)
private meta def uses_hyp (e : expr) (h : expr) : bool :=
e.fold ff $ λ t _ r, r || to_bool (t = h)
private meta def rw_hyp (cfg : rewrite_cfg) : list rw_rule → expr → tactic unit
| [] hyp := skip
| (r::rs) hyp := do
save_info r.pos,
eq_lemmas ← get_rule_eqn_lemmas r,
orelse'
(do e ← to_expr' r.rule,
(if uses_hyp e hyp then pure e else rewrite_hyp e hyp {symm := r.symm, ..cfg}) >>= rw_hyp rs)
(eq_lemmas.mfirst $ λ n, do e ← mk_const n, rewrite_hyp e hyp {symm := r.symm, ..cfg} >>= rw_hyp rs)
(eq_lemmas.empty)
meta def rw_rule_p (ep : parser pexpr) : parser rw_rule :=
rw_rule.mk <$> cur_pos <*> (option.is_some <$> (with_desc "←" (tk "←" <|> tk "<-"))?) <*> ep
@[derive has_reflect]
meta structure rw_rules_t :=
(rules : list rw_rule)
(end_pos : option pos)
-- accepts the same content as `pexpr_list_or_texpr`, but with correct goal info pos annotations
meta def rw_rules : parser rw_rules_t :=
(tk "[" *>
rw_rules_t.mk <$> sep_by (skip_info (tk ",")) (set_goal_info_pos $ rw_rule_p (parser.pexpr 0))
<*> (some <$> cur_pos <* set_goal_info_pos (tk "]")))
<|> rw_rules_t.mk <$> (list.ret <$> rw_rule_p texpr) <*> return none
private meta def rw_core (rs : parse rw_rules) (loca : parse location) (cfg : rewrite_cfg) : tactic unit :=
match loca with
| loc.wildcard := loca.try_apply (rw_hyp cfg rs.rules) (rw_goal cfg rs.rules)
| _ := loca.apply (rw_hyp cfg rs.rules) (rw_goal cfg rs.rules)
end >> try (reflexivity reducible)
>> (returnopt rs.end_pos >>= save_info <|> skip)
/--
`rewrite e` applies identity `e` as a rewrite rule to the target of the main goal. If `e` is preceded by left arrow (`←` or `<-`), the rewrite is applied in the reverse direction. If `e` is a defined constant, then the equational lemmas associated with `e` are used. This provides a convenient way to unfold `e`.
`rewrite [e₁, ..., eₙ]` applies the given rules sequentially.
`rewrite e at l` rewrites `e` at location(s) `l`, where `l` is either `*` or a list of hypotheses in the local context. In the latter case, a turnstile `⊢` or `|-` can also be used, to signify the target of the goal.
-/
meta def rewrite (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit :=
propagate_tags (rw_core q l cfg)
/--
An abbreviation for `rewrite`.
-/
meta def rw (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit :=
propagate_tags (rw_core q l cfg)
/--
`rewrite` followed by `assumption`.
-/
meta def rwa (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit :=
rewrite q l cfg >> try assumption
/--
A variant of `rewrite` that uses the unifier more aggressively, unfolding semireducible definitions.
-/
meta def erewrite (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {md := semireducible}) : tactic unit :=
propagate_tags (rw_core q l cfg)
/--
An abbreviation for `erewrite`.
-/
meta def erw (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {md := semireducible}) : tactic unit :=
propagate_tags (rw_core q l cfg)
/--
Returns the unique names of all hypotheses (local constants) in the context.
-/
private meta def hyp_unique_names : tactic name_set :=
do ctx ← local_context,
pure $ ctx.foldl (λ r h, r.insert h.local_uniq_name) mk_name_set
/--
Returns all hypotheses (local constants) from the context except those whose
unique names are in `hyp_uids`.
-/
private meta def hyps_except (hyp_uids : name_set) : tactic (list expr) :=
do ctx ← local_context,
pure $ ctx.filter (λ (h : expr), ¬ hyp_uids.contains h.local_uniq_name)
/--
Apply `t` to the main goal and revert any new hypothesis in the generated goals.
If `t` is a supported tactic or chain of supported tactics (e.g. `induction`,
`cases`, `apply`, `constructor`), the generated goals are also tagged with case
tags. You can then use `case` to focus such tagged goals.
Two typical uses of `with_cases`:
1. Applying a custom eliminator:
```
lemma my_nat_rec :
∀ n {P : ℕ → Prop} (zero : P 0) (succ : ∀ n, P n → P (n + 1)), P n := ...
example (n : ℕ) : n = n :=
begin
with_cases { apply my_nat_rec n },
case zero { refl },
case succ : m ih { refl }
end
```
2. Enabling the use of `case` after a chain of case-splitting tactics:
```
example (n m : ℕ) : unit :=
begin
with_cases { cases n; induction m },
case nat.zero nat.zero { exact () },
case nat.zero nat.succ : k { exact () },
case nat.succ nat.zero : i { exact () },
case nat.succ nat.succ : k i ih_i { exact () }
end
```
-/
meta def with_cases (t : itactic) : tactic unit :=
with_enable_tags $ focus1 $ do
input_hyp_uids ← hyp_unique_names,
t,
all_goals' $ do
in_tag ← get_main_tag,
new_hyps ← hyps_except input_hyp_uids,
n ← revert_lst new_hyps,
set_main_tag (case_tag.from_tag_pi in_tag n).render
private meta def generalize_arg_p_aux : pexpr → parser (pexpr × name)
| (app (app (macro _ [const `eq _ ]) h) (local_const x _ _ _)) := pure (h, x)
| _ := fail "parse error"
private meta def generalize_arg_p : parser (pexpr × name) :=
with_desc "expr = id" $ parser.pexpr 0 >>= generalize_arg_p_aux
/--
`generalize : e = x` replaces all occurrences of `e` in the target with a new hypothesis `x` of the same type.
`generalize h : e = x` in addition registers the hypothesis `h : e = x`.
-/
meta def generalize (h : parse ident?) (_ : parse $ tk ":") (p : parse generalize_arg_p) : tactic unit :=
propagate_tags $
do let (p, x) := p,
e ← i_to_expr p,
some h ← pure h | tactic.generalize e x >> intro1 >> skip,
tgt ← target,
-- if generalizing fails, fall back to not replacing anything
tgt' ← do {
⟨tgt', _⟩ ← solve_aux tgt (tactic.generalize e x >> target),
to_expr ``(Π x, %%e = x → %%(tgt'.binding_body.lift_vars 0 1))
} <|> to_expr ``(Π x, %%e = x → %%tgt),
t ← assert h tgt',
swap,
exact ``(%%t %%e rfl),
intro x,
intro h
meta def cases_arg_p : parser (option name × pexpr) :=
with_desc "(id :)? expr" $ do
t ← texpr,
match t with
| (local_const x _ _ _) :=
(tk ":" *> do t ← texpr, pure (some x, t)) <|> pure (none, t)
| _ := pure (none, t)
end
/--
Updates the tags of new subgoals produced by `cases` or `induction`. `in_tag`
is the initial tag, i.e. the tag of the goal on which `cases`/`induction` was
applied. `rs` should contain, for each subgoal, the constructor name
associated with that goal and the hypotheses that were introduced.
-/
private meta def set_cases_tags (in_tag : tag) (rs : list (name × list expr)) : tactic unit :=
do gs ← get_goals,
match gs with
-- if only one goal was produced, we should not make the tag longer
| [g] := set_tag g in_tag
| _ :=
let tgs : list (name × list expr × expr) :=
rs.map₂ (λ ⟨n, new_hyps⟩ g, ⟨n, new_hyps, g⟩) gs in
tgs.mmap' $ λ ⟨n, new_hyps, g⟩, with_enable_tags $
set_tag g $
(case_tag.from_tag_hyps (n :: in_tag) (new_hyps.map expr.local_uniq_name)).render
end
precedence `generalizing` : 0
/--
Assuming `x` is a variable in the local context with an inductive type, `induction x` applies induction on `x` to the main goal, producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor and an inductive hypothesis is added for each recursive argument to the constructor. If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward, so that the inductive hypothesis incorporates that hypothesis as well.
For example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `induction n` produces one goal with hypothesis `h : P 0` and target `Q 0`, and one goal with hypotheses `h : P (nat.succ a)` and `ih₁ : P a → Q a` and target `Q (nat.succ a)`. Here the names `a` and `ih₁` ire chosen automatically.
`induction e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then performs induction on the resulting variable.
`induction e with y₁ ... yₙ`, where `e` is a variable or an expression, specifies that the sequence of names `y₁ ... yₙ` should be used for the arguments to the constructors and inductive hypotheses, including implicit arguments. If the list does not include enough names for all of the arguments, additional names are generated automatically. If too many names are given, the extra ones are ignored. Underscores can be used in the list, in which case the corresponding names are generated automatically. Note that for long sequences of names, the `case` tactic provides a more convenient naming mechanism.
`induction e using r` allows the user to specify the principle of induction that should be used. Here `r` should be a theorem whose result type must be of the form `C t`, where `C` is a bound variable and `t` is a (possibly empty) sequence of bound variables
`induction e generalizing z₁ ... zₙ`, where `z₁ ... zₙ` are variables in the local context, generalizes over `z₁ ... zₙ` before applying the induction but then introduces them in each goal. In other words, the net effect is that each inductive hypothesis is generalized.
`induction h : t` will introduce an equality of the form `h : t = C x y`, asserting that the input term is equal to the current constructor case, to the context.
-/
meta def induction (hp : parse cases_arg_p) (rec_name : parse using_ident) (ids : parse with_ident_list)
(revert : parse $ (tk "generalizing" *> ident*)?) : tactic unit :=
do in_tag ← get_main_tag,
focus1 $ do {
-- process `h : t` case
e ← match hp with
| (some h, p) := do
x ← get_unused_name,
generalize h () (p, x),
get_local x
| (none, p) := i_to_expr p
end,
-- generalize major premise
e ← if e.is_local_constant then pure e
else tactic.generalize e >> intro1,
-- generalize major premise args
(e, newvars, locals) ← do {
none ← pure rec_name | pure (e, [], []),
t ← infer_type e,
t ← whnf_ginductive t,
const n _ ← pure t.get_app_fn | pure (e, [], []),
env ← get_env,
tt ← pure $ env.is_inductive n | pure (e, [], []),
let (locals, nonlocals) := (t.get_app_args.drop $ env.inductive_num_params n).partition
(λ arg : expr, arg.is_local_constant),
_ :: _ ← pure nonlocals | pure (e, [], []),
n ← tactic.revert e,
newvars ← nonlocals.mmap $ λ arg, do {
n ← revert_kdeps arg,
tactic.generalize arg,
h ← intro1,
intron n,
-- now try to clear hypotheses that may have been abstracted away
let locals := arg.fold [] (λ e _ acc, if e.is_local_constant then e::acc else acc),
locals.mmap' (try ∘ clear),
pure h
},
intron (n-1),
e ← intro1,
pure (e, newvars, locals)
},
-- revert `generalizing` params (and their dependencies, if any)
to_generalize ← (revert.get_or_else []).mmap tactic.get_local,
num_generalized ← revert_lst to_generalize,
-- perform the induction
rs ← tactic.induction e ids rec_name,
-- re-introduce the generalized hypotheses
gen_hyps ← all_goals $ do {
new_hyps ← intron' num_generalized,
clear_lst (newvars.map local_pp_name),
(e::locals).mmap' (try ∘ clear),
pure new_hyps
},
set_cases_tags in_tag $
@list.map₂ (name × list expr × list (name × expr)) _ (name × list expr)
(λ ⟨n, hyps, _⟩ gen_hyps, ⟨n, hyps ++ gen_hyps⟩) rs gen_hyps
}
open case_tag.match_result
private meta def goals_with_matching_tag (ns : list name) :
tactic (list (expr × case_tag) × list (expr × case_tag)) :=
do gs ← get_goals,
(gs : list (expr × tag)) ← gs.mmap (λ g, do t ← get_tag g, pure (g, t)),
pure $ gs.foldr
(λ ⟨g, t⟩ ⟨exact_matches, suffix_matches⟩,
match case_tag.parse t with
| none := ⟨exact_matches, suffix_matches⟩
| some t :=
match case_tag.match_tag ns t with
| exact_match := ⟨⟨g, t⟩ :: exact_matches, suffix_matches⟩
| fuzzy_match := ⟨exact_matches, ⟨g, t⟩ :: suffix_matches⟩
| no_match := ⟨exact_matches, suffix_matches⟩
end
end)
([], [])
private meta def goal_with_matching_tag (ns : list name) : tactic (expr × case_tag) :=
do ⟨exact_matches, suffix_matches⟩ ← goals_with_matching_tag ns,
match exact_matches, suffix_matches with
| [] , [] := fail format!
"Invalid `case`: there is no goal tagged with suffix {ns}."
| [] , [g] := pure g
| [] , _ :=
let tags : list (list name) := suffix_matches.map (λ ⟨_, t⟩, t.case_names.reverse) in
fail format!
"Invalid `case`: there is more than one goal tagged with suffix {ns}.\nMatching tags: {tags}"
| [g], _ := pure g
| _ , _ := fail format!
"Invalid `case`: there is more than one goal tagged with tag {ns}."
end
meta def case_arg_parser : lean.parser (list name × option (list name)) :=
prod.mk <$> ident_* <*> (tk ":" *> ident_*)?
meta def case_parser : lean.parser (list (list name × option (list name))) :=
(list_of case_arg_parser)
<|>
(functor.map (λ x, [x]) case_arg_parser)
/--
Focuses on a goal ('case') generated by `induction`, `cases` or `with_cases`.
The goal is selected by giving one or more names which must match exactly one
goal. A goal is matched if the given names are a suffix of its goal tag.
Additionally, each name in the sequence can be abbreviated to a suffix of the
corresponding name in the goal tag. Thus, a goal with tag
```
nat.zero, list.nil
```
can be selected with any of these invocations (among others):
```
case nat.zero list.nil {...}
case nat.zero nil {...}
case zero nil {...}
case nil {...}
```
Additionally, the form
```
case C : N₀ ... Nₙ {...}
```
can be used to rename hypotheses introduced by the preceding
`cases`/`induction`/`with_cases`, using the names `Nᵢ`. For example:
```
example (xs : list ℕ) : xs = xs :=
begin
induction xs,
case nil { reflexivity },
case cons : x xs ih {
-- x : ℕ, xs : list ℕ, ih : xs = xs
reflexivity }
end
```
Note that this renaming functionality only work reliably *directly after* an
`induction`/`cases`/`with_cases`. If you need to perform additional work after
an `induction` or `cases` (e.g. introduce hypotheses in all goals), use
`with_cases`.
Multiple cases can be handled by the same tactic block with
```
case [A : N₀ ... Nₙ, B : M₀ ... Mₙ] {...}
```
-/
/-
TODO `case` could be generalised to work with zero names as well. The form
case : x y z { ... }
would select the first goal (or the first goal with a case tag), renaming
hypotheses to `x, y, z`. The renaming functionality would be available only if
the goal has a case tag.
-/
meta def case (args : parse case_parser) (tac : itactic) : tactic unit :=
do
target_goals ← args.mmap (λ ⟨ns, ids⟩, do
⟨goal, tag⟩ ← goal_with_matching_tag ns,
let ids := ids.get_or_else [],
let num_ids := ids.length,
goals ← get_goals,
let other_goals := goals.filter (≠ goal),
set_goals [goal],
match tag with
| (case_tag.pi _ num_args) := do
intro_lst ids,
when (num_ids < num_args) $ intron (num_args - num_ids)
| (case_tag.hyps _ new_hyp_names) := do
let num_new_hyps := new_hyp_names.length,
when (num_ids > num_new_hyps) $ fail format!
("Invalid `case`: You gave {num_ids} names, but the case introduces " ++
"{num_new_hyps} new hypotheses."),
let renamings := native.rb_map.of_list (new_hyp_names.zip ids),
propagate_tags $ tactic.rename_many renamings tt tt
end,
goals ← get_goals,
set_goals other_goals,
match goals with
| [g] := return g
| _ := fail "Unexpected goals introduced by renaming"
end),
remaining_goals ← get_goals,
set_goals target_goals,
tac,
unsolved_goals ← get_goals,
match unsolved_goals with
| [] := set_goals remaining_goals
| _ := fail "case tactic failed, focused goals have not been solved"
end
/--
Assuming `x` is a variable in the local context with an inductive type, `destruct x` splits the main goal, producing one goal for each constructor of the inductive type, in which `x` is assumed to be a general instance of that constructor. In contrast to `cases`, the local context is unchanged, i.e. no elements are reverted or introduced.
For example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `destruct n` produces one goal with target `n = 0 → Q n`, and one goal with target `∀ (a : ℕ), (λ (w : ℕ), n = w → Q n) (nat.succ a)`. Here the name `a` is chosen automatically.
-/
meta def destruct (p : parse texpr) : tactic unit :=
i_to_expr p >>= tactic.destruct
meta def cases_core (e : expr) (ids : list name := []) : tactic unit :=
do in_tag ← get_main_tag,
focus1 $ do
rs ← tactic.cases e ids,
set_cases_tags in_tag rs
/--
Assuming `x` is a variable in the local context with an inductive type, `cases x` splits the main goal, producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor. If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward, so that the case split affects that hypothesis as well.
For example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `cases n` produces one goal with hypothesis `h : P 0` and target `Q 0`, and one goal with hypothesis `h : P (nat.succ a)` and target `Q (nat.succ a)`. Here the name `a` is chosen automatically.
`cases e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then cases on the resulting variable.
`cases e with y₁ ... yₙ`, where `e` is a variable or an expression, specifies that the sequence of names `y₁ ... yₙ` should be used for the arguments to the constructors, including implicit arguments. If the list does not include enough names for all of the arguments, additional names are generated automatically. If too many names are given, the extra ones are ignored. Underscores can be used in the list, in which case the corresponding names are generated automatically.
`cases h : e`, where `e` is a variable or an expression, performs cases on `e` as above, but also adds a hypothesis `h : e = ...` to each hypothesis, where `...` is the constructor instance for that particular case.
-/
meta def cases : parse cases_arg_p → parse with_ident_list → tactic unit
| (none, p) ids := do
e ← i_to_expr p,
cases_core e ids
| (some h, p) ids := do
x ← get_unused_name,
generalize h () (p, x),
hx ← get_local x,
cases_core hx ids
private meta def find_matching_hyp (ps : list pattern) : tactic expr :=
any_hyp $ λ h, do
type ← infer_type h,
ps.mfirst $ λ p, do
match_pattern p type,
return h
/--
`cases_matching p` applies the `cases` tactic to a hypothesis `h : type` if `type` matches the pattern `p`.
`cases_matching [p_1, ..., p_n]` applies the `cases` tactic to a hypothesis `h : type` if `type` matches one of the given patterns.
`cases_matching* p` more efficient and compact version of `focus1 { repeat { cases_matching p } }`. It is more efficient because the pattern is compiled once.
Example: The following tactic destructs all conjunctions and disjunctions in the current goal.
```
cases_matching* [_ ∨ _, _ ∧ _]
```
-/
meta def cases_matching (rec : parse $ (tk "*")?) (ps : parse pexpr_list_or_texpr) : tactic unit :=
do ps ← ps.mmap pexpr_to_pattern,
if rec.is_none
then find_matching_hyp ps >>= cases_core
else tactic.focus1 $ tactic.repeat $ find_matching_hyp ps >>= cases_core
/-- Shorthand for `cases_matching` -/
meta def casesm (rec : parse $ (tk "*")?) (ps : parse pexpr_list_or_texpr) : tactic unit :=
cases_matching rec ps
private meta def try_cases_for_types (type_names : list name) (at_most_one : bool) : tactic unit :=
any_hyp $ λ h, do
I ← expr.get_app_fn <$> (infer_type h >>= head_beta),
guard I.is_constant,
guard (I.const_name ∈ type_names),
tactic.focus1 (cases_core h >> if at_most_one then do n ← num_goals, guard (n <= 1) else skip)
/--
`cases_type I` applies the `cases` tactic to a hypothesis `h : (I ...)`
`cases_type I_1 ... I_n` applies the `cases` tactic to a hypothesis `h : (I_1 ...)` or ... or `h : (I_n ...)`
`cases_type* I` is shorthand for `focus1 { repeat { cases_type I } }`
`cases_type! I` only applies `cases` if the number of resulting subgoals is <= 1.
Example: The following tactic destructs all conjunctions and disjunctions in the current goal.
```
cases_type* or and
```
-/
meta def cases_type (one : parse $ (tk "!")?) (rec : parse $ (tk "*")?) (type_names : parse ident*) : tactic unit :=
do type_names ← type_names.mmap resolve_constant,
if rec.is_none
then try_cases_for_types type_names (bnot one.is_none)
else tactic.focus1 $ tactic.repeat $ try_cases_for_types type_names (bnot one.is_none)
/--
Tries to solve the current goal using a canonical proof of `true`, or the `reflexivity` tactic, or the `contradiction` tactic.
-/
meta def trivial : tactic unit :=
tactic.triv <|> tactic.reflexivity <|> tactic.contradiction <|> fail "trivial tactic failed"
/--
Closes the main goal using `sorry`. Takes an optional ignored tactic block.
The ignored tactic block is useful for "commenting out" part of a proof during development:
```lean
begin
split,
admit { expensive_tactic },
end
```
-/
meta def admit (t : parse (with_desc "{...}" parser.itactic)?) : tactic unit := tactic.admit
/--
Closes the main goal using `sorry`. Takes an optional ignored tactic block.
The ignored tactic block is useful for "commenting out" part of a proof during development:
```lean
begin
split,
sorry { expensive_tactic },
end
```
-/
meta def «sorry» (t : parse (with_desc "{...}" parser.itactic)?) : tactic unit := tactic.admit
/--
The contradiction tactic attempts to find in the current local context a hypothesis that is equivalent to an empty inductive type (e.g. `false`), a hypothesis of the form `c_1 ... = c_2 ...` where `c_1` and `c_2` are distinct constructors, or two contradictory hypotheses.
-/
meta def contradiction : tactic unit :=
tactic.contradiction
/--
`iterate { t }` repeatedly applies tactic `t` until `t` fails. `iterate { t }` always succeeds.
`iterate n { t }` applies `t` `n` times.
-/
meta def iterate (n : parse small_nat?) (t : itactic) : tactic unit :=
match n with
| none := tactic.iterate' t
| some n := iterate_exactly' n t
end
/--
`repeat { t }` applies `t` to each goal. If the application succeeds,
the tactic is applied recursively to all the generated subgoals until it eventually fails.
The recursion stops in a subgoal when the tactic has failed to make progress.
The tactic `repeat { t }` never fails.
-/
meta def repeat : itactic → tactic unit :=
tactic.repeat
/--
`try { t }` tries to apply tactic `t`, but succeeds whether or not `t` succeeds.
-/
meta def try : itactic → tactic unit :=
tactic.try
/--
A do-nothing tactic that always succeeds.
-/
meta def skip : tactic unit :=
tactic.skip
/--
`solve1 { t }` applies the tactic `t` to the main goal and fails if it is not solved.
-/
meta def solve1 : itactic → tactic unit :=
tactic.solve1
/--
`abstract id { t }` tries to use tactic `t` to solve the main goal. If it succeeds, it abstracts the goal as an independent definition or theorem with name `id`. If `id` is omitted, a name is generated automatically.
-/
meta def abstract (id : parse ident?) (tac : itactic) : tactic unit :=
tactic.abstract tac id
/--
`all_goals { t }` applies the tactic `t` to every goal, and succeeds if each application succeeds.
-/
meta def all_goals : itactic → tactic unit :=
tactic.all_goals'
/--
`any_goals { t }` applies the tactic `t` to every goal, and succeeds if at least one application succeeds.
-/
meta def any_goals : itactic → tactic unit :=
tactic.any_goals'
/--
`focus { t }` temporarily hides all goals other than the first, applies `t`, and then restores the other goals. It fails if there are no goals.
-/
meta def focus (tac : itactic) : tactic unit :=
tactic.focus1 tac
private meta def assume_core (n : name) (ty : pexpr) :=
do t ← target,
when (not $ t.is_pi ∨ t.is_let) whnf_target,
t ← target,
when (not $ t.is_pi ∨ t.is_let) $
fail "assume tactic failed, Pi/let expression expected",
ty ← i_to_expr ``(%%ty : Sort*),
unify ty t.binding_domain,
intro_core n >> skip
/--
Assuming the target of the goal is a Pi or a let, `assume h : t` unifies the type of the binder with `t` and introduces it with name `h`, just like `intro h`. If `h` is absent, the tactic uses the name `this`. If `t` is omitted, it will be inferred.
`assume (h₁ : t₁) ... (hₙ : tₙ)` introduces multiple hypotheses. Any of the types may be omitted, but the names must be present.
-/
meta def «assume» : parse (sum.inl <$> (tk ":" *> texpr) <|> sum.inr <$> parse_binders tac_rbp) → tactic unit
| (sum.inl ty) := assume_core `this ty
| (sum.inr binders) :=
binders.mmap' $ λ b, assume_core b.local_pp_name b.local_type
/--
`have h : t := p` adds the hypothesis `h : t` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred.
`have h : t` adds the hypothesis `h : t` to the current goal and opens a new subgoal with target `t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable.
If `h` is omitted, the name `this` is used.
-/
meta def «have» (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit :=
let h := h.get_or_else `this in
match q₁, q₂ with
| some e, some p := do
t ← i_to_expr ``(%%e : Sort*),
v ← i_to_expr ``(%%p : %%t),
tactic.assertv h t v
| none, some p := do
p ← i_to_expr p,
tactic.note h none p
| some e, none := i_to_expr ``(%%e : Sort*) >>= tactic.assert h
| none, none := do
u ← mk_meta_univ,
e ← mk_meta_var (sort u),
tactic.assert h e
end >> skip
/--
`let h : t := p` adds the hypothesis `h : t := p` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred.
`let h : t` adds the hypothesis `h : t := ?M` to the current goal and opens a new subgoal `?M : t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable.
If `h` is omitted, the name `this` is used.
-/
meta def «let» (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit :=
let h := h.get_or_else `this in
match q₁, q₂ with
| some e, some p := do
t ← i_to_expr ``(%%e : Sort*),
v ← i_to_expr ``(%%p : %%t),
tactic.definev h t v
| none, some p := do
p ← i_to_expr p,
tactic.pose h none p
| some e, none := i_to_expr ``(%%e : Sort*) >>= tactic.define h
| none, none := do
u ← mk_meta_univ,
e ← mk_meta_var (sort u),
tactic.define h e
end >> skip
/--
`suffices h : t` is the same as `have h : t, tactic.swap`. In other words, it adds the hypothesis `h : t` to the current goal and opens a new subgoal with target `t`.
-/
meta def «suffices» (h : parse ident?) (t : parse (tk ":" *> texpr)?) : tactic unit :=
«have» h t none >> tactic.swap
/--
This tactic displays the current state in the tracing buffer.
-/
meta def trace_state : tactic unit :=
tactic.trace_state
/--
`trace a` displays `a` in the tracing buffer.
-/
meta def trace {α : Type} [has_to_tactic_format α] (a : α) : tactic unit :=
tactic.trace a
/--
`existsi e` will instantiate an existential quantifier in the target with `e` and leave the instantiated body as the new target. More generally, it applies to any inductive type with one constructor and at least two arguments, applying the constructor with `e` as the first argument and leaving the remaining arguments as goals.
`existsi [e₁, ..., eₙ]` iteratively does the same for each expression in the list.
-/
meta def existsi : parse pexpr_list_or_texpr → tactic unit
| [] := return ()
| (p::ps) := i_to_expr p >>= tactic.existsi >> existsi ps
/--
This tactic applies to a goal such that its conclusion is an inductive type (say `I`). It tries to apply each constructor of `I` until it succeeds.
-/
meta def constructor : tactic unit :=
concat_tags tactic.constructor
/--
Similar to `constructor`, but only non-dependent premises are added as new goals.
-/
meta def econstructor : tactic unit :=
concat_tags tactic.econstructor
/--
Applies the first constructor when the type of the target is an inductive data type with two constructors.
-/
meta def left : tactic unit :=
concat_tags tactic.left
/--
Applies the second constructor when the type of the target is an inductive data type with two constructors.
-/
meta def right : tactic unit :=
concat_tags tactic.right
/--
Applies the constructor when the type of the target is an inductive data type with one constructor.
-/
meta def split : tactic unit :=
concat_tags tactic.split
private meta def constructor_matching_aux (ps : list pattern) : tactic unit :=
do t ← target, ps.mfirst (λ p, match_pattern p t), constructor
meta def constructor_matching (rec : parse $ (tk "*")?) (ps : parse pexpr_list_or_texpr) : tactic unit :=
do ps ← ps.mmap pexpr_to_pattern,
if rec.is_none then constructor_matching_aux ps
else tactic.focus1 $ tactic.repeat $ constructor_matching_aux ps
/--
Replaces the target of the main goal by `false`.
-/
meta def exfalso : tactic unit :=
tactic.exfalso
/--
The `injection` tactic is based on the fact that constructors of inductive data types are injections. That means that if `c` is a constructor of an inductive datatype, and if `(c t₁)` and `(c t₂)` are two terms that are equal then `t₁` and `t₂` are equal too.
If `q` is a proof of a statement of conclusion `t₁ = t₂`, then injection applies injectivity to derive the equality of all arguments of `t₁` and `t₂` placed in the same positions. For example, from `(a::b) = (c::d)` we derive `a=c` and `b=d`. To use this tactic `t₁` and `t₂` should be constructor applications of the same constructor.
Given `h : a::b = c::d`, the tactic `injection h` adds two new hypothesis with types `a = c` and `b = d` to the main goal. The tactic `injection h with h₁ h₂` uses the names `h₁` and `h₂` to name the new hypotheses.
-/
meta def injection (q : parse texpr) (hs : parse with_ident_list) : tactic unit :=
do e ← i_to_expr q, tactic.injection_with e hs, try assumption
/--
`injections with h₁ ... hₙ` iteratively applies `injection` to hypotheses using the names `h₁ ... hₙ`.
-/
meta def injections (hs : parse with_ident_list) : tactic unit :=
do tactic.injections_with hs, try assumption
end interactive
meta structure simp_config_ext extends simp_config :=
(discharger : tactic unit := failed)
section mk_simp_set
open expr interactive.types
@[derive has_reflect]
meta inductive simp_arg_type : Type
| all_hyps : simp_arg_type
| except : name → simp_arg_type
| expr : pexpr → simp_arg_type
| symm_expr : pexpr → simp_arg_type
meta instance simp_arg_type_to_tactic_format : has_to_tactic_format simp_arg_type :=
⟨λ a, match a with
| simp_arg_type.all_hyps := pure "*"
| (simp_arg_type.except n) := pure format!"-{n}"
| (simp_arg_type.expr e) := i_to_expr_no_subgoals e >>= pp
| (simp_arg_type.symm_expr e) := ((++) "←") <$> (i_to_expr_no_subgoals e >>= pp)
end⟩
meta def simp_arg : parser simp_arg_type :=
(tk "*" *> return simp_arg_type.all_hyps) <|>
(tk "-" *> simp_arg_type.except <$> ident) <|>
(tk "<-" *> simp_arg_type.symm_expr <$> texpr) <|>
(simp_arg_type.expr <$> texpr)
meta def simp_arg_list : parser (list simp_arg_type) :=
(tk "*" *> return [simp_arg_type.all_hyps]) <|> list_of simp_arg <|> return []
private meta def resolve_exception_ids (all_hyps : bool) : list name → list name → list name → tactic (list name × list name)
| [] gex hex := return (gex.reverse, hex.reverse)
| (id::ids) gex hex := do
p ← resolve_name id,
let e := p.erase_annotations.get_app_fn.erase_annotations,
match e with
| const n _ := resolve_exception_ids ids (n::gex) hex
| local_const n _ _ _ := when (not all_hyps) (fail $ sformat! "invalid local exception {id}, '*' was not used") >>
resolve_exception_ids ids gex (n::hex)
| _ := fail $ sformat! "invalid exception {id}, unknown identifier"
end
/-- Decode a list of `simp_arg_type` into lists for each type.
This is a backwards-compatibility version of `decode_simp_arg_list_with_symm`.
This version fails when an argument of the form `simp_arg_type.symm_expr`
is included, so that `simp`-like tactics that do not (yet) support backwards rewriting
should properly report an error but function normally on other inputs.
-/
meta def decode_simp_arg_list (hs : list simp_arg_type) : tactic $ list pexpr × list name × list name × bool :=
do
(hs, ex, all) ← hs.mfoldl
(λ (r : (list pexpr × list name × bool)) h, do
let (es, ex, all) := r,
match h with
| simp_arg_type.all_hyps := pure (es, ex, tt)
| simp_arg_type.except id := pure (es, id::ex, all)
| simp_arg_type.expr e := pure (e::es, ex, all)
| simp_arg_type.symm_expr _ := fail "arguments of the form '←...' are not supported"
end)
([], [], ff),
(gex, hex) ← resolve_exception_ids all ex [] [],
return (hs.reverse, gex, hex, all)
/-- Decode a list of `simp_arg_type` into lists for each type.
This is the newer version of `decode_simp_arg_list`,
and has a new name for backwards compatibility.
This version indicates the direction of a `simp` lemma by including a `bool` with the `pexpr`.
-/
meta def decode_simp_arg_list_with_symm (hs : list simp_arg_type) : tactic $ list (pexpr × bool) × list name × list name × bool :=
do
let (hs, ex, all) := hs.foldl
(λ r h,
match r, h with
| (es, ex, all), simp_arg_type.all_hyps := (es, ex, tt)
| (es, ex, all), simp_arg_type.except id := (es, id::ex, all)
| (es, ex, all), simp_arg_type.expr e := ((e, ff)::es, ex, all)
| (es, ex, all), simp_arg_type.symm_expr e := ((e, tt)::es, ex, all)
end)
([], [], ff),
(gex, hex) ← resolve_exception_ids all ex [] [],
return (hs.reverse, gex, hex, all)
private meta def add_simps : simp_lemmas → list (name × bool) → tactic simp_lemmas
| s [] := return s
| s (n::ns) := do s' ← s.add_simp n.fst n.snd, add_simps s' ns
private meta def report_invalid_simp_lemma {α : Type} (n : name): tactic α :=
fail format!"invalid simplification lemma '{n}' (use command 'set_option trace.simp_lemmas true' for more details)"
private meta def check_no_overload (p : pexpr) : tactic unit :=
when p.is_choice_macro $
match p with
| macro _ ps :=
fail $ to_fmt "ambiguous overload, possible interpretations" ++
format.join (ps.map (λ p, (to_fmt p).indent 4))
| _ := failed
end
private meta def simp_lemmas.resolve_and_add (s : simp_lemmas) (u : list name) (n : name) (ref : pexpr) (symm : bool) :
tactic (simp_lemmas × list name) :=
do
p ← resolve_name n,
check_no_overload p,
-- unpack local refs
let e := p.erase_annotations.get_app_fn.erase_annotations,
match e with
| const n _ :=
(do guard (¬ symm), has_attribute `congr n, s ← s.add_congr n, pure (s, u))
<|>
(do b ← is_valid_simp_lemma_cnst n, guard b, save_const_type_info n ref, s ← s.add_simp n symm, return (s, u))
<|>
(do eqns ← get_eqn_lemmas_for tt n,
guard (eqns.length > 0),
save_const_type_info n ref,
s ← add_simps s (eqns.map (λ e, (e, ff))),
return (s, u))
<|>
(do env ← get_env, guard (env.is_projection n).is_some, return (s, n::u))
<|>
report_invalid_simp_lemma n
| _ :=
(do e ← i_to_expr_no_subgoals p, b ← is_valid_simp_lemma e, guard b, try (save_type_info e ref), s ← s.add e symm, return (s, u))
<|>
report_invalid_simp_lemma n
end
private meta def simp_lemmas.add_pexpr (s : simp_lemmas) (u : list name) (p : pexpr) (symm : bool) :
tactic (simp_lemmas × list name) :=
match p with
| (const c []) := simp_lemmas.resolve_and_add s u c p symm
| (local_const c _ _ _) := simp_lemmas.resolve_and_add s u c p symm
| _ := do new_e ← i_to_expr_no_subgoals p,
s ← s.add new_e symm,
return (s, u)
end
private meta def simp_lemmas.append_pexprs :
simp_lemmas → list name → list (pexpr × bool) → tactic (simp_lemmas × list name)
| s u [] := return (s, u)
| s u (l::ls) := do
(s, u) ← simp_lemmas.add_pexpr s u l.fst l.snd,
simp_lemmas.append_pexprs s u ls
meta def mk_simp_set_core (no_dflt : bool) (attr_names : list name) (hs : list simp_arg_type) (at_star : bool)
: tactic (bool × simp_lemmas × list name) :=
do (hs, gex, hex, all_hyps) ← decode_simp_arg_list_with_symm hs,
when (all_hyps ∧ at_star ∧ not hex.empty) $ fail "A tactic of the form `simp [*, -h] at *` is currently not supported",
s ← join_user_simp_lemmas no_dflt attr_names,
-- Erase `h` from the default simp set for calls of the form `simp [←h]`.
let to_erase := hs.foldl (λ l h, match h with
| (const id _, tt) := id :: l
| (local_const id _ _ _, tt) := id :: l
| _ := l
end ) [],
let s := s.erase to_erase,
(s, u) ← simp_lemmas.append_pexprs s [] hs,
s ← if not at_star ∧ all_hyps then do
ctx ← collect_ctx_simps,
let ctx := ctx.filter (λ h, h.local_uniq_name ∉ hex), -- remove local exceptions
s.append ctx
else return s,
-- add equational lemmas, if any
gex ← gex.mmap (λ n, list.cons n <$> get_eqn_lemmas_for tt n),
return (all_hyps, simp_lemmas.erase s $ gex.join, u)
meta def mk_simp_set (no_dflt : bool) (attr_names : list name) (hs : list simp_arg_type) : tactic (simp_lemmas × list name) :=
prod.snd <$> (mk_simp_set_core no_dflt attr_names hs ff)
end mk_simp_set
namespace interactive
open _root_.interactive interactive.types expr
meta def simp_core_aux (cfg : simp_config) (discharger : tactic unit) (s : simp_lemmas) (u : list name) (hs : list expr) (tgt : bool) : tactic name_set :=
do (to_remove, lmss) ← @list.mfoldl tactic _ (list expr × name_set) _ (λ ⟨hs, lms⟩ h,
do h_type ← infer_type h,
(do (new_h_type, pr, new_lms) ← simplify s u h_type cfg `eq discharger,
assert h.local_pp_name new_h_type,
mk_eq_mp pr h >>= tactic.exact >> return (h::hs, lms.union new_lms))
<|>
(return (hs, lms)))
([], mk_name_set) hs,
(lms, goal_simplified) ← if tgt
then (simp_target s u cfg discharger >>= λ ns, return (ns, tt)) <|> (return (mk_name_set, ff))
else (return (mk_name_set, ff)),
guard (cfg.fail_if_unchanged = ff ∨ to_remove.length > 0 ∨ goal_simplified) <|> fail "simplify tactic failed to simplify",
to_remove.reverse.mmap' (λ h, try (clear h)),
return (lmss.union lms)
meta def simp_core (cfg : simp_config) (discharger : tactic unit)
(no_dflt : bool) (hs : list simp_arg_type) (attr_names : list name)
(locat : loc) : tactic name_set :=
do lms ← match locat with
| loc.wildcard := do (all_hyps, s, u) ← mk_simp_set_core no_dflt attr_names hs tt,
if all_hyps then tactic.simp_all s u cfg discharger
else do hyps ← non_dep_prop_hyps, simp_core_aux cfg discharger s u hyps tt
| _ := do (s, u) ← mk_simp_set no_dflt attr_names hs,
ns ← locat.get_locals,
simp_core_aux cfg discharger s u ns locat.include_goal
end,
try tactic.triv,
try (tactic.reflexivity reducible),
return lms
/--
The `simp` tactic uses lemmas and hypotheses to simplify the main goal target or non-dependent hypotheses. It has many variants.
`simp` simplifies the main goal target using lemmas tagged with the attribute `[simp]`.
`simp [h₁ h₂ ... hₙ]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and the given `hᵢ`'s, where the `hᵢ`'s are expressions. If `hᵢ` is preceded by left arrow (`←` or `<-`), the simplification is performed in the reverse direction. If an `hᵢ` is a defined constant `f`, then the equational lemmas associated with `f` are used. This provides a convenient way to unfold `f`.
`simp [*]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and all hypotheses.
`simp *` is a shorthand for `simp [*]`.
`simp only [h₁ h₂ ... hₙ]` is like `simp [h₁ h₂ ... hₙ]` but does not use `[simp]` lemmas
`simp [-id_1, ... -id_n]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]`, but removes the ones named `idᵢ`.
`simp at h₁ h₂ ... hₙ` simplifies the non-dependent hypotheses `h₁ : T₁` ... `hₙ : Tₙ`. The tactic fails if the target or another hypothesis depends on one of them. The token `⊢` or `|-` can be added to the list to include the target.
`simp at *` simplifies all the hypotheses and the target.
`simp * at *` simplifies target and all (non-dependent propositional) hypotheses using the other hypotheses.
`simp with attr₁ ... attrₙ` simplifies the main goal target using the lemmas tagged with any of the attributes `[attr₁]`, ..., `[attrₙ]` or `[simp]`.
-/
meta def simp (use_iota_eqn : parse $ (tk "!")?) (trace_lemmas : parse $ (tk "?")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list)
(locat : parse location) (cfg : simp_config_ext := {}) : tactic unit :=
let cfg := match use_iota_eqn, trace_lemmas with
| none , none := cfg
| (some _), none := {iota_eqn := tt, ..cfg}
| none , (some _) := {trace_lemmas := tt, ..cfg}
| (some _), (some _) := {iota_eqn := tt, trace_lemmas := tt, ..cfg}
end in
propagate_tags $
do lms ← simp_core cfg.to_simp_config cfg.discharger no_dflt hs attr_names locat,
if cfg.trace_lemmas then trace (↑"Try this: simp only " ++ to_fmt lms.to_list) else skip
/--
Just construct the simp set and trace it. Used for debugging.
-/
meta def trace_simp_set (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) : tactic unit :=
do (s, _) ← mk_simp_set no_dflt attr_names hs,
s.pp >>= trace
/--
`simp_intros h₁ h₂ ... hₙ` is similar to `intros h₁ h₂ ... hₙ` except that each hypothesis is simplified as it is introduced, and each introduced hypothesis is used to simplify later ones and the final target.
As with `simp`, a list of simplification lemmas can be provided. The modifiers `only` and `with` behave as with `simp`.
-/
meta def simp_intros (ids : parse ident_*) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list)
(cfg : simp_intros_config := {}) : tactic unit :=
do (s, u) ← mk_simp_set no_dflt attr_names hs,
when (¬u.empty) (fail (sformat! "simp_intros tactic does not support {u}")),
tactic.simp_intros s u ids cfg,
try triv >> try (reflexivity reducible)
private meta def to_simp_arg_list (symms : list bool) (es : list pexpr) : list simp_arg_type :=
(symms.zip es).map (λ ⟨s, e⟩, if s then simp_arg_type.symm_expr e else simp_arg_type.expr e)
/--
`dsimp` is similar to `simp`, except that it only uses definitional equalities.
-/
meta def dsimp (no_dflt : parse only_flag) (es : parse simp_arg_list) (attr_names : parse with_ident_list)
(l : parse location) (cfg : dsimp_config := {}) : tactic unit :=
do (s, u) ← mk_simp_set no_dflt attr_names es,
match l with
| loc.wildcard :=
/- Remark: we cannot revert frozen local instances.
We disable zeta expansion because to prevent `intron n` from failing.
Another option is to put a "marker" at the current target, and
implement `intro_upto_marker`. -/
do n ← revert_all,
dsimp_target s u {zeta := ff ..cfg},
intron n
| _ := l.apply (λ h, dsimp_hyp h s u cfg) (dsimp_target s u cfg)
end
/--
This tactic applies to a goal whose target has the form `t ~ u` where `~` is a reflexive relation, that is, a relation which has a reflexivity lemma tagged with the attribute `[refl]`. The tactic checks whether `t` and `u` are definitionally equal and then solves the goal.
-/
meta def reflexivity : tactic unit :=
tactic.reflexivity
/--
Shorter name for the tactic `reflexivity`.
-/
meta def refl : tactic unit :=
tactic.reflexivity
/--
This tactic applies to a goal whose target has the form `t ~ u` where `~` is a symmetric relation, that is, a relation which has a symmetry lemma tagged with the attribute `[symm]`. It replaces the target with `u ~ t`.
-/
meta def symmetry : tactic unit :=
tactic.symmetry
/--
This tactic applies to a goal whose target has the form `t ~ u` where `~` is a transitive relation, that is, a relation which has a transitivity lemma tagged with the attribute `[trans]`.
`transitivity s` replaces the goal with the two subgoals `t ~ s` and `s ~ u`. If `s` is omitted, then a metavariable is used instead.
-/
meta def transitivity (q : parse texpr?) : tactic unit :=
tactic.transitivity >> match q with
| none := skip
| some q :=
do (r, lhs, rhs) ← target_lhs_rhs,
i_to_expr q >>= unify rhs
end
/--
Proves a goal with target `s = t` when `s` and `t` are equal up to the associativity and commutativity of their binary operations.
-/
meta def ac_reflexivity : tactic unit :=
tactic.ac_refl
/--
An abbreviation for `ac_reflexivity`.
-/
meta def ac_refl : tactic unit :=
tactic.ac_refl
/--
Tries to prove the main goal using congruence closure.
-/
meta def cc : tactic unit :=
tactic.cc
/--
Given hypothesis `h : x = t` or `h : t = x`, where `x` is a local constant, `subst h` substitutes `x` by `t` everywhere in the main goal and then clears `h`.
-/
meta def subst (q : parse texpr) : tactic unit :=
i_to_expr q >>= tactic.subst >> try (tactic.reflexivity reducible)
/--
Apply `subst` to all hypotheses of the form `h : x = t` or `h : t = x`.
-/
meta def subst_vars : tactic unit :=
tactic.subst_vars
/--
`clear h₁ ... hₙ` tries to clear each hypothesis `hᵢ` from the local context.
-/
meta def clear : parse ident* → tactic unit :=
tactic.clear_lst
private meta def to_qualified_name_core : name → list name → tactic name
| n [] := fail $ "unknown declaration '" ++ to_string n ++ "'"
| n (ns::nss) := do
curr ← return $ ns ++ n,
env ← get_env,
if env.contains curr then return curr
else to_qualified_name_core n nss
private meta def to_qualified_name (n : name) : tactic name :=
do env ← get_env,
if env.contains n then return n
else do
ns ← open_namespaces,
to_qualified_name_core n ns
private meta def to_qualified_names : list name → tactic (list name)
| [] := return []
| (c::cs) := do new_c ← to_qualified_name c, new_cs ← to_qualified_names cs, return (new_c::new_cs)
/--
Similar to `unfold`, but only uses definitional equalities.
-/
meta def dunfold (cs : parse ident*) (l : parse location) (cfg : dunfold_config := {}) : tactic unit :=
match l with
| (loc.wildcard) := do ls ← tactic.local_context,
n ← revert_lst ls,
new_cs ← to_qualified_names cs,
dunfold_target new_cs cfg,
intron n
| _ := do new_cs ← to_qualified_names cs, l.apply (λ h, dunfold_hyp cs h cfg) (dunfold_target new_cs cfg)
end
private meta def delta_hyps : list name → list name → tactic unit
| cs [] := skip
| cs (h::hs) := get_local h >>= delta_hyp cs >> delta_hyps cs hs
/--
Similar to `dunfold`, but performs a raw delta reduction, rather than using an equation associated with the defined constants.
-/
meta def delta : parse ident* → parse location → tactic unit
| cs (loc.wildcard) := do ls ← tactic.local_context,
n ← revert_lst ls,
new_cs ← to_qualified_names cs,
delta_target new_cs,
intron n
| cs l := do new_cs ← to_qualified_names cs, l.apply (delta_hyp new_cs) (delta_target new_cs)
private meta def unfold_projs_hyps (cfg : unfold_proj_config := {}) (hs : list name) : tactic bool :=
hs.mfoldl (λ r h, do h ← get_local h, (unfold_projs_hyp h cfg >> return tt) <|> return r) ff
/--
This tactic unfolds all structure projections.
-/
meta def unfold_projs (l : parse location) (cfg : unfold_proj_config := {}) : tactic unit :=
match l with
| loc.wildcard := do ls ← local_context,
b₁ ← unfold_projs_hyps cfg (ls.map expr.local_pp_name),
b₂ ← (tactic.unfold_projs_target cfg >> return tt) <|> return ff,
when (not b₁ ∧ not b₂) (fail "unfold_projs failed to simplify")
| _ :=
l.try_apply (λ h, unfold_projs_hyp h cfg)
(tactic.unfold_projs_target cfg) <|> fail "unfold_projs failed to simplify"
end
end interactive
meta def ids_to_simp_arg_list (tac_name : name) (cs : list name) : tactic (list simp_arg_type) :=
cs.mmap $ λ c, do
n ← resolve_name c,
hs ← get_eqn_lemmas_for ff n.const_name,
env ← get_env,
let p := env.is_projection n.const_name,
when (hs.empty ∧ p.is_none) (fail (sformat! "{tac_name} tactic failed, {c} does not have equational lemmas nor is a projection")),
return $ simp_arg_type.expr (expr.const c [])
structure unfold_config extends simp_config :=
(zeta := ff)
(proj := ff)
(eta := ff)
(canonize_instances := ff)
(constructor_eq := ff)
namespace interactive
open _root_.interactive interactive.types expr
/--
Given defined constants `e₁ ... eₙ`, `unfold e₁ ... eₙ` iteratively unfolds all occurrences in the target of the main goal, using equational lemmas associated with the definitions.
As with `simp`, the `at` modifier can be used to specify locations for the unfolding.
-/
meta def unfold (cs : parse ident*) (locat : parse location) (cfg : unfold_config := {}) : tactic unit :=
do es ← ids_to_simp_arg_list "unfold" cs,
let no_dflt := tt,
simp_core cfg.to_simp_config failed no_dflt es [] locat,
skip
/--
Similar to `unfold`, but does not iterate the unfolding.
-/
meta def unfold1 (cs : parse ident*) (locat : parse location) (cfg : unfold_config := {single_pass := tt}) : tactic unit :=
unfold cs locat cfg
/--
If the target of the main goal is an `opt_param`, assigns the default value.
-/
meta def apply_opt_param : tactic unit :=
tactic.apply_opt_param
/--
If the target of the main goal is an `auto_param`, executes the associated tactic.
-/
meta def apply_auto_param : tactic unit :=
tactic.apply_auto_param
/--
Fails if the given tactic succeeds.
-/
meta def fail_if_success (tac : itactic) : tactic unit :=
tactic.fail_if_success tac
/--
Succeeds if the given tactic fails.
-/
meta def success_if_fail (tac : itactic) : tactic unit :=
tactic.success_if_fail tac
meta def guard_expr_eq (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit :=
do e ← to_expr p, guard (alpha_eqv t e)
/--
`guard_target t` fails if the target of the main goal is not `t`.
We use this tactic for writing tests.
-/
meta def guard_target (p : parse texpr) : tactic unit :=
do t ← target, guard_expr_eq t p
/--
`guard_hyp h : t` fails if the hypothesis `h` does not have type `t`.
We use this tactic for writing tests.
-/
meta def guard_hyp (n : parse ident)
(ty : parse (tk ":" *> texpr)?)
(val : parse (tk ":=" *> texpr)?) : tactic unit := do
h ← get_local n,
ldecl ← tactic.unsafe.type_context.run (do
lctx ← unsafe.type_context.get_local_context,
pure $ lctx.get_local_decl h.local_uniq_name),
ldecl ← ldecl | fail format!"hypothesis {h} not found",
match ty with
| some p := guard_expr_eq ldecl.type p
| none := skip
end,
match ldecl.value, val with
| none, some _ := fail format!"{h} is not a let binding"
| some _, none := fail format!"{h} is a let binding"
| some hval, some val := guard_expr_eq hval val
| none, none := skip
end
/--
`match_target t` fails if target does not match pattern `t`.
-/
meta def match_target (t : parse texpr) (m := reducible) : tactic unit :=
tactic.match_target t m >> skip
/--
`by_cases p` splits the main goal into two cases, assuming `h : p` in the first branch, and
`h : ¬ p` in the second branch. You can specify the name of the new hypothesis using the syntax
`by_cases h : p`.
-/
meta def by_cases : parse cases_arg_p → tactic unit
| (n, q) := concat_tags $ do
p ← tactic.to_expr_strict q,
tactic.by_cases p (n.get_or_else `h),
pos_g :: neg_g :: rest ← get_goals,
return [(`pos, pos_g), (`neg, neg_g)]
/--
Apply function extensionality and introduce new hypotheses.
The tactic `funext` will keep applying new the `funext` lemma until the goal target is not reducible to
```
|- ((fun x, ...) = (fun x, ...))
```
The variant `funext h₁ ... hₙ` applies `funext` `n` times, and uses the given identifiers to name the new hypotheses.
-/
meta def funext : parse ident_* → tactic unit
| [] := tactic.funext >> skip
| hs := funext_lst hs >> skip
/--
If the target of the main goal is a proposition `p`, `by_contradiction` reduces the goal to proving `false` using the additional hypothesis `h : ¬ p`. `by_contradiction h` can be used to name the hypothesis `h : ¬ p`.
This tactic will attempt to use decidability of `p` if available, and will otherwise fall back on classical reasoning.
-/
meta def by_contradiction (n : parse ident?) : tactic unit :=
tactic.by_contradiction (n.get_or_else `h) $> ()
/--
If the target of the main goal is a proposition `p`, `by_contra` reduces the goal to proving `false` using the additional hypothesis `h : ¬ p`. `by_contra h` can be used to name the hypothesis `h : ¬ p`.
This tactic will attempt to use decidability of `p` if available, and will otherwise fall back on classical reasoning.
-/
meta def by_contra (n : parse ident?) : tactic unit :=
by_contradiction n
/--
Type check the given expression, and trace its type.
-/
meta def type_check (p : parse texpr) : tactic unit :=
do e ← to_expr p, tactic.type_check e, infer_type e >>= trace
/--
Fail if there are unsolved goals.
-/
meta def done : tactic unit :=
tactic.done
private meta def show_aux (p : pexpr) : list expr → list expr → tactic unit
| [] r := fail "show tactic failed"
| (g::gs) r := do
do {set_goals [g], g_ty ← target, ty ← i_to_expr p, unify g_ty ty, set_goals (g :: r.reverse ++ gs), tactic.change ty}
<|>
show_aux gs (g::r)
/--
`show t` finds the first goal whose target unifies with `t`. It makes that the main goal, performs the unification, and replaces the target with the unified version of `t`.
-/
meta def «show» (q : parse texpr) : tactic unit :=
do gs ← get_goals,
show_aux q gs []
/--
The tactic `specialize h a₁ ... aₙ` works on local hypothesis `h`. The premises of this hypothesis, either universal quantifications or non-dependent implications, are instantiated by concrete terms coming either from arguments `a₁` ... `aₙ`. The tactic adds a new hypothesis with the same name `h := h a₁ ... aₙ` and tries to clear the previous one.
-/
meta def specialize (p : parse texpr) : tactic unit :=
focus1 $
do e ← i_to_expr p,
let h := expr.get_app_fn e,
if h.is_local_constant
then tactic.note h.local_pp_name none e >> try (tactic.clear h) >> rotate 1
else tactic.fail "specialize requires a term of the form `h x_1 .. x_n` where `h` appears in the local context"
meta def congr := tactic.congr
end interactive
end tactic
section add_interactive
open tactic
/- See add_interactive -/
private meta def add_interactive_aux (new_namespace : name) : list name → command
| [] := return ()
| (n::ns) := do
env ← get_env,
d_name ← resolve_constant n,
(declaration.defn _ ls ty val hints trusted) ← env.get d_name,
(name.mk_string h _) ← return d_name,
let new_name := new_namespace <.> h,
add_decl (declaration.defn new_name ls ty (expr.const d_name (ls.map level.param)) hints trusted),
do {
doc ← doc_string d_name,
add_doc_string new_name doc
} <|> skip,
add_interactive_aux ns
/--
Copy a list of meta definitions in the current namespace to tactic.interactive.
This command is useful when we want to update tactic.interactive without closing the current namespace.
-/
meta def add_interactive (ns : list name) (p : name := `tactic.interactive) : command :=
add_interactive_aux p ns
meta def has_dup : tactic bool :=
do ctx ← local_context,
let p : name_set × bool :=
ctx.foldl (λ ⟨s, r⟩ h,
if r then (s, r)
else if s.contains h.local_pp_name then (s, tt)
else (s.insert h.local_pp_name, ff))
(mk_name_set, ff),
return p.2
/--
Renames hypotheses with the same name.
-/
meta def dedup : tactic unit :=
mwhen has_dup $ do
ctx ← local_context,
n ← revert_lst ctx,
intron n
end add_interactive
namespace tactic
/- Helper tactic for `mk_inj_eq -/
protected meta def apply_inj_lemma : tactic unit :=
do h ← intro `h,
some (lhs, rhs) ← expr.is_eq <$> infer_type h,
(expr.const C _) ← return lhs.get_app_fn,
-- We disable auto_param and opt_param support to address issue #1943
applyc (name.mk_string "inj" C) {auto_param := ff, opt_param := ff},
assumption
/- Auxiliary tactic for proving `I.C.inj_eq` lemmas.
These lemmas are automatically generated by the equation compiler.
Example:
```
list.cons.inj_eq : forall h1 h2 t1 t2, (h1::t1 = h2::t2) = (h1 = h2 ∧ t1 = t2) :=
by mk_inj_eq
```
-/
meta def mk_inj_eq : tactic unit :=
`[
intros,
/-
We use `_root_.*` in the following tactics because
names are resolved at tactic execution time in interactive mode.
See PR #1913
TODO(Leo): This is probably not the only instance of this problem.
`[ ... ] blocks are convenient to use because they allow us to use the interactive
mode to write non interactive tactics.
One potential fix for this issue is to resolve names in `[ ... ] at tactic
compilation time.
After this issue is fixed, we should remove the `_root_.*` workaround.
-/
apply _root_.propext,
apply _root_.iff.intro,
{ tactic.apply_inj_lemma },
{ intro _, try { cases_matching* _ ∧ _ }, refl <|> { congr; { assumption <|> subst_vars } } }
]
end tactic
/- Define inj_eq lemmas for inductive datatypes that were declared before `mk_inj_eq` -/
universes u v
lemma sum.inl.inj_eq {α : Type u} (β : Type v) (a₁ a₂ : α) : (@sum.inl α β a₁ = sum.inl a₂) = (a₁ = a₂) :=
by tactic.mk_inj_eq
lemma sum.inr.inj_eq (α : Type u) {β : Type v} (b₁ b₂ : β) : (@sum.inr α β b₁ = sum.inr b₂) = (b₁ = b₂) :=
by tactic.mk_inj_eq
lemma psum.inl.inj_eq {α : Sort u} (β : Sort v) (a₁ a₂ : α) : (@psum.inl α β a₁ = psum.inl a₂) = (a₁ = a₂) :=
by tactic.mk_inj_eq
lemma psum.inr.inj_eq (α : Sort u) {β : Sort v} (b₁ b₂ : β) : (@psum.inr α β b₁ = psum.inr b₂) = (b₁ = b₂) :=
by tactic.mk_inj_eq
lemma sigma.mk.inj_eq {α : Type u} {β : α → Type v} (a₁ : α) (b₁ : β a₁) (a₂ : α) (b₂ : β a₂) : (sigma.mk a₁ b₁ = sigma.mk a₂ b₂) = (a₁ = a₂ ∧ b₁ == b₂) :=
by tactic.mk_inj_eq
lemma psigma.mk.inj_eq {α : Sort u} {β : α → Sort v} (a₁ : α) (b₁ : β a₁) (a₂ : α) (b₂ : β a₂) : (psigma.mk a₁ b₁ = psigma.mk a₂ b₂) = (a₁ = a₂ ∧ b₁ == b₂) :=
by tactic.mk_inj_eq
lemma subtype.mk.inj_eq {α : Sort u} {p : α → Prop} (a₁ : α) (h₁ : p a₁) (a₂ : α) (h₂ : p a₂) : (subtype.mk a₁ h₁ = subtype.mk a₂ h₂) = (a₁ = a₂) :=
by tactic.mk_inj_eq
lemma option.some.inj_eq {α : Type u} (a₁ a₂ : α) : (some a₁ = some a₂) = (a₁ = a₂) :=
by tactic.mk_inj_eq
lemma list.cons.inj_eq {α : Type u} (h₁ : α) (t₁ : list α) (h₂ : α) (t₂ : list α) : (list.cons h₁ t₁ = list.cons h₂ t₂) = (h₁ = h₂ ∧ t₁ = t₂) :=
by tactic.mk_inj_eq
lemma nat.succ.inj_eq (n₁ n₂ : nat) : (nat.succ n₁ = nat.succ n₂) = (n₁ = n₂) :=
by tactic.mk_inj_eq
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.