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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ca59b74cf5c49e6fe15f7f335c4a5f1e3853ccd3 | b2fe74b11b57d362c13326bc5651244f111fa6f4 | /src/algebra/ordered_ring.lean | b1c086b08be616a9e6233c63980d8a2157540a42 | [
"Apache-2.0"
] | permissive | midfield/mathlib | c4db5fa898b5ac8f2f80ae0d00c95eb6f745f4c7 | 775edc615ecec631d65b6180dbcc7bc26c3abc26 | refs/heads/master | 1,675,330,551,921 | 1,608,304,514,000 | 1,608,304,514,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 43,140 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro
-/
import algebra.ordered_group
import data.set.intervals.basic
set_option old_structure_cmd true
universe u
variable {α : Type u}
/-- An `ordered_semiring α` is a semiring `α` with a partial order such that
multiplication with a positive number and addition are monotone. -/
@[protect_proj]
class ordered_semiring (α : Type u) extends semiring α, ordered_cancel_add_comm_monoid α :=
(zero_le_one : 0 ≤ (1 : α))
(mul_lt_mul_of_pos_left : ∀ a b c : α, a < b → 0 < c → c * a < c * b)
(mul_lt_mul_of_pos_right : ∀ a b c : α, a < b → 0 < c → a * c < b * c)
section ordered_semiring
variables [ordered_semiring α] {a b c d : α}
lemma zero_le_one : 0 ≤ (1:α) :=
ordered_semiring.zero_le_one
lemma zero_le_two : 0 ≤ (2:α) :=
add_nonneg zero_le_one zero_le_one
section nontrivial
variables [nontrivial α]
lemma zero_lt_one : 0 < (1 : α) :=
lt_of_le_of_ne zero_le_one zero_ne_one
lemma zero_lt_two : 0 < (2:α) := add_pos zero_lt_one zero_lt_one
@[field_simps] lemma two_ne_zero : (2:α) ≠ 0 :=
ne.symm (ne_of_lt zero_lt_two)
lemma one_lt_two : 1 < (2:α) :=
calc (2:α) = 1+1 : one_add_one_eq_two
... > 1+0 : add_lt_add_left zero_lt_one _
... = 1 : add_zero 1
lemma one_le_two : 1 ≤ (2:α) := one_lt_two.le
lemma zero_lt_three : 0 < (3:α) := add_pos zero_lt_two zero_lt_one
lemma zero_lt_four : 0 < (4:α) := add_pos zero_lt_two zero_lt_two
end nontrivial
lemma mul_lt_mul_of_pos_left (h₁ : a < b) (h₂ : 0 < c) : c * a < c * b :=
ordered_semiring.mul_lt_mul_of_pos_left a b c h₁ h₂
lemma mul_lt_mul_of_pos_right (h₁ : a < b) (h₂ : 0 < c) : a * c < b * c :=
ordered_semiring.mul_lt_mul_of_pos_right a b c h₁ h₂
lemma mul_le_mul_of_nonneg_left (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c * a ≤ c * b :=
begin
cases classical.em (b ≤ a), { simp [h.antisymm h₁] },
cases classical.em (c ≤ 0), { simp [h_1.antisymm h₂] },
exact (mul_lt_mul_of_pos_left (h₁.lt_of_not_le h) (h₂.lt_of_not_le h_1)).le,
end
lemma mul_le_mul_of_nonneg_right (h₁ : a ≤ b) (h₂ : 0 ≤ c) : a * c ≤ b * c :=
begin
cases classical.em (b ≤ a), { simp [h.antisymm h₁] },
cases classical.em (c ≤ 0), { simp [h_1.antisymm h₂] },
exact (mul_lt_mul_of_pos_right (h₁.lt_of_not_le h) (h₂.lt_of_not_le h_1)).le,
end
-- TODO: there are four variations, depending on which variables we assume to be nonneg
lemma mul_le_mul (hac : a ≤ c) (hbd : b ≤ d) (nn_b : 0 ≤ b) (nn_c : 0 ≤ c) : a * b ≤ c * d :=
calc
a * b ≤ c * b : mul_le_mul_of_nonneg_right hac nn_b
... ≤ c * d : mul_le_mul_of_nonneg_left hbd nn_c
lemma mul_nonneg (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b :=
have h : 0 * b ≤ a * b, from mul_le_mul_of_nonneg_right ha hb,
by rwa [zero_mul] at h
lemma mul_nonpos_of_nonneg_of_nonpos (ha : 0 ≤ a) (hb : b ≤ 0) : a * b ≤ 0 :=
have h : a * b ≤ a * 0, from mul_le_mul_of_nonneg_left hb ha,
by rwa mul_zero at h
lemma mul_nonpos_of_nonpos_of_nonneg (ha : a ≤ 0) (hb : 0 ≤ b) : a * b ≤ 0 :=
have h : a * b ≤ 0 * b, from mul_le_mul_of_nonneg_right ha hb,
by rwa zero_mul at h
lemma mul_lt_mul (hac : a < c) (hbd : b ≤ d) (pos_b : 0 < b) (nn_c : 0 ≤ c) : a * b < c * d :=
calc
a * b < c * b : mul_lt_mul_of_pos_right hac pos_b
... ≤ c * d : mul_le_mul_of_nonneg_left hbd nn_c
lemma mul_lt_mul' (h1 : a ≤ c) (h2 : b < d) (h3 : 0 ≤ b) (h4 : 0 < c) : a * b < c * d :=
calc
a * b ≤ c * b : mul_le_mul_of_nonneg_right h1 h3
... < c * d : mul_lt_mul_of_pos_left h2 h4
lemma mul_pos (ha : 0 < a) (hb : 0 < b) : 0 < a * b :=
have h : 0 * b < a * b, from mul_lt_mul_of_pos_right ha hb,
by rwa zero_mul at h
lemma mul_neg_of_pos_of_neg (ha : 0 < a) (hb : b < 0) : a * b < 0 :=
have h : a * b < a * 0, from mul_lt_mul_of_pos_left hb ha,
by rwa mul_zero at h
lemma mul_neg_of_neg_of_pos (ha : a < 0) (hb : 0 < b) : a * b < 0 :=
have h : a * b < 0 * b, from mul_lt_mul_of_pos_right ha hb,
by rwa zero_mul at h
lemma mul_self_lt_mul_self (h1 : 0 ≤ a) (h2 : a < b) : a * a < b * b :=
mul_lt_mul' h2.le h2 h1 $ h1.trans_lt h2
lemma strict_mono_incr_on_mul_self : strict_mono_incr_on (λ x : α, x * x) (set.Ici 0) :=
λ x hx y hy hxy, mul_self_lt_mul_self hx hxy
lemma mul_self_le_mul_self (h1 : 0 ≤ a) (h2 : a ≤ b) : a * a ≤ b * b :=
mul_le_mul h2 h2 h1 $ h1.trans h2
lemma mul_lt_mul'' (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 h2.le b0 $ h3.trans h1.le)
(λ b0, by rw [← b0, mul_zero]; exact
mul_pos (h3.trans_lt h1) (h4.trans_lt h2))
lemma le_mul_of_one_le_right (hb : 0 ≤ b) (h : 1 ≤ a) : 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_one_le_left (hb : 0 ≤ b) (h : 1 ≤ a) : b ≤ a * b :=
suffices 1 * b ≤ a * b, by rwa one_mul at this,
mul_le_mul_of_nonneg_right h hb
section
variable [nontrivial α]
lemma bit1_pos (h : 0 ≤ a) : 0 < bit1 a :=
lt_add_of_le_of_pos (add_nonneg h h) zero_lt_one
lemma lt_add_one (a : α) : a < a + 1 :=
lt_add_of_le_of_pos le_rfl zero_lt_one
lemma lt_one_add (a : α) : a < 1 + a :=
by { rw [add_comm], apply lt_add_one }
end
lemma bit1_pos' (h : 0 < a) : 0 < bit1 a :=
begin
nontriviality,
exact bit1_pos h.le,
end
lemma one_lt_mul (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b :=
begin
nontriviality,
exact (one_mul (1 : α)) ▸ mul_lt_mul' ha hb zero_le_one (zero_lt_one.trans_le ha)
end
lemma mul_le_one (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
lemma one_lt_mul_of_le_of_lt (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b :=
begin
nontriviality,
calc 1 = 1 * 1 : by rw one_mul
... < a * b : mul_lt_mul' ha hb zero_le_one (zero_lt_one.trans_le ha)
end
lemma one_lt_mul_of_lt_of_le (ha : 1 < a) (hb : 1 ≤ b) : 1 < a * b :=
begin
nontriviality,
calc 1 = 1 * 1 : by rw one_mul
... < a * b : mul_lt_mul ha hb zero_lt_one $ zero_le_one.trans ha.le
end
lemma mul_le_of_le_one_right (ha : 0 ≤ a) (hb1 : b ≤ 1) : a * b ≤ a :=
calc a * b ≤ a * 1 : mul_le_mul_of_nonneg_left hb1 ha
... = a : mul_one a
lemma mul_le_of_le_one_left (hb : 0 ≤ b) (ha1 : a ≤ 1) : a * b ≤ b :=
calc a * b ≤ 1 * b : mul_le_mul ha1 le_rfl hb zero_le_one
... = b : one_mul b
lemma mul_lt_one_of_nonneg_of_lt_one_left (ha0 : 0 ≤ a) (ha : a < 1) (hb : b ≤ 1) : a * b < 1 :=
calc a * b ≤ a : mul_le_of_le_one_right ha0 hb
... < 1 : ha
lemma mul_lt_one_of_nonneg_of_lt_one_right (ha : a ≤ 1) (hb0 : 0 ≤ b) (hb : b < 1) : a * b < 1 :=
calc a * b ≤ b : mul_le_of_le_one_left hb0 ha
... < 1 : hb
end ordered_semiring
/--
A `linear_ordered_semiring α` is a nontrivial semiring `α` with a linear order
such that multiplication with a positive number and addition are monotone.
-/
-- It's not entirely clear we should assume `nontrivial` at this point;
-- it would be reasonable to explore changing this,
-- but be warned that the instances involving `domain` may cause
-- typeclass search loops.
@[protect_proj]
class linear_ordered_semiring (α : Type u) extends ordered_semiring α, linear_order α, nontrivial α
section linear_ordered_semiring
variables [linear_ordered_semiring α] {a b c d : α}
-- `norm_num` expects the lemma stating `0 < 1` to have a single typeclass argument
-- (see `norm_num.prove_pos_nat`).
-- Rather than working out how to relax that assumption,
-- we provide a synonym for `zero_lt_one` (which needs both `ordered_semiring α` and `nontrivial α`)
-- with only a `linear_ordered_semiring` typeclass argument.
lemma zero_lt_one' : 0 < (1 : α) := zero_lt_one
lemma lt_of_mul_lt_mul_left (h : c * a < c * b) (hc : 0 ≤ c) : a < b :=
lt_of_not_ge
(assume h1 : b ≤ a,
have h2 : c * b ≤ c * a, from mul_le_mul_of_nonneg_left h1 hc,
h2.not_lt h)
lemma lt_of_mul_lt_mul_right (h : a * c < b * c) (hc : 0 ≤ c) : a < b :=
lt_of_not_ge
(assume h1 : b ≤ a,
have h2 : b * c ≤ a * c, from mul_le_mul_of_nonneg_right h1 hc,
h2.not_lt h)
lemma le_of_mul_le_mul_left (h : c * a ≤ c * b) (hc : 0 < c) : a ≤ b :=
le_of_not_gt
(assume h1 : b < a,
have h2 : c * b < c * a, from mul_lt_mul_of_pos_left h1 hc,
h2.not_le h)
lemma le_of_mul_le_mul_right (h : a * c ≤ b * c) (hc : 0 < c) : a ≤ b :=
le_of_not_gt
(assume h1 : b < a,
have h2 : b * c < a * c, from mul_lt_mul_of_pos_right h1 hc,
h2.not_le h)
lemma pos_and_pos_or_neg_and_neg_of_mul_pos (hab : 0 < a * b) :
(0 < a ∧ 0 < b) ∨ (a < 0 ∧ b < 0) :=
begin
rcases lt_trichotomy 0 a with (ha|rfl|ha),
{ refine or.inl ⟨ha, _⟩,
contrapose! hab,
exact mul_nonpos_of_nonneg_of_nonpos ha.le hab },
{ rw [zero_mul] at hab, exact hab.false.elim },
{ refine or.inr ⟨ha, _⟩,
contrapose! hab,
exact mul_nonpos_of_nonpos_of_nonneg ha.le hab }
end
lemma nonneg_and_nonneg_or_nonpos_and_nonpos_of_mul_nnonneg (hab : 0 ≤ a * b) :
(0 ≤ a ∧ 0 ≤ b) ∨ (a ≤ 0 ∧ b ≤ 0) :=
begin
contrapose! hab,
rcases lt_trichotomy 0 a with (ha|rfl|ha),
exacts [mul_neg_of_pos_of_neg ha (hab.1 ha.le), ((hab.1 le_rfl).asymm (hab.2 le_rfl)).elim,
mul_neg_of_neg_of_pos ha (hab.2 ha.le)]
end
lemma pos_of_mul_pos_left (h : 0 < a * b) (ha : 0 ≤ a) : 0 < b :=
((pos_and_pos_or_neg_and_neg_of_mul_pos h).resolve_right $ λ h, h.1.not_le ha).2
lemma pos_of_mul_pos_right (h : 0 < a * b) (hb : 0 ≤ b) : 0 < a :=
((pos_and_pos_or_neg_and_neg_of_mul_pos h).resolve_right $ λ h, h.2.not_le hb).1
lemma nonneg_of_mul_nonneg_left (h : 0 ≤ a * b) (h1 : 0 < a) : 0 ≤ b :=
le_of_not_gt (assume h2 : b < 0, (mul_neg_of_pos_of_neg h1 h2).not_le h)
lemma nonneg_of_mul_nonneg_right (h : 0 ≤ a * b) (h1 : 0 < b) : 0 ≤ a :=
le_of_not_gt (assume h2 : a < 0, (mul_neg_of_neg_of_pos h2 h1).not_le h)
lemma neg_of_mul_neg_left (h : a * b < 0) (h1 : 0 ≤ a) : b < 0 :=
lt_of_not_ge (assume h2 : b ≥ 0, (mul_nonneg h1 h2).not_lt h)
lemma neg_of_mul_neg_right (h : a * b < 0) (h1 : 0 ≤ b) : a < 0 :=
lt_of_not_ge (assume h2 : a ≥ 0, (mul_nonneg h2 h1).not_lt h)
lemma nonpos_of_mul_nonpos_left (h : a * b ≤ 0) (h1 : 0 < a) : b ≤ 0 :=
le_of_not_gt (assume h2 : b > 0, (mul_pos h1 h2).not_le h)
lemma nonpos_of_mul_nonpos_right (h : a * b ≤ 0) (h1 : 0 < b) : a ≤ 0 :=
le_of_not_gt (assume h2 : a > 0, (mul_pos h2 h1).not_le h)
@[simp] lemma mul_le_mul_left (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' h.le⟩
@[simp] lemma mul_le_mul_right (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' h.le⟩
@[simp] lemma mul_lt_mul_left (h : 0 < c) : c * a < c * b ↔ a < b :=
⟨lt_imp_lt_of_le_imp_le $ λ h', mul_le_mul_of_nonneg_left h' h.le,
λ h', mul_lt_mul_of_pos_left h' h⟩
@[simp] lemma mul_lt_mul_right (h : 0 < c) : a * c < b * c ↔ a < b :=
⟨lt_imp_lt_of_le_imp_le $ λ h', mul_le_mul_of_nonneg_right h' h.le,
λ h', mul_lt_mul_of_pos_right h' h⟩
@[simp] lemma zero_le_mul_left (h : 0 < c) : 0 ≤ c * b ↔ 0 ≤ b :=
by { convert mul_le_mul_left h, simp }
@[simp] lemma zero_le_mul_right (h : 0 < c) : 0 ≤ b * c ↔ 0 ≤ b :=
by { convert mul_le_mul_right h, simp }
@[simp] lemma zero_lt_mul_left (h : 0 < c) : 0 < c * b ↔ 0 < b :=
by { convert mul_lt_mul_left h, simp }
@[simp] lemma zero_lt_mul_right (h : 0 < c) : 0 < b * c ↔ 0 < b :=
by { convert mul_lt_mul_right h, simp }
section
variables [nontrivial α]
@[simp] lemma bit0_le_bit0 : bit0 a ≤ bit0 b ↔ a ≤ b :=
by rw [bit0, bit0, ← two_mul, ← two_mul, mul_le_mul_left (zero_lt_two : 0 < (2:α))]
@[simp] lemma bit0_lt_bit0 : bit0 a < bit0 b ↔ a < b :=
by rw [bit0, bit0, ← two_mul, ← two_mul, mul_lt_mul_left (zero_lt_two : 0 < (2:α))]
@[simp] lemma bit1_le_bit1 : bit1 a ≤ bit1 b ↔ a ≤ b :=
(add_le_add_iff_right 1).trans bit0_le_bit0
@[simp] lemma bit1_lt_bit1 : bit1 a < bit1 b ↔ a < b :=
(add_lt_add_iff_right 1).trans bit0_lt_bit0
@[simp] lemma one_le_bit1 : (1 : α) ≤ bit1 a ↔ 0 ≤ a :=
by rw [bit1, le_add_iff_nonneg_left, bit0, ← two_mul, zero_le_mul_left (zero_lt_two : 0 < (2:α))]
@[simp] lemma one_lt_bit1 : (1 : α) < bit1 a ↔ 0 < a :=
by rw [bit1, lt_add_iff_pos_left, bit0, ← two_mul, zero_lt_mul_left (zero_lt_two : 0 < (2:α))]
@[simp] lemma zero_le_bit0 : (0 : α) ≤ bit0 a ↔ 0 ≤ a :=
by rw [bit0, ← two_mul, zero_le_mul_left (zero_lt_two : 0 < (2:α))]
@[simp] lemma zero_lt_bit0 : (0 : α) < bit0 a ↔ 0 < a :=
by rw [bit0, ← two_mul, zero_lt_mul_left (zero_lt_two : 0 < (2:α))]
end
lemma le_mul_iff_one_le_left (hb : 0 < b) : 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 (hb : 0 < b) : 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 (hb : 0 < b) : 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 (hb : 0 < b) : 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_one_lt_right (hb : 0 < b) : 1 < a → b < b * a :=
(lt_mul_iff_one_lt_right hb).2
theorem mul_nonneg_iff_right_nonneg_of_pos (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 h.le⟩
lemma mul_le_iff_le_one_left (hb : 0 < b) : a * b ≤ b ↔ a ≤ 1 :=
⟨ λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).2 h.not_lt),
λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).1 h.not_lt) ⟩
lemma mul_lt_iff_lt_one_left (hb : 0 < b) : a * b < b ↔ a < 1 :=
⟨ λ h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).2 h.not_le),
λ h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).1 h.not_le) ⟩
lemma mul_le_iff_le_one_right (hb : 0 < b) : b * a ≤ b ↔ a ≤ 1 :=
⟨ λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).2 h.not_lt),
λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).1 h.not_lt) ⟩
lemma mul_lt_iff_lt_one_right (hb : 0 < b) : b * a < b ↔ a < 1 :=
⟨ λ h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).2 h.not_le),
λ h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).1 h.not_le) ⟩
lemma nonpos_of_mul_nonneg_left (h : 0 ≤ a * b) (hb : b < 0) : a ≤ 0 :=
le_of_not_gt (λ ha, absurd h (mul_neg_of_pos_of_neg ha hb).not_le)
lemma nonpos_of_mul_nonneg_right (h : 0 ≤ a * b) (ha : a < 0) : b ≤ 0 :=
le_of_not_gt (λ hb, absurd h (mul_neg_of_neg_of_pos ha hb).not_le)
lemma neg_of_mul_pos_left (h : 0 < a * b) (hb : b ≤ 0) : a < 0 :=
lt_of_not_ge (λ ha, absurd h (mul_nonpos_of_nonneg_of_nonpos ha hb).not_lt)
lemma neg_of_mul_pos_right (h : 0 < a * b) (ha : a ≤ 0) : b < 0 :=
lt_of_not_ge (λ hb, absurd h (mul_nonpos_of_nonpos_of_nonneg ha hb).not_lt)
@[priority 100] -- see Note [lower instance priority]
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⟩⟩
end linear_ordered_semiring
section mono
variables {β : Type*} [linear_ordered_semiring α] [preorder β] {f g : β → α} {a : α}
lemma monotone_mul_left_of_nonneg (ha : 0 ≤ a) : monotone (λ x, a*x) :=
assume b c b_le_c, mul_le_mul_of_nonneg_left b_le_c ha
lemma monotone_mul_right_of_nonneg (ha : 0 ≤ a) : monotone (λ x, x*a) :=
assume b c b_le_c, mul_le_mul_of_nonneg_right b_le_c ha
lemma monotone.mul_const (hf : monotone f) (ha : 0 ≤ a) :
monotone (λ x, (f x) * a) :=
(monotone_mul_right_of_nonneg ha).comp hf
lemma monotone.const_mul (hf : monotone f) (ha : 0 ≤ a) :
monotone (λ x, a * (f x)) :=
(monotone_mul_left_of_nonneg ha).comp hf
lemma monotone.mul (hf : monotone f) (hg : monotone g) (hf0 : ∀ x, 0 ≤ f x) (hg0 : ∀ x, 0 ≤ g x) :
monotone (λ x, f x * g x) :=
λ x y h, mul_le_mul (hf h) (hg h) (hg0 x) (hf0 y)
lemma strict_mono_mul_left_of_pos (ha : 0 < a) : strict_mono (λ x, a * x) :=
assume b c b_lt_c, (mul_lt_mul_left ha).2 b_lt_c
lemma strict_mono_mul_right_of_pos (ha : 0 < a) : strict_mono (λ x, x * a) :=
assume b c b_lt_c, (mul_lt_mul_right ha).2 b_lt_c
lemma strict_mono.mul_const (hf : strict_mono f) (ha : 0 < a) :
strict_mono (λ x, (f x) * a) :=
(strict_mono_mul_right_of_pos ha).comp hf
lemma strict_mono.const_mul (hf : strict_mono f) (ha : 0 < a) :
strict_mono (λ x, a * (f x)) :=
(strict_mono_mul_left_of_pos ha).comp hf
lemma strict_mono.mul_monotone (hf : strict_mono f) (hg : monotone g) (hf0 : ∀ x, 0 ≤ f x)
(hg0 : ∀ x, 0 < g x) :
strict_mono (λ x, f x * g x) :=
λ x y h, mul_lt_mul (hf h) (hg h.le) (hg0 x) (hf0 y)
lemma monotone.mul_strict_mono (hf : monotone f) (hg : strict_mono g) (hf0 : ∀ x, 0 < f x)
(hg0 : ∀ x, 0 ≤ g x) :
strict_mono (λ x, f x * g x) :=
λ x y h, mul_lt_mul' (hf h.le) (hg h) (hg0 x) (hf0 y)
lemma strict_mono.mul (hf : strict_mono f) (hg : strict_mono g) (hf0 : ∀ x, 0 ≤ f x)
(hg0 : ∀ x, 0 ≤ g x) :
strict_mono (λ x, f x * g x) :=
λ x y h, mul_lt_mul'' (hf h) (hg h) (hf0 x) (hg0 x)
end mono
section linear_ordered_semiring
variables [linear_ordered_semiring α] {a b c : α}
@[simp] lemma decidable.mul_le_mul_left (h : 0 < c) : c * a ≤ c * b ↔ a ≤ b :=
decidable.le_iff_le_iff_lt_iff_lt.2 $ mul_lt_mul_left h
@[simp] lemma decidable.mul_le_mul_right (h : 0 < c) : a * c ≤ b * c ↔ a ≤ b :=
decidable.le_iff_le_iff_lt_iff_lt.2 $ mul_lt_mul_right h
lemma mul_max_of_nonneg (b c : α) (ha : 0 ≤ a) : a * max b c = max (a * b) (a * c) :=
(monotone_mul_left_of_nonneg ha).map_max
lemma mul_min_of_nonneg (b c : α) (ha : 0 ≤ a) : a * min b c = min (a * b) (a * c) :=
(monotone_mul_left_of_nonneg ha).map_min
lemma max_mul_of_nonneg (a b : α) (hc : 0 ≤ c) : max a b * c = max (a * c) (b * c) :=
(monotone_mul_right_of_nonneg hc).map_max
lemma min_mul_of_nonneg (a b : α) (hc : 0 ≤ c) : min a b * c = min (a * c) (b * c) :=
(monotone_mul_right_of_nonneg hc).map_min
end linear_ordered_semiring
/-- An `ordered_ring α` is a ring `α` with a partial order such that
multiplication with a positive number and addition are monotone. -/
@[protect_proj]
class ordered_ring (α : Type u) extends ring α, ordered_add_comm_group α :=
(zero_le_one : 0 ≤ (1 : α))
(mul_pos : ∀ a b : α, 0 < a → 0 < b → 0 < a * b)
section ordered_ring
variables [ordered_ring α] {a b c : α}
lemma ordered_ring.mul_nonneg (a b : α) (h₁ : 0 ≤ a) (h₂ : 0 ≤ b) : 0 ≤ a * b :=
begin
cases classical.em (a ≤ 0), { simp [le_antisymm h h₁] },
cases classical.em (b ≤ 0), { simp [le_antisymm h_1 h₂] },
exact (le_not_le_of_lt (ordered_ring.mul_pos a b (h₁.lt_of_not_le h) (h₂.lt_of_not_le h_1))).left,
end
lemma ordered_ring.mul_le_mul_of_nonneg_left (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c * a ≤ c * b :=
have 0 ≤ b - a, from sub_nonneg_of_le h₁,
have 0 ≤ c * (b - a), from ordered_ring.mul_nonneg c (b - a) h₂ this,
begin
rw mul_sub_left_distrib at this,
apply le_of_sub_nonneg this
end
lemma ordered_ring.mul_le_mul_of_nonneg_right (h₁ : a ≤ b) (h₂ : 0 ≤ c) : a * c ≤ b * c :=
have 0 ≤ b - a, from sub_nonneg_of_le h₁,
have 0 ≤ (b - a) * c, from ordered_ring.mul_nonneg (b - a) c this h₂,
begin
rw mul_sub_right_distrib at this,
apply le_of_sub_nonneg this
end
lemma ordered_ring.mul_lt_mul_of_pos_left (h₁ : a < b) (h₂ : 0 < c) : c * a < c * b :=
have 0 < b - a, from sub_pos_of_lt h₁,
have 0 < c * (b - a), from ordered_ring.mul_pos c (b - a) h₂ this,
begin
rw mul_sub_left_distrib at this,
apply lt_of_sub_pos this
end
lemma ordered_ring.mul_lt_mul_of_pos_right (h₁ : a < b) (h₂ : 0 < c) : a * c < b * c :=
have 0 < b - a, from sub_pos_of_lt h₁,
have 0 < (b - a) * c, from ordered_ring.mul_pos (b - a) c this h₂,
begin
rw mul_sub_right_distrib at this,
apply lt_of_sub_pos this
end
@[priority 100] -- see Note [lower instance priority]
instance ordered_ring.to_ordered_semiring : ordered_semiring α :=
{ mul_zero := mul_zero,
zero_mul := zero_mul,
add_left_cancel := @add_left_cancel α _,
add_right_cancel := @add_right_cancel α _,
le_of_add_le_add_left := @le_of_add_le_add_left α _,
mul_lt_mul_of_pos_left := @ordered_ring.mul_lt_mul_of_pos_left α _,
mul_lt_mul_of_pos_right := @ordered_ring.mul_lt_mul_of_pos_right α _,
..‹ordered_ring α› }
lemma mul_le_mul_of_nonpos_left {a b c : α} (h : b ≤ a) (hc : c ≤ 0) : c * a ≤ c * b :=
have -c ≥ 0, from neg_nonneg_of_nonpos hc,
have -c * b ≤ -c * a, from mul_le_mul_of_nonneg_left h this,
have -(c * b) ≤ -(c * a), by rwa [← neg_mul_eq_neg_mul, ← neg_mul_eq_neg_mul] at this,
le_of_neg_le_neg this
lemma mul_le_mul_of_nonpos_right {a b c : α} (h : b ≤ a) (hc : c ≤ 0) : a * c ≤ b * c :=
have -c ≥ 0, from neg_nonneg_of_nonpos hc,
have b * -c ≤ a * -c, from mul_le_mul_of_nonneg_right h this,
have -(b * c) ≤ -(a * c), by rwa [← neg_mul_eq_mul_neg, ← neg_mul_eq_mul_neg] at this,
le_of_neg_le_neg this
lemma mul_nonneg_of_nonpos_of_nonpos {a b : α} (ha : a ≤ 0) (hb : b ≤ 0) : 0 ≤ a * b :=
have 0 * b ≤ a * b, from mul_le_mul_of_nonpos_right ha hb,
by rwa zero_mul at this
lemma mul_lt_mul_of_neg_left {a b c : α} (h : b < a) (hc : c < 0) : c * a < c * b :=
have -c > 0, from neg_pos_of_neg hc,
have -c * b < -c * a, from mul_lt_mul_of_pos_left h this,
have -(c * b) < -(c * a), by rwa [← neg_mul_eq_neg_mul, ← neg_mul_eq_neg_mul] at this,
lt_of_neg_lt_neg this
lemma mul_lt_mul_of_neg_right {a b c : α} (h : b < a) (hc : c < 0) : a * c < b * c :=
have -c > 0, from neg_pos_of_neg hc,
have b * -c < a * -c, from mul_lt_mul_of_pos_right h this,
have -(b * c) < -(a * c), by rwa [← neg_mul_eq_mul_neg, ← neg_mul_eq_mul_neg] at this,
lt_of_neg_lt_neg this
lemma mul_pos_of_neg_of_neg {a b : α} (ha : a < 0) (hb : b < 0) : 0 < a * b :=
have 0 * b < a * b, from mul_lt_mul_of_neg_right ha hb,
by rwa zero_mul at this
end ordered_ring
/-- A `linear_ordered_ring α` is a ring `α` with a linear order such that
multiplication with a positive number and addition are monotone. -/
@[protect_proj] class linear_ordered_ring (α : Type u)
extends ordered_ring α, linear_order α, nontrivial α
@[priority 100] -- see Note [lower instance priority]
instance linear_ordered_ring.to_linear_ordered_add_comm_group [s : linear_ordered_ring α] :
linear_ordered_add_comm_group α :=
{ .. s }
section linear_ordered_ring
variables [linear_ordered_ring α] {a b c : α}
@[priority 100] -- see Note [lower instance priority]
instance linear_ordered_ring.to_linear_ordered_semiring : linear_ordered_semiring α :=
{ mul_zero := mul_zero,
zero_mul := zero_mul,
add_left_cancel := @add_left_cancel α _,
add_right_cancel := @add_right_cancel α _,
le_of_add_le_add_left := @le_of_add_le_add_left α _,
mul_lt_mul_of_pos_left := @mul_lt_mul_of_pos_left α _,
mul_lt_mul_of_pos_right := @mul_lt_mul_of_pos_right α _,
le_total := linear_ordered_ring.le_total,
..‹linear_ordered_ring α› }
@[priority 100] -- see Note [lower instance priority]
instance linear_ordered_ring.to_domain : domain α :=
{ eq_zero_or_eq_zero_of_mul_eq_zero :=
begin
intros a b hab,
contrapose! hab,
cases (lt_or_gt_of_ne hab.1) with ha ha; cases (lt_or_gt_of_ne hab.2) with hb hb,
exacts [(mul_pos_of_neg_of_neg ha hb).ne.symm, (mul_neg_of_neg_of_pos ha hb).ne,
(mul_neg_of_pos_of_neg ha hb).ne, (mul_pos ha hb).ne.symm]
end,
.. ‹linear_ordered_ring α› }
@[simp] lemma abs_one : abs (1 : α) = 1 := abs_of_pos zero_lt_one
@[simp] lemma abs_two : abs (2 : α) = 2 := abs_of_pos zero_lt_two
lemma abs_mul (a b : α) : abs (a * b) = abs a * abs b :=
begin
rw [abs_eq (mul_nonneg (abs_nonneg a) (abs_nonneg b))],
cases le_total a 0 with ha ha; cases le_total b 0 with hb hb;
simp [abs_of_nonpos, abs_of_nonneg, *]
end
/-- `abs` as a `monoid_with_zero_hom`. -/
def abs_hom : monoid_with_zero_hom α α := ⟨abs, abs_zero, abs_one, abs_mul⟩
lemma abs_mul_abs_self (a : α) : abs a * abs a = a * a :=
abs_by_cases (λ x, x * x = a * a) rfl (neg_mul_neg a a)
lemma abs_mul_self (a : α) : abs (a * a) = a * a :=
by rw [abs_mul, abs_mul_abs_self]
lemma mul_pos_iff : 0 < a * b ↔ 0 < a ∧ 0 < b ∨ a < 0 ∧ b < 0 :=
⟨pos_and_pos_or_neg_and_neg_of_mul_pos,
λ h, h.elim (and_imp.2 mul_pos) (and_imp.2 mul_pos_of_neg_of_neg)⟩
lemma mul_neg_iff : a * b < 0 ↔ 0 < a ∧ b < 0 ∨ a < 0 ∧ 0 < b :=
by rw [← neg_pos, neg_mul_eq_mul_neg, mul_pos_iff, neg_pos, neg_lt_zero]
lemma mul_nonneg_iff : 0 ≤ a * b ↔ 0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0 :=
⟨nonneg_and_nonneg_or_nonpos_and_nonpos_of_mul_nnonneg,
λ h, h.elim (and_imp.2 mul_nonneg) (and_imp.2 mul_nonneg_of_nonpos_of_nonpos)⟩
lemma mul_nonpos_iff : a * b ≤ 0 ↔ 0 ≤ a ∧ b ≤ 0 ∨ a ≤ 0 ∧ 0 ≤ b :=
by rw [← neg_nonneg, neg_mul_eq_mul_neg, mul_nonneg_iff, neg_nonneg, neg_nonpos]
lemma mul_self_nonneg (a : α) : 0 ≤ a * a :=
abs_mul_self a ▸ abs_nonneg _
lemma gt_of_mul_lt_mul_neg_left (h : c * a < c * b) (hc : c ≤ 0) : b < a :=
have nhc : 0 ≤ -c, from neg_nonneg_of_nonpos hc,
have h2 : -(c * b) < -(c * a), from neg_lt_neg h,
have h3 : (-c) * b < (-c) * a, from calc
(-c) * b = - (c * b) : by rewrite neg_mul_eq_neg_mul
... < -(c * a) : h2
... = (-c) * a : by rewrite neg_mul_eq_neg_mul,
lt_of_mul_lt_mul_left h3 nhc
lemma neg_one_lt_zero : -1 < (0:α) :=
begin
have this := neg_lt_neg (@zero_lt_one α _ _),
rwa neg_zero at this
end
lemma le_of_mul_le_of_one_le {a b c : α} (h : a * c ≤ b) (hb : 0 ≤ b) (hc : 1 ≤ c) :
a ≤ b :=
have h' : a * c ≤ b * c, from calc
a * c ≤ b : h
... = b * 1 : by rewrite mul_one
... ≤ b * c : mul_le_mul_of_nonneg_left hc hb,
le_of_mul_le_mul_right h' (zero_lt_one.trans_le hc)
lemma nonneg_le_nonneg_of_squares_le {a b : α} (hb : 0 ≤ b) (h : a * a ≤ b * b) : a ≤ b :=
le_of_not_gt (λhab, (mul_self_lt_mul_self hb hab).not_le h)
lemma mul_self_le_mul_self_iff {a b : α} (h1 : 0 ≤ a) (h2 : 0 ≤ b) : a ≤ b ↔ a * a ≤ b * b :=
⟨mul_self_le_mul_self h1, nonneg_le_nonneg_of_squares_le h2⟩
lemma mul_self_lt_mul_self_iff {a b : α} (h1 : 0 ≤ a) (h2 : 0 ≤ b) : a < b ↔ a * a < b * b :=
((@strict_mono_incr_on_mul_self α _).lt_iff_lt h1 h2).symm
lemma mul_self_inj {a b : α} (h1 : 0 ≤ a) (h2 : 0 ≤ b) : a * a = b * b ↔ a = b :=
(@strict_mono_incr_on_mul_self α _).inj_on.eq_iff h1 h2
@[simp] lemma mul_le_mul_left_of_neg {a b c : α} (h : c < 0) : c * a ≤ c * b ↔ b ≤ a :=
⟨le_imp_le_of_lt_imp_lt $ λ h', mul_lt_mul_of_neg_left h' h,
λ h', mul_le_mul_of_nonpos_left h' h.le⟩
@[simp] lemma mul_le_mul_right_of_neg {a b c : α} (h : c < 0) : a * c ≤ b * c ↔ b ≤ a :=
⟨le_imp_le_of_lt_imp_lt $ λ h', mul_lt_mul_of_neg_right h' h,
λ h', mul_le_mul_of_nonpos_right h' h.le⟩
@[simp] lemma mul_lt_mul_left_of_neg {a b c : α} (h : c < 0) : c * a < c * b ↔ b < a :=
lt_iff_lt_of_le_iff_le (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 :=
lt_iff_lt_of_le_iff_le (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_self_pos {a : α} (ha : a ≠ 0) : 0 < a * a :=
by rcases lt_trichotomy a 0 with h|h|h;
[exact mul_pos_of_neg_of_neg h h, exact (ha h).elim, exact mul_pos h h]
lemma mul_self_le_mul_self_of_le_of_neg_le {x y : α} (h₁ : x ≤ y) (h₂ : -x ≤ y) : x * x ≤ y * y :=
begin
rw [← abs_mul_abs_self x],
exact mul_self_le_mul_self (abs_nonneg x) (abs_le.2 ⟨neg_le.2 h₂, h₁⟩)
end
lemma nonneg_of_mul_nonpos_left {a b : α} (h : a * b ≤ 0) (hb : b < 0) : 0 ≤ a :=
le_of_not_gt (λ ha, absurd h (mul_pos_of_neg_of_neg ha hb).not_le)
lemma nonneg_of_mul_nonpos_right {a b : α} (h : a * b ≤ 0) (ha : a < 0) : 0 ≤ b :=
le_of_not_gt (λ hb, absurd h (mul_pos_of_neg_of_neg ha hb).not_le)
lemma pos_of_mul_neg_left {a b : α} (h : a * b < 0) (hb : b ≤ 0) : 0 < a :=
lt_of_not_ge (λ ha, absurd h (mul_nonneg_of_nonpos_of_nonpos ha hb).not_lt)
lemma pos_of_mul_neg_right {a b : α} (h : a * b < 0) (ha : a ≤ 0) : 0 < b :=
lt_of_not_ge (λ hb, absurd h (mul_nonneg_of_nonpos_of_nonpos ha hb).not_lt)
/-- The sum of two squares is zero iff both elements are zero. -/
lemma mul_self_add_mul_self_eq_zero {x y : α} : x * x + y * y = 0 ↔ x = 0 ∧ y = 0 :=
by rw [add_eq_zero_iff', mul_self_eq_zero, mul_self_eq_zero]; apply mul_self_nonneg
lemma sub_le_of_abs_sub_le_left (h : abs (a - b) ≤ c) : b - c ≤ a :=
if hz : 0 ≤ a - b then
(calc
a ≥ b : le_of_sub_nonneg hz
... ≥ b - c : sub_le_self _ $ (abs_nonneg _).trans h)
else
have habs : b - a ≤ c, by rwa [abs_of_neg (lt_of_not_ge hz), neg_sub] at h,
have habs' : b ≤ c + a, from le_add_of_sub_right_le habs,
sub_left_le_of_le_add habs'
lemma sub_le_of_abs_sub_le_right (h : abs (a - b) ≤ c) : a - c ≤ b :=
sub_le_of_abs_sub_le_left (abs_sub a b ▸ h)
lemma sub_lt_of_abs_sub_lt_left (h : abs (a - b) < c) : b - c < a :=
if hz : 0 ≤ a - b then
(calc
a ≥ b : le_of_sub_nonneg hz
... > b - c : sub_lt_self _ ((abs_nonneg _).trans_lt h))
else
have habs : b - a < c, by rwa [abs_of_neg (lt_of_not_ge hz), neg_sub] at h,
have habs' : b < c + a, from lt_add_of_sub_right_lt habs,
sub_left_lt_of_lt_add habs'
lemma sub_lt_of_abs_sub_lt_right (h : abs (a - b) < c) : a - c < b :=
sub_lt_of_abs_sub_lt_left (abs_sub a b ▸ h)
lemma eq_zero_of_mul_self_add_mul_self_eq_zero (h : a * a + b * b = 0) : a = 0 :=
(mul_self_add_mul_self_eq_zero.mp h).left
lemma abs_eq_iff_mul_self_eq : abs a = abs b ↔ a * a = b * b :=
begin
rw [← abs_mul_abs_self, ← abs_mul_abs_self b],
exact (mul_self_inj (abs_nonneg a) (abs_nonneg b)).symm,
end
lemma abs_lt_iff_mul_self_lt : abs a < abs b ↔ a * a < b * b :=
begin
rw [← abs_mul_abs_self, ← abs_mul_abs_self b],
exact mul_self_lt_mul_self_iff (abs_nonneg a) (abs_nonneg b)
end
lemma abs_le_iff_mul_self_le : abs a ≤ abs b ↔ a * a ≤ b * b :=
begin
rw [← abs_mul_abs_self, ← abs_mul_abs_self b],
exact mul_self_le_mul_self_iff (abs_nonneg a) (abs_nonneg b)
end
lemma abs_le_one_iff_mul_self_le_one : abs a ≤ 1 ↔ a * a ≤ 1 :=
by simpa only [abs_one, one_mul] using @abs_le_iff_mul_self_le α _ a 1
end linear_ordered_ring
/-- A `linear_ordered_comm_ring α` is a commutative ring `α` with a linear order
such that multiplication with a positive number and addition are monotone. -/
@[protect_proj]
class linear_ordered_comm_ring (α : Type u) extends linear_ordered_ring α, comm_monoid α
@[priority 100] -- see Note [lower instance priority]
instance linear_ordered_comm_ring.to_comm_ring [s : linear_ordered_comm_ring α] :
comm_ring α :=
{ ..s }
@[priority 100] -- see Note [lower instance priority]
instance linear_ordered_comm_ring.to_integral_domain [s : linear_ordered_comm_ring α] :
integral_domain α :=
{ ..linear_ordered_ring.to_domain, ..s }
@[priority 100] -- see Note [lower instance priority]
instance linear_ordered_comm_ring.to_linear_ordered_semiring [d : linear_ordered_comm_ring α] :
linear_ordered_semiring α :=
let s : linear_ordered_semiring α := @linear_ordered_ring.to_linear_ordered_semiring α _ in
{ zero_mul := @linear_ordered_semiring.zero_mul α s,
mul_zero := @linear_ordered_semiring.mul_zero α s,
add_left_cancel := @linear_ordered_semiring.add_left_cancel α s,
add_right_cancel := @linear_ordered_semiring.add_right_cancel α s,
le_of_add_le_add_left := @linear_ordered_semiring.le_of_add_le_add_left α s,
mul_lt_mul_of_pos_left := @linear_ordered_semiring.mul_lt_mul_of_pos_left α s,
mul_lt_mul_of_pos_right := @linear_ordered_semiring.mul_lt_mul_of_pos_right α s,
..d }
section linear_ordered_comm_ring
variables [linear_ordered_comm_ring α] {a b c d : α}
lemma max_mul_mul_le_max_mul_max (b c : α) (ha : 0 ≤ a) (hd: 0 ≤ d) :
max (a * b) (d * c) ≤ max a c * max d b :=
have ba : b * a ≤ max d b * max c a,
from mul_le_mul (le_max_right d b) (le_max_right c a) ha (le_trans hd (le_max_left d b)),
have cd : c * d ≤ max a c * max b d,
from mul_le_mul (le_max_right a c) (le_max_right b d) hd (le_trans ha (le_max_left a c)),
max_le
(by simpa [mul_comm, max_comm] using ba)
(by simpa [mul_comm, max_comm] using cd)
lemma abs_sub_square (a b : α) : abs (a - b) * abs (a - b) = a * a + b * b - (1 + 1) * a * b :=
begin
rw abs_mul_abs_self,
simp [left_distrib, right_distrib, add_assoc, add_comm, add_left_comm, mul_comm, sub_eq_add_neg],
end
end linear_ordered_comm_ring
/-- Extend `nonneg_add_comm_group` to support ordered rings
specified by their nonnegative elements -/
class nonneg_ring (α : Type*) extends ring α, nonneg_add_comm_group α :=
(one_nonneg : nonneg 1)
(mul_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a * b))
(mul_pos : ∀ {a b}, pos a → pos b → pos (a * b))
/-- Extend `nonneg_add_comm_group` to support linearly ordered rings
specified by their nonnegative elements -/
class linear_nonneg_ring (α : Type*) extends domain α, nonneg_add_comm_group α :=
(one_pos : pos 1)
(mul_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a * b))
(nonneg_total : ∀ a, nonneg a ∨ nonneg (-a))
namespace nonneg_ring
open nonneg_add_comm_group
variable [nonneg_ring α]
/-- `to_linear_nonneg_ring` shows that a `nonneg_ring` with a total order is a `domain`,
hence a `linear_nonneg_ring`. -/
def to_linear_nonneg_ring [nontrivial α]
(nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a))
: linear_nonneg_ring α :=
{ one_pos := (pos_iff 1).mpr ⟨one_nonneg, λ h, zero_ne_one (nonneg_antisymm one_nonneg h).symm⟩,
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⟩))),
..‹nontrivial α›,
..‹nonneg_ring α› }
end nonneg_ring
namespace linear_nonneg_ring
open nonneg_add_comm_group
variable [linear_nonneg_ring α]
@[priority 100] -- see Note [lower instance priority]
instance to_nonneg_ring : nonneg_ring α :=
{ one_nonneg := ((pos_iff _).mp one_pos).1,
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))⟩,
..‹linear_nonneg_ring α› }
/-- Construct `linear_order` from `linear_nonneg_ring`. This is not an instance
because we don't use it in `mathlib`. -/
local attribute [instance]
def to_linear_order [decidable_pred (nonneg : α → Prop)] : linear_order α :=
{ le_total := nonneg_total_iff.1 nonneg_total,
decidable_le := by apply_instance,
decidable_lt := by apply_instance,
..‹linear_nonneg_ring α›, ..(infer_instance : ordered_add_comm_group α) }
/-- Construct `linear_ordered_ring` from `linear_nonneg_ring`.
This is not an instance because we don't use it in `mathlib`. -/
local attribute [instance]
def to_linear_ordered_ring [decidable_pred (nonneg : α → Prop)] : linear_ordered_ring α :=
{ mul_pos := by simp [pos_def.symm]; exact @nonneg_ring.mul_pos _ _,
zero_le_one := le_of_lt $ 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,
..‹linear_nonneg_ring α›, ..(infer_instance : ordered_add_comm_group α),
..(infer_instance : linear_order α) }
/-- Convert a `linear_nonneg_ring` with a commutative multiplication and
decidable non-negativity into a `linear_ordered_comm_ring` -/
def to_linear_ordered_comm_ring
[decidable_pred (@nonneg α _)]
[comm : @is_commutative α (*)]
: linear_ordered_comm_ring α :=
{ mul_comm := is_commutative.comm,
..@linear_nonneg_ring.to_linear_ordered_ring _ _ _ }
end linear_nonneg_ring
/-- A canonically ordered commutative semiring is an ordered, commutative semiring
in which `a ≤ b` iff there exists `c` with `b = a + c`. This is satisfied by the
natural numbers, for example, but not the integers or other ordered groups. -/
class canonically_ordered_comm_semiring (α : Type*) extends
canonically_ordered_add_monoid α, comm_semiring α :=
(eq_zero_or_eq_zero_of_mul_eq_zero : ∀ a b : α, a * b = 0 → a = 0 ∨ b = 0)
namespace canonically_ordered_semiring
variables [canonically_ordered_comm_semiring α] {a b : α}
open canonically_ordered_add_monoid (le_iff_exists_add)
@[priority 100] -- see Note [lower instance priority]
instance canonically_ordered_comm_semiring.to_no_zero_divisors :
no_zero_divisors α :=
⟨canonically_ordered_comm_semiring.eq_zero_or_eq_zero_of_mul_eq_zero⟩
lemma mul_le_mul {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, _root_.add_assoc],
exact (le_iff_exists_add _ _).2 ⟨_, rfl⟩
end
lemma mul_le_mul_left' {b c : α} (h : b ≤ c) (a : α) : a * b ≤ a * c :=
mul_le_mul (le_refl a) h
lemma mul_le_mul_right' {b c : α} (h : b ≤ c) (a : α) : b * a ≤ c * a :=
mul_le_mul h (le_refl a)
/-- A version of `zero_lt_one : 0 < 1` for a `canonically_ordered_comm_semiring`. -/
lemma zero_lt_one [nontrivial α] : (0:α) < 1 := (zero_le 1).lt_of_ne zero_ne_one
lemma mul_pos : 0 < a * b ↔ (0 < a) ∧ (0 < b) :=
by simp only [zero_lt_iff_ne_zero, ne.def, mul_eq_zero, not_or_distrib]
end canonically_ordered_semiring
namespace with_top
instance [nonempty α] : nontrivial (with_top α) :=
option.nontrivial
variable [decidable_eq α]
section has_mul
variables [has_zero α] [has_mul α]
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 }
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] 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
end has_mul
section mul_zero_class
variables [mul_zero_class α]
@[norm_cast] 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
@[simp] lemma mul_eq_top_iff {a b : with_top α} : a * b = ⊤ ↔ (a ≠ 0 ∧ b = ⊤) ∨ (a = ⊤ ∧ b ≠ 0) :=
begin
cases a; cases b; simp only [none_eq_top, some_eq_coe],
{ simp [← coe_mul] },
{ suffices : ⊤ * (b : with_top α) = ⊤ ↔ b ≠ 0, by simpa,
by_cases hb : b = 0; simp [hb] },
{ suffices : (a : with_top α) * ⊤ = ⊤ ↔ a ≠ 0, by simpa,
by_cases ha : a = 0; simp [ha] },
{ simp [← coe_mul] }
end
end mul_zero_class
section no_zero_divisors
variables [mul_zero_class α] [no_zero_divisors α]
instance : no_zero_divisors (with_top α) :=
⟨λ a b, by cases a; cases b; dsimp [mul_def]; split_ifs;
simp [*, none_eq_top, some_eq_coe, mul_eq_zero] at *⟩
end no_zero_divisors
variables [canonically_ordered_comm_semiring α]
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 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] },
cases b,
{ by_cases ha : a = 0; by_cases hc : c = 0;
simp [*, none_eq_top, some_eq_coe] },
cases c,
{ by_cases ha : a = 0; by_cases hb : b = 0;
simp [*, none_eq_top, some_eq_coe] },
simp [some_eq_coe, coe_mul.symm, mul_assoc]
end
-- `nontrivial α` is needed here as otherwise
-- we have `1 * ⊤ = ⊤` but also `= 0 * ⊤ = 0`.
private lemma one_mul' [nontrivial α] : ∀a : with_top α, 1 * a = a
| none := show ((1:α) : with_top α) * ⊤ = ⊤, by simp [-with_top.coe_one]
| (some a) := show ((1:α) : with_top α) * a = a, by simp [coe_mul.symm, -with_top.coe_one]
instance [nontrivial α] : 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,
one_mul := one_mul',
mul_one := assume a, by rw [comm, one_mul'],
.. with_top.add_comm_monoid, .. with_top.mul_zero_class,
.. with_top.canonically_ordered_add_monoid,
.. with_top.no_zero_divisors, .. with_top.nontrivial }
end with_top
|
46219348216e48e8de64e9617f3fa439b98f9447 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/extra/slow1.lean | b0c462d9384f89b3fd096437044f3cb492d2928b | [
"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 | 398 | lean | open nat
definition f (a : nat) : nat := a
definition g (a : nat) : nat := zero
example (a b : nat) :
@eq nat
(g (f (f (f (f (f (f (f (f (f (f (f (f (f (f (f (f (f (f (f (f (f a))))))))))))))))))))))
(g (f (f (f (f (f (f (f (f (f (f (f (f (f (f (f (f (f (f (f (f (f b))))))))))))))))))))))
:=
@eq.refl nat (g (f (f (f (f (f (f (f (f (f (f (f (f (f (f (f (f (f (f (f (f (f a))))))))))))))))))))))
|
e12a9860adf066498f9276df2e216a3999bebcca | 5d166a16ae129621cb54ca9dde86c275d7d2b483 | /tests/lean/cases_induction_fresh.lean | 169e73accc1dfcad7a40216c7365e15ca78627a0 | [
"Apache-2.0"
] | permissive | jcarlson23/lean | b00098763291397e0ac76b37a2dd96bc013bd247 | 8de88701247f54d325edd46c0eed57aeacb64baf | refs/heads/master | 1,611,571,813,719 | 1,497,020,963,000 | 1,497,021,515,000 | 93,882,536 | 1 | 0 | null | 1,497,029,896,000 | 1,497,029,896,000 | null | UTF-8 | Lean | false | false | 334 | lean | example (p q r s: Prop): p ∧ q → r ∧ s → s ∧ q :=
begin
intros h1 h2,
cases h1,
cases h2,
trace_state,
constructor; assumption
end
#print "------------"
example (p q r s: Prop): p ∧ q → r ∧ s → s ∧ q :=
begin
intros h1 h2,
induction h1,
induction h2,
trace_state,
constructor; assumption
end
|
3c9fa5ef51f90f1801918285bb995fccf80cdf38 | 0e175f34f8dca5ea099671777e8d7446d7d74227 | /library/init/data/nat/lemmas.lean | f0ad95534582089dee82b096939c7f914ff2c760 | [
"Apache-2.0"
] | permissive | utensil-contrib/lean | b31266738071c654d96dac8b35d9ccffc8172fda | a28b9c8f78d982a4e82b1e4f7ce7988d87183ae8 | refs/heads/master | 1,670,045,564,075 | 1,597,397,599,000 | 1,597,397,599,000 | 287,528,503 | 0 | 0 | Apache-2.0 | 1,597,408,338,000 | 1,597,408,337,000 | null | UTF-8 | Lean | false | false | 50,218 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad
-/
prelude
import init.data.nat.basic init.data.nat.div init.meta init.algebra.functions
universes u
namespace nat
attribute [pre_smt] nat_zero_eq_zero
protected lemma add_comm : ∀ n m : ℕ, n + m = m + n
| n 0 := eq.symm (nat.zero_add n)
| n (m+1) :=
suffices succ (n + m) = succ (m + n), from
eq.symm (succ_add m n) ▸ this,
congr_arg succ (add_comm n m)
protected lemma add_assoc : ∀ n m k : ℕ, (n + m) + k = n + (m + k)
| n m 0 := rfl
| n m (succ k) := by rw [add_succ, add_succ, add_assoc]
protected lemma add_left_comm : ∀ (n m k : ℕ), n + (m + k) = m + (n + k) :=
left_comm nat.add nat.add_comm nat.add_assoc
protected lemma add_left_cancel : ∀ {n m k : ℕ}, n + m = n + k → m = k
| 0 m k := by simp [nat.zero_add] {contextual := tt}
| (succ n) m k := λ h,
have n+m = n+k, by { simp [succ_add] at h, assumption },
add_left_cancel this
protected lemma add_right_cancel {n m k : ℕ} (h : n + m = k + m) : n = k :=
have m + n = m + k, by rwa [nat.add_comm n m, nat.add_comm k m] at h,
nat.add_left_cancel this
lemma succ_ne_zero (n : ℕ) : succ n ≠ 0 :=
assume h, nat.no_confusion h
lemma succ_ne_self : ∀ n : ℕ, succ n ≠ n
| 0 h := absurd h (nat.succ_ne_zero 0)
| (n+1) h := succ_ne_self n (nat.no_confusion h (λ h, h))
protected lemma one_ne_zero : 1 ≠ (0 : ℕ) :=
assume h, nat.no_confusion h
protected lemma zero_ne_one : 0 ≠ (1 : ℕ) :=
assume h, nat.no_confusion h
lemma eq_zero_of_add_eq_zero_right : ∀ {n m : ℕ}, n + m = 0 → n = 0
| 0 m := by simp [nat.zero_add]
| (n+1) m := λ h,
begin
exfalso,
rw [add_one, succ_add] at h,
apply succ_ne_zero _ h
end
lemma eq_zero_of_add_eq_zero_left {n m : ℕ} (h : n + m = 0) : m = 0 :=
@eq_zero_of_add_eq_zero_right m n (nat.add_comm n m ▸ h)
@[simp]
lemma pred_zero : pred 0 = 0 :=
rfl
@[simp]
lemma pred_succ (n : ℕ) : pred (succ n) = n :=
rfl
protected lemma mul_zero (n : ℕ) : n * 0 = 0 :=
rfl
lemma mul_succ (n m : ℕ) : n * succ m = n * m + n :=
rfl
protected theorem zero_mul : ∀ (n : ℕ), 0 * n = 0
| 0 := rfl
| (succ n) := by rw [mul_succ, zero_mul]
private meta def sort_add :=
`[simp [nat.add_assoc, nat.add_comm, nat.add_left_comm]]
lemma succ_mul : ∀ (n m : ℕ), (succ n) * m = (n * m) + m
| n 0 := rfl
| n (succ m) :=
begin
simp [mul_succ, add_succ, succ_mul n m],
sort_add
end
protected lemma right_distrib : ∀ (n m k : ℕ), (n + m) * k = n * k + m * k
| n m 0 := rfl
| n m (succ k) :=
begin simp [mul_succ, right_distrib n m k], sort_add end
protected lemma left_distrib : ∀ (n m k : ℕ), n * (m + k) = n * m + n * k
| 0 m k := by simp [nat.zero_mul]
| (succ n) m k :=
begin simp [succ_mul, left_distrib n m k], sort_add end
protected lemma mul_comm : ∀ (n m : ℕ), n * m = m * n
| n 0 := by rw [nat.zero_mul, nat.mul_zero]
| n (succ m) := by simp [mul_succ, succ_mul, mul_comm n m]
protected lemma mul_assoc : ∀ (n m k : ℕ), (n * m) * k = n * (m * k)
| n m 0 := rfl
| n m (succ k) := by simp [mul_succ, nat.left_distrib, mul_assoc n m k]
protected lemma mul_one : ∀ (n : ℕ), n * 1 = n := nat.zero_add
protected lemma one_mul (n : ℕ) : 1 * n = n :=
by rw [nat.mul_comm, nat.mul_one]
/- properties of inequality -/
protected lemma le_of_eq {n m : ℕ} (p : n = m) : n ≤ m :=
p ▸ less_than_or_equal.refl
lemma le_succ_of_le {n m : ℕ} (h : n ≤ m) : n ≤ succ m :=
nat.le_trans h (le_succ m)
lemma le_of_succ_le {n m : ℕ} (h : succ n ≤ m) : n ≤ m :=
nat.le_trans (le_succ n) h
protected lemma le_of_lt {n m : ℕ} (h : n < m) : n ≤ m :=
le_of_succ_le h
def lt.step {n m : ℕ} : n < m → n < succ m := less_than_or_equal.step
lemma eq_zero_or_pos (n : ℕ) : n = 0 ∨ n > 0 :=
by {cases n, exact or.inl rfl, exact or.inr (succ_pos _)}
protected lemma pos_of_ne_zero {n : nat} : n ≠ 0 → n > 0 :=
or.resolve_left (eq_zero_or_pos n)
protected lemma lt_trans {n m k : ℕ} (h₁ : n < m) : m < k → n < k :=
nat.le_trans (less_than_or_equal.step h₁)
protected lemma lt_of_le_of_lt {n m k : ℕ} (h₁ : n ≤ m) : m < k → n < k :=
nat.le_trans (succ_le_succ h₁)
def lt.base (n : ℕ) : n < succ n := nat.le_refl (succ n)
lemma lt_succ_self (n : ℕ) : n < succ n := lt.base n
protected lemma le_antisymm {n m : ℕ} (h₁ : n ≤ m) : m ≤ n → n = m :=
less_than_or_equal.cases_on h₁ (λ a, rfl) (λ a b c, absurd (nat.lt_of_le_of_lt b c) (nat.lt_irrefl n))
protected lemma lt_or_ge : ∀ (a b : ℕ), a < b ∨ a ≥ b
| a 0 := or.inr (zero_le a)
| a (b+1) :=
match lt_or_ge a b with
| or.inl h := or.inl (le_succ_of_le h)
| or.inr h :=
match nat.eq_or_lt_of_le h with
| or.inl h1 := or.inl (h1 ▸ lt_succ_self b)
| or.inr h1 := or.inr h1
end
end
protected lemma le_total {m n : ℕ} : m ≤ n ∨ n ≤ m :=
or.imp_left nat.le_of_lt (nat.lt_or_ge m n)
protected lemma lt_of_le_and_ne {m n : ℕ} (h1 : m ≤ n) : m ≠ n → m < n :=
or.resolve_right (or.swap (nat.eq_or_lt_of_le h1))
protected lemma lt_iff_le_not_le {m n : ℕ} : m < n ↔ (m ≤ n ∧ ¬ n ≤ m) :=
⟨λ hmn, ⟨nat.le_of_lt hmn, λ hnm, nat.lt_irrefl _ (nat.lt_of_le_of_lt hnm hmn)⟩,
λ ⟨hmn, hnm⟩, nat.lt_of_le_and_ne hmn (λ heq, hnm (heq ▸ nat.le_refl _))⟩
instance : linear_order ℕ :=
{ le := nat.less_than_or_equal,
le_refl := @nat.le_refl,
le_trans := @nat.le_trans,
le_antisymm := @nat.le_antisymm,
le_total := @nat.le_total,
lt := nat.lt,
lt_iff_le_not_le := @nat.lt_iff_le_not_le }
lemma eq_zero_of_le_zero {n : nat} (h : n ≤ 0) : n = 0 :=
le_antisymm h (zero_le _)
lemma succ_lt_succ {a b : ℕ} : a < b → succ a < succ b :=
succ_le_succ
lemma lt_of_succ_lt {a b : ℕ} : succ a < b → a < b :=
le_of_succ_le
lemma lt_of_succ_lt_succ {a b : ℕ} : succ a < succ b → a < b :=
le_of_succ_le_succ
lemma pred_lt_pred : ∀ {n m : ℕ}, n ≠ 0 → n < m → pred n < pred m
| 0 _ h₁ h := absurd rfl h₁
| _ 0 h₁ h := absurd h (not_lt_zero _)
| (succ n) (succ m) _ h := lt_of_succ_lt_succ h
lemma lt_of_succ_le {a b : ℕ} (h : succ a ≤ b) : a < b := h
lemma succ_le_of_lt {a b : ℕ} (h : a < b) : succ a ≤ b := h
lemma le_add_right : ∀ (n k : ℕ), n ≤ n + k
| n 0 := nat.le_refl n
| n (k+1) := le_succ_of_le (le_add_right n k)
lemma le_add_left (n m : ℕ): n ≤ m + n :=
nat.add_comm n m ▸ le_add_right n m
lemma le.dest : ∀ {n m : ℕ}, n ≤ m → ∃ k, n + k = m
| n _ less_than_or_equal.refl := ⟨0, rfl⟩
| n _ (less_than_or_equal.step h) :=
match le.dest h with
| ⟨w, hw⟩ := ⟨succ w, hw ▸ add_succ n w⟩
end
lemma le.intro {n m k : ℕ} (h : n + k = m) : n ≤ m :=
h ▸ le_add_right n k
protected lemma add_le_add_left {n m : ℕ} (h : n ≤ m) (k : ℕ) : k + n ≤ k + m :=
match le.dest h with
| ⟨w, hw⟩ := @le.intro _ _ w begin rw [nat.add_assoc, hw] end
end
protected lemma add_le_add_right {n m : ℕ} (h : n ≤ m) (k : ℕ) : n + k ≤ m + k :=
begin rw [nat.add_comm n k, nat.add_comm m k], apply nat.add_le_add_left h end
protected lemma le_of_add_le_add_left {k n m : ℕ} (h : k + n ≤ k + m) : n ≤ m :=
match le.dest h with
| ⟨w, hw⟩ := @le.intro _ _ w
begin
rw [nat.add_assoc] at hw,
apply nat.add_left_cancel hw
end
end
protected lemma le_of_add_le_add_right {k n m : ℕ} : n + k ≤ m + k → n ≤ m :=
begin
rw [nat.add_comm _ k, nat.add_comm _ k],
apply nat.le_of_add_le_add_left
end
protected lemma add_le_add_iff_le_right (k n m : ℕ) : n + k ≤ m + k ↔ n ≤ m :=
⟨ nat.le_of_add_le_add_right , assume h, nat.add_le_add_right h _ ⟩
protected theorem lt_of_add_lt_add_left {k n m : ℕ} (h : k + n < k + m) : n < m :=
let h' := nat.le_of_lt h in
nat.lt_of_le_and_ne
(nat.le_of_add_le_add_left h')
(λ heq, nat.lt_irrefl (k + m) begin rw heq at h, assumption end)
protected lemma lt_of_add_lt_add_right {a b c : ℕ} (h : a + b < c + b) : a < c :=
nat.lt_of_add_lt_add_left $
show b + a < b + c, by rwa [nat.add_comm b a, nat.add_comm b c]
protected lemma add_lt_add_left {n m : ℕ} (h : n < m) (k : ℕ) : k + n < k + m :=
lt_of_succ_le (add_succ k n ▸ nat.add_le_add_left (succ_le_of_lt h) k)
protected lemma add_lt_add_right {n m : ℕ} (h : n < m) (k : ℕ) : n + k < m + k :=
nat.add_comm k m ▸ nat.add_comm k n ▸ nat.add_lt_add_left h k
protected lemma lt_add_of_pos_right {n k : ℕ} (h : k > 0) : n < n + k :=
nat.add_lt_add_left h n
protected lemma lt_add_of_pos_left {n k : ℕ} (h : k > 0) : n < k + n :=
by rw nat.add_comm; exact nat.lt_add_of_pos_right h
protected lemma add_lt_add {a b c d : ℕ} (h₁ : a < b) (h₂ : c < d) : a + c < b + d :=
lt_trans (nat.add_lt_add_right h₁ c) (nat.add_lt_add_left h₂ b)
protected lemma add_le_add {a b c d : ℕ} (h₁ : a ≤ b) (h₂ : c ≤ d) : a + c ≤ b + d :=
le_trans (nat.add_le_add_right h₁ c) (nat.add_le_add_left h₂ b)
protected lemma zero_lt_one : 0 < (1:nat) :=
zero_lt_succ 0
lemma mul_le_mul_left {n m : ℕ} (k : ℕ) (h : n ≤ m) : k * n ≤ k * m :=
match le.dest h with
| ⟨l, hl⟩ :=
have k * n + k * l = k * m, by rw [← nat.left_distrib, hl],
le.intro this
end
lemma mul_le_mul_right {n m : ℕ} (k : ℕ) (h : n ≤ m) : n * k ≤ m * k :=
nat.mul_comm k m ▸ nat.mul_comm k n ▸ mul_le_mul_left k h
protected lemma mul_lt_mul_of_pos_left {n m k : ℕ} (h : n < m) (hk : k > 0) : k * n < k * m :=
nat.lt_of_lt_of_le (nat.lt_add_of_pos_right hk) (mul_succ k n ▸ nat.mul_le_mul_left k (succ_le_of_lt h))
protected lemma mul_lt_mul_of_pos_right {n m k : ℕ} (h : n < m) (hk : k > 0) : n * k < m * k :=
nat.mul_comm k m ▸ nat.mul_comm k n ▸ nat.mul_lt_mul_of_pos_left h hk
protected lemma le_of_mul_le_mul_left {a b c : ℕ} (h : c * a ≤ c * b) (hc : c > 0) : a ≤ b :=
le_of_not_gt
(assume h1 : b < a,
have h2 : c * b < c * a, from nat.mul_lt_mul_of_pos_left h1 hc,
not_le_of_gt h2 h)
instance : decidable_linear_order nat :=
{ lt := nat.lt,
le := nat.le,
le_refl := nat.le_refl,
le_trans := @nat.le_trans,
le_antisymm := @nat.le_antisymm,
le_total := @nat.le_total,
lt_iff_le_not_le := @lt_iff_le_not_le _ _,
decidable_lt := nat.decidable_lt,
decidable_le := nat.decidable_le,
decidable_eq := nat.decidable_eq }
lemma le_of_lt_succ {m n : nat} : m < succ n → m ≤ n :=
le_of_succ_le_succ
theorem eq_of_mul_eq_mul_left {m k n : ℕ} (Hn : n > 0) (H : n * m = n * k) : m = k :=
le_antisymm (nat.le_of_mul_le_mul_left (le_of_eq H) Hn)
(nat.le_of_mul_le_mul_left (le_of_eq H.symm) Hn)
/- sub properties -/
@[simp] protected lemma zero_sub : ∀ a : ℕ, 0 - a = 0
| 0 := rfl
| (a+1) := congr_arg pred (zero_sub a)
lemma sub_lt_succ (a b : ℕ) : a - b < succ a :=
lt_succ_of_le (sub_le a b)
protected theorem sub_le_sub_right {n m : ℕ} (h : n ≤ m) : ∀ k, n - k ≤ m - k
| 0 := h
| (succ z) := pred_le_pred (sub_le_sub_right z)
/- bit0/bit1 properties -/
protected lemma bit1_eq_succ_bit0 (n : ℕ) : bit1 n = succ (bit0 n) :=
rfl
protected lemma bit1_succ_eq (n : ℕ) : bit1 (succ n) = succ (succ (bit1 n)) :=
eq.trans (nat.bit1_eq_succ_bit0 (succ n)) (congr_arg succ (nat.bit0_succ_eq n))
protected lemma bit1_ne_one : ∀ {n : ℕ}, n ≠ 0 → bit1 n ≠ 1
| 0 h h1 := absurd rfl h
| (n+1) h h1 := nat.no_confusion h1 (λ h2, absurd h2 (succ_ne_zero _))
protected lemma bit0_ne_one : ∀ n : ℕ, bit0 n ≠ 1
| 0 h := absurd h (ne.symm nat.one_ne_zero)
| (n+1) h :=
have h1 : succ (succ (n + n)) = 1, from succ_add n n ▸ h,
nat.no_confusion h1
(λ h2, absurd h2 (succ_ne_zero (n + n)))
protected lemma add_self_ne_one : ∀ (n : ℕ), n + n ≠ 1
| 0 h := nat.no_confusion h
| (n+1) h :=
have h1 : succ (succ (n + n)) = 1, from succ_add n n ▸ h,
nat.no_confusion h1 (λ h2, absurd h2 (nat.succ_ne_zero (n + n)))
protected lemma bit1_ne_bit0 : ∀ (n m : ℕ), bit1 n ≠ bit0 m
| 0 m h := absurd h (ne.symm (nat.add_self_ne_one m))
| (n+1) 0 h :=
have h1 : succ (bit0 (succ n)) = 0, from h,
absurd h1 (nat.succ_ne_zero _)
| (n+1) (m+1) h :=
have h1 : succ (succ (bit1 n)) = succ (succ (bit0 m)), from
nat.bit0_succ_eq m ▸ nat.bit1_succ_eq n ▸ h,
have h2 : bit1 n = bit0 m, from
nat.no_confusion h1 (λ h2', nat.no_confusion h2' (λ h2'', h2'')),
absurd h2 (bit1_ne_bit0 n m)
protected lemma bit0_ne_bit1 : ∀ (n m : ℕ), bit0 n ≠ bit1 m :=
λ n m : nat, ne.symm (nat.bit1_ne_bit0 m n)
protected lemma bit0_inj : ∀ {n m : ℕ}, bit0 n = bit0 m → n = m
| 0 0 h := rfl
| 0 (m+1) h := by contradiction
| (n+1) 0 h := by contradiction
| (n+1) (m+1) h :=
have succ (succ (n + n)) = succ (succ (m + m)),
by { unfold bit0 at h, simp [add_one, add_succ, succ_add] at h,
have aux : n + n = m + m := h, rw aux },
have n + n = m + m, by iterate { injection this with this },
have n = m, from bit0_inj this,
by rw this
protected lemma bit1_inj : ∀ {n m : ℕ}, bit1 n = bit1 m → n = m :=
λ n m h,
have succ (bit0 n) = succ (bit0 m), begin simp [nat.bit1_eq_succ_bit0] at h, rw h end,
have bit0 n = bit0 m, by injection this,
nat.bit0_inj this
protected lemma bit0_ne {n m : ℕ} : n ≠ m → bit0 n ≠ bit0 m :=
λ h₁ h₂, absurd (nat.bit0_inj h₂) h₁
protected lemma bit1_ne {n m : ℕ} : n ≠ m → bit1 n ≠ bit1 m :=
λ h₁ h₂, absurd (nat.bit1_inj h₂) h₁
protected lemma zero_ne_bit0 {n : ℕ} : n ≠ 0 → 0 ≠ bit0 n :=
λ h, ne.symm (nat.bit0_ne_zero h)
protected lemma zero_ne_bit1 (n : ℕ) : 0 ≠ bit1 n :=
ne.symm (nat.bit1_ne_zero n)
protected lemma one_ne_bit0 (n : ℕ) : 1 ≠ bit0 n :=
ne.symm (nat.bit0_ne_one n)
protected lemma one_ne_bit1 {n : ℕ} : n ≠ 0 → 1 ≠ bit1 n :=
λ h, ne.symm (nat.bit1_ne_one h)
protected lemma one_lt_bit1 : ∀ {n : nat}, n ≠ 0 → 1 < bit1 n
| 0 h := by contradiction
| (succ n) h :=
begin
rw nat.bit1_succ_eq,
apply succ_lt_succ,
apply zero_lt_succ
end
protected lemma one_lt_bit0 : ∀ {n : nat}, n ≠ 0 → 1 < bit0 n
| 0 h := by contradiction
| (succ n) h :=
begin
rw nat.bit0_succ_eq,
apply succ_lt_succ,
apply zero_lt_succ
end
protected lemma bit0_lt {n m : nat} (h : n < m) : bit0 n < bit0 m :=
nat.add_lt_add h h
protected lemma bit1_lt {n m : nat} (h : n < m) : bit1 n < bit1 m :=
succ_lt_succ (nat.add_lt_add h h)
protected lemma bit0_lt_bit1 {n m : nat} (h : n ≤ m) : bit0 n < bit1 m :=
lt_succ_of_le (nat.add_le_add h h)
protected lemma bit1_lt_bit0 : ∀ {n m : nat}, n < m → bit1 n < bit0 m
| n 0 h := absurd h (not_lt_zero _)
| n (succ m) h :=
have n ≤ m, from le_of_lt_succ h,
have succ (n + n) ≤ succ (m + m), from succ_le_succ (nat.add_le_add this this),
have succ (n + n) ≤ succ m + m, {rw succ_add, assumption},
show succ (n + n) < succ (succ m + m), from lt_succ_of_le this
protected lemma one_le_bit1 (n : ℕ) : 1 ≤ bit1 n :=
show 1 ≤ succ (bit0 n), from
succ_le_succ (zero_le (bit0 n))
protected lemma one_le_bit0 : ∀ (n : ℕ), n ≠ 0 → 1 ≤ bit0 n
| 0 h := absurd rfl h
| (n+1) h :=
suffices 1 ≤ succ (succ (bit0 n)), from
eq.symm (nat.bit0_succ_eq n) ▸ this,
succ_le_succ (zero_le (succ (bit0 n)))
/- subtraction -/
@[simp]
protected theorem sub_zero (n : ℕ) : n - 0 = n :=
rfl
theorem sub_succ (n m : ℕ) : n - succ m = pred (n - m) :=
rfl
theorem succ_sub_succ (n m : ℕ) : succ n - succ m = n - m :=
succ_sub_succ_eq_sub n m
protected theorem sub_self : ∀ (n : ℕ), n - n = 0
| 0 := by rw nat.sub_zero
| (succ n) := by rw [succ_sub_succ, sub_self n]
/- TODO(Leo): remove the following ematch annotations as soon as we have
arithmetic theory in the smt_stactic -/
@[ematch_lhs]
protected theorem add_sub_add_right : ∀ (n k m : ℕ), (n + k) - (m + k) = n - m
| n 0 m := by rw [nat.add_zero, nat.add_zero]
| n (succ k) m := by rw [add_succ, add_succ, succ_sub_succ, add_sub_add_right n k m]
@[ematch_lhs]
protected theorem add_sub_add_left (k n m : ℕ) : (k + n) - (k + m) = n - m :=
by rw [nat.add_comm k n, nat.add_comm k m, nat.add_sub_add_right]
@[ematch_lhs]
protected theorem add_sub_cancel (n m : ℕ) : n + m - m = n :=
suffices n + m - (0 + m) = n, from
by rwa [nat.zero_add] at this,
by rw [nat.add_sub_add_right, nat.sub_zero]
@[ematch_lhs]
protected theorem add_sub_cancel_left (n m : ℕ) : n + m - n = m :=
show n + m - (n + 0) = m, from
by rw [nat.add_sub_add_left, nat.sub_zero]
protected theorem sub_sub : ∀ (n m k : ℕ), n - m - k = n - (m + k)
| n m 0 := by rw [nat.add_zero, nat.sub_zero]
| n m (succ k) := by rw [add_succ, nat.sub_succ, nat.sub_succ, sub_sub n m k]
theorem le_of_le_of_sub_le_sub_right {n m k : ℕ}
(h₀ : k ≤ m)
(h₁ : n - k ≤ m - k)
: n ≤ m :=
begin
revert k m,
induction n with n ; intros k m h₀ h₁,
{ apply zero_le },
{ cases k with k,
{ apply h₁ },
cases m with m,
{ cases not_succ_le_zero _ h₀ },
{ simp [succ_sub_succ] at h₁,
apply succ_le_succ,
apply n_ih _ h₁,
apply le_of_succ_le_succ h₀ }, }
end
protected theorem sub_le_sub_right_iff (n m k : ℕ)
(h : k ≤ m)
: n - k ≤ m - k ↔ n ≤ m :=
⟨ le_of_le_of_sub_le_sub_right h , assume h, nat.sub_le_sub_right h k ⟩
theorem sub_self_add (n m : ℕ) : n - (n + m) = 0 :=
show (n + 0) - (n + m) = 0, from
by rw [nat.add_sub_add_left, nat.zero_sub]
theorem add_le_to_le_sub (x : ℕ) {y k : ℕ}
(h : k ≤ y)
: x + k ≤ y ↔ x ≤ y - k :=
by rw [← nat.add_sub_cancel x k, nat.sub_le_sub_right_iff _ _ _ h, nat.add_sub_cancel]
lemma sub_lt_of_pos_le (a b : ℕ) (h₀ : 0 < a) (h₁ : a ≤ b)
: b - a < b :=
begin
apply sub_lt _ h₀,
apply lt_of_lt_of_le h₀ h₁
end
theorem sub_one (n : ℕ) : n - 1 = pred n :=
rfl
theorem succ_sub_one (n : ℕ) : succ n - 1 = n :=
rfl
theorem succ_pred_eq_of_pos : ∀ {n : ℕ}, n > 0 → succ (pred n) = n
| 0 h := absurd h (lt_irrefl 0)
| (succ k) h := rfl
theorem sub_eq_zero_of_le {n m : ℕ} (h : n ≤ m) : n - m = 0 :=
exists.elim (nat.le.dest h)
(assume k, assume hk : n + k = m, by rw [← hk, sub_self_add])
protected theorem le_of_sub_eq_zero : ∀{n m : ℕ}, n - m = 0 → n ≤ m
| n 0 H := begin rw [nat.sub_zero] at H, simp [H] end
| 0 (m+1) H := zero_le _
| (n+1) (m+1) H := nat.add_le_add_right
(le_of_sub_eq_zero begin simp [nat.add_sub_add_right] at H, exact H end) _
protected theorem sub_eq_zero_iff_le {n m : ℕ} : n - m = 0 ↔ n ≤ m :=
⟨nat.le_of_sub_eq_zero, nat.sub_eq_zero_of_le⟩
theorem add_sub_of_le {n m : ℕ} (h : n ≤ m) : n + (m - n) = m :=
exists.elim (nat.le.dest h)
(assume k, assume hk : n + k = m,
by rw [← hk, nat.add_sub_cancel_left])
protected theorem sub_add_cancel {n m : ℕ} (h : n ≥ m) : n - m + m = n :=
by rw [nat.add_comm, add_sub_of_le h]
protected theorem add_sub_assoc {m k : ℕ} (h : k ≤ m) (n : ℕ) : n + m - k = n + (m - k) :=
exists.elim (nat.le.dest h)
(assume l, assume hl : k + l = m,
by rw [← hl, nat.add_sub_cancel_left, 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 :=
⟨assume c_eq, begin rw [c_eq.symm, nat.sub_add_cancel ab] end,
assume a_eq, begin rw [a_eq, nat.add_sub_cancel] end⟩
protected lemma lt_of_sub_eq_succ {m n l : ℕ} (H : m - n = nat.succ l) : n < m :=
lt_of_not_ge
(assume (H' : n ≥ m), begin simp [nat.sub_eq_zero_of_le H'] at H, contradiction end)
@[simp] lemma zero_min (a : ℕ) : min 0 a = 0 :=
min_eq_left (zero_le a)
@[simp] lemma min_zero (a : ℕ) : min a 0 = 0 :=
min_eq_right (zero_le a)
-- Distribute succ over min
theorem min_succ_succ (x y : ℕ) : min (succ x) (succ y) = succ (min x y) :=
have f : x ≤ y → min (succ x) (succ y) = succ (min x y), from λp,
calc min (succ x) (succ y)
= succ x : if_pos (succ_le_succ p)
... = succ (min x y) : congr_arg succ (eq.symm (if_pos p)),
have g : ¬ (x ≤ y) → min (succ x) (succ y) = succ (min x y), from λp,
calc min (succ x) (succ y)
= succ y : if_neg (λeq, p (pred_le_pred eq))
... = succ (min x y) : congr_arg succ (eq.symm (if_neg p)),
decidable.by_cases f g
theorem sub_eq_sub_min (n m : ℕ) : n - m = n - min n m :=
if h : n ≥ m then by rewrite [min_eq_right h]
else by rewrite [sub_eq_zero_of_le (le_of_not_ge h), min_eq_left (le_of_not_ge h), nat.sub_self]
@[simp] theorem sub_add_min_cancel (n m : ℕ) : n - m + min n m = n :=
by rw [sub_eq_sub_min, nat.sub_add_cancel (min_le_left n m)]
/- TODO(Leo): sub + inequalities -/
protected def strong_rec_on {p : nat → Sort u} (n : nat) (h : ∀ n, (∀ m, m < n → p m) → p n) : p n :=
suffices ∀ n m, m < n → p m, from this (succ n) n (lt_succ_self _),
begin
intros n, induction n with n ih,
{intros m h₁, exact absurd h₁ (not_lt_zero _)},
{intros m h₁,
apply or.by_cases (lt_or_eq_of_le (le_of_lt_succ h₁)),
{intros, apply ih, assumption},
{intros, subst m, apply h _ ih}}
end
protected lemma strong_induction_on {p : nat → Prop} (n : nat) (h : ∀ n, (∀ m, m < n → p m) → p n) : p n :=
nat.strong_rec_on n h
protected lemma case_strong_induction_on {p : nat → Prop} (a : nat)
(hz : p 0)
(hi : ∀ n, (∀ m, m ≤ n → p m) → p (succ n)) : p a :=
nat.strong_induction_on a $ λ n,
match n with
| 0 := λ _, hz
| (n+1) := λ h₁, hi n (λ m h₂, h₁ _ (lt_succ_of_le h₂))
end
/- mod -/
lemma mod_def (x y : nat) : x % y = if 0 < y ∧ y ≤ x then (x - y) % y else x :=
by have h := mod_def_aux x y; rwa [dif_eq_if] at h
@[simp] lemma mod_zero (a : nat) : a % 0 = a :=
begin
rw mod_def,
have h : ¬ (0 < 0 ∧ 0 ≤ a),
simp [lt_irrefl],
simp [if_neg, h]
end
lemma mod_eq_of_lt {a b : nat} (h : a < b) : a % b = a :=
begin
rw mod_def,
have h' : ¬(0 < b ∧ b ≤ a),
simp [not_le_of_gt h],
simp [if_neg, h']
end
@[simp] lemma zero_mod (b : nat) : 0 % b = 0 :=
begin
rw mod_def,
have h : ¬(0 < b ∧ b ≤ 0),
{intro hn, cases hn with l r, exact absurd (lt_of_lt_of_le l r) (lt_irrefl 0)},
simp [if_neg, h]
end
lemma mod_eq_sub_mod {a b : nat} (h : a ≥ b) : a % b = (a - b) % b :=
or.elim (eq_zero_or_pos b)
(λb0, by rw [b0, nat.sub_zero])
(λh₂, by rw [mod_def, if_pos (and.intro h₂ h)])
lemma mod_lt (x : nat) {y : nat} (h : y > 0) : x % y < y :=
begin
induction x using nat.case_strong_induction_on with x ih,
{rw zero_mod, assumption},
{apply or.elim (decidable.em (succ x < y)),
{intro h₁, rwa [mod_eq_of_lt h₁]},
{intro h₁,
have h₁ : succ x % y = (succ x - y) % y, {exact mod_eq_sub_mod (le_of_not_gt h₁)},
have this : succ x - y ≤ x, {exact le_of_lt_succ (sub_lt (succ_pos x) h)},
have h₂ : (succ x - y) % y < y, {exact ih _ this},
rwa [← h₁] at h₂}}
end
@[simp] theorem mod_self (n : nat) : n % n = 0 :=
by rw [mod_eq_sub_mod (le_refl _), nat.sub_self, zero_mod]
@[simp] lemma mod_one (n : ℕ) : n % 1 = 0 :=
have n % 1 < 1, from (mod_lt n) (succ_pos 0),
eq_zero_of_le_zero (le_of_lt_succ this)
lemma mod_two_eq_zero_or_one (n : ℕ) : n % 2 = 0 ∨ n % 2 = 1 :=
match n % 2, @nat.mod_lt n 2 dec_trivial with
| 0, _ := or.inl rfl
| 1, _ := or.inr rfl
| k+2, h := absurd h dec_trivial
end
/- div & mod -/
lemma div_def (x y : nat) : x / y = if 0 < y ∧ y ≤ x then (x - y) / y + 1 else 0 :=
by have h := div_def_aux x y; rwa dif_eq_if at h
lemma mod_add_div (m k : ℕ)
: m % k + k * (m / k) = m :=
begin
apply nat.strong_induction_on m,
clear m,
intros m IH,
cases decidable.em (0 < k ∧ k ≤ m) with h h',
-- 0 < k ∧ k ≤ m
{ have h' : m - k < m,
{ apply nat.sub_lt _ h.left,
apply lt_of_lt_of_le h.left h.right },
rw [div_def, mod_def, if_pos h, if_pos h],
simp [nat.left_distrib, IH _ h', nat.add_comm, nat.add_left_comm],
rw [nat.add_comm, ← nat.add_sub_assoc h.right, nat.mul_one, nat.add_sub_cancel_left] },
-- ¬ (0 < k ∧ k ≤ m)
{ rw [div_def, mod_def, if_neg h', if_neg h', nat.mul_zero, nat.add_zero] },
end
/- div -/
@[simp] protected lemma div_one (n : ℕ) : n / 1 = n :=
have n % 1 + 1 * (n / 1) = n, from mod_add_div _ _,
by { rwa [mod_one, nat.zero_add, nat.one_mul] at this }
@[simp] protected lemma div_zero (n : ℕ) : n / 0 = 0 :=
begin rw [div_def], simp [lt_irrefl] end
@[simp] protected lemma zero_div (b : ℕ) : 0 / b = 0 :=
eq.trans (div_def 0 b) $ if_neg (and.rec not_le_of_gt)
protected lemma div_le_of_le_mul {m n : ℕ} : ∀ {k}, m ≤ k * n → m / k ≤ n
| 0 h := by simp [nat.div_zero]; apply zero_le
| (succ k) h :=
suffices succ k * (m / succ k) ≤ succ k * n, from nat.le_of_mul_le_mul_left this (zero_lt_succ _),
calc
succ k * (m / succ k) ≤ m % succ k + succ k * (m / succ k) : le_add_left _ _
... = m : by rw mod_add_div
... ≤ succ k * n : h
protected lemma div_le_self : ∀ (m n : ℕ), m / n ≤ m
| m 0 := by simp [nat.div_zero]; apply zero_le
| m (succ n) :=
have m ≤ succ n * m, from calc
m = 1 * m : by rw nat.one_mul
... ≤ succ n * m : mul_le_mul_right _ (succ_le_succ (zero_le _)),
nat.div_le_of_le_mul this
lemma div_eq_sub_div {a b : nat} (h₁ : b > 0) (h₂ : a ≥ b) : a / b = (a - b) / b + 1 :=
begin
rw [div_def a, if_pos],
split ; assumption
end
lemma div_eq_of_lt {a b : ℕ} (h₀ : a < b) : a / b = 0 :=
begin
rw [div_def a, if_neg],
intro h₁,
apply not_le_of_gt h₀ h₁.right
end
-- this is a Galois connection
-- f x ≤ y ↔ x ≤ g y
-- with
-- f x = x * k
-- g y = y / k
theorem le_div_iff_mul_le (x y : ℕ) {k : ℕ}
(Hk : k > 0)
: x ≤ y / k ↔ x * k ≤ y :=
begin
-- Hk is needed because, despite div being made total, y / 0 := 0
-- x * 0 ≤ y ↔ x ≤ y / 0
-- ↔ 0 ≤ y ↔ x ≤ 0
-- ↔ true ↔ x = 0
-- ↔ x = 0
revert x,
apply nat.strong_induction_on y _,
clear y,
intros y IH x,
cases lt_or_ge y k with h h,
-- base case: y < k
{ rw [div_eq_of_lt h],
cases x with x,
{ simp [nat.zero_mul, zero_le] },
{ simp [succ_mul, not_succ_le_zero, nat.add_comm],
apply not_le_of_gt,
apply lt_of_lt_of_le h,
apply le_add_right } },
-- step: k ≤ y
{ rw [div_eq_sub_div Hk h],
cases x with x,
{ simp [nat.zero_mul, zero_le] },
{ have Hlt : y - k < y,
{ apply sub_lt_of_pos_le ; assumption },
rw [ ← add_one
, nat.add_le_add_iff_le_right
, IH (y - k) Hlt x
, add_one
, succ_mul, add_le_to_le_sub _ h ]
} }
end
theorem div_lt_iff_lt_mul (x y : ℕ) {k : ℕ}
(Hk : k > 0)
: x / k < y ↔ x < y * k :=
begin
simp [lt_iff_not_ge],
apply not_iff_not_of_iff,
apply le_div_iff_mul_le _ _ Hk
end
def iterate {α : Sort u} (op : α → α) : ℕ → α → α
| 0 a := a
| (succ k) a := iterate k (op a)
notation f`^[`n`]` := iterate f n
/- successor and predecessor -/
theorem add_one_ne_zero (n : ℕ) : n + 1 ≠ 0 := succ_ne_zero _
theorem eq_zero_or_eq_succ_pred (n : ℕ) : n = 0 ∨ n = succ (pred n) :=
by cases n; simp
theorem exists_eq_succ_of_ne_zero {n : ℕ} (H : n ≠ 0) : ∃k : ℕ, n = succ k :=
⟨_, (eq_zero_or_eq_succ_pred _).resolve_left H⟩
theorem discriminate {B : Sort u} {n : ℕ} (H1: n = 0 → B) (H2 : ∀m, n = succ m → B) : B :=
by induction h : n; [exact H1 h, exact H2 _ h]
theorem one_succ_zero : 1 = succ 0 := rfl
theorem two_step_induction {P : ℕ → Sort u} (H1 : P 0) (H2 : P 1)
(H3 : ∀ (n : ℕ) (IH1 : P n) (IH2 : P (succ n)), P (succ (succ n))) : Π (a : ℕ), P a
| 0 := H1
| 1 := H2
| (succ (succ n)) := H3 _ (two_step_induction _) (two_step_induction _)
theorem sub_induction {P : ℕ → ℕ → Sort u} (H1 : ∀m, P 0 m)
(H2 : ∀n, P (succ n) 0) (H3 : ∀n m, P n m → P (succ n) (succ m)) : Π (n m : ℕ), P n m
| 0 m := H1 _
| (succ n) 0 := H2 _
| (succ n) (succ m) := H3 _ _ (sub_induction n m)
/- addition -/
theorem succ_add_eq_succ_add (n m : ℕ) : succ n + m = n + succ m :=
by simp [succ_add, add_succ]
-- theorem one_add (n : ℕ) : 1 + n = succ n := by simp [add_comm]
protected theorem add_right_comm : ∀ (n m k : ℕ), n + m + k = n + k + m :=
right_comm nat.add nat.add_comm nat.add_assoc
theorem eq_zero_of_add_eq_zero {n m : ℕ} (H : n + m = 0) : n = 0 ∧ m = 0 :=
⟨nat.eq_zero_of_add_eq_zero_right H, nat.eq_zero_of_add_eq_zero_left H⟩
theorem eq_zero_of_mul_eq_zero : ∀ {n m : ℕ}, n * m = 0 → n = 0 ∨ m = 0
| 0 m := λ h, or.inl rfl
| (succ n) m :=
begin
rw succ_mul, intro h,
exact or.inr (eq_zero_of_add_eq_zero_left h)
end
/- properties of inequality -/
theorem le_succ_of_pred_le {n m : ℕ} : pred n ≤ m → n ≤ succ m :=
nat.cases_on n less_than_or_equal.step (λ a, succ_le_succ)
theorem le_lt_antisymm {n m : ℕ} (h₁ : n ≤ m) (h₂ : m < n) : false :=
nat.lt_irrefl n (nat.lt_of_le_of_lt h₁ h₂)
theorem lt_le_antisymm {n m : ℕ} (h₁ : n < m) (h₂ : m ≤ n) : false :=
le_lt_antisymm h₂ h₁
protected theorem lt_asymm {n m : ℕ} (h₁ : n < m) : ¬ m < n :=
le_lt_antisymm (nat.le_of_lt h₁)
protected def lt_ge_by_cases {a b : ℕ} {C : Sort u} (h₁ : a < b → C) (h₂ : a ≥ b → C) : C :=
decidable.by_cases h₁ (λ h, h₂ (or.elim (nat.lt_or_ge a b) (λ a, absurd a h) (λ a, a)))
protected def lt_by_cases {a b : ℕ} {C : Sort u} (h₁ : a < b → C) (h₂ : a = b → C)
(h₃ : b < a → C) : C :=
nat.lt_ge_by_cases h₁ (λ h₁,
nat.lt_ge_by_cases h₃ (λ h, h₂ (nat.le_antisymm h h₁)))
protected theorem lt_trichotomy (a b : ℕ) : a < b ∨ a = b ∨ b < a :=
nat.lt_by_cases (λ h, or.inl h) (λ h, or.inr (or.inl h)) (λ h, or.inr (or.inr h))
protected theorem eq_or_lt_of_not_lt {a b : ℕ} (hnlt : ¬ a < b) : a = b ∨ b < a :=
(nat.lt_trichotomy a b).resolve_left hnlt
theorem lt_succ_of_lt {a b : nat} (h : a < b) : a < succ b := le_succ_of_le h
def one_pos := nat.zero_lt_one
/- subtraction -/
protected theorem sub_le_sub_left {n m : ℕ} (k) (h : n ≤ m) : k - m ≤ k - n :=
by induction h; [refl, exact le_trans (pred_le _) h_ih]
theorem succ_sub_sub_succ (n m k : ℕ) : succ n - m - succ k = n - m - k :=
by rw [nat.sub_sub, nat.sub_sub, add_succ, succ_sub_succ]
protected theorem sub.right_comm (m n k : ℕ) : m - n - k = m - k - n :=
by rw [nat.sub_sub, nat.sub_sub, nat.add_comm]
theorem mul_pred_left : ∀ (n m : ℕ), pred n * m = n * m - m
| 0 m := by simp [nat.zero_sub, pred_zero, nat.zero_mul]
| (succ n) m := by rw [pred_succ, succ_mul, nat.add_sub_cancel]
theorem mul_pred_right (n m : ℕ) : n * pred m = n * m - n :=
by rw [nat.mul_comm, mul_pred_left, nat.mul_comm]
protected theorem mul_sub_right_distrib : ∀ (n m k : ℕ), (n - m) * k = n * k - m * k
| n 0 k := by simp [nat.sub_zero, nat.zero_mul]
| n (succ m) k := by rw [nat.sub_succ, mul_pred_left, mul_sub_right_distrib, succ_mul, nat.sub_sub]
protected theorem mul_sub_left_distrib (n m k : ℕ) : n * (m - k) = n * m - n * k :=
by rw [nat.mul_comm, nat.mul_sub_right_distrib, nat.mul_comm m n, nat.mul_comm n k]
protected theorem mul_self_sub_mul_self_eq (a b : nat) : a * a - b * b = (a + b) * (a - b) :=
by rw [nat.mul_sub_left_distrib, nat.right_distrib, nat.right_distrib, nat.mul_comm b a, nat.add_comm (a*a) (a*b),
nat.add_sub_add_left]
theorem succ_mul_succ_eq (a b : nat) : succ a * succ b = a*b + a + b + 1 :=
begin
rw [← add_one, ← add_one],
simp [nat.right_distrib, nat.left_distrib, nat.add_left_comm, nat.mul_one, nat.one_mul, nat.add_assoc],
end
theorem succ_sub {m n : ℕ} (h : m ≥ n) : succ m - n = succ (m - n) :=
exists.elim (nat.le.dest h)
(assume k, assume hk : n + k = m,
by rw [← hk, nat.add_sub_cancel_left, ← add_succ, nat.add_sub_cancel_left])
protected theorem sub_pos_of_lt {m n : ℕ} (h : m < n) : n - m > 0 :=
have 0 + m < n - m + m, begin rw [nat.zero_add, nat.sub_add_cancel (le_of_lt h)], exact h end,
nat.lt_of_add_lt_add_right this
protected theorem sub_sub_self {n m : ℕ} (h : m ≤ n) : n - (n - m) = m :=
(nat.sub_eq_iff_eq_add (nat.sub_le _ _)).2 (eq.symm (add_sub_of_le h))
protected theorem sub_add_comm {n m k : ℕ} (h : k ≤ n) : n + m - k = n - k + m :=
(nat.sub_eq_iff_eq_add (nat.le_trans h (nat.le_add_right _ _))).2
(by rwa [nat.add_right_comm, nat.sub_add_cancel])
theorem sub_one_sub_lt {n i} (h : i < n) : n - 1 - i < n := begin
rw nat.sub_sub,
apply nat.sub_lt,
apply lt_of_lt_of_le (nat.zero_lt_succ _) h,
rw nat.add_comm,
apply nat.zero_lt_succ
end
theorem pred_inj : ∀ {a b : nat}, a > 0 → b > 0 → nat.pred a = nat.pred b → a = b
| (succ a) (succ b) ha hb h := have a = b, from h, by rw this
| (succ a) 0 ha hb h := absurd hb (lt_irrefl _)
| 0 (succ b) ha hb h := absurd ha (lt_irrefl _)
| 0 0 ha hb h := rfl
/- find -/
section find
parameter {p : ℕ → Prop}
private def lbp (m n : ℕ) : Prop := m = n + 1 ∧ ∀ k ≤ n, ¬p k
parameters [decidable_pred p] (H : ∃n, p n)
private def wf_lbp : well_founded lbp :=
⟨let ⟨n, pn⟩ := H in
suffices ∀m k, n ≤ k + m → acc lbp k, from λa, this _ _ (nat.le_add_left _ _),
λm, nat.rec_on m
(λk kn, ⟨_, λy r, match y, r with ._, ⟨rfl, a⟩ := absurd pn (a _ kn) end⟩)
(λm IH k kn, ⟨_, λy r, match y, r with ._, ⟨rfl, a⟩ := IH _ (by rw nat.add_right_comm; exact kn) end⟩)⟩
protected def find_x : {n // p n ∧ ∀m < n, ¬p m} :=
@well_founded.fix _ (λk, (∀n < k, ¬p n) → {n // p n ∧ ∀m < n, ¬p m}) lbp wf_lbp
(λm IH al, if pm : p m then ⟨m, pm, al⟩ else
have ∀ n ≤ m, ¬p n, from λn h, or.elim (lt_or_eq_of_le h) (al n) (λe, by rw e; exact pm),
IH _ ⟨rfl, this⟩ (λn h, this n $ nat.le_of_succ_le_succ h))
0 (λn h, absurd h (nat.not_lt_zero _))
protected def find : ℕ := nat.find_x.1
protected theorem find_spec : p nat.find := nat.find_x.2.left
protected theorem find_min : ∀ {m : ℕ}, m < nat.find → ¬p m := nat.find_x.2.right
protected theorem find_min' {m : ℕ} (h : p m) : nat.find ≤ m :=
le_of_not_gt (λ l, find_min l h)
end find
/- mod -/
theorem mod_le (x y : ℕ) : x % y ≤ x :=
or.elim (lt_or_ge x y)
(λxlty, by rw mod_eq_of_lt xlty; refl)
(λylex, or.elim (eq_zero_or_pos y)
(λy0, by rw [y0, mod_zero]; refl)
(λypos, le_trans (le_of_lt (mod_lt _ ypos)) ylex))
@[simp] theorem add_mod_right (x z : ℕ) : (x + z) % z = x % z :=
by rw [mod_eq_sub_mod (nat.le_add_left _ _), nat.add_sub_cancel]
@[simp] theorem add_mod_left (x z : ℕ) : (x + z) % x = z % x :=
by rw [nat.add_comm, add_mod_right]
@[simp] theorem add_mul_mod_self_left (x y z : ℕ) : (x + y * z) % y = x % y :=
by {induction z with z ih, rw [nat.mul_zero, nat.add_zero], rw [mul_succ, ← nat.add_assoc, add_mod_right, ih]}
@[simp] theorem 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] theorem mul_mod_right (m n : ℕ) : (m * n) % m = 0 :=
by rw [← nat.zero_add (m*n), add_mul_mod_self_left, zero_mod]
@[simp] theorem mul_mod_left (m n : ℕ) : (m * n) % n = 0 :=
by rw [nat.mul_comm, mul_mod_right]
theorem mul_mod_mul_left (z x y : ℕ) : (z * x) % (z * y) = z * (x % y) :=
if y0 : y = 0 then
by rw [y0, 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 x.strong_induction_on $ λn IH,
have y0 : y > 0, from nat.pos_of_ne_zero y0,
have z0 : z > 0, from nat.pos_of_ne_zero z0,
or.elim (le_or_gt y n)
(λyn, by rw [
mod_eq_sub_mod yn,
mod_eq_sub_mod (mul_le_mul_left z yn),
← nat.mul_sub_left_distrib];
exact IH _ (sub_lt (lt_of_lt_of_le y0 yn) y0))
(λyn, by rw [mod_eq_of_lt yn, mod_eq_of_lt (nat.mul_lt_mul_of_pos_left yn z0)])
theorem mul_mod_mul_right (z x y : ℕ) : (x * z) % (y * z) = (x % y) * z :=
by rw [nat.mul_comm x z, nat.mul_comm y z, nat.mul_comm (x % y) z]; apply mul_mod_mul_left
theorem cond_to_bool_mod_two (x : ℕ) [d : decidable (x % 2 = 1)]
: cond (@to_bool (x % 2 = 1) d) 1 0 = x % 2 :=
begin
by_cases h : x % 2 = 1,
{ simp! [*] },
{ cases mod_two_eq_zero_or_one x; simp! [*, nat.zero_ne_one] }
end
theorem sub_mul_mod (x k n : ℕ) (h₁ : n*k ≤ x) : (x - n*k) % n = x % n :=
begin
induction k with k,
{ rw [nat.mul_zero, nat.sub_zero] },
{ have h₂ : n * k ≤ x,
{ rw [mul_succ] at h₁,
apply nat.le_trans _ h₁,
apply le_add_right _ n },
have h₄ : x - n * k ≥ n,
{ apply @nat.le_of_add_le_add_right (n*k),
rw [nat.sub_add_cancel h₂],
simp [mul_succ, nat.add_comm] at h₁, simp [h₁] },
rw [mul_succ, ← nat.sub_sub, ← mod_eq_sub_mod h₄, k_ih h₂] }
end
/- div -/
theorem sub_mul_div (x n p : ℕ) (h₁ : n*p ≤ x) : (x - n*p) / n = x / n - p :=
begin
cases eq_zero_or_pos n with h₀ h₀,
{ rw [h₀, nat.div_zero, nat.div_zero, nat.zero_sub] },
{ induction p with p,
{ rw [nat.mul_zero, nat.sub_zero, nat.sub_zero] },
{ have h₂ : n*p ≤ x,
{ transitivity,
{ apply nat.mul_le_mul_left, apply le_succ },
{ apply h₁ } },
have h₃ : x - n * p ≥ n,
{ 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, ← p_ih h₂],
rw [@div_eq_sub_div (x - n*p) _ h₀ h₃],
simp [add_one, pred_succ, mul_succ, nat.sub_sub] } }
end
theorem div_mul_le_self : ∀ (m n : ℕ), m / n * n ≤ m
| m 0 := by simp; apply zero_le
| m (succ n) := (le_div_iff_mul_le _ _ (nat.succ_pos _)).1 (le_refl _)
@[simp] theorem add_div_right (x : ℕ) {z : ℕ} (H : z > 0) : (x + z) / z = succ (x / z) :=
by rw [div_eq_sub_div H (nat.le_add_left _ _), nat.add_sub_cancel]
@[simp] theorem add_div_left (x : ℕ) {z : ℕ} (H : z > 0) : (z + x) / z = succ (x / z) :=
by rw [nat.add_comm, add_div_right x H]
@[simp] theorem mul_div_right (n : ℕ) {m : ℕ} (H : m > 0) : m * n / m = n :=
by {induction n; simp [*, mul_succ, nat.mul_zero] }
@[simp] theorem mul_div_left (m : ℕ) {n : ℕ} (H : n > 0) : m * n / n = m :=
by rw [nat.mul_comm, mul_div_right _ H]
protected theorem div_self {n : ℕ} (H : n > 0) : n / n = 1 :=
let t := add_div_right 0 H in by rwa [nat.zero_add, nat.zero_div] at t
theorem add_mul_div_left (x z : ℕ) {y : ℕ} (H : y > 0) : (x + y * z) / y = x / y + z :=
begin
induction z with z ih,
{ rw [nat.mul_zero, nat.add_zero, nat.add_zero] },
{ rw [mul_succ, ← nat.add_assoc, add_div_right _ H, ih] }
end
theorem add_mul_div_right (x y : ℕ) {z : ℕ} (H : z > 0) : (x + y * z) / z = x / z + y :=
by rw [nat.mul_comm, add_mul_div_left _ _ H]
protected theorem mul_div_cancel (m : ℕ) {n : ℕ} (H : n > 0) : m * n / n = m :=
let t := add_mul_div_right 0 m H in by rwa [nat.zero_add, nat.zero_div, nat.zero_add] at t
protected theorem mul_div_cancel_left (m : ℕ) {n : ℕ} (H : n > 0) : n * m / n = m :=
by rw [nat.mul_comm, nat.mul_div_cancel _ H]
protected theorem div_eq_of_eq_mul_left {m n k : ℕ} (H1 : n > 0) (H2 : m = k * n) :
m / n = k :=
by rw [H2, nat.mul_div_cancel _ H1]
protected theorem div_eq_of_eq_mul_right {m n k : ℕ} (H1 : n > 0) (H2 : m = n * k) :
m / n = k :=
by rw [H2, nat.mul_div_cancel_left _ H1]
protected theorem div_eq_of_lt_le {m n k : ℕ}
(lo : k * n ≤ m) (hi : m < succ k * n) :
m / n = k :=
have npos : n > 0, from (eq_zero_or_pos _).resolve_left $ λ hn,
by rw [hn, nat.mul_zero] at hi lo; exact absurd lo (not_le_of_gt hi),
le_antisymm
(le_of_lt_succ ((nat.div_lt_iff_lt_mul _ _ npos).2 hi))
((nat.le_div_iff_mul_le _ _ npos).2 lo)
theorem mul_sub_div (x n p : ℕ) (h₁ : x < n*p) : (n * p - succ x) / n = p - succ (x / n) :=
begin
have npos : n > 0 := (eq_zero_or_pos _).resolve_left (λ n0,
by rw [n0, 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₁),
succ_pred_eq_of_pos (nat.sub_pos_of_lt _)],
{ 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 } }
end
protected lemma mul_pos {a b : ℕ} (ha : a > 0) (hb : b > 0) : a * b > 0 :=
have h : 0 * b < a * b, from nat.mul_lt_mul_of_pos_right ha hb,
by rwa nat.zero_mul at h
protected theorem div_div_eq_div_mul (m n k : ℕ) : m / n / k = m / (n * k) :=
begin
cases eq_zero_or_pos k with k0 kpos, {rw [k0, nat.mul_zero, nat.div_zero, nat.div_zero]},
cases eq_zero_or_pos n with n0 npos, {rw [n0, nat.zero_mul, nat.div_zero, nat.zero_div]},
apply 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,
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,
refl }
end
protected theorem mul_div_mul {m : ℕ} (n k : ℕ) (H : m > 0) : m * n / (m * k) = n / k :=
by rw [← nat.div_div_eq_div_mul, nat.mul_div_cancel_left _ H]
/- dvd -/
@[simp]
protected theorem dvd_mul_right (a b : ℕ) : a ∣ a * b := ⟨b, rfl⟩
protected theorem dvd_trans {a b c : ℕ} (h₁ : a ∣ b) (h₂ : b ∣ c) : a ∣ c :=
match h₁, h₂ with
| ⟨d, (h₃ : b = a * d)⟩, ⟨e, (h₄ : c = b * e)⟩ :=
⟨d * e, show c = a * (d * e), by simp [h₃, h₄, nat.mul_assoc]⟩
end
protected theorem eq_zero_of_zero_dvd {a : ℕ} (h : 0 ∣ a) : a = 0 :=
exists.elim h (assume c, assume H' : a = 0 * c, eq.trans H' (nat.zero_mul c))
protected theorem dvd_add {a b c : ℕ} (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b + c :=
exists.elim h₁ (λ d hd, exists.elim h₂ (λ e he, ⟨d + e, by simp [nat.left_distrib, hd, he]⟩))
protected theorem dvd_add_iff_right {k m n : ℕ} (h : k ∣ m) : k ∣ n ↔ k ∣ m + n :=
⟨nat.dvd_add h, exists.elim h $ λd hd, match m, hd with
| ._, rfl := λh₂, exists.elim h₂ $ λe he, ⟨e - d,
by rw [nat.mul_sub_left_distrib, ← he, nat.add_sub_cancel_left]⟩
end⟩
protected theorem dvd_add_iff_left {k m n : ℕ} (h : k ∣ n) : k ∣ m ↔ k ∣ m + n :=
by rw nat.add_comm; exact nat.dvd_add_iff_right h
theorem dvd_sub {k m n : ℕ} (H : n ≤ m) (h₁ : k ∣ m) (h₂ : k ∣ n) : k ∣ m - n :=
(nat.dvd_add_iff_left h₂).2 $ by rw nat.sub_add_cancel H; exact h₁
theorem dvd_mod_iff {k m n : ℕ} (h : k ∣ n) : k ∣ m % n ↔ k ∣ m :=
let t := @nat.dvd_add_iff_left _ (m % n) _ (nat.dvd_trans h (nat.dvd_mul_right n (m / n))) in
by rwa mod_add_div at t
theorem le_of_dvd {m n : ℕ} (h : n > 0) : m ∣ n → m ≤ n :=
λ⟨k, e⟩, by {
revert h, rw e, refine k.cases_on _ _,
exact λhn, absurd hn (lt_irrefl _),
exact λk _, let t := mul_le_mul_left m (succ_pos k) in by rwa nat.mul_one at t }
theorem dvd_antisymm : Π {m n : ℕ}, m ∣ n → n ∣ m → m = n
| m 0 h₁ h₂ := nat.eq_zero_of_zero_dvd h₂
| 0 n h₁ h₂ := (nat.eq_zero_of_zero_dvd h₁).symm
| (succ m) (succ n) h₁ h₂ := le_antisymm (le_of_dvd (succ_pos _) h₁) (le_of_dvd (succ_pos _) h₂)
theorem pos_of_dvd_of_pos {m n : ℕ} (H1 : m ∣ n) (H2 : n > 0) : m > 0 :=
nat.pos_of_ne_zero $ λm0, by rw m0 at H1; rw nat.eq_zero_of_zero_dvd H1 at H2; exact lt_irrefl _ H2
theorem eq_one_of_dvd_one {n : ℕ} (H : n ∣ 1) : n = 1 :=
le_antisymm (le_of_dvd dec_trivial H) (pos_of_dvd_of_pos H dec_trivial)
theorem dvd_of_mod_eq_zero {m n : ℕ} (H : n % m = 0) : m ∣ n :=
⟨n / m, by { have t := (mod_add_div n m).symm, rwa [H, nat.zero_add] at t }⟩
theorem mod_eq_zero_of_dvd {m n : ℕ} (H : m ∣ n) : n % m = 0 :=
exists.elim H (λ z H1, by rw [H1, mul_mod_right])
theorem dvd_iff_mod_eq_zero (m n : ℕ) : m ∣ n ↔ n % m = 0 :=
⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩
instance decidable_dvd : @decidable_rel ℕ (∣) :=
λm n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm
protected theorem mul_div_cancel' {m n : ℕ} (H : n ∣ m) : n * (m / n) = m :=
let t := mod_add_div m n in by rwa [mod_eq_zero_of_dvd H, nat.zero_add] at t
protected theorem div_mul_cancel {m n : ℕ} (H : n ∣ m) : m / n * n = m :=
by rw [nat.mul_comm, nat.mul_div_cancel' H]
protected theorem mul_div_assoc (m : ℕ) {n k : ℕ} (H : k ∣ n) : m * n / k = m * (n / k) :=
or.elim (eq_zero_or_pos k)
(λh, by rw [h, nat.div_zero, nat.div_zero, nat.mul_zero])
(λh, have m * n / k = m * (n / k * k) / k, by rw nat.div_mul_cancel H,
by rw[this, ← nat.mul_assoc, nat.mul_div_cancel _ h])
theorem dvd_of_mul_dvd_mul_left {m n k : ℕ} (kpos : k > 0) (H : k * m ∣ k * n) : m ∣ n :=
exists.elim H (λl H1, by rw nat.mul_assoc at H1; exact ⟨_, eq_of_mul_eq_mul_left kpos H1⟩)
theorem dvd_of_mul_dvd_mul_right {m n k : ℕ} (kpos : k > 0) (H : m * k ∣ n * k) : m ∣ n :=
by rw [nat.mul_comm m k, nat.mul_comm n k] at H; exact dvd_of_mul_dvd_mul_left kpos H
/- --- -/
protected lemma mul_le_mul_of_nonneg_left {a b c : ℕ} (h₁ : a ≤ b) : c * a ≤ c * b :=
begin
by_cases hba : b ≤ a, { simp [le_antisymm hba h₁] },
by_cases hc0 : c ≤ 0, { simp [le_antisymm hc0 (zero_le c), nat.zero_mul] },
exact (le_not_le_of_lt (nat.mul_lt_mul_of_pos_left (lt_of_le_not_le h₁ hba) (lt_of_le_not_le (zero_le c) hc0))).left,
end
protected lemma mul_le_mul_of_nonneg_right {a b c : ℕ} (h₁ : a ≤ b) : a * c ≤ b * c :=
begin
by_cases hba : b ≤ a, { simp [le_antisymm hba h₁] },
by_cases hc0 : c ≤ 0, { simp [le_antisymm hc0 (zero_le c), nat.mul_zero] },
exact (le_not_le_of_lt (nat.mul_lt_mul_of_pos_right (lt_of_le_not_le h₁ hba) (lt_of_le_not_le (zero_le c) hc0))).left,
end
protected lemma mul_lt_mul {a b c d : ℕ} (hac : a < c) (hbd : b ≤ d) (pos_b : 0 < b) : a * b < c * d :=
calc
a * b < c * b : nat.mul_lt_mul_of_pos_right hac pos_b
... ≤ c * d : nat.mul_le_mul_of_nonneg_left hbd
protected lemma mul_lt_mul' {a b c d : ℕ} (h1 : a ≤ c) (h2 : b < d) (h3 : 0 < c) :
a * b < c * d :=
calc
a * b ≤ c * b : nat.mul_le_mul_of_nonneg_right h1
... < c * d : nat.mul_lt_mul_of_pos_left h2 h3
-- TODO: there are four variations, depending on which variables we assume to be nonneg
protected lemma mul_le_mul {a b c d : ℕ} (hac : a ≤ c) (hbd : b ≤ d) : a * b ≤ c * d :=
calc
a * b ≤ c * b : nat.mul_le_mul_of_nonneg_right hac
... ≤ c * d : nat.mul_le_mul_of_nonneg_left hbd
/- pow -/
@[simp] theorem pow_one (b : ℕ) : b^1 = b := by simp [pow_succ, nat.one_mul]
theorem pow_le_pow_of_le_left {x y : ℕ} (H : x ≤ y) : ∀ i : ℕ, x^i ≤ y^i
| 0 := le_refl _
| (succ i) := nat.mul_le_mul (pow_le_pow_of_le_left i) H
theorem pow_le_pow_of_le_right {x : ℕ} (H : x > 0) {i : ℕ} : ∀ {j}, i ≤ j → x^i ≤ x^j
| 0 h := by rw eq_zero_of_le_zero h; apply le_refl
| (succ j) h := (lt_or_eq_of_le h).elim
(λhl, by rw [pow_succ, ← nat.mul_one (x^i)]; exact
nat.mul_le_mul (pow_le_pow_of_le_right $ le_of_lt_succ hl) H)
(λe, by rw e; refl)
theorem pos_pow_of_pos {b : ℕ} (n : ℕ) (h : 0 < b) : 0 < b^n :=
pow_le_pow_of_le_right h (zero_le _)
theorem zero_pow {n : ℕ} (h : 0 < n) : 0^n = 0 :=
by rw [← succ_pred_eq_of_pos h, pow_succ, nat.mul_zero]
theorem pow_lt_pow_of_lt_left {x y : ℕ} (H : x < y) {i} (h : i > 0) : x^i < y^i :=
begin
cases i with i, { exact absurd h (not_lt_zero _) },
rw [pow_succ, pow_succ],
exact nat.mul_lt_mul' (pow_le_pow_of_le_left (le_of_lt H) _) H
(pos_pow_of_pos _ $ lt_of_le_of_lt (zero_le _) H)
end
theorem pow_lt_pow_of_lt_right {x : ℕ} (H : x > 1) {i j : ℕ} (h : i < j) : x^i < x^j :=
begin
have xpos := lt_of_succ_lt H,
refine lt_of_lt_of_le _ (pow_le_pow_of_le_right xpos h),
rw [← nat.mul_one (x^i), pow_succ],
exact nat.mul_lt_mul_of_pos_left H (pos_pow_of_pos _ xpos)
end
/- mod / div / pow -/
local attribute [simp] nat.mul_comm
theorem mod_pow_succ {b : ℕ} (b_pos : b > 0) (w m : ℕ)
: m % (b^succ w) = b * (m/b % b^w) + m % b :=
begin
apply nat.strong_induction_on m,
clear m,
intros p IH,
cases lt_or_ge p (b^succ w) with h₁ h₁,
-- base case: p < b^succ w
{ have h₂ : p / b < b^w,
{ rw [div_lt_iff_lt_mul p _ b_pos],
simp [pow_succ] at h₁,
simp [h₁] },
rw [mod_eq_of_lt h₁, mod_eq_of_lt h₂],
simp [mod_add_div, nat.add_comm] },
-- step: p ≥ b^succ w
{ -- Generate condiition for induction principal
have h₂ : p - b^succ w < p,
{ apply sub_lt_of_pos_le _ _ (pos_pow_of_pos _ b_pos) h₁ },
-- Apply induction
rw [mod_eq_sub_mod h₁, IH _ h₂],
-- Normalize goal and h1
simp [pow_succ],
simp [ge, pow_succ] at h₁,
-- Pull subtraction outside mod and div
rw [sub_mul_mod _ _ _ h₁, sub_mul_div _ _ _ h₁],
-- Cancel subtraction inside mod b^w
have p_b_ge : b^w ≤ p / b,
{ rw [le_div_iff_mul_le _ _ b_pos],
simp [h₁] },
rw [eq.symm (mod_eq_sub_mod p_b_ge)] }
end
lemma div_lt_self {n m : nat} : n > 0 → m > 1 → n / m < n :=
begin
intros h₁ h₂,
have m_pos : m > 0, { apply lt_trans _ h₂, comp_val },
suffices : 1 * n < m * n, {
rw [nat.one_mul, nat.mul_comm] at this,
exact iff.mpr (nat.div_lt_iff_lt_mul n n m_pos) this
},
exact nat.mul_lt_mul h₂ (le_refl _) h₁
end
end nat
|
d83e150baf749ec8677de3b86e4b9dad0829e6c3 | 8c9f90127b78cbeb5bb17fd6b5db1db2ffa3cbc4 | /two_definitions_of_prime_numbers.lean | d6e7a2104297fd75b66624cc7c1ae501c4918083 | [] | no_license | picrin/lean | 420f4d08bb3796b911d56d0938e4410e1da0e072 | 3d10c509c79704aa3a88ebfb24d08b30ce1137cc | refs/heads/master | 1,611,166,610,726 | 1,536,671,438,000 | 1,536,671,438,000 | 60,029,899 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,930 | lean | def is_divisible: nat → nat → Prop :=
λ n m : nat, ∃ k : nat, m * k = n
def is_prime1: nat → Prop :=
λ p, p > 1 ∧ ∀ (m : nat) (Pmdp : is_divisible p m), ((m = 1) ∨ (m = p))
def is_prime2: nat → Prop :=
λ p, p > 1 ∧ ∀ (k : nat), (∀ (b1 : k < p) (b2 : 1 < k), (¬ is_divisible p k))
def prime_equiv_left : ∀ (p : nat) (Pp: is_prime1 p), (is_prime2 p) :=
λ (p : nat) (Pp: is_prime1 p),
and.intro
(and.elim_left Pp)
(λ (k : nat) (b1 : k < p) (b2 : 1 < k),
λ (Pmdp : is_divisible p k),
(or.elim (and.elim_right Pp k Pmdp)) (λ P1 : k = 1, ne_of_lt b2 (eq.symm P1)) (λ P2 : k = p, ne_of_lt b1 P2))
def gt0or0 (a : nat) : a = 0 ∨ a > 0 :=
or.elim (classical.em (a = 0)) (λ H : a = 0, or.intro_left (a > 0) H) (λ H : a ≠ 0, or.intro_right (a = 0) (nat.pos_of_ne_zero H))
def nat.le_add_right_of_le: ∀ (n m k : nat) (n_le_m : n <= m), n <= m + k
| n m 0 n_le_m := n_le_m
| n m (k + 1) n_le_m := nat.le_succ_of_le (nat.le_add_right_of_le n m k n_le_m)
def le_succ_of_lt_right {a b : nat} : a < b → a + 1 <= b :=
λ H : a < b,
have S1: a + 1 < b + 1, from nat.add_lt_add_right H 1,
show a + 1 <= b, from nat.le_of_lt_succ S1
def le_mul_right_of_pos (a b : nat) (P : b ≠ 0) : a <= a * b :=
nat.rec_on a
(have zero_le_zero : 0 <= 0, from le_refl 0,
have zero_eq_b_mul_zero : 0 = b * 0, from rfl,
have zero_comm : b * 0 = 0 * b, from mul_comm b 0,
have zero_eq_zero_mul_b : 0 = 0 * b, from eq.trans zero_eq_b_mul_zero zero_comm,
eq.subst zero_eq_zero_mul_b zero_le_zero)
(λ j: nat, λ H : j <= j * b,
have S0 : j * b = b * j, from mul_comm j b,
have S1 : j <= b * j, from eq.subst S0 H,
have S2 : j + 1 <= b * j + 1, from nat.add_le_add_right S1 1,
have S8 : 0 <= b, from nat.zero_le b,
have S9 : 1 <= b, from or.elim (iff.elim_left le_iff_lt_or_eq S8) (λ H : 0 < b, le_succ_of_lt_right H) (λ H, false.elim $ P $ eq.symm H),
have S4 : b * (j + 1) = b * j + b, from rfl,
have S5 : b * j + 1 <= b * j + b, from nat.add_le_add_left S9 (b * j),
have S6 : b * j + 1 <= b * (j + 1), from eq.subst S4 S5,
have S7 : b * j + 1 <= (j + 1) * b, from eq.subst (mul_comm b (j + 1)) S6,
le_trans S2 S7)
def never_zero (a b c : nat) (H : b * a = c) (H1 : c ≠ 0): a ≠ 0 :=
λ (Pa0 : a = 0),
have Pbt0 : b * 0 = c, from eq.subst Pa0 H,
have Pb0 : b * 0 = 0, from mul_zero b,
have D1: c = 0, from eq.trans (eq.symm Pbt0) Pb0,
show false, from H1 D1
def divisor_leq (p : nat) (m : nat) (not_zero : p ≠ 0) (divisible : is_divisible p m) : m <= p :=
show m <= p, from (
exists.elim divisible (λ k : nat, λ m_split : m * k = p,
have k_not_zero: k ≠ 0, from never_zero k m p m_split not_zero,
have m_le : m <= m * k, from (le_mul_right_of_pos m k k_not_zero),
eq.subst m_split m_le)
)
def big_not_zero (a : nat) (P : 1 < a) : a ≠ 0 :=
λ Pp : a = 0, have olt0 : 1 < 0, from eq.subst Pp P,
(show 1 < 0 → false, from dec_trivial) olt0
def big_greater_than_one {m : nat} (A : m ≠ 0) (B : m ≠ 1) : 1 < m :=
have H : 0 <= m, from nat.zero_le m,
or.elim (iff.elim_left le_iff_lt_or_eq H) (
λ H : 0 < m, show 1 < m, from
have H : 1 <= m, from le_succ_of_lt_right H, or.elim (iff.elim_left le_iff_lt_or_eq H) (λ H, H) (λ H, false.elim (B (eq.symm H)))
) (λ H, false.elim (A (eq.symm H)))
def prime_equiv_right : ∀ (p : nat) (Pp : is_prime2 p), is_prime1 p :=
λ p : nat, λ Pp : is_prime2 p,
and.intro (and.elim_left Pp) (
have Ppr : ∀ (k : nat), ∀ (b1 : k < p) (b2 : 1 < k), (¬ is_divisible p k), from and.elim_right Pp,
λ (m : nat), λ (Pmdp : is_divisible p m), or.elim(classical.em (m = 1)) (λ Pme1 : m = 1, or.intro_left (m = p) Pme1) (λ Pmep : m ≠ 1, have Pmep : m = p, from (
have Pn0 : p ≠ 0, from big_not_zero p (and.elim_left Pp),
have mlep : m <= p, from divisor_leq p m (Pn0) Pmdp,
have X : m ≠ 0, from exists.elim (Pmdp) (λ (a : ℕ), λ D : m * a = p, λ H : m = 0, have A : 0 * a = p, from eq.subst H D, have I: 0 * a = 0, from zero_mul a, have R : 0 = p, from eq.subst I A, Pn0 $ eq.symm R),
have P1lp: 1 < m, from big_greater_than_one X Pmep,
have Pnmlp: ¬ m < p, from λ (Pmlp : m < p), Ppr m Pmlp P1lp Pmdp,
have bleh : m < p ∨ m = p, from iff.elim_left le_iff_lt_or_eq mlep,
or.elim bleh (λ mlp : m < p, false.elim (Pnmlp mlp)) (λ blah : m = p, blah)
), show m = 1 ∨ m = p, from or.intro_right (m = 1) Pmep
)
)
def prime_equiv (p : nat) : (is_prime1 p) ↔ (is_prime2 p) :=
iff.intro (prime_equiv_left p) (prime_equiv_right p) |
4931d0423e60f1265cbb891902d0a02a313266a8 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/data/list/big_operators.lean | 293952ebd1164abe29be9d8b45ddec7d358885b9 | [
"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 | 16,203 | 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, Floris van Doorn, Sébastien Gouëzel
-/
import data.list.basic
/-!
# Sums and products from lists
This file provides basic results about `list.prod` and `list.sum`, which calculate the product and
sum of elements of a list. These are defined in [`data.list.defs`](./data/list/defs).
-/
variables {α β γ : Type*}
namespace list
section monoid
variables [monoid α] {l l₁ l₂ : list α} {a : α}
@[simp, to_additive]
lemma prod_nil : ([] : list α).prod = 1 := rfl
@[to_additive]
lemma prod_singleton : [a].prod = a := one_mul a
@[simp, to_additive]
lemma prod_cons : (a :: l).prod = a * l.prod :=
calc (a :: l).prod = foldl (*) (a * 1) l : by simp only [list.prod, foldl_cons, one_mul, mul_one]
... = _ : foldl_assoc
@[simp, to_additive]
lemma prod_append : (l₁ ++ l₂).prod = l₁.prod * l₂.prod :=
calc (l₁ ++ l₂).prod = foldl (*) (foldl (*) 1 l₁ * 1) l₂ : by simp [list.prod]
... = l₁.prod * l₂.prod : foldl_assoc
@[to_additive]
lemma prod_concat : (l.concat a).prod = l.prod * a :=
by rw [concat_eq_append, prod_append, prod_cons, prod_nil, mul_one]
@[simp, to_additive]
lemma prod_join {l : list (list α)} : l.join.prod = (l.map list.prod).prod :=
by induction l; [refl, simp only [*, list.join, map, prod_append, prod_cons]]
/-- If zero is an element of a list `L`, then `list.prod L = 0`. If the domain is a nontrivial
monoid with zero with no divisors, then this implication becomes an `iff`, see
`list.prod_eq_zero_iff`. -/
lemma prod_eq_zero {M₀ : Type*} [monoid_with_zero M₀] {L : list M₀} (h : (0 : M₀) ∈ L) :
L.prod = 0 :=
begin
induction L with a L ihL,
{ exact absurd h (not_mem_nil _) },
{ rw prod_cons,
cases (mem_cons_iff _ _ _).1 h with ha hL,
exacts [mul_eq_zero_of_left ha.symm _, mul_eq_zero_of_right _ (ihL hL)] }
end
/-- Product of elements of a list `L` equals zero if and only if `0 ∈ L`. See also
`list.prod_eq_zero` for an implication that needs weaker typeclass assumptions. -/
@[simp] lemma prod_eq_zero_iff {M₀ : Type*} [monoid_with_zero M₀] [nontrivial M₀]
[no_zero_divisors M₀] {L : list M₀} :
L.prod = 0 ↔ (0 : M₀) ∈ L :=
begin
induction L with a L ihL,
{ simp },
{ rw [prod_cons, mul_eq_zero, ihL, mem_cons_iff, eq_comm] }
end
lemma prod_ne_zero {M₀ : Type*} [monoid_with_zero M₀] [nontrivial M₀] [no_zero_divisors M₀]
{L : list M₀} (hL : (0 : M₀) ∉ L) : L.prod ≠ 0 :=
mt prod_eq_zero_iff.1 hL
@[to_additive]
lemma prod_eq_foldr : l.prod = foldr (*) 1 l :=
list.rec_on l rfl $ λ a l ihl, by rw [prod_cons, foldr_cons, ihl]
@[to_additive]
lemma prod_hom_rel {α β γ : Type*} [monoid β] [monoid γ] (l : list α) {r : β → γ → Prop}
{f : α → β} {g : α → γ} (h₁ : r 1 1) (h₂ : ∀⦃a b c⦄, r b c → r (f a * b) (g a * c)) :
r (l.map f).prod (l.map g).prod :=
list.rec_on l h₁ (λ a l hl, by simp only [map_cons, prod_cons, h₂ hl])
@[to_additive]
lemma prod_hom [monoid β] (l : list α) (f : α →* β) :
(l.map f).prod = f l.prod :=
by { simp only [prod, foldl_map, f.map_one.symm],
exact l.foldl_hom _ _ _ 1 f.map_mul }
@[to_additive]
lemma prod_is_unit [monoid β] : Π {L : list β} (u : ∀ m ∈ L, is_unit m), is_unit L.prod
| [] _ := by simp
| (h :: t) u :=
begin
simp only [list.prod_cons],
exact is_unit.mul (u h (mem_cons_self h t)) (prod_is_unit (λ m mt, u m (mem_cons_of_mem h mt)))
end
@[simp, to_additive]
lemma prod_take_mul_prod_drop :
∀ (L : list α) (i : ℕ), (L.take i).prod * (L.drop i).prod = L.prod
| [] i := by simp
| L 0 := by simp
| (h :: t) (n+1) := by { dsimp, rw [prod_cons, prod_cons, mul_assoc, prod_take_mul_prod_drop] }
@[simp, to_additive]
lemma prod_take_succ :
∀ (L : list α) (i : ℕ) (p), (L.take (i + 1)).prod = (L.take i).prod * L.nth_le i p
| [] i p := by cases p
| (h :: t) 0 _ := by simp
| (h :: t) (n+1) _ := by { dsimp, rw [prod_cons, prod_cons, prod_take_succ, mul_assoc] }
/-- A list with product not one must have positive length. -/
@[to_additive]
lemma length_pos_of_prod_ne_one (L : list α) (h : L.prod ≠ 1) : 0 < L.length :=
by { cases L, { simp at h, cases h }, { simp } }
@[to_additive]
lemma prod_update_nth : ∀ (L : list α) (n : ℕ) (a : α),
(L.update_nth n a).prod =
(L.take n).prod * (if n < L.length then a else 1) * (L.drop (n + 1)).prod
| (x :: xs) 0 a := by simp [update_nth]
| (x :: xs) (i+1) a := by simp [update_nth, prod_update_nth xs i a, mul_assoc]
| [] _ _ := by simp [update_nth, (nat.zero_le _).not_lt]
open opposite
lemma _root_.opposite.op_list_prod : ∀ (l : list α), op (l.prod) = (l.map op).reverse.prod
| [] := rfl
| (x :: xs) := by rw [list.prod_cons, list.map_cons, list.reverse_cons', list.prod_concat, op_mul,
_root_.opposite.op_list_prod]
lemma _root_.opposite.unop_list_prod : ∀ (l : list αᵒᵖ), (l.prod).unop = (l.map unop).reverse.prod
| [] := rfl
| (x :: xs) := by rw [list.prod_cons, list.map_cons, list.reverse_cons', list.prod_concat, unop_mul,
_root_.opposite.unop_list_prod]
end monoid
section group
variables [group α]
/-- This is the `list.prod` version of `mul_inv_rev` -/
@[to_additive "This is the `list.sum` version of `add_neg_rev`"]
lemma prod_inv_reverse : ∀ (L : list α), L.prod⁻¹ = (L.map (λ x, x⁻¹)).reverse.prod
| [] := by simp
| (x :: xs) := by simp [prod_inv_reverse xs]
/-- A non-commutative variant of `list.prod_reverse` -/
@[to_additive "A non-commutative variant of `list.sum_reverse`"]
lemma prod_reverse_noncomm : ∀ (L : list α), L.reverse.prod = (L.map (λ x, x⁻¹)).prod⁻¹ :=
by simp [prod_inv_reverse]
/-- Counterpart to `list.prod_take_succ` when we have an inverse operation -/
@[simp, to_additive /-"Counterpart to `list.sum_take_succ` when we have an negation operation"-/]
lemma prod_drop_succ :
∀ (L : list α) (i : ℕ) (p), (L.drop (i + 1)).prod = (L.nth_le i p)⁻¹ * (L.drop i).prod
| [] i p := false.elim (nat.not_lt_zero _ p)
| (x :: xs) 0 p := by simp
| (x :: xs) (i + 1) p := prod_drop_succ xs i _
end group
section comm_group
variables [comm_group α]
/-- This is the `list.prod` version of `mul_inv` -/
@[to_additive "This is the `list.sum` version of `add_neg`"]
lemma prod_inv : ∀ (L : list α), L.prod⁻¹ = (L.map (λ x, x⁻¹)).prod
| [] := by simp
| (x :: xs) := by simp [mul_comm, prod_inv xs]
/-- Alternative version of `list.prod_update_nth` when the list is over a group -/
@[to_additive /-"Alternative version of `list.sum_update_nth` when the list is over a group"-/]
lemma prod_update_nth' (L : list α) (n : ℕ) (a : α) :
(L.update_nth n a).prod =
L.prod * (if hn : n < L.length then (L.nth_le n hn)⁻¹ * a else 1) :=
begin
refine (prod_update_nth L n a).trans _,
split_ifs with hn hn,
{ rw [mul_comm _ a, mul_assoc a, prod_drop_succ L n hn, mul_comm _ (drop n L).prod,
← mul_assoc (take n L).prod, prod_take_mul_prod_drop, mul_comm a, mul_assoc] },
{ simp only [take_all_of_le (le_of_not_lt hn), prod_nil, mul_one,
drop_eq_nil_of_le ((le_of_not_lt hn).trans n.le_succ)] }
end
end comm_group
lemma eq_of_sum_take_eq [add_left_cancel_monoid α] {L L' : list α} (h : L.length = L'.length)
(h' : ∀ i ≤ L.length, (L.take i).sum = (L'.take i).sum) : L = L' :=
begin
apply ext_le h (λ i h₁ h₂, _),
have : (L.take (i + 1)).sum = (L'.take (i + 1)).sum := h' _ (nat.succ_le_of_lt h₁),
rw [sum_take_succ L i h₁, sum_take_succ L' i h₂, h' i (le_of_lt h₁)] at this,
exact add_left_cancel this
end
lemma monotone_sum_take [canonically_ordered_add_monoid α] (L : list α) :
monotone (λ i, (L.take i).sum) :=
begin
apply monotone_nat_of_le_succ (λ n, _),
by_cases h : n < L.length,
{ rw sum_take_succ _ _ h,
exact le_self_add },
{ push_neg at h,
simp [take_all_of_le h, take_all_of_le (le_trans h (nat.le_succ _))] }
end
@[to_additive sum_nonneg]
lemma one_le_prod_of_one_le [ordered_comm_monoid α] {l : list α} (hl₁ : ∀ x ∈ l, (1 : α) ≤ x) :
1 ≤ l.prod :=
begin
induction l with hd tl ih,
{ simp },
rw prod_cons,
exact one_le_mul (hl₁ hd (mem_cons_self hd tl)) (ih (λ x h, hl₁ x (mem_cons_of_mem hd h))),
end
@[to_additive]
lemma single_le_prod [ordered_comm_monoid α] {l : list α} (hl₁ : ∀ x ∈ l, (1 : α) ≤ x) :
∀ x ∈ l, x ≤ l.prod :=
begin
induction l,
{ simp },
simp_rw [prod_cons, forall_mem_cons] at ⊢ hl₁,
split,
{ exact le_mul_of_one_le_right' (one_le_prod_of_one_le hl₁.2) },
{ exact λ x H, le_mul_of_one_le_of_le hl₁.1 (l_ih hl₁.right x H) },
end
@[to_additive all_zero_of_le_zero_le_of_sum_eq_zero]
lemma all_one_of_le_one_le_of_prod_eq_one [ordered_comm_monoid α]
{l : list α} (hl₁ : ∀ x ∈ l, (1 : α) ≤ x) (hl₂ : l.prod = 1) {x : α} (hx : x ∈ l) :
x = 1 :=
le_antisymm (hl₂ ▸ single_le_prod hl₁ _ hx) (hl₁ x hx)
lemma sum_eq_zero_iff [canonically_ordered_add_monoid α] (l : list α) :
l.sum = 0 ↔ ∀ x ∈ l, x = (0 : α) :=
⟨all_zero_of_le_zero_le_of_sum_eq_zero (λ _ _, zero_le _),
begin
induction l,
{ simp },
{ intro h,
rw [sum_cons, add_eq_zero_iff],
rw forall_mem_cons at h,
exact ⟨h.1, l_ih h.2⟩ },
end⟩
/-- If all elements in a list are bounded below by `1`, then the length of the list is bounded
by the sum of the elements. -/
lemma length_le_sum_of_one_le (L : list ℕ) (h : ∀ i ∈ L, 1 ≤ i) : L.length ≤ L.sum :=
begin
induction L with j L IH h, { simp },
rw [sum_cons, length, add_comm],
exact add_le_add (h _ (set.mem_insert _ _)) (IH (λ i hi, h i (set.mem_union_right _ hi)))
end
/-- A list with positive sum must have positive length. -/
-- This is an easy consequence of `length_pos_of_sum_ne_zero`, but often useful in applications.
lemma length_pos_of_sum_pos [ordered_cancel_add_comm_monoid α] (L : list α) (h : 0 < L.sum) :
0 < L.length :=
length_pos_of_sum_ne_zero L h.ne'
-- TODO: develop theory of tropical rings
lemma sum_le_foldr_max [add_monoid α] [add_monoid β] [linear_order β] (f : α → β)
(h0 : f 0 ≤ 0) (hadd : ∀ x y, f (x + y) ≤ max (f x) (f y)) (l : list α) :
f l.sum ≤ (l.map f).foldr max 0 :=
begin
induction l with hd tl IH,
{ simpa using h0 },
simp only [list.sum_cons, list.foldr_map, le_max_iff, list.foldr] at IH ⊢,
cases le_or_lt (f tl.sum) (f hd),
{ left,
refine (hadd _ _).trans _,
simpa using h },
{ right,
refine (hadd _ _).trans _,
simp only [IH, max_le_iff, and_true, h.le.trans IH] }
end
@[simp, to_additive]
lemma prod_erase [decidable_eq α] [comm_monoid α] {a} :
∀ {l : list α}, a ∈ l → a * (l.erase a).prod = l.prod
| (b :: l) h :=
begin
obtain rfl | ⟨ne, h⟩ := decidable.list.eq_or_ne_mem_of_mem h,
{ simp only [list.erase, if_pos, prod_cons] },
{ simp only [list.erase, if_neg (mt eq.symm ne), prod_cons, prod_erase h, mul_left_comm a b] }
end
lemma dvd_prod [comm_monoid α] {a} {l : list α} (ha : a ∈ l) : a ∣ l.prod :=
let ⟨s, t, h⟩ := mem_split ha in
by { rw [h, prod_append, prod_cons, mul_left_comm], exact dvd_mul_right _ _ }
@[simp] lemma sum_const_nat (m n : ℕ) : sum (list.repeat m n) = m * n :=
by induction n; [refl, simp only [*, repeat_succ, sum_cons, nat.mul_succ, add_comm]]
lemma dvd_sum [comm_semiring α] {a} {l : list α} (h : ∀ x ∈ l, a ∣ x) : a ∣ l.sum :=
begin
induction l with x l ih,
{ exact dvd_zero _ },
{ rw [list.sum_cons],
exact dvd_add (h _ (mem_cons_self _ _)) (ih (λ x hx, h x (mem_cons_of_mem _ hx))) }
end
lemma exists_lt_of_sum_lt [linear_ordered_cancel_add_comm_monoid β] {l : list α} (f g : α → β)
(h : (l.map f).sum < (l.map g).sum) :
∃ x ∈ l, f x < g x :=
begin
induction l with x l,
{ exact (lt_irrefl _ h).elim },
obtain h' | h' := lt_or_le (f x) (g x),
{ exact ⟨x, mem_cons_self _ _, h'⟩ },
simp at h,
obtain ⟨y, h1y, h2y⟩ := l_ih (lt_of_add_lt_add_left (h.trans_le $ add_le_add_right h' _)),
exact ⟨y, mem_cons_of_mem x h1y, h2y⟩,
end
lemma exists_le_of_sum_le [linear_ordered_cancel_add_comm_monoid β] {l : list α} (hl : l ≠ [])
(f g : α → β) (h : (l.map f).sum ≤ (l.map g).sum) :
∃ x ∈ l, f x ≤ g x :=
begin
cases l with x l,
{ contradiction },
obtain h' | h' := le_or_lt (f x) (g x),
{ exact ⟨x, mem_cons_self _ _, h'⟩ },
obtain ⟨y, h1y, h2y⟩ := exists_lt_of_sum_lt f g _,
exact ⟨y, mem_cons_of_mem x h1y, le_of_lt h2y⟩, simp at h,
exact lt_of_add_lt_add_left (h.trans_lt $ add_lt_add_right h' _),
end
/-- We'd like to state this as `L.head * L.tail.prod = L.prod`, but because `L.head` relies on an
inhabited instance to return a garbage value on the empty list, this is not possible.
Instead, we write the statement in terms of `(L.nth 0).get_or_else 1` and state the lemma for `ℕ` as
-/
@[to_additive]
lemma nth_zero_mul_tail_prod [monoid α] (l : list α) :
(l.nth 0).get_or_else 1 * l.tail.prod = l.prod :=
by cases l; simp
/-- Same as `nth_zero_mul_tail_prod`, but avoiding the `list.head` garbage complication by requiring
the list to be nonempty. -/
@[to_additive]
lemma head_mul_tail_prod_of_ne_nil [monoid α] [inhabited α] (l : list α) (h : l ≠ []) :
l.head * l.tail.prod = l.prod :=
by cases l; [contradiction, simp]
/-- The product of a list of positive natural numbers is positive,
and likewise for any nontrivial ordered semiring. -/
lemma prod_pos [ordered_semiring α] [nontrivial α] (l : list α) (h : ∀ a ∈ l, (0 : α) < a) :
0 < l.prod :=
begin
induction l with a l ih,
{ simp },
{ rw prod_cons,
exact mul_pos (h _ $ mem_cons_self _ _) (ih $ λ a ha, h a $ mem_cons_of_mem _ ha) }
end
/-!
Several lemmas about sum/head/tail for `list ℕ`.
These are hard to generalize well, as they rely on the fact that `default ℕ = 0`.
If desired, we could add a class stating that `default α = 0`.
-/
/-- This relies on `default ℕ = 0`. -/
lemma head_add_tail_sum (L : list ℕ) : L.head + L.tail.sum = L.sum :=
by { cases L, { simp, refl }, { simp } }
/-- This relies on `default ℕ = 0`. -/
lemma head_le_sum (L : list ℕ) : L.head ≤ L.sum := nat.le.intro (head_add_tail_sum L)
/-- This relies on `default ℕ = 0`. -/
lemma tail_sum (L : list ℕ) : L.tail.sum = L.sum - L.head :=
by rw [← head_add_tail_sum L, add_comm, add_tsub_cancel_right]
section alternating
variables {G : Type*} [comm_group G]
@[simp, to_additive] lemma alternating_prod_nil : alternating_prod ([] : list G) = 1 := rfl
@[simp, to_additive] lemma alternating_prod_singleton (g : G) : alternating_prod [g] = g := rfl
@[simp, to_additive alternating_sum_cons_cons']
lemma alternating_prod_cons_cons (g h : G) (l : list G) :
alternating_prod (g :: h :: l) = g * h⁻¹ * alternating_prod l := rfl
lemma alternating_sum_cons_cons {G : Type*} [add_comm_group G] (g h : G) (l : list G) :
alternating_sum (g :: h :: l) = g - h + alternating_sum l :=
by rw [sub_eq_add_neg, alternating_sum]
end alternating
@[to_additive]
lemma _root_.monoid_hom.map_list_prod [monoid α] [monoid β] (f : α →* β) (l : list α) :
f l.prod = (l.map f).prod :=
(l.prod_hom f).symm
open opposite
/-- A morphism into the opposite monoid acts on the product by acting on the reversed elements -/
lemma _root_.monoid_hom.unop_map_list_prod [monoid α] [monoid β] (f : α →* βᵒᵖ) (l : list α) :
unop (f l.prod) = (l.map (unop ∘ f)).reverse.prod :=
begin
rw [f.map_list_prod l, opposite.unop_list_prod, list.map_map],
end
@[to_additive]
lemma prod_map_hom [monoid β] [monoid γ] (L : list α) (f : α → β) (g : β →* γ) :
(L.map (g ∘ f)).prod = g ((L.map f).prod) :=
by {rw g.map_list_prod, exact congr_arg _ (map_map _ _ _).symm}
lemma sum_map_mul_left [semiring α] (L : list β) (f : β → α) (r : α) :
(L.map (λ b, r * f b)).sum = r * (L.map f).sum :=
sum_map_hom L f $ add_monoid_hom.mul_left r
lemma sum_map_mul_right [semiring α] (L : list β) (f : β → α) (r : α) :
(L.map (λ b, f b * r)).sum = (L.map f).sum * r :=
sum_map_hom L f $ add_monoid_hom.mul_right r
end list
|
bfbffb0b50ea8b53f2b506d9f0ca347e7380dddc | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/analysis/convex/combination.lean | 15443b1b1fa4f9648a44e57c88ce90734d8f6242 | [
"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 | 23,039 | lean | /-
Copyright (c) 2019 Yury Kudriashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudriashov
-/
import algebra.big_operators.order
import analysis.convex.hull
import linear_algebra.affine_space.basis
/-!
# Convex combinations
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines convex combinations of points in a vector space.
## Main declarations
* `finset.center_mass`: Center of mass of a finite family of points.
## Implementation notes
We divide by the sum of the weights in the definition of `finset.center_mass` because of the way
mathematical arguments go: one doesn't change weights, but merely adds some. This also makes a few
lemmas unconditional on the sum of the weights being `1`.
-/
open set function
open_locale big_operators classical pointwise
universes u u'
variables {R E F ι ι' α : Type*} [linear_ordered_field R] [add_comm_group E] [add_comm_group F]
[linear_ordered_add_comm_group α] [module R E] [module R F] [module R α] [ordered_smul R α]
{s : set E}
/-- Center of mass of a finite collection of points with prescribed weights.
Note that we require neither `0 ≤ w i` nor `∑ w = 1`. -/
def finset.center_mass (t : finset ι) (w : ι → R) (z : ι → E) : E :=
(∑ i in t, w i)⁻¹ • (∑ i in t, w i • z i)
variables (i j : ι) (c : R) (t : finset ι) (w : ι → R) (z : ι → E)
open finset
lemma finset.center_mass_empty : (∅ : finset ι).center_mass w z = 0 :=
by simp only [center_mass, sum_empty, smul_zero]
lemma finset.center_mass_pair (hne : i ≠ j) :
({i, j} : finset ι).center_mass w z = (w i / (w i + w j)) • z i + (w j / (w i + w j)) • z j :=
by simp only [center_mass, sum_pair hne, smul_add, (mul_smul _ _ _).symm, div_eq_inv_mul]
variable {w}
lemma finset.center_mass_insert (ha : i ∉ t) (hw : ∑ j in t, w j ≠ 0) :
(insert i t).center_mass w z = (w i / (w i + ∑ j in t, w j)) • z i +
((∑ j in t, w j) / (w i + ∑ j in t, w j)) • t.center_mass w z :=
begin
simp only [center_mass, sum_insert ha, smul_add, (mul_smul _ _ _).symm, ← div_eq_inv_mul],
congr' 2,
rw [div_mul_eq_mul_div, mul_inv_cancel hw, one_div]
end
lemma finset.center_mass_singleton (hw : w i ≠ 0) : ({i} : finset ι).center_mass w z = z i :=
by rw [center_mass, sum_singleton, sum_singleton, ← mul_smul, inv_mul_cancel hw, one_smul]
lemma finset.center_mass_eq_of_sum_1 (hw : ∑ i in t, w i = 1) :
t.center_mass w z = ∑ i in t, w i • z i :=
by simp only [finset.center_mass, hw, inv_one, one_smul]
lemma finset.center_mass_smul : t.center_mass w (λ i, c • z i) = c • t.center_mass w z :=
by simp only [finset.center_mass, finset.smul_sum, (mul_smul _ _ _).symm, mul_comm c, mul_assoc]
/-- A convex combination of two centers of mass is a center of mass as well. This version
deals with two different index types. -/
lemma finset.center_mass_segment'
(s : finset ι) (t : finset ι') (ws : ι → R) (zs : ι → E) (wt : ι' → R) (zt : ι' → E)
(hws : ∑ i in s, ws i = 1) (hwt : ∑ i in t, wt i = 1) (a b : R) (hab : a + b = 1) :
a • s.center_mass ws zs + b • t.center_mass wt zt =
(s.disj_sum t).center_mass (sum.elim (λ i, a * ws i) (λ j, b * wt j)) (sum.elim zs zt) :=
begin
rw [s.center_mass_eq_of_sum_1 _ hws, t.center_mass_eq_of_sum_1 _ hwt,
smul_sum, smul_sum, ← finset.sum_sum_elim, finset.center_mass_eq_of_sum_1],
{ congr' with ⟨⟩; simp only [sum.elim_inl, sum.elim_inr, mul_smul] },
{ rw [sum_sum_elim, ← mul_sum, ← mul_sum, hws, hwt, mul_one, mul_one, hab] }
end
/-- A convex combination of two centers of mass is a center of mass as well. This version
works if two centers of mass share the set of original points. -/
lemma finset.center_mass_segment
(s : finset ι) (w₁ w₂ : ι → R) (z : ι → E)
(hw₁ : ∑ i in s, w₁ i = 1) (hw₂ : ∑ i in s, w₂ i = 1) (a b : R) (hab : a + b = 1) :
a • s.center_mass w₁ z + b • s.center_mass w₂ z =
s.center_mass (λ i, a * w₁ i + b * w₂ i) z :=
have hw : ∑ i in s, (a * w₁ i + b * w₂ i) = 1,
by simp only [mul_sum.symm, sum_add_distrib, mul_one, *],
by simp only [finset.center_mass_eq_of_sum_1, smul_sum, sum_add_distrib, add_smul, mul_smul, *]
lemma finset.center_mass_ite_eq (hi : i ∈ t) :
t.center_mass (λ j, if (i = j) then (1 : R) else 0) z = z i :=
begin
rw [finset.center_mass_eq_of_sum_1],
transitivity ∑ j in t, if (i = j) then z i else 0,
{ congr' with i, split_ifs, exacts [h ▸ one_smul _ _, zero_smul _ _] },
{ rw [sum_ite_eq, if_pos hi] },
{ rw [sum_ite_eq, if_pos hi] }
end
variables {t w}
lemma finset.center_mass_subset {t' : finset ι} (ht : t ⊆ t')
(h : ∀ i ∈ t', i ∉ t → w i = 0) :
t.center_mass w z = t'.center_mass w z :=
begin
rw [center_mass, sum_subset ht h, smul_sum, center_mass, smul_sum],
apply sum_subset ht,
assume i hit' hit,
rw [h i hit' hit, zero_smul, smul_zero]
end
lemma finset.center_mass_filter_ne_zero :
(t.filter (λ i, w i ≠ 0)).center_mass w z = t.center_mass w z :=
finset.center_mass_subset z (filter_subset _ _) $ λ i hit hit',
by simpa only [hit, mem_filter, true_and, ne.def, not_not] using hit'
namespace finset
lemma center_mass_le_sup {s : finset ι} {f : ι → α} {w : ι → R}
(hw₀ : ∀ i ∈ s, 0 ≤ w i) (hw₁ : 0 < ∑ i in s, w i) :
s.center_mass w f ≤ s.sup' (nonempty_of_ne_empty $ by { rintro rfl, simpa using hw₁ }) f :=
begin
rw [center_mass, inv_smul_le_iff hw₁, sum_smul],
exact sum_le_sum (λ i hi, smul_le_smul_of_nonneg (le_sup' _ hi) $ hw₀ i hi),
apply_instance,
end
lemma inf_le_center_mass {s : finset ι} {f : ι → α} {w : ι → R}
(hw₀ : ∀ i ∈ s, 0 ≤ w i) (hw₁ : 0 < ∑ i in s, w i) :
s.inf' (nonempty_of_ne_empty $ by { rintro rfl, simpa using hw₁ }) f ≤ s.center_mass w f :=
@center_mass_le_sup R _ αᵒᵈ _ _ _ _ _ _ _ hw₀ hw₁
end finset
variable {z}
/-- The center of mass of a finite subset of a convex set belongs to the set
provided that all weights are non-negative, and the total weight is positive. -/
lemma convex.center_mass_mem (hs : convex R s) :
(∀ i ∈ t, 0 ≤ w i) → (0 < ∑ i in t, w i) → (∀ i ∈ t, z i ∈ s) → t.center_mass w z ∈ s :=
begin
induction t using finset.induction with i t hi ht, { simp [lt_irrefl] },
intros h₀ hpos hmem,
have zi : z i ∈ s, from hmem _ (mem_insert_self _ _),
have hs₀ : ∀ j ∈ t, 0 ≤ w j, from λ j hj, h₀ j $ mem_insert_of_mem hj,
rw [sum_insert hi] at hpos,
by_cases hsum_t : ∑ j in t, w j = 0,
{ have ws : ∀ j ∈ t, w j = 0, from (sum_eq_zero_iff_of_nonneg hs₀).1 hsum_t,
have wz : ∑ j in t, w j • z j = 0, from sum_eq_zero (λ i hi, by simp [ws i hi]),
simp only [center_mass, sum_insert hi, wz, hsum_t, add_zero],
simp only [hsum_t, add_zero] at hpos,
rw [← mul_smul, inv_mul_cancel (ne_of_gt hpos), one_smul],
exact zi },
{ rw [finset.center_mass_insert _ _ _ hi hsum_t],
refine convex_iff_div.1 hs zi (ht hs₀ _ _) _ (sum_nonneg hs₀) hpos,
{ exact lt_of_le_of_ne (sum_nonneg hs₀) (ne.symm hsum_t) },
{ intros j hj, exact hmem j (mem_insert_of_mem hj) },
{ exact h₀ _ (mem_insert_self _ _) } }
end
lemma convex.sum_mem (hs : convex R s) (h₀ : ∀ i ∈ t, 0 ≤ w i) (h₁ : ∑ i in t, w i = 1)
(hz : ∀ i ∈ t, z i ∈ s) :
∑ i in t, w i • z i ∈ s :=
by simpa only [h₁, center_mass, inv_one, one_smul] using
hs.center_mass_mem h₀ (h₁.symm ▸ zero_lt_one) hz
/-- A version of `convex.sum_mem` for `finsum`s. If `s` is a convex set, `w : ι → R` is a family of
nonnegative weights with sum one and `z : ι → E` is a family of elements of a module over `R` such
that `z i ∈ s` whenever `w i ≠ 0``, then the sum `∑ᶠ i, w i • z i` belongs to `s`. See also
`partition_of_unity.finsum_smul_mem_convex`. -/
lemma convex.finsum_mem {ι : Sort*} {w : ι → R} {z : ι → E} {s : set E}
(hs : convex R s) (h₀ : ∀ i, 0 ≤ w i) (h₁ : ∑ᶠ i, w i = 1) (hz : ∀ i, w i ≠ 0 → z i ∈ s) :
∑ᶠ i, w i • z i ∈ s :=
begin
have hfin_w : (support (w ∘ plift.down)).finite,
{ by_contra H,
rw [finsum, dif_neg H] at h₁,
exact zero_ne_one h₁ },
have hsub : support ((λ i, w i • z i) ∘ plift.down) ⊆ hfin_w.to_finset,
from (support_smul_subset_left _ _).trans hfin_w.coe_to_finset.ge,
rw [finsum_eq_sum_plift_of_support_subset hsub],
refine hs.sum_mem (λ _ _, h₀ _) _ (λ i hi, hz _ _),
{ rwa [finsum, dif_pos hfin_w] at h₁ },
{ rwa [hfin_w.mem_to_finset] at hi }
end
lemma convex_iff_sum_mem :
convex R s ↔
(∀ (t : finset E) (w : E → R),
(∀ i ∈ t, 0 ≤ w i) → ∑ i in t, w i = 1 → (∀ x ∈ t, x ∈ s) → ∑ x in t, w x • x ∈ s ) :=
begin
refine ⟨λ hs t w hw₀ hw₁ hts, hs.sum_mem hw₀ hw₁ hts, _⟩,
intros h x hx y hy a b ha hb hab,
by_cases h_cases: x = y,
{ rw [h_cases, ←add_smul, hab, one_smul], exact hy },
{ convert h {x, y} (λ z, if z = y then b else a) _ _ _,
{ simp only [sum_pair h_cases, if_neg h_cases, if_pos rfl] },
{ simp_intros i hi,
cases hi; subst i; simp [ha, hb, if_neg h_cases] },
{ simp only [sum_pair h_cases, if_neg h_cases, if_pos rfl, hab] },
{ simp_intros i hi,
cases hi; subst i; simp [hx, hy, if_neg h_cases] } }
end
lemma finset.center_mass_mem_convex_hull (t : finset ι) {w : ι → R} (hw₀ : ∀ i ∈ t, 0 ≤ w i)
(hws : 0 < ∑ i in t, w i) {z : ι → E} (hz : ∀ i ∈ t, z i ∈ s) :
t.center_mass w z ∈ convex_hull R s :=
(convex_convex_hull R s).center_mass_mem hw₀ hws (λ i hi, subset_convex_hull R s $ hz i hi)
/-- A refinement of `finset.center_mass_mem_convex_hull` when the indexed family is a `finset` of
the space. -/
lemma finset.center_mass_id_mem_convex_hull (t : finset E) {w : E → R} (hw₀ : ∀ i ∈ t, 0 ≤ w i)
(hws : 0 < ∑ i in t, w i) :
t.center_mass w id ∈ convex_hull R (t : set E) :=
t.center_mass_mem_convex_hull hw₀ hws (λ i, mem_coe.2)
lemma affine_combination_eq_center_mass {ι : Type*} {t : finset ι} {p : ι → E} {w : ι → R}
(hw₂ : ∑ i in t, w i = 1) :
t.affine_combination R p w = center_mass t w p :=
begin
rw [affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one _ w _ hw₂ (0 : E),
finset.weighted_vsub_of_point_apply, vadd_eq_add, add_zero, t.center_mass_eq_of_sum_1 _ hw₂],
simp_rw [vsub_eq_sub, sub_zero],
end
lemma affine_combination_mem_convex_hull
{s : finset ι} {v : ι → E} {w : ι → R} (hw₀ : ∀ i ∈ s, 0 ≤ w i) (hw₁ : s.sum w = 1) :
s.affine_combination R v w ∈ convex_hull R (range v) :=
begin
rw affine_combination_eq_center_mass hw₁,
apply s.center_mass_mem_convex_hull hw₀,
{ simp [hw₁], },
{ simp, },
end
/-- The centroid can be regarded as a center of mass. -/
@[simp] lemma finset.centroid_eq_center_mass (s : finset ι) (hs : s.nonempty) (p : ι → E) :
s.centroid R p = s.center_mass (s.centroid_weights R) p :=
affine_combination_eq_center_mass (s.sum_centroid_weights_eq_one_of_nonempty R hs)
lemma finset.centroid_mem_convex_hull (s : finset E) (hs : s.nonempty) :
s.centroid R id ∈ convex_hull R (s : set E) :=
begin
rw s.centroid_eq_center_mass hs,
apply s.center_mass_id_mem_convex_hull,
{ simp only [inv_nonneg, implies_true_iff, nat.cast_nonneg, finset.centroid_weights_apply], },
{ have hs_card : (s.card : R) ≠ 0, { simp [finset.nonempty_iff_ne_empty.mp hs] },
simp only [hs_card, finset.sum_const, nsmul_eq_mul, mul_inv_cancel, ne.def, not_false_iff,
finset.centroid_weights_apply, zero_lt_one] }
end
lemma convex_hull_range_eq_exists_affine_combination (v : ι → E) :
convex_hull R (range v) = { x | ∃ (s : finset ι) (w : ι → R)
(hw₀ : ∀ i ∈ s, 0 ≤ w i) (hw₁ : s.sum w = 1), s.affine_combination R v w = x } :=
begin
refine subset.antisymm (convex_hull_min _ _) _,
{ intros x hx,
obtain ⟨i, hi⟩ := set.mem_range.mp hx,
refine ⟨{i}, function.const ι (1 : R), by simp, by simp, by simp [hi]⟩, },
{ rintro x ⟨s, w, hw₀, hw₁, rfl⟩ y ⟨s', w', hw₀', hw₁', rfl⟩ a b ha hb hab,
let W : ι → R := λ i, (if i ∈ s then a * w i else 0) + (if i ∈ s' then b * w' i else 0),
have hW₁ : (s ∪ s').sum W = 1,
{ rw [sum_add_distrib, ← sum_subset (subset_union_left s s'),
← sum_subset (subset_union_right s s'), sum_ite_of_true _ _ (λ i hi, hi),
sum_ite_of_true _ _ (λ i hi, hi), ← mul_sum, ← mul_sum, hw₁, hw₁', ← add_mul, hab, mul_one];
intros i hi hi';
simp [hi'], },
refine ⟨s ∪ s', W, _, hW₁, _⟩,
{ rintros i -,
by_cases hi : i ∈ s;
by_cases hi' : i ∈ s';
simp [hi, hi', add_nonneg, mul_nonneg ha (hw₀ i _), mul_nonneg hb (hw₀' i _)], },
{ simp_rw [affine_combination_eq_linear_combination (s ∪ s') v _ hW₁,
affine_combination_eq_linear_combination s v w hw₁,
affine_combination_eq_linear_combination s' v w' hw₁', add_smul, sum_add_distrib],
rw [← sum_subset (subset_union_left s s'), ← sum_subset (subset_union_right s s')],
{ simp only [ite_smul, sum_ite_of_true _ _ (λ i hi, hi), mul_smul, ← smul_sum], },
{ intros i hi hi', simp [hi'], },
{ intros i hi hi', simp [hi'], }, }, },
{ rintros x ⟨s, w, hw₀, hw₁, rfl⟩,
exact affine_combination_mem_convex_hull hw₀ hw₁, },
end
/-- Convex hull of `s` is equal to the set of all centers of masses of `finset`s `t`, `z '' t ⊆ s`.
This version allows finsets in any type in any universe. -/
lemma convex_hull_eq (s : set E) :
convex_hull R s = {x : E | ∃ (ι : Type u') (t : finset ι) (w : ι → R) (z : ι → E)
(hw₀ : ∀ i ∈ t, 0 ≤ w i) (hw₁ : ∑ i in t, w i = 1) (hz : ∀ i ∈ t, z i ∈ s),
t.center_mass w z = x} :=
begin
refine subset.antisymm (convex_hull_min _ _) _,
{ intros x hx,
use [punit, {punit.star}, λ _, 1, λ _, x, λ _ _, zero_le_one,
finset.sum_singleton, λ _ _, hx],
simp only [finset.center_mass, finset.sum_singleton, inv_one, one_smul] },
{ rintros x ⟨ι, sx, wx, zx, hwx₀, hwx₁, hzx, rfl⟩ y ⟨ι', sy, wy, zy, hwy₀, hwy₁, hzy, rfl⟩
a b ha hb hab,
rw [finset.center_mass_segment' _ _ _ _ _ _ hwx₁ hwy₁ _ _ hab],
refine ⟨_, _, _, _, _, _, _, rfl⟩,
{ rintros i hi,
rw [finset.mem_disj_sum] at hi,
rcases hi with ⟨j, hj, rfl⟩|⟨j, hj, rfl⟩;
simp only [sum.elim_inl, sum.elim_inr];
apply_rules [mul_nonneg, hwx₀, hwy₀] },
{ simp [finset.sum_sum_elim, finset.mul_sum.symm, *], },
{ intros i hi,
rw [finset.mem_disj_sum] at hi,
rcases hi with ⟨j, hj, rfl⟩|⟨j, hj, rfl⟩; apply_rules [hzx, hzy] } },
{ rintros _ ⟨ι, t, w, z, hw₀, hw₁, hz, rfl⟩,
exact t.center_mass_mem_convex_hull hw₀ (hw₁.symm ▸ zero_lt_one) hz }
end
lemma finset.convex_hull_eq (s : finset E) :
convex_hull R ↑s = {x : E | ∃ (w : E → R) (hw₀ : ∀ y ∈ s, 0 ≤ w y) (hw₁ : ∑ y in s, w y = 1),
s.center_mass w id = x} :=
begin
refine subset.antisymm (convex_hull_min _ _) _,
{ intros x hx,
rw [finset.mem_coe] at hx,
refine ⟨_, _, _, finset.center_mass_ite_eq _ _ _ hx⟩,
{ intros, split_ifs, exacts [zero_le_one, le_refl 0] },
{ rw [finset.sum_ite_eq, if_pos hx] } },
{ rintro x ⟨wx, hwx₀, hwx₁, rfl⟩ y ⟨wy, hwy₀, hwy₁, rfl⟩ a b ha hb hab,
rw [finset.center_mass_segment _ _ _ _ hwx₁ hwy₁ _ _ hab],
refine ⟨_, _, _, rfl⟩,
{ rintros i hi,
apply_rules [add_nonneg, mul_nonneg, hwx₀, hwy₀], },
{ simp only [finset.sum_add_distrib, finset.mul_sum.symm, mul_one, *] } },
{ rintros _ ⟨w, hw₀, hw₁, rfl⟩,
exact s.center_mass_mem_convex_hull (λ x hx, hw₀ _ hx)
(hw₁.symm ▸ zero_lt_one) (λ x hx, hx) }
end
lemma finset.mem_convex_hull {s : finset E} {x : E} :
x ∈ convex_hull R (s : set E) ↔
∃ (w : E → R) (hw₀ : ∀ y ∈ s, 0 ≤ w y) (hw₁ : ∑ y in s, w y = 1), s.center_mass w id = x :=
by rw [finset.convex_hull_eq, set.mem_set_of_eq]
lemma set.finite.convex_hull_eq {s : set E} (hs : s.finite) :
convex_hull R s = {x : E | ∃ (w : E → R) (hw₀ : ∀ y ∈ s, 0 ≤ w y)
(hw₁ : ∑ y in hs.to_finset, w y = 1), hs.to_finset.center_mass w id = x} :=
by simpa only [set.finite.coe_to_finset, set.finite.mem_to_finset, exists_prop]
using hs.to_finset.convex_hull_eq
/-- A weak version of Carathéodory's theorem. -/
lemma convex_hull_eq_union_convex_hull_finite_subsets (s : set E) :
convex_hull R s = ⋃ (t : finset E) (w : ↑t ⊆ s), convex_hull R ↑t :=
begin
refine subset.antisymm _ _,
{ rw convex_hull_eq,
rintros x ⟨ι, t, w, z, hw₀, hw₁, hz, rfl⟩,
simp only [mem_Union],
refine ⟨t.image z, _, _⟩,
{ rw [coe_image, set.image_subset_iff],
exact hz },
{ apply t.center_mass_mem_convex_hull hw₀,
{ simp only [hw₁, zero_lt_one] },
{ exact λ i hi, finset.mem_coe.2 (finset.mem_image_of_mem _ hi) } } },
{ exact Union_subset (λ i, Union_subset convex_hull_mono), },
end
lemma mk_mem_convex_hull_prod {t : set F} {x : E} {y : F} (hx : x ∈ convex_hull R s)
(hy : y ∈ convex_hull R t) :
(x, y) ∈ convex_hull R (s ×ˢ t) :=
begin
rw convex_hull_eq at ⊢ hx hy,
obtain ⟨ι, a, w, S, hw, hw', hS, hSp⟩ := hx,
obtain ⟨κ, b, v, T, hv, hv', hT, hTp⟩ := hy,
have h_sum : ∑ (i : ι × κ) in a ×ˢ b, w i.fst * v i.snd = 1,
{ rw [finset.sum_product, ← hw'],
congr,
ext i,
have : ∑ (y : κ) in b, w i * v y = ∑ (y : κ) in b, v y * w i,
{ congr, ext, simp [mul_comm] },
rw [this, ← finset.sum_mul, hv'],
simp },
refine ⟨ι × κ, a ×ˢ b, λ p, (w p.1) * (v p.2), λ p, (S p.1, T p.2),
λ p hp, _, h_sum, λ p hp, _, _⟩,
{ rw mem_product at hp,
exact mul_nonneg (hw p.1 hp.1) (hv p.2 hp.2) },
{ rw mem_product at hp,
exact ⟨hS p.1 hp.1, hT p.2 hp.2⟩ },
ext,
{ rw [←hSp, finset.center_mass_eq_of_sum_1 _ _ hw', finset.center_mass_eq_of_sum_1 _ _ h_sum],
simp_rw [prod.fst_sum, prod.smul_mk],
rw finset.sum_product,
congr,
ext i,
have : ∑ (j : κ) in b, (w i * v j) • S i = ∑ (j : κ) in b, v j • w i • S i,
{ congr, ext, rw [mul_smul, smul_comm] },
rw [this, ←finset.sum_smul, hv', one_smul] },
{ rw [←hTp, finset.center_mass_eq_of_sum_1 _ _ hv', finset.center_mass_eq_of_sum_1 _ _ h_sum],
simp_rw [prod.snd_sum, prod.smul_mk],
rw [finset.sum_product, finset.sum_comm],
congr,
ext j,
simp_rw mul_smul,
rw [←finset.sum_smul, hw', one_smul] }
end
@[simp] lemma convex_hull_prod (s : set E) (t : set F) :
convex_hull R (s ×ˢ t) = convex_hull R s ×ˢ convex_hull R t :=
subset.antisymm (convex_hull_min (prod_mono (subset_convex_hull _ _) $ subset_convex_hull _ _) $
(convex_convex_hull _ _).prod $ convex_convex_hull _ _) $
prod_subset_iff.2 $ λ x hx y, mk_mem_convex_hull_prod hx
lemma convex_hull_add (s t : set E) : convex_hull R (s + t) = convex_hull R s + convex_hull R t :=
by simp_rw [←image2_add, ←image_prod, is_linear_map.is_linear_map_add.convex_hull_image,
convex_hull_prod]
variables (R E)
/-- `convex_hull` is an additive monoid morphism under pointwise addition. -/
@[simps]
def convex_hull_add_monoid_hom : set E →+ set E :=
{ to_fun := convex_hull R,
map_add' := convex_hull_add,
map_zero' := convex_hull_zero }
variables {R E}
lemma convex_hull_sub (s t : set E) : convex_hull R (s - t) = convex_hull R s - convex_hull R t :=
by simp_rw [sub_eq_add_neg, convex_hull_add, convex_hull_neg]
lemma convex_hull_list_sum (l : list (set E)) : convex_hull R l.sum = (l.map $ convex_hull R).sum :=
map_list_sum (convex_hull_add_monoid_hom R E) l
lemma convex_hull_multiset_sum (s : multiset (set E)) :
convex_hull R s.sum = (s.map $ convex_hull R).sum :=
map_multiset_sum (convex_hull_add_monoid_hom R E) s
lemma convex_hull_sum {ι} (s : finset ι) (t : ι → set E) :
convex_hull R (∑ i in s, t i) = ∑ i in s, convex_hull R (t i):=
map_sum (convex_hull_add_monoid_hom R E) _ _
/-! ### `std_simplex` -/
variables (ι) [fintype ι] {f : ι → R}
/-- `std_simplex 𝕜 ι` is the convex hull of the canonical basis in `ι → 𝕜`. -/
lemma convex_hull_basis_eq_std_simplex :
convex_hull R (range $ λ(i j:ι), if i = j then (1:R) else 0) = std_simplex R ι :=
begin
refine subset.antisymm (convex_hull_min _ (convex_std_simplex R ι)) _,
{ rintros _ ⟨i, rfl⟩,
exact ite_eq_mem_std_simplex R i },
{ rintros w ⟨hw₀, hw₁⟩,
rw [pi_eq_sum_univ w, ← finset.univ.center_mass_eq_of_sum_1 _ hw₁],
exact finset.univ.center_mass_mem_convex_hull (λ i hi, hw₀ i)
(hw₁.symm ▸ zero_lt_one) (λ i hi, mem_range_self i) }
end
variable {ι}
/-- The convex hull of a finite set is the image of the standard simplex in `s → ℝ`
under the linear map sending each function `w` to `∑ x in s, w x • x`.
Since we have no sums over finite sets, we use sum over `@finset.univ _ hs.fintype`.
The map is defined in terms of operations on `(s → ℝ) →ₗ[ℝ] ℝ` so that later we will not need
to prove that this map is linear. -/
lemma set.finite.convex_hull_eq_image {s : set E} (hs : s.finite) :
convex_hull R s = by haveI := hs.fintype; exact
(⇑(∑ x : s, (@linear_map.proj R s _ (λ i, R) _ _ x).smul_right x.1)) '' (std_simplex R s) :=
begin
rw [← convex_hull_basis_eq_std_simplex, ← linear_map.convex_hull_image, ← set.range_comp, (∘)],
apply congr_arg,
convert subtype.range_coe.symm,
ext x,
simp [linear_map.sum_apply, ite_smul, finset.filter_eq]
end
/-- All values of a function `f ∈ std_simplex 𝕜 ι` belong to `[0, 1]`. -/
lemma mem_Icc_of_mem_std_simplex (hf : f ∈ std_simplex R ι) (x) :
f x ∈ Icc (0 : R) 1 :=
⟨hf.1 x, hf.2 ▸ finset.single_le_sum (λ y hy, hf.1 y) (finset.mem_univ x)⟩
/-- The convex hull of an affine basis is the intersection of the half-spaces defined by the
corresponding barycentric coordinates. -/
lemma affine_basis.convex_hull_eq_nonneg_coord {ι : Type*} (b : affine_basis ι R E) :
convex_hull R (range b) = {x | ∀ i, 0 ≤ b.coord i x} :=
begin
rw convex_hull_range_eq_exists_affine_combination,
ext x,
refine ⟨_, λ hx, _⟩,
{ rintros ⟨s, w, hw₀, hw₁, rfl⟩ i,
by_cases hi : i ∈ s,
{ rw b.coord_apply_combination_of_mem hi hw₁,
exact hw₀ i hi, },
{ rw b.coord_apply_combination_of_not_mem hi hw₁, }, },
{ have hx' : x ∈ affine_span R (range b),
{ rw b.tot, exact affine_subspace.mem_top R E x, },
obtain ⟨s, w, hw₁, rfl⟩ := (mem_affine_span_iff_eq_affine_combination R E).mp hx',
refine ⟨s, w, _, hw₁, rfl⟩,
intros i hi,
specialize hx i,
rw b.coord_apply_combination_of_mem hi hw₁ at hx,
exact hx, },
end
|
bdaf043e61de10f8ba36b8aa91a14c48fed462da | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/order/iterate.lean | 69a9d6be42f9afbb0102401893d80ea9aa62261a | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,090 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Yury G. Kudryashov
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.order.basic
import Mathlib.logic.function.iterate
import Mathlib.data.nat.basic
import Mathlib.PostPort
universes u_1
namespace Mathlib
/-!
# Inequalities on iterates
In this file we prove some inequalities comparing `f^[n] x` and `g^[n] x` where `f` and `g` are
two self-maps that commute with each other.
Current selection of inequalities is motivated by formalization of the rotation number of
a circle homeomorphism.
-/
namespace monotone
theorem seq_le_seq {α : Type u_1} [preorder α] {f : α → α} {x : ℕ → α} {y : ℕ → α} (hf : monotone f) (n : ℕ) (h₀ : x 0 ≤ y 0) (hx : ∀ (k : ℕ), k < n → x (k + 1) ≤ f (x k)) (hy : ∀ (k : ℕ), k < n → f (y k) ≤ y (k + 1)) : x n ≤ y n := sorry
theorem seq_pos_lt_seq_of_lt_of_le {α : Type u_1} [preorder α] {f : α → α} {x : ℕ → α} {y : ℕ → α} (hf : monotone f) {n : ℕ} (hn : 0 < n) (h₀ : x 0 ≤ y 0) (hx : ∀ (k : ℕ), k < n → x (k + 1) < f (x k)) (hy : ∀ (k : ℕ), k < n → f (y k) ≤ y (k + 1)) : x n < y n := sorry
theorem seq_pos_lt_seq_of_le_of_lt {α : Type u_1} [preorder α] {f : α → α} {x : ℕ → α} {y : ℕ → α} (hf : monotone f) {n : ℕ} (hn : 0 < n) (h₀ : x 0 ≤ y 0) (hx : ∀ (k : ℕ), k < n → x (k + 1) ≤ f (x k)) (hy : ∀ (k : ℕ), k < n → f (y k) < y (k + 1)) : x n < y n :=
seq_pos_lt_seq_of_lt_of_le (monotone.order_dual hf) hn h₀ hy hx
theorem seq_lt_seq_of_lt_of_le {α : Type u_1} [preorder α] {f : α → α} {x : ℕ → α} {y : ℕ → α} (hf : monotone f) (n : ℕ) (h₀ : x 0 < y 0) (hx : ∀ (k : ℕ), k < n → x (k + 1) < f (x k)) (hy : ∀ (k : ℕ), k < n → f (y k) ≤ y (k + 1)) : x n < y n := sorry
theorem seq_lt_seq_of_le_of_lt {α : Type u_1} [preorder α] {f : α → α} {x : ℕ → α} {y : ℕ → α} (hf : monotone f) (n : ℕ) (h₀ : x 0 < y 0) (hx : ∀ (k : ℕ), k < n → x (k + 1) ≤ f (x k)) (hy : ∀ (k : ℕ), k < n → f (y k) < y (k + 1)) : x n < y n :=
seq_lt_seq_of_lt_of_le (monotone.order_dual hf) n h₀ hy hx
end monotone
namespace function
namespace commute
theorem iterate_le_of_map_le {α : Type u_1} [preorder α] {f : α → α} {g : α → α} (h : commute f g) (hf : monotone f) (hg : monotone g) {x : α} (hx : f x ≤ g x) (n : ℕ) : nat.iterate f n x ≤ nat.iterate g n x := sorry
theorem iterate_pos_lt_of_map_lt {α : Type u_1} [preorder α] {f : α → α} {g : α → α} (h : commute f g) (hf : monotone f) (hg : strict_mono g) {x : α} (hx : f x < g x) {n : ℕ} (hn : 0 < n) : nat.iterate f n x < nat.iterate g n x := sorry
theorem iterate_pos_lt_of_map_lt' {α : Type u_1} [preorder α] {f : α → α} {g : α → α} (h : commute f g) (hf : strict_mono f) (hg : monotone g) {x : α} (hx : f x < g x) {n : ℕ} (hn : 0 < n) : nat.iterate f n x < nat.iterate g n x :=
iterate_pos_lt_of_map_lt (symm h) (monotone.order_dual hg) (strict_mono.order_dual hf) hx hn
theorem iterate_pos_lt_iff_map_lt {α : Type u_1} [linear_order α] {f : α → α} {g : α → α} (h : commute f g) (hf : monotone f) (hg : strict_mono g) {x : α} {n : ℕ} (hn : 0 < n) : nat.iterate f n x < nat.iterate g n x ↔ f x < g x := sorry
theorem iterate_pos_lt_iff_map_lt' {α : Type u_1} [linear_order α] {f : α → α} {g : α → α} (h : commute f g) (hf : strict_mono f) (hg : monotone g) {x : α} {n : ℕ} (hn : 0 < n) : nat.iterate f n x < nat.iterate g n x ↔ f x < g x :=
iterate_pos_lt_iff_map_lt (symm h) (monotone.order_dual hg) (strict_mono.order_dual hf) hn
theorem iterate_pos_le_iff_map_le {α : Type u_1} [linear_order α] {f : α → α} {g : α → α} (h : commute f g) (hf : monotone f) (hg : strict_mono g) {x : α} {n : ℕ} (hn : 0 < n) : nat.iterate f n x ≤ nat.iterate g n x ↔ f x ≤ g x := sorry
theorem iterate_pos_le_iff_map_le' {α : Type u_1} [linear_order α] {f : α → α} {g : α → α} (h : commute f g) (hf : strict_mono f) (hg : monotone g) {x : α} {n : ℕ} (hn : 0 < n) : nat.iterate f n x ≤ nat.iterate g n x ↔ f x ≤ g x := sorry
theorem iterate_pos_eq_iff_map_eq {α : Type u_1} [linear_order α] {f : α → α} {g : α → α} (h : commute f g) (hf : monotone f) (hg : strict_mono g) {x : α} {n : ℕ} (hn : 0 < n) : nat.iterate f n x = nat.iterate g n x ↔ f x = g x := sorry
end commute
end function
namespace monotone
/-- If `f ≤ g` and `f` is monotone, then `f^[n] ≤ g^[n]`. -/
theorem iterate_le_of_le {α : Type u_1} [preorder α] {f : α → α} {g : α → α} (hf : monotone f) (h : f ≤ g) (n : ℕ) : nat.iterate f n ≤ nat.iterate g n := sorry
/-- If `f ≤ g` and `f` is monotone, then `f^[n] ≤ g^[n]`. -/
theorem iterate_ge_of_ge {α : Type u_1} [preorder α] {f : α → α} {g : α → α} (hg : monotone g) (h : f ≤ g) (n : ℕ) : nat.iterate f n ≤ nat.iterate g n :=
iterate_le_of_le (monotone.order_dual hg) h n
|
6883f96ccb37bc4d6271322f784dfd6c023f4dd0 | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/group_theory/perm/cycle_type.lean | a8467566c273b5df9412c527eefb2249ae41c068 | [
"Apache-2.0"
] | permissive | ayush1801/mathlib | 78949b9f789f488148142221606bf15c02b960d2 | ce164e28f262acbb3de6281b3b03660a9f744e3c | refs/heads/master | 1,692,886,907,941 | 1,635,270,866,000 | 1,635,270,866,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 26,329 | lean | /-
Copyright (c) 2020 Thomas Browning. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Thomas Browning
-/
import algebra.gcd_monoid.multiset
import combinatorics.partition
import group_theory.perm.cycles
import ring_theory.int.basic
import tactic.linarith
/-!
# Cycle Types
In this file we define the cycle type of a permutation.
## Main definitions
- `σ.cycle_type` where `σ` is a permutation of a `fintype`
- `σ.partition` where `σ` is a permutation of a `fintype`
## Main results
- `sum_cycle_type` : The sum of `σ.cycle_type` equals `σ.support.card`
- `lcm_cycle_type` : The lcm of `σ.cycle_type` equals `order_of σ`
- `is_conj_iff_cycle_type_eq` : Two permutations are conjugate if and only if they have the same
cycle type.
* `exists_prime_order_of_dvd_card`: For every prime `p` dividing the order of a finite group `G`
there exists an element of order `p` in `G`. This is known as Cauchy`s theorem.
-/
namespace equiv.perm
open equiv list multiset
variables {α : Type*} [fintype α]
section cycle_type
variables [decidable_eq α]
/-- The cycle type of a permutation -/
def cycle_type (σ : perm α) : multiset ℕ :=
σ.cycle_factors_finset.1.map (finset.card ∘ support)
lemma cycle_type_def (σ : perm α) :
σ.cycle_type = σ.cycle_factors_finset.1.map (finset.card ∘ support) := rfl
lemma cycle_type_eq' {σ : perm α} (s : finset (perm α))
(h1 : ∀ f : perm α, f ∈ s → f.is_cycle) (h2 : ∀ (a ∈ s) (b ∈ s), a ≠ b → disjoint a b)
(h0 : s.noncomm_prod id
(λ a ha b hb, (em (a = b)).by_cases (λ h, h ▸ commute.refl a)
(set.pairwise_on.mono' (λ _ _, disjoint.commute) h2 a ha b hb)) = σ) :
σ.cycle_type = s.1.map (finset.card ∘ support) :=
begin
rw cycle_type_def,
congr,
rw cycle_factors_finset_eq_finset,
exact ⟨h1, h2, h0⟩
end
lemma cycle_type_eq {σ : perm α} (l : list (perm α)) (h0 : l.prod = σ)
(h1 : ∀ σ : perm α, σ ∈ l → σ.is_cycle) (h2 : l.pairwise disjoint) :
σ.cycle_type = l.map (finset.card ∘ support) :=
begin
have hl : l.nodup := nodup_of_pairwise_disjoint_cycles h1 h2,
rw cycle_type_eq' l.to_finset,
{ simp [list.erase_dup_eq_self.mpr hl] },
{ simpa using h1 },
{ simpa [hl] using h0 },
{ simpa [list.erase_dup_eq_self.mpr hl] using list.forall_of_pairwise disjoint.symmetric h2 }
end
lemma cycle_type_one : (1 : perm α).cycle_type = 0 :=
cycle_type_eq [] rfl (λ _, false.elim) pairwise.nil
lemma cycle_type_eq_zero {σ : perm α} : σ.cycle_type = 0 ↔ σ = 1 :=
by simp [cycle_type_def, cycle_factors_finset_eq_empty_iff]
lemma card_cycle_type_eq_zero {σ : perm α} : σ.cycle_type.card = 0 ↔ σ = 1 :=
by rw [card_eq_zero, cycle_type_eq_zero]
lemma two_le_of_mem_cycle_type {σ : perm α} {n : ℕ} (h : n ∈ σ.cycle_type) : 2 ≤ n :=
begin
simp only [cycle_type_def, ←finset.mem_def, function.comp_app, multiset.mem_map,
mem_cycle_factors_finset_iff] at h,
obtain ⟨_, ⟨hc, -⟩, rfl⟩ := h,
exact hc.two_le_card_support
end
lemma one_lt_of_mem_cycle_type {σ : perm α} {n : ℕ} (h : n ∈ σ.cycle_type) : 1 < n :=
two_le_of_mem_cycle_type h
lemma is_cycle.cycle_type {σ : perm α} (hσ : is_cycle σ) : σ.cycle_type = [σ.support.card] :=
cycle_type_eq [σ] (mul_one σ) (λ τ hτ, (congr_arg is_cycle (list.mem_singleton.mp hτ)).mpr hσ)
(pairwise_singleton disjoint σ)
lemma card_cycle_type_eq_one {σ : perm α} : σ.cycle_type.card = 1 ↔ σ.is_cycle :=
begin
rw card_eq_one,
simp_rw [cycle_type_def, multiset.map_eq_singleton, ←finset.singleton_val,
finset.val_inj, cycle_factors_finset_eq_singleton_iff],
split,
{ rintro ⟨_, _, ⟨h, -⟩, -⟩,
exact h },
{ intro h,
use [σ.support.card, σ],
simp [h] }
end
lemma disjoint.cycle_type {σ τ : perm α} (h : disjoint σ τ) :
(σ * τ).cycle_type = σ.cycle_type + τ.cycle_type :=
begin
rw [cycle_type_def, cycle_type_def, cycle_type_def, h.cycle_factors_finset_mul_eq_union,
←map_add, finset.union_val, multiset.add_eq_union_iff_disjoint.mpr _],
rw [←finset.disjoint_val],
exact h.disjoint_cycle_factors_finset
end
lemma cycle_type_inv (σ : perm α) : σ⁻¹.cycle_type = σ.cycle_type :=
cycle_induction_on (λ τ : perm α, τ⁻¹.cycle_type = τ.cycle_type) σ rfl
(λ σ hσ, by rw [hσ.cycle_type, hσ.inv.cycle_type, support_inv])
(λ σ τ hστ hc hσ hτ, by rw [mul_inv_rev, hστ.cycle_type, ←hσ, ←hτ, add_comm,
disjoint.cycle_type (λ x, or.imp (λ h : τ x = x, inv_eq_iff_eq.mpr h.symm)
(λ h : σ x = x, inv_eq_iff_eq.mpr h.symm) (hστ x).symm)])
lemma cycle_type_conj {σ τ : perm α} : (τ * σ * τ⁻¹).cycle_type = σ.cycle_type :=
begin
revert τ,
apply cycle_induction_on _ σ,
{ intro,
simp },
{ intros σ hσ τ,
rw [hσ.cycle_type, hσ.is_cycle_conj.cycle_type, card_support_conj] },
{ intros σ τ hd hc hσ hτ π,
rw [← conj_mul, hd.cycle_type, disjoint.cycle_type, hσ, hτ],
intro a,
apply (hd (π⁻¹ a)).imp _ _;
{ intro h, rw [perm.mul_apply, perm.mul_apply, h, apply_inv_self] } }
end
lemma sum_cycle_type (σ : perm α) : σ.cycle_type.sum = σ.support.card :=
cycle_induction_on (λ τ : perm α, τ.cycle_type.sum = τ.support.card) σ
(by rw [cycle_type_one, sum_zero, support_one, finset.card_empty])
(λ σ hσ, by rw [hσ.cycle_type, coe_sum, list.sum_singleton])
(λ σ τ hστ hc hσ hτ, by rw [hστ.cycle_type, sum_add, hσ, hτ, hστ.card_support_mul])
lemma sign_of_cycle_type (σ : perm α) :
sign σ = (σ.cycle_type.map (λ n, -(-1 : units ℤ) ^ n)).prod :=
cycle_induction_on (λ τ : perm α, sign τ = (τ.cycle_type.map (λ n, -(-1 : units ℤ) ^ n)).prod) σ
(by rw [sign_one, cycle_type_one, map_zero, prod_zero])
(λ σ hσ, by rw [hσ.sign, hσ.cycle_type, coe_map, coe_prod,
list.map_singleton, list.prod_singleton])
(λ σ τ hστ hc hσ hτ, by rw [sign_mul, hσ, hτ, hστ.cycle_type, map_add, prod_add])
lemma lcm_cycle_type (σ : perm α) : σ.cycle_type.lcm = order_of σ :=
cycle_induction_on (λ τ : perm α, τ.cycle_type.lcm = order_of τ) σ
(by rw [cycle_type_one, lcm_zero, order_of_one])
(λ σ hσ, by rw [hσ.cycle_type, ←singleton_coe, ←singleton_eq_cons, lcm_singleton,
order_of_is_cycle hσ, normalize_eq])
(λ σ τ hστ hc hσ hτ, by rw [hστ.cycle_type, lcm_add, lcm_eq_nat_lcm, hστ.order_of, hσ, hτ])
lemma dvd_of_mem_cycle_type {σ : perm α} {n : ℕ} (h : n ∈ σ.cycle_type) : n ∣ order_of σ :=
begin
rw ← lcm_cycle_type,
exact dvd_lcm h,
end
lemma order_of_cycle_of_dvd_order_of (f : perm α) (x : α) :
order_of (cycle_of f x) ∣ order_of f :=
begin
by_cases hx : f x = x,
{ rw ←cycle_of_eq_one_iff at hx,
simp [hx] },
{ refine dvd_of_mem_cycle_type _,
rw [cycle_type, multiset.mem_map],
refine ⟨f.cycle_of x, _, _⟩,
{ rwa [←finset.mem_def, cycle_of_mem_cycle_factors_finset_iff, mem_support] },
{ simp [order_of_is_cycle (is_cycle_cycle_of _ hx)] } }
end
lemma two_dvd_card_support {σ : perm α} (hσ : σ ^ 2 = 1) : 2 ∣ σ.support.card :=
(congr_arg (has_dvd.dvd 2) σ.sum_cycle_type).mp
(multiset.dvd_sum (λ n hn, by rw le_antisymm (nat.le_of_dvd zero_lt_two $
(dvd_of_mem_cycle_type hn).trans $ order_of_dvd_of_pow_eq_one hσ) (two_le_of_mem_cycle_type hn)))
lemma cycle_type_prime_order {σ : perm α} (hσ : (order_of σ).prime) :
∃ n : ℕ, σ.cycle_type = repeat (order_of σ) (n + 1) :=
begin
rw eq_repeat_of_mem (λ n hn, or_iff_not_imp_left.mp
(hσ.2 n (dvd_of_mem_cycle_type hn)) (ne_of_gt (one_lt_of_mem_cycle_type hn))),
use σ.cycle_type.card - 1,
rw tsub_add_cancel_of_le,
rw [nat.succ_le_iff, pos_iff_ne_zero, ne, card_cycle_type_eq_zero],
rintro rfl,
rw order_of_one at hσ,
exact hσ.ne_one rfl,
end
lemma is_cycle_of_prime_order {σ : perm α} (h1 : (order_of σ).prime)
(h2 : σ.support.card < 2 * (order_of σ)) : σ.is_cycle :=
begin
obtain ⟨n, hn⟩ := cycle_type_prime_order h1,
rw [←σ.sum_cycle_type, hn, multiset.sum_repeat, nsmul_eq_mul, nat.cast_id, mul_lt_mul_right
(order_of_pos σ), nat.succ_lt_succ_iff, nat.lt_succ_iff, nat.le_zero_iff] at h2,
rw [←card_cycle_type_eq_one, hn, card_repeat, h2],
end
lemma cycle_type_le_of_mem_cycle_factors_finset {f g : perm α}
(hf : f ∈ g.cycle_factors_finset) :
f.cycle_type ≤ g.cycle_type :=
begin
rw mem_cycle_factors_finset_iff at hf,
rw [cycle_type_def, cycle_type_def, hf.left.cycle_factors_finset_eq_singleton],
refine map_le_map _,
simpa [←finset.mem_def, mem_cycle_factors_finset_iff] using hf
end
lemma cycle_type_mul_mem_cycle_factors_finset_eq_sub {f g : perm α}
(hf : f ∈ g.cycle_factors_finset) :
(g * f⁻¹).cycle_type = g.cycle_type - f.cycle_type :=
begin
suffices : (g * f⁻¹).cycle_type + f.cycle_type = g.cycle_type - f.cycle_type + f.cycle_type,
{ rw tsub_add_cancel_of_le (cycle_type_le_of_mem_cycle_factors_finset hf) at this,
simp [←this] },
simp [←(disjoint_mul_inv_of_mem_cycle_factors_finset hf).cycle_type,
tsub_add_cancel_of_le (cycle_type_le_of_mem_cycle_factors_finset hf)]
end
theorem is_conj_of_cycle_type_eq {σ τ : perm α} (h : cycle_type σ = cycle_type τ) : is_conj σ τ :=
begin
revert τ,
apply cycle_induction_on _ σ,
{ intros τ h,
rw [cycle_type_one, eq_comm, cycle_type_eq_zero] at h,
rw h },
{ intros σ hσ τ hστ,
have hτ := card_cycle_type_eq_one.2 hσ,
rw [hστ, card_cycle_type_eq_one] at hτ,
apply hσ.is_conj hτ,
rw [hσ.cycle_type, hτ.cycle_type, coe_eq_coe, singleton_perm] at hστ,
simp only [and_true, eq_self_iff_true] at hστ,
exact hστ },
{ intros σ τ hστ hσ h1 h2 π hπ,
rw [hστ.cycle_type] at hπ,
{ have h : σ.support.card ∈ map (finset.card ∘ perm.support) π.cycle_factors_finset.val,
{ simp [←cycle_type_def, ←hπ, hσ.cycle_type] },
obtain ⟨σ', hσ'l, hσ'⟩ := multiset.mem_map.mp h,
have key : is_conj (σ' * (π * σ'⁻¹)) π,
{ rw is_conj_iff,
use σ'⁻¹,
simp [mul_assoc] },
refine is_conj.trans _ key,
have hs : σ.cycle_type = σ'.cycle_type,
{ rw [←finset.mem_def, mem_cycle_factors_finset_iff] at hσ'l,
rw [hσ.cycle_type, ←hσ', hσ'l.left.cycle_type] },
refine hστ.is_conj_mul (h1 hs) (h2 _) _,
{ rw [cycle_type_mul_mem_cycle_factors_finset_eq_sub, ←hπ, add_comm, hs,
add_tsub_cancel_right],
rwa finset.mem_def },
{ exact (disjoint_mul_inv_of_mem_cycle_factors_finset hσ'l).symm } } }
end
theorem is_conj_iff_cycle_type_eq {σ τ : perm α} :
is_conj σ τ ↔ σ.cycle_type = τ.cycle_type :=
⟨λ h, begin
obtain ⟨π, rfl⟩ := is_conj_iff.1 h,
rw cycle_type_conj,
end, is_conj_of_cycle_type_eq⟩
@[simp] lemma cycle_type_extend_domain {β : Type*} [fintype β] [decidable_eq β]
{p : β → Prop} [decidable_pred p] (f : α ≃ subtype p) {g : perm α} :
cycle_type (g.extend_domain f) = cycle_type g :=
begin
apply cycle_induction_on _ g,
{ rw [extend_domain_one, cycle_type_one, cycle_type_one] },
{ intros σ hσ,
rw [(hσ.extend_domain f).cycle_type, hσ.cycle_type, card_support_extend_domain] },
{ intros σ τ hd hc hσ hτ,
rw [hd.cycle_type, ← extend_domain_mul, (hd.extend_domain f).cycle_type, hσ, hτ] }
end
lemma mem_cycle_type_iff {n : ℕ} {σ : perm α} :
n ∈ cycle_type σ ↔ ∃ c τ : perm α, σ = c * τ ∧ disjoint c τ ∧ is_cycle c ∧ c.support.card = n :=
begin
split,
{ intro h,
obtain ⟨l, rfl, hlc, hld⟩ := trunc_cycle_factors σ,
rw cycle_type_eq _ rfl hlc hld at h,
obtain ⟨c, cl, rfl⟩ := list.exists_of_mem_map h,
rw (list.perm_cons_erase cl).pairwise_iff (λ _ _ hd, _) at hld,
swap, { exact hd.symm },
refine ⟨c, (l.erase c).prod, _, _, hlc _ cl, rfl⟩,
{ rw [← list.prod_cons,
(list.perm_cons_erase cl).symm.prod_eq' (hld.imp (λ _ _, disjoint.commute))] },
{ exact disjoint_prod_right _ (λ g, list.rel_of_pairwise_cons hld) } },
{ rintros ⟨c, t, rfl, hd, hc, rfl⟩,
simp [hd.cycle_type, hc.cycle_type] }
end
lemma le_card_support_of_mem_cycle_type {n : ℕ} {σ : perm α} (h : n ∈ cycle_type σ) :
n ≤ σ.support.card :=
(le_sum_of_mem h).trans (le_of_eq σ.sum_cycle_type)
lemma cycle_type_of_card_le_mem_cycle_type_add_two {n : ℕ} {g : perm α}
(hn2 : fintype.card α < n + 2) (hng : n ∈ g.cycle_type) :
g.cycle_type = {n} :=
begin
obtain ⟨c, g', rfl, hd, hc, rfl⟩ := mem_cycle_type_iff.1 hng,
by_cases g'1 : g' = 1,
{ rw [hd.cycle_type, hc.cycle_type, multiset.singleton_eq_cons, multiset.singleton_coe,
g'1, cycle_type_one, add_zero] },
contrapose! hn2,
apply le_trans _ (c * g').support.card_le_univ,
rw [hd.card_support_mul],
exact add_le_add_left (two_le_card_support_of_ne_one g'1) _,
end
end cycle_type
lemma card_compl_support_modeq [decidable_eq α] {p n : ℕ} [hp : fact p.prime] {σ : perm α}
(hσ : σ ^ p ^ n = 1) : σ.supportᶜ.card ≡ fintype.card α [MOD p] :=
begin
rw [nat.modeq_iff_dvd' σ.supportᶜ.card_le_univ, ←finset.card_compl, compl_compl],
refine (congr_arg _ σ.sum_cycle_type).mp (multiset.dvd_sum (λ k hk, _)),
obtain ⟨m, -, hm⟩ := (nat.dvd_prime_pow hp.out).mp (order_of_dvd_of_pow_eq_one hσ),
obtain ⟨l, -, rfl⟩ := (nat.dvd_prime_pow hp.out).mp
((congr_arg _ hm).mp (dvd_of_mem_cycle_type hk)),
exact dvd_pow_self _ (λ h, (one_lt_of_mem_cycle_type hk).ne $ by rw [h, pow_zero]),
end
lemma exists_fixed_point_of_prime {p n : ℕ} [hp : fact p.prime] (hα : ¬ p ∣ fintype.card α)
{σ : perm α} (hσ : σ ^ p ^ n = 1) : ∃ a : α, σ a = a :=
begin
classical,
contrapose! hα,
simp_rw ← mem_support at hα,
exact nat.modeq_zero_iff_dvd.mp ((congr_arg _ (finset.card_eq_zero.mpr (compl_eq_bot.mpr
(finset.eq_univ_iff_forall.mpr hα)))).mp (card_compl_support_modeq hσ).symm),
end
lemma exists_fixed_point_of_prime' {p n : ℕ} [hp : fact p.prime] (hα : p ∣ fintype.card α)
{σ : perm α} (hσ : σ ^ p ^ n = 1) {a : α} (ha : σ a = a) : ∃ b : α, σ b = b ∧ b ≠ a :=
begin
classical,
have h : ∀ b : α, b ∈ σ.supportᶜ ↔ σ b = b :=
λ b, by rw [finset.mem_compl, mem_support, not_not],
obtain ⟨b, hb1, hb2⟩ := finset.exists_ne_of_one_lt_card (lt_of_lt_of_le hp.out.one_lt
(nat.le_of_dvd (finset.card_pos.mpr ⟨a, (h a).mpr ha⟩) (nat.modeq_zero_iff_dvd.mp
((card_compl_support_modeq hσ).trans (nat.modeq_zero_iff_dvd.mpr hα))))) a,
exact ⟨b, (h b).mp hb1, hb2⟩,
end
lemma is_cycle_of_prime_order' {σ : perm α} (h1 : (order_of σ).prime)
(h2 : fintype.card α < 2 * (order_of σ)) : σ.is_cycle :=
begin
classical,
exact is_cycle_of_prime_order h1 (lt_of_le_of_lt σ.support.card_le_univ h2),
end
lemma is_cycle_of_prime_order'' {σ : perm α} (h1 : (fintype.card α).prime)
(h2 : order_of σ = fintype.card α) : σ.is_cycle :=
is_cycle_of_prime_order' ((congr_arg nat.prime h2).mpr h1)
begin
classical,
rw [←one_mul (fintype.card α), ←h2, mul_lt_mul_right (order_of_pos σ)],
exact one_lt_two,
end
section cauchy
variables (G : Type*) [group G] (n : ℕ)
/-- The type of vectors with terms from `G`, length `n`, and product equal to `1:G`. -/
def vectors_prod_eq_one : set (vector G n) :=
{v | v.to_list.prod = 1}
namespace vectors_prod_eq_one
lemma mem_iff {n : ℕ} (v : vector G n) :
v ∈ vectors_prod_eq_one G n ↔ v.to_list.prod = 1 := iff.rfl
lemma zero_eq : vectors_prod_eq_one G 0 = {vector.nil} :=
set.eq_singleton_iff_unique_mem.mpr ⟨eq.refl (1 : G), λ v hv, v.eq_nil⟩
lemma one_eq : vectors_prod_eq_one G 1 = {vector.nil.cons 1} :=
begin
simp_rw [set.eq_singleton_iff_unique_mem, mem_iff,
vector.to_list_singleton, list.prod_singleton, vector.head_cons],
exact ⟨rfl, λ v hv, v.cons_head_tail.symm.trans (congr_arg2 vector.cons hv v.tail.eq_nil)⟩,
end
instance zero_unique : unique (vectors_prod_eq_one G 0) :=
by { rw zero_eq, exact set.unique_singleton vector.nil }
instance one_unique : unique (vectors_prod_eq_one G 1) :=
by { rw one_eq, exact set.unique_singleton (vector.nil.cons 1) }
/-- Given a vector `v` of length `n`, make a vector of length `n + 1` whose product is `1`,
by appending the inverse of the product of `v`. -/
@[simps] def vector_equiv : vector G n ≃ vectors_prod_eq_one G (n + 1) :=
{ to_fun := λ v, ⟨v.to_list.prod⁻¹ ::ᵥ v,
by rw [mem_iff, vector.to_list_cons, list.prod_cons, inv_mul_self]⟩,
inv_fun := λ v, v.1.tail,
left_inv := λ v, v.tail_cons v.to_list.prod⁻¹,
right_inv := λ v, subtype.ext ((congr_arg2 vector.cons (eq_inv_of_mul_eq_one (by
{ rw [←list.prod_cons, ←vector.to_list_cons, v.1.cons_head_tail],
exact v.2 })).symm rfl).trans v.1.cons_head_tail) }
/-- Given a vector `v` of length `n` whose product is 1, make a vector of length `n - 1`,
by deleting the last entry of `v`. -/
def equiv_vector : vectors_prod_eq_one G n ≃ vector G (n - 1) :=
((vector_equiv G (n - 1)).trans (if hn : n = 0 then (show vectors_prod_eq_one G (n - 1 + 1) ≃
vectors_prod_eq_one G n, by { rw hn, exact equiv_of_unique_of_unique })
else by rw tsub_add_cancel_of_le (nat.pos_of_ne_zero hn).nat_succ_le)).symm
instance [fintype G] : fintype (vectors_prod_eq_one G n) :=
fintype.of_equiv (vector G (n - 1)) (equiv_vector G n).symm
lemma card [fintype G] :
fintype.card (vectors_prod_eq_one G n) = fintype.card G ^ (n - 1) :=
(fintype.card_congr (equiv_vector G n)).trans (card_vector (n - 1))
variables {G n} {g : G} (v : vectors_prod_eq_one G n) (j k : ℕ)
/-- Rotate a vector whose product is 1. -/
def rotate : vectors_prod_eq_one G n :=
⟨⟨_, (v.1.1.length_rotate k).trans v.1.2⟩, list.prod_rotate_eq_one_of_prod_eq_one v.2 k⟩
lemma rotate_zero : rotate v 0 = v :=
subtype.ext (subtype.ext v.1.1.rotate_zero)
lemma rotate_rotate : rotate (rotate v j) k = rotate v (j + k) :=
subtype.ext (subtype.ext (v.1.1.rotate_rotate j k))
lemma rotate_length : rotate v n = v :=
subtype.ext (subtype.ext ((congr_arg _ v.1.2.symm).trans v.1.1.rotate_length))
end vectors_prod_eq_one
lemma exists_prime_order_of_dvd_card {G : Type*} [group G] [fintype G] (p : ℕ) [hp : fact p.prime]
(hdvd : p ∣ fintype.card G) : ∃ x : G, order_of x = p :=
begin
have hp' : p - 1 ≠ 0 := mt tsub_eq_zero_iff_le.mp (not_le_of_lt hp.out.one_lt),
have Scard := calc p ∣ fintype.card G ^ (p - 1) : hdvd.trans (dvd_pow (dvd_refl _) hp')
... = fintype.card (vectors_prod_eq_one G p) : (vectors_prod_eq_one.card G p).symm,
let f : ℕ → vectors_prod_eq_one G p → vectors_prod_eq_one G p :=
λ k v, vectors_prod_eq_one.rotate v k,
have hf1 : ∀ v, f 0 v = v := vectors_prod_eq_one.rotate_zero,
have hf2 : ∀ j k v, f k (f j v) = f (j + k) v :=
λ j k v, vectors_prod_eq_one.rotate_rotate v j k,
have hf3 : ∀ v, f p v = v := vectors_prod_eq_one.rotate_length,
let σ := equiv.mk (f 1) (f (p - 1))
(λ s, by rw [hf2, add_tsub_cancel_of_le hp.out.one_lt.le, hf3])
(λ s, by rw [hf2, tsub_add_cancel_of_le hp.out.one_lt.le, hf3]),
have hσ : ∀ k v, (σ ^ k) v = f k v :=
λ k v, nat.rec (hf1 v).symm (λ k hk, eq.trans (by exact congr_arg σ hk) (hf2 k 1 v)) k,
replace hσ : σ ^ (p ^ 1) = 1 := perm.ext (λ v, by rw [pow_one, hσ, hf3, one_apply]),
let v₀ : vectors_prod_eq_one G p := ⟨vector.repeat 1 p, (list.prod_repeat 1 p).trans (one_pow p)⟩,
have hv₀ : σ v₀ = v₀ := subtype.ext (subtype.ext (list.rotate_repeat (1 : G) p 1)),
obtain ⟨v, hv1, hv2⟩ := exists_fixed_point_of_prime' Scard hσ hv₀,
refine exists_imp_exists (λ g hg, order_of_eq_prime _ (λ hg', hv2 _))
(list.rotate_one_eq_self_iff_eq_repeat.mp (subtype.ext_iff.mp (subtype.ext_iff.mp hv1))),
{ rw [←list.prod_repeat, ←v.1.2, ←hg, (show v.val.val.prod = 1, from v.2)] },
{ rw [subtype.ext_iff_val, subtype.ext_iff_val, hg, hg', v.1.2],
refl },
end
end cauchy
lemma subgroup_eq_top_of_swap_mem [decidable_eq α] {H : subgroup (perm α)}
[d : decidable_pred (∈ H)] {τ : perm α} (h0 : (fintype.card α).prime)
(h1 : fintype.card α ∣ fintype.card H) (h2 : τ ∈ H) (h3 : is_swap τ) :
H = ⊤ :=
begin
haveI : fact (fintype.card α).prime := ⟨h0⟩,
obtain ⟨σ, hσ⟩ := exists_prime_order_of_dvd_card (fintype.card α) h1,
have hσ1 : order_of (σ : perm α) = fintype.card α := (order_of_subgroup σ).trans hσ,
have hσ2 : is_cycle ↑σ := is_cycle_of_prime_order'' h0 hσ1,
have hσ3 : (σ : perm α).support = ⊤ :=
finset.eq_univ_of_card (σ : perm α).support ((order_of_is_cycle hσ2).symm.trans hσ1),
have hσ4 : subgroup.closure {↑σ, τ} = ⊤ := closure_prime_cycle_swap h0 hσ2 hσ3 h3,
rw [eq_top_iff, ←hσ4, subgroup.closure_le, set.insert_subset, set.singleton_subset_iff],
exact ⟨subtype.mem σ, h2⟩,
end
section partition
variables [decidable_eq α]
/-- The partition corresponding to a permutation -/
def partition (σ : perm α) : (fintype.card α).partition :=
{ parts := σ.cycle_type + repeat 1 (fintype.card α - σ.support.card),
parts_pos := λ n hn,
begin
cases mem_add.mp hn with hn hn,
{ exact zero_lt_one.trans (one_lt_of_mem_cycle_type hn) },
{ exact lt_of_lt_of_le zero_lt_one (ge_of_eq (multiset.eq_of_mem_repeat hn)) },
end,
parts_sum := by rw [sum_add, sum_cycle_type, multiset.sum_repeat, nsmul_eq_mul,
nat.cast_id, mul_one, add_tsub_cancel_of_le σ.support.card_le_univ] }
lemma parts_partition {σ : perm α} :
σ.partition.parts = σ.cycle_type + repeat 1 (fintype.card α - σ.support.card) := rfl
lemma filter_parts_partition_eq_cycle_type {σ : perm α} :
(partition σ).parts.filter (λ n, 2 ≤ n) = σ.cycle_type :=
begin
rw [parts_partition, filter_add, multiset.filter_eq_self.2 (λ _, two_le_of_mem_cycle_type),
multiset.filter_eq_nil.2 (λ a h, _), add_zero],
rw multiset.eq_of_mem_repeat h,
dec_trivial
end
lemma partition_eq_of_is_conj {σ τ : perm α} :
is_conj σ τ ↔ σ.partition = τ.partition :=
begin
rw [is_conj_iff_cycle_type_eq],
refine ⟨λ h, _, λ h, _⟩,
{ rw [nat.partition.ext_iff, parts_partition, parts_partition,
← sum_cycle_type, ← sum_cycle_type, h] },
{ rw [← filter_parts_partition_eq_cycle_type, ← filter_parts_partition_eq_cycle_type, h] }
end
end partition
/-!
### 3-cycles
-/
/-- A three-cycle is a cycle of length 3. -/
def is_three_cycle [decidable_eq α] (σ : perm α) : Prop := σ.cycle_type = {3}
namespace is_three_cycle
variables [decidable_eq α] {σ : perm α}
lemma cycle_type (h : is_three_cycle σ) : σ.cycle_type = {3} := h
lemma card_support (h : is_three_cycle σ) : σ.support.card = 3 :=
by rw [←sum_cycle_type, h.cycle_type, multiset.sum_singleton]
lemma _root_.card_support_eq_three_iff : σ.support.card = 3 ↔ σ.is_three_cycle :=
begin
refine ⟨λ h, _, is_three_cycle.card_support⟩,
by_cases h0 : σ.cycle_type = 0,
{ rw [←sum_cycle_type, h0, sum_zero] at h,
exact (ne_of_lt zero_lt_three h).elim },
obtain ⟨n, hn⟩ := exists_mem_of_ne_zero h0,
by_cases h1 : σ.cycle_type.erase n = 0,
{ rw [←sum_cycle_type, ←cons_erase hn, h1, ←singleton_eq_cons, multiset.sum_singleton] at h,
rw [is_three_cycle, ←cons_erase hn, h1, h, singleton_eq_cons] },
obtain ⟨m, hm⟩ := exists_mem_of_ne_zero h1,
rw [←sum_cycle_type, ←cons_erase hn, ←cons_erase hm, multiset.sum_cons, multiset.sum_cons] at h,
linarith [two_le_of_mem_cycle_type hn, two_le_of_mem_cycle_type (mem_of_mem_erase hm)],
end
lemma is_cycle (h : is_three_cycle σ) : is_cycle σ :=
by rw [←card_cycle_type_eq_one, h.cycle_type, card_singleton]
lemma sign (h : is_three_cycle σ) : sign σ = 1 :=
begin
rw [sign_of_cycle_type, h.cycle_type],
refl,
end
lemma inv {f : perm α} (h : is_three_cycle f) : is_three_cycle (f⁻¹) :=
by rwa [is_three_cycle, cycle_type_inv]
@[simp] lemma inv_iff {f : perm α} : is_three_cycle (f⁻¹) ↔ is_three_cycle f :=
⟨by { rw ← inv_inv f, apply inv }, inv⟩
lemma order_of {g : perm α} (ht : is_three_cycle g) :
order_of g = 3 :=
by rw [←lcm_cycle_type, ht.cycle_type, multiset.lcm_singleton, normalize_eq]
lemma is_three_cycle_sq {g : perm α} (ht : is_three_cycle g) :
is_three_cycle (g * g) :=
begin
rw [←pow_two, ←card_support_eq_three_iff, support_pow_coprime, ht.card_support],
rw [ht.order_of, nat.coprime_iff_gcd_eq_one],
norm_num,
end
end is_three_cycle
section
variable [decidable_eq α]
lemma is_three_cycle_swap_mul_swap_same
{a b c : α} (ab : a ≠ b) (ac : a ≠ c) (bc : b ≠ c) :
is_three_cycle (swap a b * swap a c) :=
begin
suffices h : support (swap a b * swap a c) = {a, b, c},
{ rw [←card_support_eq_three_iff, h],
simp [ab, ac, bc] },
apply le_antisymm ((support_mul_le _ _).trans (λ x, _)) (λ x hx, _),
{ simp [ab, ac, bc] },
{ simp only [finset.mem_insert, finset.mem_singleton] at hx,
rw mem_support,
simp only [perm.coe_mul, function.comp_app, ne.def],
obtain rfl | rfl | rfl := hx,
{ rw [swap_apply_left, swap_apply_of_ne_of_ne ac.symm bc.symm],
exact ac.symm },
{ rw [swap_apply_of_ne_of_ne ab.symm bc, swap_apply_right],
exact ab },
{ rw [swap_apply_right, swap_apply_left],
exact bc } }
end
open subgroup
lemma swap_mul_swap_same_mem_closure_three_cycles
{a b c : α} (ab : a ≠ b) (ac : a ≠ c) :
(swap a b * swap a c) ∈ closure {σ : perm α | is_three_cycle σ } :=
begin
by_cases bc : b = c,
{ subst bc,
simp [one_mem] },
exact subset_closure (is_three_cycle_swap_mul_swap_same ab ac bc)
end
lemma is_swap.mul_mem_closure_three_cycles {σ τ : perm α}
(hσ : is_swap σ) (hτ : is_swap τ) :
σ * τ ∈ closure {σ : perm α | is_three_cycle σ } :=
begin
obtain ⟨a, b, ab, rfl⟩ := hσ,
obtain ⟨c, d, cd, rfl⟩ := hτ,
by_cases ac : a = c,
{ subst ac,
exact swap_mul_swap_same_mem_closure_three_cycles ab cd },
have h' : swap a b * swap c d = swap a b * swap a c * (swap c a * swap c d),
{ simp [swap_comm c a, mul_assoc] },
rw h',
exact mul_mem _ (swap_mul_swap_same_mem_closure_three_cycles ab ac)
(swap_mul_swap_same_mem_closure_three_cycles (ne.symm ac) cd),
end
end
end equiv.perm
|
5726ee551354b8d8c19ee0741bc548e1a96bb79e | 5749d8999a76f3a8fddceca1f6941981e33aaa96 | /src/data/semiquot.lean | 0f133d3e984be0886455585bc534df8a2cab4b91 | [
"Apache-2.0"
] | permissive | jdsalchow/mathlib | 13ab43ef0d0515a17e550b16d09bd14b76125276 | 497e692b946d93906900bb33a51fd243e7649406 | refs/heads/master | 1,585,819,143,348 | 1,580,072,892,000 | 1,580,072,892,000 | 154,287,128 | 0 | 0 | Apache-2.0 | 1,540,281,610,000 | 1,540,281,609,000 | null | UTF-8 | Lean | false | false | 7,487 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
A data type for semiquotients, which are classically equivalent to
nonempty sets, but are useful for programming; the idea is that
a semiquotient set `S` represents some (particular but unknown)
element of `S`. This can be used to model nondeterministic functions,
which return something in a range of values (represented by the
predicate `S`) but are not completely determined.
-/
import data.set.lattice data.quot
/-- A member of `semiquot α` is classically a nonempty `set α`,
and in the VM is represented by an element of `α`; the relation
between these is that the VM element is required to be a member
of the set `s`. The specific element of `s` that the VM computes
is hidden by a quotient construction, allowing for the representation
of nondeterministic functions. -/
structure {u} semiquot (α : Type*) := mk' ::
(s : set α)
(val : trunc ↥s)
namespace semiquot
variables {α : Type*} {β : Type*}
instance : has_mem α (semiquot α) := ⟨λ a q, a ∈ q.s⟩
/-- Construct a `semiquot α` from `h : a ∈ s` where `s : set α`. -/
def mk {a : α} {s : set α} (h : a ∈ s) : semiquot α :=
⟨s, trunc.mk ⟨a, h⟩⟩
theorem ext_s {q₁ q₂ : semiquot α} : q₁ = q₂ ↔ q₁.s = q₂.s :=
⟨congr_arg _,
λ h, by cases q₁; cases q₂; congr; exact h⟩
theorem ext {q₁ q₂ : semiquot α} : q₁ = q₂ ↔ ∀ a, a ∈ q₁ ↔ a ∈ q₂ :=
ext_s.trans (set.ext_iff _ _)
theorem exists_mem (q : semiquot α) : ∃ a, a ∈ q :=
let ⟨⟨a, h⟩, h₂⟩ := q.2.exists_rep in ⟨a, h⟩
theorem eq_mk_of_mem {q : semiquot α} {a : α} (h : a ∈ q) :
q = @mk _ a q.1 h := ext_s.2 rfl
theorem ne_empty (q : semiquot α) : q.s ≠ ∅ :=
let ⟨a, h⟩ := q.exists_mem in set.ne_empty_of_mem h
/-- `pure a` is `a` reinterpreted as an unspecified element of `{a}`. -/
protected def pure (a : α) : semiquot α := mk (set.mem_singleton a)
@[simp] theorem mem_pure' {a b : α} : a ∈ semiquot.pure b ↔ a = b :=
set.mem_singleton_iff
/-- Replace `s` in a `semiquot` with a superset. -/
def blur' (q : semiquot α) {s : set α} (h : q.s ⊆ s) : semiquot α :=
⟨s, trunc.lift (λ a : q.s, trunc.mk ⟨a.1, h a.2⟩)
(λ _ _, trunc.eq _ _) q.2⟩
/-- Replace `s` in a `q : semiquot α` with a union `s ∪ q.s` -/
def blur (s : set α) (q : semiquot α) : semiquot α :=
blur' q (set.subset_union_right s q.s)
theorem blur_eq_blur' (q : semiquot α) (s : set α) (h : q.s ⊆ s) :
blur s q = blur' q h :=
by unfold blur; congr; exact set.union_eq_self_of_subset_right h
@[simp] theorem mem_blur' (q : semiquot α) {s : set α} (h : q.s ⊆ s)
{a : α} : a ∈ blur' q h ↔ a ∈ s := iff.rfl
/-- Convert a `trunc α` to a `semiquot α`. -/
def of_trunc (q : trunc α) : semiquot α :=
⟨set.univ, q.map (λ a, ⟨a, trivial⟩)⟩
/-- Convert a `semiquot α` to a `trunc α`. -/
def to_trunc (q : semiquot α) : trunc α :=
q.2.map subtype.val
/-- If `f` is a constant on `q.s`, then `q.lift_on f` is the value of `f`
at any point of `q`. -/
def lift_on (q : semiquot α) (f : α → β) (h : ∀ a b ∈ q, f a = f b) : β :=
trunc.lift_on q.2 (λ x, f x.1) (λ x y, h _ _ x.2 y.2)
theorem lift_on_of_mem (q : semiquot α)
(f : α → β) (h : ∀ a b ∈ q, f a = f b)
(a : α) (aq : a ∈ q) : lift_on q f h = f a :=
by revert h; rw eq_mk_of_mem aq; intro; refl
def map (f : α → β) (q : semiquot α) : semiquot β :=
⟨f '' q.1, q.2.map (λ x, ⟨f x.1, set.mem_image_of_mem _ x.2⟩)⟩
@[simp] theorem mem_map (f : α → β) (q : semiquot α) (b : β) :
b ∈ map f q ↔ ∃ a, a ∈ q ∧ f a = b := set.mem_image _ _ _
def bind (q : semiquot α) (f : α → semiquot β) : semiquot β :=
⟨⋃ a ∈ q.1, (f a).1,
q.2.bind (λ a, (f a.1).2.map (λ b, ⟨b.1, set.mem_bUnion a.2 b.2⟩))⟩
@[simp] theorem mem_bind (q : semiquot α) (f : α → semiquot β) (b : β) :
b ∈ bind q f ↔ ∃ a ∈ q, b ∈ f a := set.mem_bUnion_iff
instance : monad semiquot :=
{ pure := @semiquot.pure,
map := @semiquot.map,
bind := @semiquot.bind }
@[simp] theorem mem_pure {a b : α} : a ∈ (pure b : semiquot α) ↔ a = b :=
set.mem_singleton_iff
theorem mem_pure_self (a : α) : a ∈ (pure a : semiquot α) :=
set.mem_singleton a
@[simp] theorem pure_inj {a b : α} : (pure a : semiquot α) = pure b ↔ a = b :=
ext_s.trans set.singleton_eq_singleton_iff
instance : is_lawful_monad semiquot :=
{ pure_bind := λ α β x f, ext.2 $ by simp,
bind_assoc := λ α β γ s f g, ext.2 $ by simp; exact
λ c, ⟨λ ⟨b, ⟨a, as, bf⟩, cg⟩, ⟨a, as, b, bf, cg⟩,
λ ⟨a, as, b, bf, cg⟩, ⟨b, ⟨a, as, bf⟩, cg⟩⟩,
id_map := λ α q, ext.2 $ by simp,
bind_pure_comp_eq_map := λ α β f s, ext.2 $ by simp [eq_comm] }
instance : has_le (semiquot α) := ⟨λ s t, s.s ⊆ t.s⟩
instance : partial_order (semiquot α) :=
{ le := λ s t, ∀ ⦃x⦄, x ∈ s → x ∈ t,
le_refl := λ s, set.subset.refl _,
le_trans := λ s t u, set.subset.trans,
le_antisymm := λ s t h₁ h₂, ext_s.2 (set.subset.antisymm h₁ h₂) }
instance : lattice.semilattice_sup (semiquot α) :=
{ sup := λ s, blur s.s,
le_sup_left := λ s t, set.subset_union_left _ _,
le_sup_right := λ s t, set.subset_union_right _ _,
sup_le := λ s t u, set.union_subset,
..semiquot.partial_order }
@[simp] theorem pure_le {a : α} {s : semiquot α} : pure a ≤ s ↔ a ∈ s :=
set.singleton_subset_iff
def is_pure (q : semiquot α) := ∀ a b ∈ q, a = b
def get (q : semiquot α) (h : q.is_pure) : α := lift_on q id h
theorem get_mem {q : semiquot α} (p) : get q p ∈ q :=
let ⟨a, h⟩ := exists_mem q in
by unfold get; rw lift_on_of_mem q _ _ a h; exact h
theorem eq_pure {q : semiquot α} (p) : q = pure (get q p) :=
ext.2 $ λ a, by simp; exact
⟨λ h, p _ _ h (get_mem _), λ e, e.symm ▸ get_mem _⟩
@[simp] theorem pure_is_pure (a : α) : is_pure (pure a)
| b c ab ac := by { simp at ab ac, cc }
theorem is_pure_iff {s : semiquot α} : is_pure s ↔ ∃ a, s = pure a :=
⟨λ h, ⟨_, eq_pure h⟩, λ ⟨a, e⟩, e.symm ▸ pure_is_pure _⟩
theorem is_pure.mono {s t : semiquot α}
(st : s ≤ t) (h : is_pure t) : is_pure s
| a b as bs := h _ _ (st as) (st bs)
theorem is_pure.min {s t : semiquot α} (h : is_pure t) : s ≤ t ↔ s = t :=
⟨λ st, le_antisymm st $ by rw [eq_pure h, eq_pure (h.mono st)]; simp;
exact h _ _ (get_mem _) (st $ get_mem _),
le_of_eq⟩
theorem is_pure_of_subsingleton [subsingleton α] (q : semiquot α) : is_pure q
| a b aq bq := subsingleton.elim _ _
/-- `univ : semiquot α` represents an unspecified element of `univ : set α`. -/
def univ [inhabited α] : semiquot α :=
mk $ set.mem_univ (default _)
@[simp] theorem mem_univ [inhabited α] : ∀ a, a ∈ @univ α _ :=
@set.mem_univ α
@[congr] theorem univ_unique (I J : inhabited α) : @univ _ I = @univ _ J :=
ext.2 $ by simp
@[simp] theorem is_pure_univ [inhabited α] : @is_pure α univ ↔ subsingleton α :=
⟨λ h, ⟨λ a b, h a b trivial trivial⟩, λ ⟨h⟩ a b _ _, h a b⟩
instance [inhabited α] : lattice.order_top (semiquot α) :=
{ top := univ,
le_top := λ s, set.subset_univ _,
..semiquot.partial_order }
instance [inhabited α] : lattice.semilattice_sup_top (semiquot α) :=
{ ..semiquot.lattice.order_top,
..semiquot.lattice.semilattice_sup }
end semiquot
|
542c10e8756b0a2dc2f3a2d81a4b588ce9987e2d | a4673261e60b025e2c8c825dfa4ab9108246c32e | /tests/lean/run/meta3.lean | 55ba4dec8a0caba9f2ed0f415e9a7f327a91accf | [
"Apache-2.0"
] | permissive | jcommelin/lean4 | c02dec0cc32c4bccab009285475f265f17d73228 | 2909313475588cc20ac0436e55548a4502050d0a | refs/heads/master | 1,674,129,550,893 | 1,606,415,348,000 | 1,606,415,348,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,847 | lean | import Lean.Meta
open Lean
open Lean.Meta
def dbgOpt : Options :=
let opt : Options := {};
let opt := opt.setBool `trace.Meta true;
-- let opt := opt.setBool `trace.Meta.check false;
opt
def print (msg : MessageData) : MetaM Unit :=
trace! `Meta.debug msg
def check (x : MetaM Bool) : MetaM Unit :=
unless (← x) do throwError "check failed"
def getAssignment (m : Expr) : MetaM Expr :=
do let v? ← getExprMVarAssignment? m.mvarId!;
(match v? with
| some v => pure v
| none => throwError "metavariable is not assigned")
unsafe def run (mods : List Name) (x : MetaM Unit) (opts : Options := dbgOpt) : IO Unit :=
withImportModules (mods.map $ fun m => {module := m}) {} 0 fun env => do
let x : MetaM Unit := do { x; printTraces };
x.toIO { options := opts } { env := env };
pure ()
def nat := mkConst `Nat
def succ := mkConst `Nat.succ
def add := mkAppN (mkConst `Add.add [levelZero]) #[nat, mkConst `Nat.Add]
def tst1 : MetaM Unit :=
do let d : DiscrTree Nat := {};
let mvar ← mkFreshExprMVar nat;
let d ← d.insert (mkAppN add #[mvar, mkNatLit 10]) 1;
let d ← d.insert (mkAppN add #[mkNatLit 0, mkNatLit 10]) 2;
let d ← d.insert (mkAppN (mkConst `Nat.add) #[mkNatLit 0, mkNatLit 20]) 3;
let d ← d.insert (mkAppN add #[mvar, mkNatLit 20]) 4;
let d ← d.insert mvar 5;
print (format d);
let vs ← d.getMatch (mkAppN add #[mkNatLit 1, mkNatLit 10]);
print (format vs);
let t := mkAppN add #[mvar, mvar];
print t;
let vs ← d.getMatch t;
print (format vs);
let vs ← d.getUnify t;
print (format vs);
let vs ← d.getUnify mvar;
print (format vs);
let vs ← d.getUnify $ mkAppN add #[mkNatLit 0, mvar];
print (format vs);
let vs ← d.getUnify $ mkAppN add #[mvar, mkNatLit 20];
print (format vs);
pure ()
#eval run [`Init.Data.Nat] tst1
|
a8bf664f140832aa153854251b4c72cbfccf0eb0 | 8cd68b0e4eb405ef573e16a6d92dcbcdb92d1c29 | /tests/lean/revert_err.lean | 4b18ebbf3d30828d5f98913611b7480c83bf26c8 | [
"Apache-2.0"
] | permissive | ratmice/lean | 5d7a7bbaa652899941fe73dff2154ddc5ab2f20a | 139ac0d773dbf0f54cc682612bf8f02297c211dd | refs/heads/master | 1,590,259,859,627 | 1,557,951,491,000 | 1,558,099,319,000 | 186,896,142 | 0 | 0 | Apache-2.0 | 1,557,951,143,000 | 1,557,951,143,000 | null | UTF-8 | Lean | false | false | 81 | lean | open tactic
example (a b : Prop) : true :=
by do to_expr ```(a ∧ b) >>= revert
|
4698e81fef4a8bbf79cad0e479ab2f2e700f486c | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/data/list/defs.lean | e3e3c2930a1e6c5d822c001016851787a8f2fcd8 | [
"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 | 32,108 | lean | /-
Copyright (c) 2014 Parikshit Khanna. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro
-/
import data.option.defs
import logic.basic
import tactic.cache
/-!
## Definitions on lists
This file contains various definitions on lists. It does not contain
proofs about these definitions, those are contained in other files in `data/list`
-/
namespace list
open function nat
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
/-- Returns whether a list is []. Returns a boolean even if `l = []` is not decidable. -/
def is_nil {α} : list α → bool
| [] := tt
| _ := ff
instance [decidable_eq α] : has_sdiff (list α) :=
⟨ list.diff ⟩
/-- Split a list at an index.
split_at 2 [a, b, c] = ([a, b], [c]) -/
def split_at : ℕ → list α → list α × list α
| 0 a := ([], a)
| (succ n) [] := ([], [])
| (succ n) (x :: xs) := let (l, r) := split_at n xs in (x :: l, r)
/-- An auxiliary function for `split_on_p`. -/
def split_on_p_aux {α : Type u} (P : α → Prop) [decidable_pred P] :
list α → (list α → list α) → list (list α)
| [] f := [f []]
| (h :: t) f :=
if P h then f [] :: split_on_p_aux t id
else split_on_p_aux t (λ l, f (h :: l))
/-- Split a list at every element satisfying a predicate. -/
def split_on_p {α : Type u} (P : α → Prop) [decidable_pred P] (l : list α) : list (list α) :=
split_on_p_aux P l id
/-- Split a list at every occurrence of an element.
[1,1,2,3,2,4,4].split_on 2 = [[1,1],[3],[4,4]] -/
def split_on {α : Type u} [decidable_eq α] (a : α) (as : list α) : list (list α) :=
as.split_on_p (=a)
/-- Concatenate an element at the end of a list.
concat [a, b] c = [a, b, c] -/
@[simp] def concat : list α → α → list α
| [] a := [a]
| (b::l) a := b :: concat l a
/-- `head' xs` returns the first element of `xs` if `xs` is non-empty;
it returns `none` otherwise -/
@[simp] def head' : list α → option α
| [] := none
| (a :: l) := some a
/-- Convert a list into an array (whose length is the length of `l`). -/
def to_array (l : list α) : array l.length α :=
{data := λ v, l.nth_le v.1 v.2}
/-- "inhabited" `nth` function: returns `default` instead of `none` in the case
that the index is out of bounds. -/
@[simp] def inth [h : inhabited α] (l : list α) (n : nat) : α := (nth l n).iget
/-- Apply a function to the nth tail of `l`. Returns the input without
using `f` if the index is larger than the length of the list.
modify_nth_tail f 2 [a, b, c] = [a, b] ++ f [c] -/
@[simp] def modify_nth_tail (f : list α → list α) : ℕ → list α → list α
| 0 l := f l
| (n+1) [] := []
| (n+1) (a::l) := a :: modify_nth_tail n l
/-- Apply `f` to the head of the list, if it exists. -/
@[simp] def modify_head (f : α → α) : list α → list α
| [] := []
| (a::l) := f a :: l
/-- Apply `f` to the nth element of the list, if it exists. -/
def modify_nth (f : α → α) : ℕ → list α → list α :=
modify_nth_tail (modify_head f)
/-- Apply `f` to the last element of `l`, if it exists. -/
@[simp] def modify_last (f : α → α) : list α → list α
| [] := []
| [x] := [f x]
| (x :: xs) := x :: modify_last xs
/-- `insert_nth n a l` inserts `a` into the list `l` after the first `n` elements of `l`
`insert_nth 2 1 [1, 2, 3, 4] = [1, 2, 1, 3, 4]`-/
def insert_nth (n : ℕ) (a : α) : list α → list α := modify_nth_tail (list.cons a) n
section take'
variable [inhabited α]
/-- Take `n` elements from a list `l`. If `l` has less than `n` elements, append `n - length l`
elements `default α`. -/
def take' : ∀ n, list α → list α
| 0 l := []
| (n+1) l := l.head :: take' n l.tail
end take'
/-- Get the longest initial segment of the list whose members all satisfy `p`.
take_while (λ x, x < 3) [0, 2, 5, 1] = [0, 2] -/
def take_while (p : α → Prop) [decidable_pred p] : list α → list α
| [] := []
| (a::l) := if p a then a :: take_while l else []
/-- Fold a function `f` over the list from the left, returning the list
of partial results.
scanl (+) 0 [1, 2, 3] = [0, 1, 3, 6] -/
def scanl (f : α → β → α) : α → list β → list α
| a [] := [a]
| a (b::l) := a :: scanl (f a b) l
/-- Auxiliary definition used to define `scanr`. If `scanr_aux f b l = (b', l')`
then `scanr f b l = b' :: l'` -/
def scanr_aux (f : α → β → β) (b : β) : list α → β × list β
| [] := (b, [])
| (a::l) := let (b', l') := scanr_aux l in (f a b', b' :: l')
/-- Fold a function `f` over the list from the right, returning the list
of partial results.
scanr (+) 0 [1, 2, 3] = [6, 5, 3, 0] -/
def scanr (f : α → β → β) (b : β) (l : list α) : list β :=
let (b', l') := scanr_aux f b l in b' :: l'
/-- Product of a list.
prod [a, b, c] = ((1 * a) * b) * c -/
def prod [has_mul α] [has_one α] : list α → α := foldl (*) 1
/-- Sum of a list.
sum [a, b, c] = ((0 + a) + b) + c -/
-- Later this will be tagged with `to_additive`, but this can't be done yet because of import
-- dependencies.
def sum [has_add α] [has_zero α] : list α → α := foldl (+) 0
/-- The alternating sum of a list. -/
def alternating_sum {G : Type*} [has_zero G] [has_add G] [has_neg G] : list G → G
| [] := 0
| (g :: []) := g
| (g :: h :: t) := g + -h + alternating_sum t
/-- The alternating product of a list. -/
def alternating_prod {G : Type*} [has_one G] [has_mul G] [has_inv G] : list G → G
| [] := 1
| (g :: []) := g
| (g :: h :: t) := g * h⁻¹ * alternating_prod t
/-- Given a function `f : α → β ⊕ γ`, `partition_map f l` maps the list by `f`
whilst partitioning the result it into a pair of lists, `list β × list γ`,
partitioning the `sum.inl _` into the left list, and the `sum.inr _` into the right list.
`partition_map (id : ℕ ⊕ ℕ → ℕ ⊕ ℕ) [inl 0, inr 1, inl 2] = ([0,2], [1])` -/
def partition_map (f : α → β ⊕ γ) : list α → list β × list γ
| [] := ([],[])
| (x::xs) :=
match f x with
| (sum.inr r) := prod.map id (cons r) $ partition_map xs
| (sum.inl l) := prod.map (cons l) id $ partition_map xs
end
/-- `find p l` is the first element of `l` satisfying `p`, or `none` if no such
element exists. -/
def find (p : α → Prop) [decidable_pred p] : list α → option α
| [] := none
| (a::l) := if p a then some a else find l
/-- `mfind tac l` returns the first element of `l` on which `tac` succeeds, and
fails otherwise. -/
def mfind {α} {m : Type u → Type v} [monad m] [alternative m] (tac : α → m punit) : list α → m α :=
list.mfirst $ λ a, tac a $> a
/-- `mbfind' p l` returns the first element `a` of `l` for which `p a` returns
true. `mbfind'` short-circuits, so `p` is not necessarily run on every `a` in
`l`. This is a monadic version of `list.find`. -/
def mbfind' {m : Type u → Type v} [monad m] {α : Type u} (p : α → m (ulift bool)) :
list α → m (option α)
| [] := pure none
| (x :: xs) := do
⟨px⟩ ← p x,
if px then pure (some x) else mbfind' xs
section
variables {m : Type → Type v} [monad m]
/-- A variant of `mbfind'` with more restrictive universe levels. -/
def mbfind {α} (p : α → m bool) (xs : list α) : m (option α) :=
xs.mbfind' (functor.map ulift.up ∘ p)
/-- `many p as` returns true iff `p` returns true for any element of `l`.
`many` short-circuits, so if `p` returns true for any element of `l`, later
elements are not checked. This is a monadic version of `list.any`. -/
-- Implementing this via `mbfind` would give us less universe polymorphism.
def many {α : Type u} (p : α → m bool) : list α → m bool
| [] := pure false
| (x :: xs) := do px ← p x, if px then pure tt else many xs
/-- `mall p as` returns true iff `p` returns true for all elements of `l`.
`mall` short-circuits, so if `p` returns false for any element of `l`, later
elements are not checked. This is a monadic version of `list.all`. -/
def mall {α : Type u} (p : α → m bool) (as : list α) : m bool :=
bnot <$> many (λ a, bnot <$> p a) as
/-- `mbor xs` runs the actions in `xs`, returning true if any of them returns
true. `mbor` short-circuits, so if an action returns true, later actions are
not run. This is a monadic version of `list.bor`. -/
def mbor : list (m bool) → m bool :=
many id
/-- `mband xs` runs the actions in `xs`, returning true if all of them return
true. `mband` short-circuits, so if an action returns false, later actions are
not run. This is a monadic version of `list.band`. -/
def mband : list (m bool) → m bool :=
mall id
end
/-- Auxiliary definition for `foldl_with_index`. -/
def foldl_with_index_aux (f : ℕ → α → β → α) : ℕ → α → list β → α
| _ a [] := a
| i a (b :: l) := foldl_with_index_aux (i + 1) (f i a b) l
/-- Fold a list from left to right as with `foldl`, but the combining function
also receives each element's index. -/
def foldl_with_index (f : ℕ → α → β → α) (a : α) (l : list β) : α :=
foldl_with_index_aux f 0 a l
/-- Auxiliary definition for `foldr_with_index`. -/
def foldr_with_index_aux (f : ℕ → α → β → β) : ℕ → β → list α → β
| _ b [] := b
| i b (a :: l) := f i a (foldr_with_index_aux (i + 1) b l)
/-- Fold a list from right to left as with `foldr`, but the combining function
also receives each element's index. -/
def foldr_with_index (f : ℕ → α → β → β) (b : β) (l : list α) : β :=
foldr_with_index_aux f 0 b l
/-- `find_indexes p l` is the list of indexes of elements of `l` that satisfy `p`. -/
def find_indexes (p : α → Prop) [decidable_pred p] (l : list α) : list nat :=
foldr_with_index (λ i a is, if p a then i :: is else is) [] l
/-- Returns the elements of `l` that satisfy `p` together with their indexes in
`l`. The returned list is ordered by index. -/
def indexes_values (p : α → Prop) [decidable_pred p] (l : list α) : list (ℕ × α) :=
foldr_with_index (λ i a l, if p a then (i , a) :: l else l) [] l
/-- `indexes_of a l` is the list of all indexes of `a` in `l`. For example:
```
indexes_of a [a, b, a, a] = [0, 2, 3]
```
-/
def indexes_of [decidable_eq α] (a : α) : list α → list nat := find_indexes (eq a)
section mfold_with_index
variables {m : Type v → Type w} [monad m]
/-- Monadic variant of `foldl_with_index`. -/
def mfoldl_with_index {α β} (f : ℕ → β → α → m β) (b : β) (as : list α) : m β :=
as.foldl_with_index (λ i ma b, do a ← ma, f i a b) (pure b)
/-- Monadic variant of `foldr_with_index`. -/
def mfoldr_with_index {α β} (f : ℕ → α → β → m β) (b : β) (as : list α) : m β :=
as.foldr_with_index (λ i a mb, do b ← mb, f i a b) (pure b)
end mfold_with_index
section mmap_with_index
variables {m : Type v → Type w} [applicative m]
/-- Auxiliary definition for `mmap_with_index`. -/
def mmap_with_index_aux {α β} (f : ℕ → α → m β) : ℕ → list α → m (list β)
| _ [] := pure []
| i (a :: as) := list.cons <$> f i a <*> mmap_with_index_aux (i + 1) as
/-- Applicative variant of `map_with_index`. -/
def mmap_with_index {α β} (f : ℕ → α → m β) (as : list α) : m (list β) :=
mmap_with_index_aux f 0 as
/-- Auxiliary definition for `mmap_with_index'`. -/
def mmap_with_index'_aux {α} (f : ℕ → α → m punit) : ℕ → list α → m punit
| _ [] := pure ⟨⟩
| i (a :: as) := f i a *> mmap_with_index'_aux (i + 1) as
/-- A variant of `mmap_with_index` specialised to applicative actions which
return `unit`. -/
def mmap_with_index' {α} (f : ℕ → α → m punit) (as : list α) : m punit :=
mmap_with_index'_aux f 0 as
end mmap_with_index
/-- `lookmap` is a combination of `lookup` and `filter_map`.
`lookmap f l` will apply `f : α → option α` to each element of the list,
replacing `a → b` at the first value `a` in the list such that `f a = some b`. -/
def lookmap (f : α → option α) : list α → list α
| [] := []
| (a::l) :=
match f a with
| some b := b :: l
| none := a :: lookmap l
end
/-- `countp p l` is the number of elements of `l` that satisfy `p`. -/
def countp (p : α → Prop) [decidable_pred p] : list α → nat
| [] := 0
| (x::xs) := if p x then succ (countp xs) else countp xs
/-- `count a l` is the number of occurrences of `a` in `l`. -/
def count [decidable_eq α] (a : α) : list α → nat := countp (eq a)
/-- `is_prefix l₁ l₂`, or `l₁ <+: l₂`, means that `l₁` is a prefix of `l₂`,
that is, `l₂` has the form `l₁ ++ t` for some `t`. -/
def is_prefix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, l₁ ++ t = l₂
/-- `is_suffix l₁ l₂`, or `l₁ <:+ l₂`, means that `l₁` is a suffix of `l₂`,
that is, `l₂` has the form `t ++ l₁` for some `t`. -/
def is_suffix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, t ++ l₁ = l₂
/-- `is_infix l₁ l₂`, or `l₁ <:+: l₂`, means that `l₁` is a contiguous
substring of `l₂`, that is, `l₂` has the form `s ++ l₁ ++ t` for some `s, t`. -/
def is_infix (l₁ : list α) (l₂ : list α) : Prop := ∃ s t, s ++ l₁ ++ t = l₂
infix ` <+: `:50 := is_prefix
infix ` <:+ `:50 := is_suffix
infix ` <:+: `:50 := is_infix
/-- `inits l` is the list of initial segments of `l`.
inits [1, 2, 3] = [[], [1], [1, 2], [1, 2, 3]] -/
@[simp] def inits : list α → list (list α)
| [] := [[]]
| (a::l) := [] :: map (λt, a::t) (inits l)
/-- `tails l` is the list of terminal segments of `l`.
tails [1, 2, 3] = [[1, 2, 3], [2, 3], [3], []] -/
@[simp] def tails : list α → list (list α)
| [] := [[]]
| (a::l) := (a::l) :: tails l
def sublists'_aux : list α → (list α → list β) → list (list β) → list (list β)
| [] f r := f [] :: r
| (a::l) f r := sublists'_aux l f (sublists'_aux l (f ∘ cons a) r)
/-- `sublists' l` is the list of all (non-contiguous) sublists of `l`.
It differs from `sublists` only in the order of appearance of the sublists;
`sublists'` uses the first element of the list as the MSB,
`sublists` uses the first element of the list as the LSB.
sublists' [1, 2, 3] = [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]] -/
def sublists' (l : list α) : list (list α) :=
sublists'_aux l id []
def sublists_aux : list α → (list α → list β → list β) → list β
| [] f := []
| (a::l) f := f [a] (sublists_aux l (λys r, f ys (f (a :: ys) r)))
/-- `sublists l` is the list of all (non-contiguous) sublists of `l`; cf. `sublists'`
for a different ordering.
sublists [1, 2, 3] = [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] -/
def sublists (l : list α) : list (list α) :=
[] :: sublists_aux l cons
def sublists_aux₁ : list α → (list α → list β) → list β
| [] f := []
| (a::l) f := f [a] ++ sublists_aux₁ l (λys, f ys ++ f (a :: ys))
section forall₂
variables {r : α → β → Prop} {p : γ → δ → Prop}
/-- `forall₂ R l₁ l₂` means that `l₁` and `l₂` have the same length,
and whenever `a` is the nth element of `l₁`, and `b` is the nth element of `l₂`,
then `R a b` is satisfied. -/
inductive forall₂ (R : α → β → Prop) : list α → list β → Prop
| nil : forall₂ [] []
| cons {a b l₁ l₂} : R a b → forall₂ l₁ l₂ → forall₂ (a::l₁) (b::l₂)
attribute [simp] forall₂.nil
end forall₂
/-- Auxiliary definition used to define `transpose`.
`transpose_aux l L` takes each element of `l` and appends it to the start of
each element of `L`.
`transpose_aux [a, b, c] [l₁, l₂, l₃] = [a::l₁, b::l₂, c::l₃]` -/
def transpose_aux : list α → list (list α) → list (list α)
| [] ls := ls
| (a::i) [] := [a] :: transpose_aux i []
| (a::i) (l::ls) := (a::l) :: transpose_aux i ls
/-- transpose of a list of lists, treated as a matrix.
transpose [[1, 2], [3, 4], [5, 6]] = [[1, 3, 5], [2, 4, 6]] -/
def transpose : list (list α) → list (list α)
| [] := []
| (l::ls) := transpose_aux l (transpose ls)
/-- List of all sections through a list of lists. A section
of `[L₁, L₂, ..., Lₙ]` is a list whose first element comes from
`L₁`, whose second element comes from `L₂`, and so on. -/
def sections : list (list α) → list (list α)
| [] := [[]]
| (l::L) := bind (sections L) $ λ s, map (λ a, a::s) l
section permutations
def permutations_aux2 (t : α) (ts : list α) (r : list β) : list α → (list α → β) → list α × list β
| [] f := (ts, r)
| (y::ys) f := let (us, zs) := permutations_aux2 ys (λx : list α, f (y::x)) in
(y :: us, f (t :: y :: us) :: zs)
private def meas : (Σ'_:list α, list α) → ℕ × ℕ | ⟨l, i⟩ := (length l + length i, length l)
local infix ` ≺ `:50 := inv_image (prod.lex (<) (<)) meas
@[elab_as_eliminator] def permutations_aux.rec {C : list α → list α → Sort v}
(H0 : ∀ is, C [] is)
(H1 : ∀ t ts is, C ts (t::is) → C is [] → C (t::ts) is) : ∀ l₁ l₂, C l₁ l₂
| [] is := H0 is
| (t::ts) is :=
have h1 : ⟨ts, t :: is⟩ ≺ ⟨t :: ts, is⟩, from
show prod.lex _ _ (succ (length ts + length is), length ts) (succ (length ts) + length is,
length (t :: ts)),
by rw nat.succ_add; exact prod.lex.right _ (lt_succ_self _),
have h2 : ⟨is, []⟩ ≺ ⟨t :: ts, is⟩, from prod.lex.left _ _ (nat.lt_add_of_pos_left (succ_pos _)),
H1 t ts is (permutations_aux.rec ts (t::is)) (permutations_aux.rec is [])
using_well_founded {
dec_tac := tactic.assumption,
rel_tac := λ _ _, `[exact ⟨(≺), @inv_image.wf _ _ _ meas (prod.lex_wf lt_wf lt_wf)⟩] }
def permutations_aux : list α → list α → list (list α) :=
@@permutations_aux.rec (λ _ _, list (list α)) (λ is, [])
(λ t ts is IH1 IH2, foldr (λy r, (permutations_aux2 t ts r y id).2) IH1 (is :: IH2))
/-- List of all permutations of `l`.
permutations [1, 2, 3] =
[[1, 2, 3], [2, 1, 3], [3, 2, 1],
[2, 3, 1], [3, 1, 2], [1, 3, 2]] -/
def permutations (l : list α) : list (list α) :=
l :: permutations_aux l []
end permutations
/-- `erase p l` removes all elements of `l` satisfying the predicate `p` -/
def erasep (p : α → Prop) [decidable_pred p] : list α → list α
| [] := []
| (a::l) := if p a then l else a :: erasep l
/-- `extractp p l` returns a pair of an element `a` of `l` satisfying the predicate
`p`, and `l`, with `a` removed. If there is no such element `a` it returns `(none, l)`. -/
def extractp (p : α → Prop) [decidable_pred p] : list α → option α × list α
| [] := (none, [])
| (a::l) := if p a then (some a, l) else
let (a', l') := extractp l in (a', a :: l')
/-- `revzip l` returns a list of pairs of the elements of `l` paired
with the elements of `l` in reverse order.
`revzip [1,2,3,4,5] = [(1, 5), (2, 4), (3, 3), (4, 2), (5, 1)]`
-/
def revzip (l : list α) : list (α × α) := zip l l.reverse
/-- `product l₁ l₂` is the list of pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂`.
product [1, 2] [5, 6] = [(1, 5), (1, 6), (2, 5), (2, 6)] -/
def product (l₁ : list α) (l₂ : list β) : list (α × β) :=
l₁.bind $ λ a, l₂.map $ prod.mk a
/-- `sigma l₁ l₂` is the list of dependent pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂ a`.
sigma [1, 2] (λ_, [(5 : ℕ), 6]) = [(1, 5), (1, 6), (2, 5), (2, 6)] -/
protected def sigma {σ : α → Type*} (l₁ : list α) (l₂ : Π a, list (σ a)) : list (Σ a, σ a) :=
l₁.bind $ λ a, (l₂ a).map $ sigma.mk a
/-- Auxliary definition used to define `of_fn`.
`of_fn_aux f m h l` returns the first `m` elements of `of_fn f`
appended to `l` -/
def of_fn_aux {n} (f : fin n → α) : ∀ m, m ≤ n → list α → list α
| 0 h l := l
| (succ m) h l := of_fn_aux m (le_of_lt h) (f ⟨m, h⟩ :: l)
/-- `of_fn f` with `f : fin n → α` returns the list whose ith element is `f i`
`of_fun f = [f 0, f 1, ... , f(n - 1)]` -/
def of_fn {n} (f : fin n → α) : list α :=
of_fn_aux f n (le_refl _) []
/-- `of_fn_nth_val f i` returns `some (f i)` if `i < n` and `none` otherwise. -/
def of_fn_nth_val {n} (f : fin n → α) (i : ℕ) : option α :=
if h : i < n then some (f ⟨i, h⟩) else none
/-- `disjoint l₁ l₂` means that `l₁` and `l₂` have no elements in common. -/
def disjoint (l₁ l₂ : list α) : Prop := ∀ ⦃a⦄, a ∈ l₁ → a ∈ l₂ → false
section pairwise
variables (R : α → α → Prop)
/-- `pairwise R l` means that all the elements with earlier indexes are
`R`-related to all the elements with later indexes.
pairwise R [1, 2, 3] ↔ R 1 2 ∧ R 1 3 ∧ R 2 3
For example if `R = (≠)` then it asserts `l` has no duplicates,
and if `R = (<)` then it asserts that `l` is (strictly) sorted. -/
inductive pairwise : list α → Prop
| nil : pairwise []
| cons : ∀ {a : α} {l : list α}, (∀ a' ∈ l, R a a') → pairwise l → pairwise (a::l)
variables {R}
@[simp] theorem pairwise_cons {a : α} {l : list α} :
pairwise R (a::l) ↔ (∀ a' ∈ l, R a a') ∧ pairwise R l :=
⟨λ p, by cases p with a l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩
attribute [simp] pairwise.nil
instance decidable_pairwise [decidable_rel R] (l : list α) : decidable (pairwise R l) :=
by induction l with hd tl ih; [exact is_true pairwise.nil,
exactI decidable_of_iff' _ pairwise_cons]
end pairwise
/-- `pw_filter R l` is a maximal sublist of `l` which is `pairwise R`.
`pw_filter (≠)` is the erase duplicates function (cf. `erase_dup`), and `pw_filter (<)` finds
a maximal increasing subsequence in `l`. For example,
pw_filter (<) [0, 1, 5, 2, 6, 3, 4] = [0, 1, 2, 3, 4] -/
def pw_filter (R : α → α → Prop) [decidable_rel R] : list α → list α
| [] := []
| (x :: xs) := let IH := pw_filter xs in if ∀ y ∈ IH, R x y then x :: IH else IH
section chain
variable (R : α → α → Prop)
/-- `chain R a l` means that `R` holds between adjacent elements of `a::l`.
chain R a [b, c, d] ↔ R a b ∧ R b c ∧ R c d -/
inductive chain : α → list α → Prop
| nil {a : α} : chain a []
| cons : ∀ {a b : α} {l : list α}, R a b → chain b l → chain a (b::l)
/-- `chain' R l` means that `R` holds between adjacent elements of `l`.
chain' R [a, b, c, d] ↔ R a b ∧ R b c ∧ R c d -/
def chain' : list α → Prop
| [] := true
| (a :: l) := chain R a l
variable {R}
@[simp] theorem chain_cons {a b : α} {l : list α} :
chain R a (b::l) ↔ R a b ∧ chain R b l :=
⟨λ p, by cases p with _ a b l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩
attribute [simp] chain.nil
instance decidable_chain [decidable_rel R] (a : α) (l : list α) : decidable (chain R a l) :=
by induction l generalizing a; simp only [chain.nil, chain_cons]; resetI; apply_instance
instance decidable_chain' [decidable_rel R] (l : list α) : decidable (chain' R l) :=
by cases l; dunfold chain'; apply_instance
end chain
/-- `nodup l` means that `l` has no duplicates, that is, any element appears at most
once in the list. It is defined as `pairwise (≠)`. -/
def nodup : list α → Prop := pairwise (≠)
instance nodup_decidable [decidable_eq α] : ∀ l : list α, decidable (nodup l) :=
list.decidable_pairwise
/-- `erase_dup l` removes duplicates from `l` (taking only the first occurrence).
Defined as `pw_filter (≠)`.
erase_dup [1, 0, 2, 2, 1] = [0, 2, 1] -/
def erase_dup [decidable_eq α] : list α → list α := pw_filter (≠)
/-- `range' s n` is the list of numbers `[s, s+1, ..., s+n-1]`.
It is intended mainly for proving properties of `range` and `iota`. -/
@[simp] def range' : ℕ → ℕ → list ℕ
| s 0 := []
| s (n+1) := s :: range' (s+1) n
/-- Drop `none`s from a list, and replace each remaining `some a` with `a`. -/
def reduce_option {α} : list (option α) → list α :=
list.filter_map id
/-- `ilast' x xs` returns the last element of `xs` if `xs` is non-empty;
it returns `x` otherwise -/
@[simp] def ilast' {α} : α → list α → α
| a [] := a
| a (b::l) := ilast' b l
/-- `last' xs` returns the last element of `xs` if `xs` is non-empty;
it returns `none` otherwise -/
@[simp] def last' {α} : list α → option α
| [] := none
| [a] := some a
| (b::l) := last' l
/-- `rotate l n` rotates the elements of `l` to the left by `n`
rotate [0, 1, 2, 3, 4, 5] 2 = [2, 3, 4, 5, 0, 1] -/
def rotate (l : list α) (n : ℕ) : list α :=
let (l₁, l₂) := list.split_at (n % l.length) l in l₂ ++ l₁
/-- rotate' is the same as `rotate`, but slower. Used for proofs about `rotate`-/
def rotate' : list α → ℕ → list α
| [] n := []
| l 0 := l
| (a::l) (n+1) := rotate' (l ++ [a]) n
section choose
variables (p : α → Prop) [decidable_pred p] (l : list α)
/-- Given a decidable predicate `p` and a proof of existence of `a ∈ l` such that `p a`,
choose the first element with this property. This version returns both `a` and proofs
of `a ∈ l` and `p a`. -/
def choose_x : Π l : list α, Π hp : (∃ a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a }
| [] hp := false.elim (exists.elim hp (assume a h, not_mem_nil a h.left))
| (l :: ls) hp := if pl : p l then ⟨l, ⟨or.inl rfl, pl⟩⟩ else
let ⟨a, ⟨a_mem_ls, pa⟩⟩ := choose_x ls (hp.imp
(λ b ⟨o, h₂⟩, ⟨o.resolve_left (λ e, pl $ e ▸ h₂), h₂⟩)) in
⟨a, ⟨or.inr a_mem_ls, pa⟩⟩
/-- Given a decidable predicate `p` and a proof of existence of `a ∈ l` such that `p a`,
choose the first element with this property. This version returns `a : α`, and properties
are given by `choose_mem` and `choose_property`. -/
def choose (hp : ∃ a, a ∈ l ∧ p a) : α := choose_x p l hp
end choose
/-- Filters and maps elements of a list -/
def mmap_filter {m : Type → Type v} [monad m] {α β} (f : α → m (option β)) :
list α → m (list β)
| [] := return []
| (h :: t) := do b ← f h, t' ← t.mmap_filter, return $
match b with none := t' | (some x) := x::t' end
/--
`mmap_upper_triangle f l` calls `f` on all elements in the upper triangular part of `l × l`.
That is, for each `e ∈ l`, it will run `f e e` and then `f e e'`
for each `e'` that appears after `e` in `l`.
Example: suppose `l = [1, 2, 3]`. `mmap_upper_triangle f l` will produce the list
`[f 1 1, f 1 2, f 1 3, f 2 2, f 2 3, f 3 3]`.
-/
def mmap_upper_triangle {m} [monad m] {α β : Type u} (f : α → α → m β) : list α → m (list β)
| [] := return []
| (h::t) := do v ← f h h, l ← t.mmap (f h), t ← t.mmap_upper_triangle, return $ (v::l) ++ t
/--
`mmap'_diag f l` calls `f` on all elements in the upper triangular part of `l × l`.
That is, for each `e ∈ l`, it will run `f e e` and then `f e e'`
for each `e'` that appears after `e` in `l`.
Example: suppose `l = [1, 2, 3]`. `mmap'_diag f l` will evaluate, in this order,
`f 1 1`, `f 1 2`, `f 1 3`, `f 2 2`, `f 2 3`, `f 3 3`.
-/
def mmap'_diag {m} [monad m] {α} (f : α → α → m unit) : list α → m unit
| [] := return ()
| (h::t) := f h h >> t.mmap' (f h) >> t.mmap'_diag
protected def traverse {F : Type u → Type v} [applicative F] {α β : Type*} (f : α → F β) :
list α → F (list β)
| [] := pure []
| (x :: xs) := list.cons <$> f x <*> traverse xs
/-- `get_rest l l₁` returns `some l₂` if `l = l₁ ++ l₂`.
If `l₁` is not a prefix of `l`, returns `none` -/
def get_rest [decidable_eq α] : list α → list α → option (list α)
| l [] := some l
| [] _ := none
| (x::l) (y::l₁) := if x = y then get_rest l l₁ else none
/--
`list.slice n m xs` removes a slice of length `m` at index `n` in list `xs`.
-/
def slice {α} : ℕ → ℕ → list α → list α
| 0 n xs := xs.drop n
| (succ n) m [] := []
| (succ n) m (x :: xs) := x :: slice n m xs
/--
Left-biased version of `list.map₂`. `map₂_left' f as bs` applies `f` to each
pair of elements `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, `f` is
applied to `none` for the remaining `aᵢ`. Returns the results of the `f`
applications and the remaining `bs`.
```
map₂_left' prod.mk [1, 2] ['a'] = ([(1, some 'a'), (2, none)], [])
map₂_left' prod.mk [1] ['a', 'b'] = ([(1, some 'a')], ['b'])
```
-/
@[simp] def map₂_left' (f : α → option β → γ) : list α → list β → (list γ × list β)
| [] bs := ([], bs)
| (a :: as) [] :=
((a :: as).map (λ a, f a none), [])
| (a :: as) (b :: bs) :=
let rec := map₂_left' as bs in
(f a (some b) :: rec.fst, rec.snd)
/--
Right-biased version of `list.map₂`. `map₂_right' f as bs` applies `f` to each
pair of elements `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, `f` is
applied to `none` for the remaining `bᵢ`. Returns the results of the `f`
applications and the remaining `as`.
```
map₂_right' prod.mk [1] ['a', 'b'] = ([(some 1, 'a'), (none, 'b')], [])
map₂_right' prod.mk [1, 2] ['a'] = ([(some 1, 'a')], [2])
```
-/
def map₂_right' (f : option α → β → γ) (as : list α) (bs : list β) : (list γ × list α) :=
map₂_left' (flip f) bs as
/--
Left-biased version of `list.zip`. `zip_left' as bs` returns the list of
pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, the
remaining `aᵢ` are paired with `none`. Also returns the remaining `bs`.
```
zip_left' [1, 2] ['a'] = ([(1, some 'a'), (2, none)], [])
zip_left' [1] ['a', 'b'] = ([(1, some 'a')], ['b'])
zip_left' = map₂_left' prod.mk
```
-/
def zip_left' : list α → list β → list (α × option β) × list β :=
map₂_left' prod.mk
/--
Right-biased version of `list.zip`. `zip_right' as bs` returns the list of
pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, the
remaining `bᵢ` are paired with `none`. Also returns the remaining `as`.
```
zip_right' [1] ['a', 'b'] = ([(some 1, 'a'), (none, 'b')], [])
zip_right' [1, 2] ['a'] = ([(some 1, 'a')], [2])
zip_right' = map₂_right' prod.mk
```
-/
def zip_right' : list α → list β → list (option α × β) × list α :=
map₂_right' prod.mk
/--
Left-biased version of `list.map₂`. `map₂_left f as bs` applies `f` to each pair
`aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, `f` is applied to `none`
for the remaining `aᵢ`.
```
map₂_left prod.mk [1, 2] ['a'] = [(1, some 'a'), (2, none)]
map₂_left prod.mk [1] ['a', 'b'] = [(1, some 'a')]
map₂_left f as bs = (map₂_left' f as bs).fst
```
-/
@[simp] def map₂_left (f : α → option β → γ) : list α → list β → list γ
| [] _ := []
| (a :: as) [] := (a :: as).map (λ a, f a none)
| (a :: as) (b :: bs) := f a (some b) :: map₂_left as bs
/--
Right-biased version of `list.map₂`. `map₂_right f as bs` applies `f` to each
pair `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, `f` is applied to
`none` for the remaining `bᵢ`.
```
map₂_right prod.mk [1, 2] ['a'] = [(some 1, 'a')]
map₂_right prod.mk [1] ['a', 'b'] = [(some 1, 'a'), (none, 'b')]
map₂_right f as bs = (map₂_right' f as bs).fst
```
-/
def map₂_right (f : option α → β → γ) (as : list α) (bs : list β) :
list γ :=
map₂_left (flip f) bs as
/--
Left-biased version of `list.zip`. `zip_left as bs` returns the list of pairs
`(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, the
remaining `aᵢ` are paired with `none`.
```
zip_left [1, 2] ['a'] = [(1, some 'a'), (2, none)]
zip_left [1] ['a', 'b'] = [(1, some 'a')]
zip_left = map₂_left prod.mk
```
-/
def zip_left : list α → list β → list (α × option β) :=
map₂_left prod.mk
/--
Right-biased version of `list.zip`. `zip_right as bs` returns the list of pairs
`(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, the
remaining `bᵢ` are paired with `none`.
```
zip_right [1, 2] ['a'] = [(some 1, 'a')]
zip_right [1] ['a', 'b'] = [(some 1, 'a'), (none, 'b')]
zip_right = map₂_right prod.mk
```
-/
def zip_right : list α → list β → list (option α × β) :=
map₂_right prod.mk
end list
|
aac2220d574107a34864ee2434c050e92a7e13d2 | 30b012bb72d640ec30c8fdd4c45fdfa67beb012c | /data/set/countable.lean | cb4bfbb4ae655af71d92504d70ef057def15c74e | [
"Apache-2.0"
] | permissive | kckennylau/mathlib | 21fb810b701b10d6606d9002a4004f7672262e83 | 47b3477e20ffb5a06588dd3abb01fe0fe3205646 | refs/heads/master | 1,634,976,409,281 | 1,542,042,832,000 | 1,542,319,733,000 | 109,560,458 | 0 | 0 | Apache-2.0 | 1,542,369,208,000 | 1,509,867,494,000 | Lean | UTF-8 | Lean | false | false | 5,342 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl
Countable sets.
-/
import data.equiv.list data.set.finite logic.function data.set.function
noncomputable theory
open function set encodable
open classical (hiding some)
local attribute [instance] prop_decidable
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
namespace set
/-- Countable sets
A set is countable if there exists an encoding of the set into the natural numbers.
An encoding is an injection with a partial inverse, which can be viewed as a
constructive analogue of countability. (For the most part, theorems about
`countable` will be classical and `encodable` will be constructive.)
-/
def countable (s : set α) : Prop := nonempty (encodable s)
lemma countable_iff_exists_injective {s : set α} :
countable s ↔ ∃f:s → ℕ, injective f :=
⟨λ ⟨h⟩, by exactI ⟨encode, encode_injective⟩,
λ ⟨f, h⟩, ⟨⟨f, partial_inv f, partial_inv_left h⟩⟩⟩
lemma countable_iff_exists_inj_on {s : set α} :
countable s ↔ ∃ f : α → ℕ, inj_on f s :=
countable_iff_exists_injective.trans
⟨λ ⟨f, hf⟩, ⟨λ a, if h : a ∈ s then f ⟨a, h⟩ else 0,
λ a b as bs h, congr_arg subtype.val $
hf $ by simpa [as, bs] using h⟩,
λ ⟨f, hf⟩, ⟨_, inj_on_iff_injective.1 hf⟩⟩
lemma countable_iff_exists_surjective [ne : inhabited α] {s : set α} :
countable s ↔ ∃f:ℕ → α, s ⊆ range f :=
⟨λ ⟨h⟩, by exactI ⟨λ n, ((decode s n).map subtype.val).iget,
λ a as, ⟨encode (⟨a, as⟩ : s), by simp [encodek]⟩⟩,
λ ⟨f, hf⟩, ⟨⟨
λ x, inv_fun f x.1,
λ n, if h : f n ∈ s then some ⟨f n, h⟩ else none,
λ ⟨x, hx⟩, begin
have := inv_fun_eq (hf hx), dsimp at this ⊢,
simp [this, hx]
end⟩⟩⟩
def countable.to_encodable {s : set α} : countable s → encodable s :=
classical.choice
lemma countable_encodable' (s : set α) [H : encodable s] : countable s :=
⟨H⟩
lemma countable_encodable [encodable α] (s : set α) : countable s :=
⟨by apply_instance⟩
@[simp] lemma countable_empty : countable (∅ : set α) :=
⟨⟨λ x, x.2.elim, λ n, none, λ x, x.2.elim⟩⟩
@[simp] lemma countable_singleton (a : α) : countable ({a} : set α) :=
⟨of_equiv _ (equiv.set.singleton a)⟩
lemma countable_subset {s₁ s₂ : set α} (h : s₁ ⊆ s₂) : countable s₂ → countable s₁
| ⟨H⟩ := ⟨@of_inj _ _ H _ (embedding_of_subset h).2⟩
lemma countable_image {s : set α} (f : α → β) (hs : countable s) : countable (f '' s) :=
let f' : s → f '' s := λ⟨a, ha⟩, ⟨f a, mem_image_of_mem f ha⟩ in
have hf' : surjective f', from assume ⟨b, a, ha, hab⟩, ⟨⟨a, ha⟩, subtype.eq hab⟩,
⟨@encodable.of_inj _ _ hs.to_encodable (surj_inv hf') (injective_surj_inv hf')⟩
lemma countable_range [encodable α] (f : α → β) : countable (range f) :=
by rw ← image_univ; exact countable_image _ (countable_encodable _)
lemma countable_Union {t : α → set β} [encodable α] (ht : ∀a, countable (t a)) :
countable (⋃a, t a) :=
by haveI := (λ a, (ht a).to_encodable);
rw Union_eq_range_sigma; apply countable_range
lemma countable_bUnion {s : set α} {t : α → set β} (hs : countable s) (ht : ∀a∈s, countable (t a)) :
countable (⋃a∈s, t a) :=
begin
rw bUnion_eq_Union,
haveI := hs.to_encodable,
exact countable_Union (by simpa using ht)
end
lemma countable_sUnion {s : set (set α)} (hs : countable s) (h : ∀a∈s, countable a) :
countable (⋃₀ s) :=
by rw sUnion_eq_bUnion; exact countable_bUnion hs h
lemma countable_Union_Prop {p : Prop} {t : p → set β} (ht : ∀h:p, countable (t h)) :
countable (⋃h:p, t h) :=
by by_cases p; simp [h, ht]
lemma countable_union {s₁ s₂ : set α} (h₁ : countable s₁) (h₂ : countable s₂) : countable (s₁ ∪ s₂) :=
by rw union_eq_Union; exact
countable_Union (bool.forall_bool.2 ⟨h₂, h₁⟩)
lemma countable_insert {s : set α} {a : α} (h : countable s) : countable (insert a s) :=
by rw [set.insert_eq]; from countable_union (countable_singleton _) h
lemma countable_finite {s : set α} : finite s → countable s
| ⟨h⟩ := nonempty_of_trunc (by exactI trunc_encodable_of_fintype s)
lemma countable_set_of_finite_subset {s : set α} : countable s →
countable {t | finite t ∧ t ⊆ s} | ⟨h⟩ :=
begin
resetI,
refine countable_subset _ (countable_range
(λ t : finset s, {a | ∃ h:a ∈ s, subtype.mk a h ∈ t})),
rintro t ⟨⟨ht⟩, ts⟩,
refine ⟨finset.univ.map (embedding_of_subset ts),
set.ext $ λ a, _⟩,
simp, split,
{ rintro ⟨as, b, bt, e⟩,
cases congr_arg subtype.val e, exact bt },
{ exact λ h, ⟨ts h, _, h, rfl⟩ }
end
lemma countable_pi {π : α → Type*} [fintype α] {s : Πa, set (π a)} (hs : ∀a, countable (s a)) :
countable {f : Πa, π a | ∀a, f a ∈ s a} :=
countable_subset
(show {f : Πa, π a | ∀a, f a ∈ s a} ⊆ range (λf : Πa, s a, λa, (f a).1), from
assume f hf, ⟨λa, ⟨f a, hf a⟩, funext $ assume a, rfl⟩) $
have trunc (encodable (Π (a : α), s a)), from
@encodable.fintype_pi α _ _ _ (assume a, (hs a).to_encodable),
trunc.induction_on this $ assume h,
@countable_range _ _ h _
end set
|
a85f8acb0b89e2f0e068423cd4763949517d77a7 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/ring_theory/dedekind_domain/integral_closure.lean | 9c7c808642bfabd0f2c3e80e233a2e9fe2897548 | [
"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 | 10,273 | lean | /-
Copyright (c) 2020 Kenji Nakagawa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenji Nakagawa, Anne Baanen, Filippo A. E. Nuccio
-/
import ring_theory.dedekind_domain.basic
import ring_theory.trace
/-!
# Integral closure of Dedekind domains
This file shows the integral closure of a Dedekind domain (in particular, the ring of integers
of a number field) is a Dedekind domain.
## Implementation notes
The definitions that involve a field of fractions choose a canonical field of fractions,
but are independent of that choice. The `..._iff` lemmas express this independence.
Often, definitions assume that Dedekind domains are not fields. We found it more practical
to add a `(h : ¬ is_field A)` assumption whenever this is explicitly needed.
## References
* [D. Marcus, *Number Fields*][marcus1977number]
* [J.W.S. Cassels, A. Frölich, *Algebraic Number Theory*][cassels1967algebraic]
* [J. Neukirch, *Algebraic Number Theory*][Neukirch1992]
## Tags
dedekind domain, dedekind ring
-/
variables (R A K : Type*) [comm_ring R] [comm_ring A] [field K]
open_locale non_zero_divisors polynomial
variables [is_domain A]
section is_integral_closure
/-! ### `is_integral_closure` section
We show that an integral closure of a Dedekind domain in a finite separable
field extension is again a Dedekind domain. This implies the ring of integers
of a number field is a Dedekind domain. -/
open algebra
open_locale big_operators
variables {A K} [algebra A K] [is_fraction_ring A K]
variables {L : Type*} [field L] (C : Type*) [comm_ring C]
variables [algebra K L] [finite_dimensional K L] [algebra A L] [is_scalar_tower A K L]
variables [algebra C L] [is_integral_closure C A L] [algebra A C] [is_scalar_tower A C L]
lemma is_integral_closure.range_le_span_dual_basis [is_separable K L]
{ι : Type*} [fintype ι] [decidable_eq ι] (b : basis ι K L)
(hb_int : ∀ i, is_integral A (b i)) [is_integrally_closed A] :
((algebra.linear_map C L).restrict_scalars A).range ≤
submodule.span A (set.range $ (trace_form K L).dual_basis (trace_form_nondegenerate K L) b) :=
begin
let db := (trace_form K L).dual_basis (trace_form_nondegenerate K L) b,
rintros _ ⟨x, rfl⟩,
simp only [linear_map.coe_restrict_scalars_eq_coe, algebra.linear_map_apply],
have hx : is_integral A (algebra_map C L x) :=
(is_integral_closure.is_integral A L x).algebra_map,
suffices : ∃ (c : ι → A), algebra_map C L x = ∑ i, c i • db i,
{ obtain ⟨c, x_eq⟩ := this,
rw x_eq,
refine submodule.sum_mem _ (λ i _, submodule.smul_mem _ _ (submodule.subset_span _)),
rw set.mem_range,
exact ⟨i, rfl⟩ },
suffices : ∃ (c : ι → K), ((∀ i, is_integral A (c i)) ∧ algebra_map C L x = ∑ i, c i • db i),
{ obtain ⟨c, hc, hx⟩ := this,
have hc' : ∀ i, is_localization.is_integer A (c i) :=
λ i, is_integrally_closed.is_integral_iff.mp (hc i),
use λ i, classical.some (hc' i),
refine hx.trans (finset.sum_congr rfl (λ i _, _)),
conv_lhs { rw [← classical.some_spec (hc' i)] },
rw [← is_scalar_tower.algebra_map_smul K (classical.some (hc' i)) (db i)] },
refine ⟨λ i, db.repr (algebra_map C L x) i, (λ i, _), (db.sum_repr _).symm⟩,
rw bilin_form.dual_basis_repr_apply,
exact is_integral_trace (is_integral_mul hx (hb_int i))
end
lemma integral_closure_le_span_dual_basis [is_separable K L]
{ι : Type*} [fintype ι] [decidable_eq ι] (b : basis ι K L)
(hb_int : ∀ i, is_integral A (b i)) [is_integrally_closed A] :
(integral_closure A L).to_submodule ≤ submodule.span A (set.range $
(trace_form K L).dual_basis (trace_form_nondegenerate K L) b) :=
begin
refine le_trans _ (is_integral_closure.range_le_span_dual_basis (integral_closure A L) b hb_int),
intros x hx,
exact ⟨⟨x, hx⟩, rfl⟩
end
variables (A) (K)
include K
/-- Send a set of `x`'es in a finite extension `L` of the fraction field of `R`
to `(y : R) • x ∈ integral_closure R L`. -/
lemma exists_integral_multiples (s : finset L) :
∃ (y ≠ (0 : A)), ∀ x ∈ s, is_integral A (y • x) :=
begin
haveI := classical.dec_eq L,
refine s.induction _ _,
{ use [1, one_ne_zero],
rintros x ⟨⟩ },
{ rintros x s hx ⟨y, hy, hs⟩,
obtain ⟨x', y', hy', hx'⟩ := exists_integral_multiple
((is_fraction_ring.is_algebraic_iff A K L).mpr (is_algebraic_of_finite _ _ x))
((injective_iff_map_eq_zero (algebra_map A L)).mp _),
refine ⟨y * y', mul_ne_zero hy hy', λ x'' hx'', _⟩,
rcases finset.mem_insert.mp hx'' with (rfl | hx''),
{ rw [mul_smul, algebra.smul_def, algebra.smul_def, mul_comm _ x'', hx'],
exact is_integral_mul is_integral_algebra_map x'.2 },
{ rw [mul_comm, mul_smul, algebra.smul_def],
exact is_integral_mul is_integral_algebra_map (hs _ hx'') },
{ rw is_scalar_tower.algebra_map_eq A K L,
apply (algebra_map K L).injective.comp,
exact is_fraction_ring.injective _ _ } }
end
variables (L)
/-- If `L` is a finite extension of `K = Frac(A)`,
then `L` has a basis over `A` consisting of integral elements. -/
lemma finite_dimensional.exists_is_basis_integral :
∃ (s : finset L) (b : basis s K L), (∀ x, is_integral A (b x)) :=
begin
letI := classical.dec_eq L,
letI : is_noetherian K L := is_noetherian.iff_fg.2 infer_instance,
let s' := is_noetherian.finset_basis_index K L,
let bs' := is_noetherian.finset_basis K L,
obtain ⟨y, hy, his'⟩ := exists_integral_multiples A K (finset.univ.image bs'),
have hy' : algebra_map A L y ≠ 0,
{ refine mt ((injective_iff_map_eq_zero (algebra_map A L)).mp _ _) hy,
rw is_scalar_tower.algebra_map_eq A K L,
exact (algebra_map K L).injective.comp (is_fraction_ring.injective A K) },
refine ⟨s', bs'.map { to_fun := λ x, algebra_map A L y * x,
inv_fun := λ x, (algebra_map A L y)⁻¹ * x,
left_inv := _,
right_inv := _,
.. algebra.lmul _ _ (algebra_map A L y) },
_⟩,
{ intros x, simp only [inv_mul_cancel_left₀ hy'] },
{ intros x, simp only [mul_inv_cancel_left₀ hy'] },
{ rintros ⟨x', hx'⟩,
simp only [algebra.smul_def, finset.mem_image, exists_prop, finset.mem_univ, true_and] at his',
simp only [basis.map_apply, linear_equiv.coe_mk],
exact his' _ ⟨_, rfl⟩ }
end
variables (A K L) [is_separable K L]
include L
/- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is
integrally closed and Noetherian, the integral closure `C` of `A` in `L` is
Noetherian over `A`. -/
lemma is_integral_closure.is_noetherian [is_integrally_closed A] [is_noetherian_ring A] :
is_noetherian A C :=
begin
haveI := classical.dec_eq L,
obtain ⟨s, b, hb_int⟩ := finite_dimensional.exists_is_basis_integral A K L,
let b' := (trace_form K L).dual_basis (trace_form_nondegenerate K L) b,
letI := is_noetherian_span_of_finite A (set.finite_range b'),
let f : C →ₗ[A] submodule.span A (set.range b') :=
(submodule.of_le (is_integral_closure.range_le_span_dual_basis C b hb_int)).comp
((algebra.linear_map C L).restrict_scalars A).range_restrict,
refine is_noetherian_of_ker_bot f _,
rw [linear_map.ker_comp, submodule.ker_of_le, submodule.comap_bot, linear_map.ker_cod_restrict],
exact linear_map.ker_eq_bot_of_injective (is_integral_closure.algebra_map_injective C A L)
end
/- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is
integrally closed and Noetherian, the integral closure `C` of `A` in `L` is
Noetherian. -/
lemma is_integral_closure.is_noetherian_ring [is_integrally_closed A] [is_noetherian_ring A] :
is_noetherian_ring C :=
is_noetherian_ring_iff.mpr $ is_noetherian_of_tower A (is_integral_closure.is_noetherian A K L C)
variables {A K}
/- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is
integrally closed and Noetherian, the integral closure of `A` in `L` is
Noetherian. -/
lemma integral_closure.is_noetherian_ring [is_integrally_closed A] [is_noetherian_ring A] :
is_noetherian_ring (integral_closure A L) :=
is_integral_closure.is_noetherian_ring A K L (integral_closure A L)
variables (A K) [is_domain C]
/- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is a Dedekind domain,
the integral closure `C` of `A` in `L` is a Dedekind domain.
Can't be an instance since `A`, `K` or `L` can't be inferred. See also the instance
`integral_closure.is_dedekind_domain_fraction_ring` where `K := fraction_ring A`
and `C := integral_closure A L`.
-/
lemma is_integral_closure.is_dedekind_domain [h : is_dedekind_domain A] :
is_dedekind_domain C :=
begin
haveI : is_fraction_ring C L := is_integral_closure.is_fraction_ring_of_finite_extension A K L C,
exact
⟨is_integral_closure.is_noetherian_ring A K L C,
h.dimension_le_one.is_integral_closure _ L _,
(is_integrally_closed_iff L).mpr (λ x hx, ⟨is_integral_closure.mk' C x
(is_integral_trans (is_integral_closure.is_integral_algebra A L) _ hx),
is_integral_closure.algebra_map_mk' _ _ _⟩)⟩
end
/- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is a Dedekind domain,
the integral closure of `A` in `L` is a Dedekind domain.
Can't be an instance since `K` can't be inferred. See also the instance
`integral_closure.is_dedekind_domain_fraction_ring` where `K := fraction_ring A`.
-/
lemma integral_closure.is_dedekind_domain [h : is_dedekind_domain A] :
is_dedekind_domain (integral_closure A L) :=
is_integral_closure.is_dedekind_domain A K L (integral_closure A L)
omit K
variables [algebra (fraction_ring A) L] [is_scalar_tower A (fraction_ring A) L]
variables [finite_dimensional (fraction_ring A) L] [is_separable (fraction_ring A) L]
/- If `L` is a finite separable extension of `Frac(A)`, where `A` is a Dedekind domain,
the integral closure of `A` in `L` is a Dedekind domain.
See also the lemma `integral_closure.is_dedekind_domain` where you can choose
the field of fractions yourself.
-/
instance integral_closure.is_dedekind_domain_fraction_ring
[is_dedekind_domain A] : is_dedekind_domain (integral_closure A L) :=
integral_closure.is_dedekind_domain A (fraction_ring A) L
end is_integral_closure
|
970d3be6eb1a7a8d6234c080e93537f031838dfd | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /tests/lean/439.lean | e31c43acb3cb802a19d36753764b55f977a17baf | [
"Apache-2.0"
] | permissive | WojciechKarpiel/lean4 | 7f89706b8e3c1f942b83a2c91a3a00b05da0e65b | f6e1314fa08293dea66a329e05b6c196a0189163 | refs/heads/master | 1,686,633,402,214 | 1,625,821,189,000 | 1,625,821,258,000 | 384,640,886 | 0 | 0 | Apache-2.0 | 1,625,903,617,000 | 1,625,903,026,000 | null | UTF-8 | Lean | false | false | 747 | lean | universe u
structure Fn (E I : Sort u) := (exp : E) (imp : I)
instance (E I : Sort u) : CoeFun (Fn E I) (fun _ => I) := {coe := fun K => K.imp}
class Bar.{w} (P : Sort u) :=
fn : P -> Sort w
variable {P : Sort u} (B : Bar P)
variable (fn : Fn ((p : P) -> B.fn p) ({p : P} -> B.fn p))
#check coeFun fn -- Result is as expected (implicit)
/-
fn : {p : P} → Bar.fn p
-/
variable (p : P)
variable (Bp : Bar.fn p)
#check fn Bp
/-
application type mismatch
Fn.imp fn Bp
argument
Bp
has type
Bar.fn p : Sort ?u.635
but is expected to have type
P : Sort u
-/
#check fn p
#check fn (p := p)
variable (fn' : Fn ((p : P) -> B.fn p -> B.fn p) ({p : P} -> B.fn p -> B.fn p))
-- Expect no error
#check fn' Bp
-- Expect error
#check fn' p
|
ca806718e6b89be09e86b77d3e1774a9ab7b0c68 | 0845ae2ca02071debcfd4ac24be871236c01784f | /library/init/lean/parser/trie.lean | 121907d971b853ad1a00c81a0c52309809a33844 | [
"Apache-2.0"
] | permissive | GaloisInc/lean4 | 74c267eb0e900bfaa23df8de86039483ecbd60b7 | 228ddd5fdcd98dd4e9c009f425284e86917938aa | refs/heads/master | 1,643,131,356,301 | 1,562,715,572,000 | 1,562,715,572,000 | 192,390,898 | 0 | 0 | null | 1,560,792,750,000 | 1,560,792,749,000 | null | UTF-8 | Lean | false | false | 2,881 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Sebastian Ullrich, Leonardo de Moura
Trie for tokenizing the Lean language
-/
prelude
import init.data.rbmap
import init.lean.format
namespace Lean
namespace Parser
inductive Trie (α : Type)
| Node : Option α → RBNode Char (fun _ => Trie) → Trie
namespace Trie
variables {α : Type}
def empty : Trie α :=
⟨none, RBNode.leaf⟩
instance : HasEmptyc (Trie α) :=
⟨empty⟩
instance : Inhabited (Trie α) :=
⟨Node none RBNode.leaf⟩
private partial def insertEmptyAux (s : String) (val : α) : String.Pos → Trie α
| i := match s.atEnd i with
| true => Trie.Node (some val) RBNode.leaf
| false =>
let c := s.get i;
let t := insertEmptyAux (s.next i);
Trie.Node none (RBNode.singleton c t)
private partial def insertAux (s : String) (val : α) : Trie α → String.Pos → Trie α
| (Trie.Node v m) i :=
match s.atEnd i with
| true => Trie.Node (some val) m -- overrides old value
| false =>
let c := s.get i;
let i := s.next i;
let t := match RBNode.find Char.lt m c with
| none => insertEmptyAux s val i
| some t => insertAux t i;
Trie.Node v (RBNode.insert Char.lt m c t)
def insert (t : Trie α) (s : String) (val : α) : Trie α :=
insertAux s val t 0
private partial def findAux (s : String) : Trie α → String.Pos → Option α
| (Trie.Node val m) i :=
match s.atEnd i with
| true => val
| false =>
let c := s.get i;
let i := s.next i;
match RBNode.find Char.lt m c with
| none => none
| some t => findAux t i
def find (t : Trie α) (s : String) : Option α :=
findAux s t 0
private def updtAcc (v : Option α) (i : String.Pos) (acc : String.Pos × Option α) : String.Pos × Option α :=
match v, acc with
| some v, (j, w) => (i, some v) -- we pattern match on `acc` to enable memory reuse
| none, acc => acc
private partial def matchPrefixAux (s : String) : Trie α → String.Pos → (String.Pos × Option α) → String.Pos × Option α
| (Trie.Node v m) i acc :=
match s.atEnd i with
| true => updtAcc v i acc
| false =>
let acc := updtAcc v i acc;
let c := s.get i;
let i := s.next i;
match RBNode.find Char.lt m c with
| some t => matchPrefixAux t i acc
| none => acc
def matchPrefix (s : String) (t : Trie α) (i : String.Pos) : String.Pos × Option α :=
matchPrefixAux s t i (i, none)
private partial def toStringAux {α : Type} : Trie α → List Format
| (Trie.Node val map) := map.fold (fun Fs c t =>
format (repr c) :: (Format.group $ Format.nest 2 $ flip Format.joinSep Format.line $ toStringAux t) :: Fs) []
instance {α : Type} : HasToString (Trie α) :=
⟨fun t => (flip Format.joinSep Format.line $ toStringAux t).pretty⟩
end Trie
end Parser
end Lean
|
33df33b10fe37a83b94b4cdc3ba3cc821531ee01 | 6fca17f8d5025f89be1b2d9d15c9e0c4b4900cbf | /src/game/world10/level8.lean | 8b3dc8b576ad84f9c2701a699768d8faf6a392dc | [
"Apache-2.0"
] | permissive | arolihas/natural_number_game | 4f0c93feefec93b8824b2b96adff8b702b8b43ce | 8e4f7b4b42888a3b77429f90cce16292bd288138 | refs/heads/master | 1,621,872,426,808 | 1,586,270,467,000 | 1,586,270,467,000 | 253,648,466 | 0 | 0 | null | 1,586,219,694,000 | 1,586,219,694,000 | null | UTF-8 | Lean | false | false | 375 | lean | import game.world10.level7 -- hide
namespace mynat -- hide
/-
# Inequality world.
## Level 8: `succ_le_succ`
Another straightforward one.
-/
/- Lemma
For all naturals $a$ and $b$, if $a\le b$, then $\operatorname{succ}(a)\le\operatorname{succ}(b)$.
-/
lemma succ_le_succ (a b : mynat) (h : a ≤ b) : succ a ≤ succ b :=
begin [nat_num_game]
end
end mynat -- hide
|
16260d447793009a684b0be6b6bb1af5905b218b | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/rb_map1.lean | 9e2628217128475ac59c8b12b5583b9a20ed806b | [
"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 | 786 | lean | import system.io
open io
section
open native.nat_map
#eval size (insert (insert (mk nat) 10 20) 10 21)
meta definition m := (insert (insert (insert (mk nat) 10 20) 5 50) 10 21)
#eval find m 10
#eval find m 5
#eval find m 8
#eval contains m 5
#eval contains m 8
open list
meta definition m2 := of_list [((1:nat), "one"), (2, "two"), (3, "three")]
#eval size m2
#eval find m2 1
#eval find m2 4
#eval find m2 3
section
#eval do pp m2, put_str "\n"
end
#eval m2
end
section
open native.rb_map
instance : has_lt (nat × nat) := { lt := λ a b, a.1 < b.1 ∨ a.1 = b.1 ∧ a.2 < b.2 }
-- Mapping from (nat × nat) → nat
meta definition m3 := insert (insert (mk (nat × nat) nat) (1, 2) 3) (2, 2) 4
#eval find m3 (1, 2)
#eval find m3 (2, 1)
#eval find m3 (2, 2)
#eval pp m3
end
|
9303b8d1873c17e91fd23ec2e39fba306c6c8ef0 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/analysis/calculus/extend_deriv.lean | f29f87d24d725fbdb5b133ffc811b6909ad84ccc | [
"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 | 11,068 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import analysis.calculus.mean_value
import tactic.monotonicity
/-!
# Extending differentiability to the boundary
We investigate how differentiable functions inside a set extend to differentiable functions
on the boundary. For this, it suffices that the function and its derivative admit limits there.
A general version of this statement is given in `has_fderiv_at_boundary_of_tendsto_fderiv`.
One-dimensional versions, in which one wants to obtain differentiability at the left endpoint or
the right endpoint of an interval, are given in
`has_deriv_at_interval_left_endpoint_of_tendsto_deriv` and
`has_deriv_at_interval_right_endpoint_of_tendsto_deriv`. These versions are formulated in terms
of the one-dimensional derivative `deriv ℝ f`.
-/
variables {E : Type*} [normed_group E] [normed_space ℝ E]
{F : Type*} [normed_group F] [normed_space ℝ F]
open filter set metric continuous_linear_map
open_locale topological_space
local attribute [mono] prod_mono
/-- If a function `f` is differentiable in a convex open set and continuous on its closure, and its
derivative converges to a limit `f'` at a point on the boundary, then `f` is differentiable there
with derivative `f'`. -/
theorem has_fderiv_at_boundary_of_tendsto_fderiv {f : E → F} {s : set E} {x : E} {f' : E →L[ℝ] F}
(f_diff : differentiable_on ℝ f s) (s_conv : convex s) (s_open : is_open s)
(f_cont : ∀y ∈ closure s, continuous_within_at f s y)
(h : tendsto (λy, fderiv ℝ f y) (𝓝[s] x) (𝓝 f')) :
has_fderiv_within_at f f' (closure s) x :=
begin
classical,
-- one can assume without loss of generality that `x` belongs to the closure of `s`, as the
-- statement is empty otherwise
by_cases hx : x ∉ closure s,
{ rw ← closure_closure at hx, exact has_fderiv_within_at_of_not_mem_closure hx },
push_neg at hx,
rw [has_fderiv_within_at, has_fderiv_at_filter, asymptotics.is_o_iff],
/- One needs to show that `∥f y - f x - f' (y - x)∥ ≤ ε ∥y - x∥` for `y` close to `x` in `closure
s`, where `ε` is an arbitrary positive constant. By continuity of the functions, it suffices to
prove this for nearby points inside `s`. In a neighborhood of `x`, the derivative of `f` is
arbitrarily close to f' by assumption. The mean value inequality completes the proof. -/
assume ε ε_pos,
obtain ⟨δ, δ_pos, hδ⟩ : ∃ δ > 0, ∀ y ∈ s, dist y x < δ → ∥fderiv ℝ f y - f'∥ < ε,
by simpa [dist_zero_right] using tendsto_nhds_within_nhds.1 h ε ε_pos,
set B := ball x δ,
suffices : ∀ y ∈ B ∩ (closure s), ∥f y - f x - (f' y - f' x)∥ ≤ ε * ∥y - x∥,
from mem_nhds_within_iff.2 ⟨δ, δ_pos, λy hy, by simpa using this y hy⟩,
suffices : ∀ p : E × E, p ∈ closure ((B ∩ s).prod (B ∩ s)) → ∥f p.2 - f p.1 - (f' p.2 - f' p.1)∥
≤ ε * ∥p.2 - p.1∥,
{ rw closure_prod_eq at this,
intros y y_in,
apply this ⟨x, y⟩,
have : B ∩ closure s ⊆ closure (B ∩ s), from closure_inter_open is_open_ball,
exact ⟨this ⟨mem_ball_self δ_pos, hx⟩, this y_in⟩ },
have key : ∀ p : E × E, p ∈ (B ∩ s).prod (B ∩ s) → ∥f p.2 - f p.1 - (f' p.2 - f' p.1)∥
≤ ε * ∥p.2 - p.1∥,
{ rintros ⟨u, v⟩ ⟨u_in, v_in⟩,
have conv : convex (B ∩ s) := (convex_ball _ _).inter s_conv,
have diff : differentiable_on ℝ f (B ∩ s) := f_diff.mono (inter_subset_right _ _),
have bound : ∀ z ∈ (B ∩ s), ∥fderiv_within ℝ f (B ∩ s) z - f'∥ ≤ ε,
{ intros z z_in,
convert le_of_lt (hδ _ z_in.2 z_in.1),
have op : is_open (B ∩ s) := is_open_inter is_open_ball s_open,
rw differentiable_at.fderiv_within _ (op.unique_diff_on z z_in),
exact (diff z z_in).differentiable_at (mem_nhds_sets op z_in) },
simpa using conv.norm_image_sub_le_of_norm_fderiv_within_le' diff bound u_in v_in },
rintros ⟨u, v⟩ uv_in,
refine continuous_within_at.closure_le uv_in _ _ key,
have f_cont' : ∀y ∈ closure s, continuous_within_at (f - f') s y,
{ intros y y_in,
exact tendsto.sub (f_cont y y_in) (f'.cont.continuous_within_at) },
all_goals { -- common start for both continuity proofs
have : (B ∩ s).prod (B ∩ s) ⊆ s.prod s, by mono ; exact inter_subset_right _ _,
obtain ⟨u_in, v_in⟩ : u ∈ closure s ∧ v ∈ closure s,
by simpa [closure_prod_eq] using closure_mono this uv_in,
apply continuous_within_at.mono _ this,
simp only [continuous_within_at] },
rw nhds_within_prod_eq,
{ have : f v - f u - (f' v - f' u) = f v - f' v - (f u - f' u) := by abel,
rw this,
convert tendsto.comp continuous_norm.continuous_at
((tendsto.comp (f_cont' v v_in) tendsto_snd).sub $ tendsto.comp (f_cont' u u_in) tendsto_fst),
intros, simp, abel },
{ apply tendsto_nhds_within_of_tendsto_nhds,
rw nhds_prod_eq,
exact tendsto_const_nhds.mul
(tendsto.comp continuous_norm.continuous_at $ tendsto_snd.sub tendsto_fst) },
end
/-- If a function is differentiable on the right of a point `a : ℝ`, continuous at `a`, and
its derivative also converges at `a`, then `f` is differentiable on the right at `a`. -/
lemma has_deriv_at_interval_left_endpoint_of_tendsto_deriv {s : set ℝ} {e : E} {a : ℝ} {f : ℝ → E}
(f_diff : differentiable_on ℝ f s) (f_lim : continuous_within_at f s a)
(hs : s ∈ 𝓝[Ioi a] a)
(f_lim' : tendsto (λx, deriv f x) (𝓝[Ioi a] a) (𝓝 e)) :
has_deriv_within_at f e (Ici a) a :=
begin
/- This is a specialization of `has_fderiv_at_boundary_of_tendsto_fderiv`. To be in the setting of
this theorem, we need to work on an open interval with closure contained in `s ∪ {a}`, that we
call `t = (a, b)`. Then, we check all the assumptions of this theorem and we apply it. -/
obtain ⟨b, ab, sab⟩ : ∃ b ∈ Ioi a, Ioc a b ⊆ s :=
mem_nhds_within_Ioi_iff_exists_Ioc_subset.1 hs,
let t := Ioo a b,
have ts : t ⊆ s := subset.trans Ioo_subset_Ioc_self sab,
have t_diff : differentiable_on ℝ f t := f_diff.mono ts,
have t_conv : convex t := convex_Ioo a b,
have t_open : is_open t := is_open_Ioo,
have t_closure : closure t = Icc a b := closure_Ioo ab,
have t_cont : ∀y ∈ closure t, continuous_within_at f t y,
{ rw t_closure,
assume y hy,
by_cases h : y = a,
{ rw h, exact f_lim.mono ts },
{ have : y ∈ s := sab ⟨lt_of_le_of_ne hy.1 (ne.symm h), hy.2⟩,
exact (f_diff.continuous_on y this).mono ts } },
have t_diff' : tendsto (λx, fderiv ℝ f x) (𝓝[t] a) (𝓝 (smul_right 1 e)),
{ simp [deriv_fderiv.symm],
refine tendsto.comp is_bounded_bilinear_map_smul_right.continuous_right.continuous_at _,
exact tendsto_nhds_within_mono_left Ioo_subset_Ioi_self f_lim' },
-- now we can apply `has_fderiv_at_boundary_of_differentiable`
have : has_deriv_within_at f e (Icc a b) a,
{ rw [has_deriv_within_at_iff_has_fderiv_within_at, ← t_closure],
exact has_fderiv_at_boundary_of_tendsto_fderiv t_diff t_conv t_open t_cont t_diff' },
exact this.nhds_within (mem_nhds_within_Ici_iff_exists_Icc_subset.2 ⟨b, ab, subset.refl _⟩)
end
/-- If a function is differentiable on the left of a point `a : ℝ`, continuous at `a`, and
its derivative also converges at `a`, then `f` is differentiable on the left at `a`. -/
lemma has_deriv_at_interval_right_endpoint_of_tendsto_deriv {s : set ℝ} {e : E} {a : ℝ} {f : ℝ → E}
(f_diff : differentiable_on ℝ f s) (f_lim : continuous_within_at f s a)
(hs : s ∈ 𝓝[Iio a] a)
(f_lim' : tendsto (λx, deriv f x) (𝓝[Iio a] a) (𝓝 e)) :
has_deriv_within_at f e (Iic a) a :=
begin
/- This is a specialization of `has_fderiv_at_boundary_of_differentiable`. To be in the setting of
this theorem, we need to work on an open interval with closure contained in `s ∪ {a}`, that we
call `t = (b, a)`. Then, we check all the assumptions of this theorem and we apply it. -/
obtain ⟨b, ba, sab⟩ : ∃ b ∈ Iio a, Ico b a ⊆ s :=
mem_nhds_within_Iio_iff_exists_Ico_subset.1 hs,
let t := Ioo b a,
have ts : t ⊆ s := subset.trans Ioo_subset_Ico_self sab,
have t_diff : differentiable_on ℝ f t := f_diff.mono ts,
have t_conv : convex t := convex_Ioo b a,
have t_open : is_open t := is_open_Ioo,
have t_closure : closure t = Icc b a := closure_Ioo ba,
have t_cont : ∀y ∈ closure t, continuous_within_at f t y,
{ rw t_closure,
assume y hy,
by_cases h : y = a,
{ rw h, exact f_lim.mono ts },
{ have : y ∈ s := sab ⟨hy.1, lt_of_le_of_ne hy.2 h⟩,
exact (f_diff.continuous_on y this).mono ts } },
have t_diff' : tendsto (λx, fderiv ℝ f x) (𝓝[t] a) (𝓝 (smul_right 1 e)),
{ simp [deriv_fderiv.symm],
refine tendsto.comp is_bounded_bilinear_map_smul_right.continuous_right.continuous_at _,
exact tendsto_nhds_within_mono_left Ioo_subset_Iio_self f_lim' },
-- now we can apply `has_fderiv_at_boundary_of_differentiable`
have : has_deriv_within_at f e (Icc b a) a,
{ rw [has_deriv_within_at_iff_has_fderiv_within_at, ← t_closure],
exact has_fderiv_at_boundary_of_tendsto_fderiv t_diff t_conv t_open t_cont t_diff' },
exact this.nhds_within (mem_nhds_within_Iic_iff_exists_Icc_subset.2 ⟨b, ba, subset.refl _⟩)
end
/-- If a real function `f` has a derivative `g` everywhere but at a point, and `f` and `g` are
continuous at this point, then `g` is also the derivative of `f` at this point. -/
lemma has_deriv_at_of_has_deriv_at_of_ne {f g : ℝ → E} {x : ℝ}
(f_diff : ∀ y ≠ x, has_deriv_at f (g y) y)
(hf : continuous_at f x) (hg : continuous_at g x) :
has_deriv_at f (g x) x :=
begin
have A : has_deriv_within_at f (g x) (Ici x) x,
{ have diff : differentiable_on ℝ f (Ioi x) :=
λy hy, (f_diff y (ne_of_gt hy)).differentiable_at.differentiable_within_at,
-- next line is the nontrivial bit of this proof, appealing to differentiability
-- extension results.
apply has_deriv_at_interval_left_endpoint_of_tendsto_deriv diff hf.continuous_within_at
self_mem_nhds_within,
have : tendsto g (𝓝[Ioi x] x) (𝓝 (g x)) := tendsto_inf_left hg,
apply this.congr' _,
apply mem_sets_of_superset self_mem_nhds_within (λy hy, _),
exact (f_diff y (ne_of_gt hy)).deriv.symm },
have B : has_deriv_within_at f (g x) (Iic x) x,
{ have diff : differentiable_on ℝ f (Iio x) :=
λy hy, (f_diff y (ne_of_lt hy)).differentiable_at.differentiable_within_at,
-- next line is the nontrivial bit of this proof, appealing to differentiability
-- extension results.
apply has_deriv_at_interval_right_endpoint_of_tendsto_deriv diff hf.continuous_within_at
self_mem_nhds_within,
have : tendsto g (𝓝[Iio x] x) (𝓝 (g x)) := tendsto_inf_left hg,
apply this.congr' _,
apply mem_sets_of_superset self_mem_nhds_within (λy hy, _),
exact (f_diff y (ne_of_lt hy)).deriv.symm },
simpa using B.union A
end
|
de9436a1163f2259b5e7832d93355067618c0539 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /archive/imo/imo2011_q5.lean | 08d4e6a1b8da5518e47e1f9a4831452a285acfc6 | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 2,103 | lean | /-
Copyright (c) 2021 Alain Verberkmoes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alain Verberkmoes
-/
import data.int.basic
/-!
# IMO 2011 Q5
Let `f` be a function from the set of integers to the set
of positive integers. Suppose that, for any two integers
`m` and `n`, the difference `f(m) − f(n)` is divisible by
`f(m − n)`. Prove that, for all integers `m` and `n` with
`f(m) ≤ f(n)`, the number `f(n)` is divisible by `f(m)`.
-/
open int
theorem imo2011_q5 (f : ℤ → ℤ) (hpos : ∀ n : ℤ, 0 < f n)
(hdvd : ∀ m n : ℤ, f (m - n) ∣ f m - f n) :
∀ m n : ℤ, f m ≤ f n → f m ∣ f n :=
begin
intros m n h_fm_le_fn,
cases lt_or_eq_of_le h_fm_le_fn with h_fm_lt_fn h_fm_eq_fn,
{ -- m < n
let d := f m - f (m - n),
have h_fn_dvd_d : f n ∣ d,
{ rw ←sub_sub_self m n,
exact hdvd m (m - n) },
have h_d_lt_fn : d < f n,
{ calc d < f m : sub_lt_self _ (hpos (m - n))
... < f n : h_fm_lt_fn },
have h_neg_d_lt_fn : -d < f n,
{ calc -d = f (m - n) - f m : neg_sub _ _
... < f (m - n) : sub_lt_self _ (hpos m)
... ≤ f n - f m : le_of_dvd (sub_pos.mpr h_fm_lt_fn) _
... < f n : sub_lt_self _ (hpos m),
-- ⊢ f (m - n) ∣ f n - f m
rw [←dvd_neg, neg_sub], exact hdvd m n },
have h_d_eq_zero : d = 0,
{ obtain (hd | hd | hd) : d > 0 ∨ d = 0 ∨ d < 0 := trichotomous d 0,
{ -- d > 0
have h₁ : f n ≤ d, from le_of_dvd hd h_fn_dvd_d,
have h₂ : ¬ f n ≤ d, from not_le.mpr h_d_lt_fn,
contradiction },
{ -- d = 0
exact hd },
{ -- d < 0
have h₁ : f n ≤ -d, from le_of_dvd (neg_pos.mpr hd) ((dvd_neg _ _).mpr h_fn_dvd_d),
have h₂ : ¬ f n ≤ -d, from not_le.mpr h_neg_d_lt_fn,
contradiction } },
have h₁ : f m = f (m - n), from sub_eq_zero.mp h_d_eq_zero,
have h₂ : f (m - n) ∣ f m - f n, from hdvd m n,
rw ←h₁ at h₂,
exact (dvd_iff_dvd_of_dvd_sub h₂).mp (dvd_refl _) },
{ -- m = n
rw h_fm_eq_fn }
end
|
b8a6be1faadf26284c03f8f72c6a002f45049886 | 32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7 | /tests/lean/run/matchArrayLit.lean | d4a4b2eca36a24ba17a624c3e6a64493ee43cac9 | [
"Apache-2.0"
] | permissive | walterhu1015/lean4 | b2c71b688975177402758924eaa513475ed6ce72 | 2214d81e84646a905d0b20b032c89caf89c737ad | refs/heads/master | 1,671,342,096,906 | 1,599,695,985,000 | 1,599,695,985,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,084 | lean | universes u v
theorem eqLitOfSize0 {α : Type u} (a : Array α) (hsz : a.size = 0) : a = #[] :=
a.toArrayLitEq 0 hsz
theorem eqLitOfSize1 {α : Type u} (a : Array α) (hsz : a.size = 1) : a = #[a.getLit 0 hsz (ofDecideEqTrue rfl)] :=
a.toArrayLitEq 1 hsz
theorem eqLitOfSize2 {α : Type u} (a : Array α) (hsz : a.size = 2) : a = #[a.getLit 0 hsz (ofDecideEqTrue rfl), a.getLit 1 hsz (ofDecideEqTrue rfl)] :=
a.toArrayLitEq 2 hsz
theorem eqLitOfSize3 {α : Type u} (a : Array α) (hsz : a.size = 3) :
a = #[a.getLit 0 hsz (ofDecideEqTrue rfl), a.getLit 1 hsz (ofDecideEqTrue rfl), a.getLit 2 hsz (ofDecideEqTrue rfl)] :=
a.toArrayLitEq 3 hsz
/-
Matcher for the following patterns
```
| #[] => _
| #[a₁] => _
| #[a₁, a₂, a₃] => _
| a => _
``` -/
def matchArrayLit {α : Type u} (C : Array α → Sort v) (a : Array α)
(h₁ : Unit → C #[])
(h₂ : ∀ a₁, C #[a₁])
(h₃ : ∀ a₁ a₂ a₃, C #[a₁, a₂, a₃])
(h₄ : ∀ a, C a)
: C a :=
if h : a.size = 0 then
@Eq.rec _ _ (fun x _ => C x) (h₁ ()) _ (a.toArrayLitEq 0 h).symm
else if h : a.size = 1 then
@Eq.rec _ _ (fun x _ => C x) (h₂ (a.getLit 0 h (ofDecideEqTrue rfl))) _ (a.toArrayLitEq 1 h).symm
else if h : a.size = 3 then
@Eq.rec _ _ (fun x _ => C x) (h₃ (a.getLit 0 h (ofDecideEqTrue rfl)) (a.getLit 1 h (ofDecideEqTrue rfl)) (a.getLit 2 h (ofDecideEqTrue rfl))) _ (a.toArrayLitEq 3 h).symm
else
h₄ a
/- Equational lemmas that should be generated automatically. -/
theorem matchArrayLit.eq1 {α : Type u} (C : Array α → Sort v)
(h₁ : Unit → C #[])
(h₂ : ∀ a₁, C #[a₁])
(h₃ : ∀ a₁ a₂ a₃, C #[a₁, a₂, a₃])
(h₄ : ∀ a, C a)
: matchArrayLit C #[] h₁ h₂ h₃ h₄ = h₁ () :=
rfl
theorem matchArrayLit.eq2 {α : Type u} (C : Array α → Sort v)
(h₁ : Unit → C #[])
(h₂ : ∀ a₁, C #[a₁])
(h₃ : ∀ a₁ a₂ a₃, C #[a₁, a₂, a₃])
(h₄ : ∀ a, C a)
(a₁ : α)
: matchArrayLit C #[a₁] h₁ h₂ h₃ h₄ = h₂ a₁ :=
rfl
theorem matchArrayLit.eq3 {α : Type u} (C : Array α → Sort v)
(h₁ : Unit → C #[])
(h₂ : ∀ a₁, C #[a₁])
(h₃ : ∀ a₁ a₂ a₃, C #[a₁, a₂, a₃])
(h₄ : ∀ a, C a)
(a₁ a₂ a₃ : α)
: matchArrayLit C #[a₁, a₂, a₃] h₁ h₂ h₃ h₄ = h₃ a₁ a₂ a₃ :=
rfl
theorem matchArrayLit.eq4 {α : Type u} (C : Array α → Sort v)
(h₁ : Unit → C #[])
(h₂ : ∀ a₁, C #[a₁])
(h₃ : ∀ a₁ a₂ a₃, C #[a₁, a₂, a₃])
(h₄ : ∀ a, C a)
(a : Array α)
(n₁ : a.size ≠ 0) (n₂ : a.size ≠ 1) (n₃ : a.size ≠ 3)
: matchArrayLit C a h₁ h₂ h₃ h₄ = h₄ a :=
match a, n₁, n₂, n₃ with
| ⟨0, _⟩, n₁, _, _ => absurd rfl n₁
| ⟨1, _⟩, _, n₂, _ => absurd rfl n₂
| ⟨2, _⟩, _, _, _ => rfl
| ⟨3, _⟩, _, _, n₃ => absurd rfl n₃
| ⟨n+4, _⟩, _, _, _ => rfl
|
910284c55bbb137594469e540346de4f05c4760a | d1a52c3f208fa42c41df8278c3d280f075eb020c | /stage0/src/Lean/Util/ForEachExpr.lean | efd97b5947a2015f1851032605926661d1f870de | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | cipher1024/lean4 | 6e1f98bb58e7a92b28f5364eb38a14c8d0aae393 | 69114d3b50806264ef35b57394391c3e738a9822 | refs/heads/master | 1,642,227,983,603 | 1,642,011,696,000 | 1,642,011,696,000 | 228,607,691 | 0 | 0 | Apache-2.0 | 1,576,584,269,000 | 1,576,584,268,000 | null | UTF-8 | Lean | false | false | 1,476 | 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.Expr
import Lean.Util.MonadCache
namespace Lean
/-
Remark: we cannot use the caching trick used at `FindExpr` and `ReplaceExpr` because they
may visit the same expression multiple times if they are stored in different memory
addresses. Note that the following code is parametric in a monad `m`.
-/
variable {ω : Type} {m : Type → Type} [STWorld ω m] [MonadLiftT (ST ω) m] [Monad m]
namespace ForEachExpr
@[specialize] partial def visit (g : Expr → m Bool) (e : Expr) : MonadCacheT Expr Unit m Unit :=
checkCache e fun _ => do
if (← g e) then
match e with
| Expr.forallE _ d b _ => do visit g d; visit g b
| Expr.lam _ d b _ => do visit g d; visit g b
| Expr.letE _ t v b _ => do visit g t; visit g v; visit g b
| Expr.app f a _ => do visit g f; visit g a
| Expr.mdata _ b _ => visit g b
| Expr.proj _ _ b _ => visit g b
| _ => pure ()
end ForEachExpr
/-- Apply `f` to each sub-expression of `e`. If `f t` return true, then t's children are not visited. -/
@[inline] def Expr.forEach' (e : Expr) (f : Expr → m Bool) : m Unit :=
(ForEachExpr.visit f e).run
@[inline] def Expr.forEach (e : Expr) (f : Expr → m Unit) : m Unit :=
e.forEach' fun e => do f e; pure true
end Lean
|
d7ffca203ff24d5ba7200c81324ec4e8f05d3a3b | c777c32c8e484e195053731103c5e52af26a25d1 | /src/set_theory/ordinal/basic.lean | 2e146285a1f99141d6cbf105f682884dfc41ef39 | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 49,626 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Floris van Doorn
-/
import data.sum.order
import order.initial_seg
import set_theory.cardinal.basic
/-!
# Ordinals
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Ordinals are defined as equivalences of well-ordered sets under order isomorphism. They are endowed
with a total order, where an ordinal is smaller than another one if it embeds into it as an
initial segment (or, equivalently, in any way). This total order is well founded.
## Main definitions
* `ordinal`: the type of ordinals (in a given universe)
* `ordinal.type r`: given a well-founded order `r`, this is the corresponding ordinal
* `ordinal.typein r a`: given a well-founded order `r` on a type `α`, and `a : α`, the ordinal
corresponding to all elements smaller than `a`.
* `enum r o h`: given a well-order `r` on a type `α`, and an ordinal `o` strictly smaller than
the ordinal corresponding to `r` (this is the assumption `h`), returns the `o`-th element of `α`.
In other words, the elements of `α` can be enumerated using ordinals up to `type r`.
* `ordinal.card o`: the cardinality of an ordinal `o`.
* `ordinal.lift` lifts an ordinal in universe `u` to an ordinal in universe `max u v`.
For a version registering additionally that this is an initial segment embedding, see
`ordinal.lift.initial_seg`.
For a version regiserting that it is a principal segment embedding if `u < v`, see
`ordinal.lift.principal_seg`.
* `ordinal.omega` or `ω` is the order type of `ℕ`. This definition is universe polymorphic:
`ordinal.omega.{u} : ordinal.{u}` (contrast with `ℕ : Type`, which lives in a specific
universe). In some cases the universe level has to be given explicitly.
* `o₁ + o₂` is the order on the disjoint union of `o₁` and `o₂` obtained by declaring that
every element of `o₁` is smaller than every element of `o₂`. The main properties of addition
(and the other operations on ordinals) are stated and proved in `ordinal_arithmetic.lean`. Here,
we only introduce it and prove its basic properties to deduce the fact that the order on ordinals
is total (and well founded).
* `succ o` is the successor of the ordinal `o`.
* `cardinal.ord c`: when `c` is a cardinal, `ord c` is the smallest ordinal with this cardinality.
It is the canonical way to represent a cardinal with an ordinal.
A conditionally complete linear order with bot structure is registered on ordinals, where `⊥` is
`0`, the ordinal corresponding to the empty type, and `Inf` is the minimum for nonempty sets and `0`
for the empty set by convention.
## Notations
* `ω` is a notation for the first infinite ordinal in the locale `ordinal`.
-/
noncomputable theory
open function cardinal set equiv order
open_locale classical cardinal initial_seg
universes u v w
variables {α : Type*} {β : Type*} {γ : Type*}
{r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop}
/-! ### Well order on an arbitrary type -/
section well_ordering_thm
parameter {σ : Type u}
open function
theorem nonempty_embedding_to_cardinal : nonempty (σ ↪ cardinal.{u}) :=
(embedding.total _ _).resolve_left $ λ ⟨⟨f, hf⟩⟩,
let g : σ → cardinal.{u} := inv_fun f in
let ⟨x, (hx : g x = 2 ^ sum g)⟩ := inv_fun_surjective hf (2 ^ sum g) in
have g x ≤ sum g, from le_sum.{u u} g x,
not_le_of_gt (by rw hx; exact cantor _) this
/-- An embedding of any type to the set of cardinals. -/
def embedding_to_cardinal : σ ↪ cardinal.{u} := classical.choice nonempty_embedding_to_cardinal
/-- Any type can be endowed with a well order, obtained by pulling back the well order over
cardinals by some embedding. -/
def well_ordering_rel : σ → σ → Prop := embedding_to_cardinal ⁻¹'o (<)
instance well_ordering_rel.is_well_order : is_well_order σ well_ordering_rel :=
(rel_embedding.preimage _ _).is_well_order
instance is_well_order.subtype_nonempty : nonempty {r // is_well_order σ r} :=
⟨⟨well_ordering_rel, infer_instance⟩⟩
end well_ordering_thm
/-! ### Definition of ordinals -/
/-- Bundled structure registering a well order on a type. Ordinals will be defined as a quotient
of this type. -/
structure Well_order : Type (u+1) :=
(α : Type u)
(r : α → α → Prop)
(wo : is_well_order α r)
attribute [instance] Well_order.wo
namespace Well_order
instance : inhabited Well_order := ⟨⟨pempty, _, empty_relation.is_well_order⟩⟩
@[simp] lemma eta (o : Well_order) : mk o.α o.r o.wo = o := by { cases o, refl }
end Well_order
/-- Equivalence relation on well orders on arbitrary types in universe `u`, given by order
isomorphism. -/
instance ordinal.is_equivalent : setoid Well_order :=
{ r := λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r ≃r s),
iseqv := ⟨λ ⟨α, r, _⟩, ⟨rel_iso.refl _⟩,
λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨e⟩, ⟨e.symm⟩,
λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ }
/-- `ordinal.{u}` is the type of well orders in `Type u`, up to order isomorphism. -/
def ordinal : Type (u + 1) := quotient ordinal.is_equivalent
instance has_well_founded_out (o : ordinal) : has_well_founded o.out.α := ⟨o.out.r, o.out.wo.wf⟩
instance linear_order_out (o : ordinal) : linear_order o.out.α :=
is_well_order.linear_order o.out.r
instance is_well_order_out_lt (o : ordinal) : is_well_order o.out.α (<) :=
o.out.wo
namespace ordinal
/- ### Basic properties of the order type -/
/-- The order type of a well order is an ordinal. -/
def type (r : α → α → Prop) [wo : is_well_order α r] : ordinal :=
⟦⟨α, r, wo⟩⟧
instance : has_zero ordinal := ⟨type $ @empty_relation pempty⟩
instance : inhabited ordinal := ⟨0⟩
instance : has_one ordinal := ⟨type $ @empty_relation punit⟩
/-- The order type of an element inside a well order. For the embedding as a principal segment, see
`typein.principal_seg`. -/
def typein (r : α → α → Prop) [is_well_order α r] (a : α) : ordinal :=
type (subrel r {b | r b a})
@[simp] theorem type_def' (w : Well_order) : ⟦w⟧ = type w.r :=
by { cases w, refl }
@[simp] theorem type_def (r) [wo : is_well_order α r] : (⟦⟨α, r, wo⟩⟧ : ordinal) = type r :=
rfl
@[simp] lemma type_out (o : ordinal) : ordinal.type o.out.r = o :=
by rw [ordinal.type, Well_order.eta, quotient.out_eq]
theorem type_eq {α β} {r : α → α → Prop} {s : β → β → Prop}
[is_well_order α r] [is_well_order β s] : type r = type s ↔ nonempty (r ≃r s) :=
quotient.eq
theorem _root_.rel_iso.ordinal_type_eq {α β} {r : α → α → Prop} {s : β → β → Prop}
[is_well_order α r] [is_well_order β s] (h : r ≃r s) : type r = type s :=
type_eq.2 ⟨h⟩
@[simp] theorem type_lt (o : ordinal) : type ((<) : o.out.α → o.out.α → Prop) = o :=
(type_def' _).symm.trans $ quotient.out_eq o
theorem type_eq_zero_of_empty (r) [is_well_order α r] [is_empty α] : type r = 0 :=
(rel_iso.rel_iso_of_is_empty r _).ordinal_type_eq
@[simp] theorem type_eq_zero_iff_is_empty [is_well_order α r] : type r = 0 ↔ is_empty α :=
⟨λ h, let ⟨s⟩ := type_eq.1 h in s.to_equiv.is_empty, @type_eq_zero_of_empty α r _⟩
theorem type_ne_zero_iff_nonempty [is_well_order α r] : type r ≠ 0 ↔ nonempty α := by simp
theorem type_ne_zero_of_nonempty (r) [is_well_order α r] [h : nonempty α] : type r ≠ 0 :=
type_ne_zero_iff_nonempty.2 h
theorem type_pempty : type (@empty_relation pempty) = 0 := rfl
theorem type_empty : type (@empty_relation empty) = 0 := type_eq_zero_of_empty _
theorem type_eq_one_of_unique (r) [is_well_order α r] [unique α] : type r = 1 :=
(rel_iso.rel_iso_of_unique_of_irrefl r _).ordinal_type_eq
@[simp] theorem type_eq_one_iff_unique [is_well_order α r] : type r = 1 ↔ nonempty (unique α) :=
⟨λ h, let ⟨s⟩ := type_eq.1 h in ⟨s.to_equiv.unique⟩, λ ⟨h⟩, @type_eq_one_of_unique α r _ h⟩
theorem type_punit : type (@empty_relation punit) = 1 := rfl
theorem type_unit : type (@empty_relation unit) = 1 := rfl
@[simp] theorem out_empty_iff_eq_zero {o : ordinal} : is_empty o.out.α ↔ o = 0 :=
by rw [←@type_eq_zero_iff_is_empty o.out.α (<), type_lt]
lemma eq_zero_of_out_empty (o : ordinal) [h : is_empty o.out.α] : o = 0 :=
out_empty_iff_eq_zero.1 h
instance is_empty_out_zero : is_empty (0 : ordinal).out.α := out_empty_iff_eq_zero.2 rfl
@[simp] theorem out_nonempty_iff_ne_zero {o : ordinal} : nonempty o.out.α ↔ o ≠ 0 :=
by rw [←@type_ne_zero_iff_nonempty o.out.α (<), type_lt]
lemma ne_zero_of_out_nonempty (o : ordinal) [h : nonempty o.out.α] : o ≠ 0 :=
out_nonempty_iff_ne_zero.1 h
protected lemma one_ne_zero : (1 : ordinal) ≠ 0 := type_ne_zero_of_nonempty _
instance : nontrivial ordinal.{u} := ⟨⟨1, 0, ordinal.one_ne_zero⟩⟩
@[simp] theorem type_preimage {α β : Type u} (r : α → α → Prop) [is_well_order α r] (f : β ≃ α) :
type (f ⁻¹'o r) = type r :=
(rel_iso.preimage f r).ordinal_type_eq
@[elab_as_eliminator] theorem induction_on {C : ordinal → Prop}
(o : ordinal) (H : ∀ α r [is_well_order α r], by exactI C (type r)) : C o :=
quot.induction_on o $ λ ⟨α, r, wo⟩, @H α r wo
/-! ### The order on ordinals -/
instance : partial_order ordinal :=
{ le := λ a b, quotient.lift_on₂ a b (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r ≼i s)) $
λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩,
propext ⟨
λ ⟨h⟩, ⟨(initial_seg.of_iso f.symm).trans $
h.trans (initial_seg.of_iso g)⟩,
λ ⟨h⟩, ⟨(initial_seg.of_iso f).trans $
h.trans (initial_seg.of_iso g.symm)⟩⟩,
lt := λ a b, quotient.lift_on₂ a b (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r ≺i s)) $
λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩,
by exactI propext ⟨
λ ⟨h⟩, ⟨principal_seg.equiv_lt f.symm $
h.lt_le (initial_seg.of_iso g)⟩,
λ ⟨h⟩, ⟨principal_seg.equiv_lt f $
h.lt_le (initial_seg.of_iso g.symm)⟩⟩,
le_refl := quot.ind $ by exact λ ⟨α, r, wo⟩, ⟨initial_seg.refl _⟩,
le_trans := λ a b c, quotient.induction_on₃ a b c $
λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩ ⟨g⟩, ⟨f.trans g⟩,
lt_iff_le_not_le := λ a b, quotient.induction_on₂ a b $
λ ⟨α, r, _⟩ ⟨β, s, _⟩, by exactI
⟨λ ⟨f⟩, ⟨⟨f⟩, λ ⟨g⟩, (f.lt_le g).irrefl⟩,
λ ⟨⟨f⟩, h⟩, sum.rec_on f.lt_or_eq (λ g, ⟨g⟩)
(λ g, (h ⟨initial_seg.of_iso g.symm⟩).elim)⟩,
le_antisymm := λ a b,
quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨h₁⟩ ⟨h₂⟩,
by exactI quot.sound ⟨initial_seg.antisymm h₁ h₂⟩ }
/-- Ordinal less-equal is defined such that
well orders `r` and `s` satisfy `type r ≤ type s` if there exists
a function embedding `r` as an initial segment of `s`. -/
add_decl_doc ordinal.partial_order.le
/-- Ordinal less-than is defined such that
well orders `r` and `s` satisfy `type r < type s` if there exists
a function embedding `r` as a principal segment of `s`. -/
add_decl_doc ordinal.partial_order.lt
theorem type_le_iff {α β} {r : α → α → Prop} {s : β → β → Prop}
[is_well_order α r] [is_well_order β s] :
type r ≤ type s ↔ nonempty (r ≼i s) := iff.rfl
theorem type_le_iff' {α β} {r : α → α → Prop} {s : β → β → Prop}
[is_well_order α r] [is_well_order β s] : type r ≤ type s ↔ nonempty (r ↪r s) :=
⟨λ ⟨f⟩, ⟨f⟩, λ ⟨f⟩, ⟨f.collapse⟩⟩
theorem _root_.initial_seg.ordinal_type_le {α β} {r : α → α → Prop} {s : β → β → Prop}
[is_well_order α r] [is_well_order β s] (h : r ≼i s) : type r ≤ type s := ⟨h⟩
theorem _root_.rel_embedding.ordinal_type_le {α β} {r : α → α → Prop} {s : β → β → Prop}
[is_well_order α r] [is_well_order β s] (h : r ↪r s) : type r ≤ type s := ⟨h.collapse⟩
@[simp] theorem type_lt_iff {α β} {r : α → α → Prop} {s : β → β → Prop}
[is_well_order α r] [is_well_order β s] :
type r < type s ↔ nonempty (r ≺i s) := iff.rfl
theorem _root_.principal_seg.ordinal_type_lt {α β} {r : α → α → Prop} {s : β → β → Prop}
[is_well_order α r] [is_well_order β s] (h : r ≺i s) : type r < type s := ⟨h⟩
protected theorem zero_le (o : ordinal) : 0 ≤ o :=
induction_on o $ λ α r _, by exactI (initial_seg.of_is_empty _ r).ordinal_type_le
instance : order_bot ordinal := ⟨0, ordinal.zero_le⟩
@[simp] lemma bot_eq_zero : (⊥ : ordinal) = 0 := rfl
@[simp] protected theorem le_zero {o : ordinal} : o ≤ 0 ↔ o = 0 := le_bot_iff
protected theorem pos_iff_ne_zero {o : ordinal} : 0 < o ↔ o ≠ 0 := bot_lt_iff_ne_bot
protected theorem not_lt_zero (o : ordinal) : ¬ o < 0 := not_lt_bot
theorem eq_zero_or_pos : ∀ a : ordinal, a = 0 ∨ 0 < a := eq_bot_or_bot_lt
instance : zero_le_one_class ordinal := ⟨ordinal.zero_le _⟩
instance ne_zero.one : ne_zero (1 : ordinal) := ⟨ordinal.one_ne_zero⟩
/-- Given two ordinals `α ≤ β`, then `initial_seg_out α β` is the initial segment embedding
of `α` to `β`, as map from a model type for `α` to a model type for `β`. -/
def initial_seg_out {α β : ordinal} (h : α ≤ β) :
initial_seg ((<) : α.out.α → α.out.α → Prop) ((<) : β.out.α → β.out.α → Prop) :=
begin
change α.out.r ≼i β.out.r,
rw [←quotient.out_eq α, ←quotient.out_eq β] at h, revert h,
cases quotient.out α, cases quotient.out β, exact classical.choice
end
/-- Given two ordinals `α < β`, then `principal_seg_out α β` is the principal segment embedding
of `α` to `β`, as map from a model type for `α` to a model type for `β`. -/
def principal_seg_out {α β : ordinal} (h : α < β) :
principal_seg ((<) : α.out.α → α.out.α → Prop) ((<) : β.out.α → β.out.α → Prop) :=
begin
change α.out.r ≺i β.out.r,
rw [←quotient.out_eq α, ←quotient.out_eq β] at h, revert h,
cases quotient.out α, cases quotient.out β, exact classical.choice
end
theorem typein_lt_type (r : α → α → Prop) [is_well_order α r] (a : α) : typein r a < type r :=
⟨principal_seg.of_element _ _⟩
theorem typein_lt_self {o : ordinal} (i : o.out.α) : typein (<) i < o :=
by { simp_rw ←type_lt o, apply typein_lt_type }
@[simp] theorem typein_top {α β} {r : α → α → Prop} {s : β → β → Prop}
[is_well_order α r] [is_well_order β s] (f : r ≺i s) :
typein s f.top = type r :=
eq.symm $ quot.sound ⟨rel_iso.of_surjective
(rel_embedding.cod_restrict _ f f.lt_top)
(λ ⟨a, h⟩, by rcases f.down.1 h with ⟨b, rfl⟩; exact ⟨b, rfl⟩)⟩
@[simp] theorem typein_apply {α β} {r : α → α → Prop} {s : β → β → Prop}
[is_well_order α r] [is_well_order β s] (f : r ≼i s) (a : α) :
ordinal.typein s (f a) = ordinal.typein r a :=
eq.symm $ quotient.sound ⟨rel_iso.of_surjective
(rel_embedding.cod_restrict _
((subrel.rel_embedding _ _).trans f)
(λ ⟨x, h⟩, by rw [rel_embedding.trans_apply]; exact f.to_rel_embedding.map_rel_iff.2 h))
(λ ⟨y, h⟩, by rcases f.init h with ⟨a, rfl⟩;
exact ⟨⟨a, f.to_rel_embedding.map_rel_iff.1 h⟩, subtype.eq $ rel_embedding.trans_apply _ _ _⟩)⟩
@[simp] theorem typein_lt_typein (r : α → α → Prop) [is_well_order α r]
{a b : α} : typein r a < typein r b ↔ r a b :=
⟨λ ⟨f⟩, begin
have : f.top.1 = a,
{ let f' := principal_seg.of_element r a,
let g' := f.trans (principal_seg.of_element r b),
have : g'.top = f'.top, {rw subsingleton.elim f' g'},
exact this },
rw ← this, exact f.top.2
end, λ h, ⟨principal_seg.cod_restrict _
(principal_seg.of_element r a)
(λ x, @trans _ r _ _ _ _ x.2 h) h⟩⟩
theorem typein_surj (r : α → α → Prop) [is_well_order α r]
{o} (h : o < type r) : ∃ a, typein r a = o :=
induction_on o (λ β s _ ⟨f⟩, by exactI ⟨f.top, typein_top _⟩) h
lemma typein_injective (r : α → α → Prop) [is_well_order α r] : injective (typein r) :=
injective_of_increasing r (<) (typein r) (λ x y, (typein_lt_typein r).2)
@[simp] theorem typein_inj (r : α → α → Prop) [is_well_order α r]
{a b} : typein r a = typein r b ↔ a = b :=
(typein_injective r).eq_iff
/-! ### Enumerating elements in a well-order with ordinals. -/
/-- `enum r o h` is the `o`-th element of `α` ordered by `r`.
That is, `enum` maps an initial segment of the ordinals, those
less than the order type of `r`, to the elements of `α`. -/
def enum (r : α → α → Prop) [is_well_order α r] (o) : o < type r → α :=
quot.rec_on o (λ ⟨β, s, _⟩ h, (classical.choice h).top) $
λ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨h⟩, begin
resetI, refine funext (λ (H₂ : type t < type r), _),
have H₁ : type s < type r, {rwa type_eq.2 ⟨h⟩},
have : ∀ {o e} (H : o < type r), @@eq.rec
(λ (o : ordinal), o < type r → α)
(λ (h : type s < type r), (classical.choice h).top)
e H = (classical.choice H₁).top, {intros, subst e},
exact (this H₂).trans (principal_seg.top_eq h
(classical.choice H₁) (classical.choice H₂))
end
theorem enum_type {α β} {r : α → α → Prop} {s : β → β → Prop}
[is_well_order α r] [is_well_order β s] (f : s ≺i r)
{h : type s < type r} : enum r (type s) h = f.top :=
principal_seg.top_eq (rel_iso.refl _) _ _
@[simp] theorem enum_typein (r : α → α → Prop) [is_well_order α r] (a : α) :
enum r (typein r a) (typein_lt_type r a) = a :=
enum_type (principal_seg.of_element r a)
@[simp] theorem typein_enum (r : α → α → Prop) [is_well_order α r]
{o} (h : o < type r) : typein r (enum r o h) = o :=
let ⟨a, e⟩ := typein_surj r h in
by clear _let_match; subst e; rw enum_typein
theorem enum_lt_enum {r : α → α → Prop} [is_well_order α r]
{o₁ o₂ : ordinal} (h₁ : o₁ < type r) (h₂ : o₂ < type r) :
r (enum r o₁ h₁) (enum r o₂ h₂) ↔ o₁ < o₂ :=
by rw [← typein_lt_typein r, typein_enum, typein_enum]
lemma rel_iso_enum' {α β : Type u} {r : α → α → Prop} {s : β → β → Prop}
[is_well_order α r] [is_well_order β s]
(f : r ≃r s) (o : ordinal) : ∀(hr : o < type r) (hs : o < type s),
f (enum r o hr) = enum s o hs :=
begin
refine induction_on o _, rintros γ t wo ⟨g⟩ ⟨h⟩,
resetI, rw [enum_type g, enum_type (principal_seg.lt_equiv g f)], refl
end
lemma rel_iso_enum {α β : Type u} {r : α → α → Prop} {s : β → β → Prop}
[is_well_order α r] [is_well_order β s]
(f : r ≃r s) (o : ordinal) (hr : o < type r) :
f (enum r o hr) =
enum s o (by {convert hr using 1, apply quotient.sound, exact ⟨f.symm⟩ }) :=
rel_iso_enum' _ _ _ _
theorem lt_wf : @well_founded ordinal (<) :=
⟨λ a, induction_on a $ λ α r wo, by exactI
suffices ∀ a, acc (<) (typein r a), from
⟨_, λ o h, let ⟨a, e⟩ := typein_surj r h in e ▸ this a⟩,
λ a, acc.rec_on (wo.wf.apply a) $ λ x H IH, ⟨_, λ o h, begin
rcases typein_surj r (lt_trans h (typein_lt_type r _)) with ⟨b, rfl⟩,
exact IH _ ((typein_lt_typein r).1 h)
end⟩⟩
instance : has_well_founded ordinal := ⟨(<), lt_wf⟩
/-- Reformulation of well founded induction on ordinals as a lemma that works with the
`induction` tactic, as in `induction i using ordinal.induction with i IH`. -/
lemma induction {p : ordinal.{u} → Prop} (i : ordinal.{u})
(h : ∀ j, (∀ k, k < j → p k) → p j) : p i :=
lt_wf.induction i h
/-- Principal segment version of the `typein` function, embedding a well order into
ordinals as a principal segment. -/
def typein.principal_seg {α : Type u} (r : α → α → Prop) [is_well_order α r] :
@principal_seg α ordinal.{u} r (<) :=
⟨rel_embedding.of_monotone (typein r)
(λ a b, (typein_lt_typein r).2), type r, λ b,
⟨λ h, ⟨enum r _ h, typein_enum r h⟩,
λ ⟨a, e⟩, e ▸ typein_lt_type _ _⟩⟩
@[simp] theorem typein.principal_seg_coe (r : α → α → Prop) [is_well_order α r] :
(typein.principal_seg r : α → ordinal) = typein r := rfl
/-! ### Cardinality of ordinals -/
/-- The cardinal of an ordinal is the cardinality of any type on which a relation with that order
type is defined. -/
def card : ordinal → cardinal := quotient.map Well_order.α $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨e⟩, ⟨e.to_equiv⟩
@[simp] theorem card_type (r : α → α → Prop) [is_well_order α r] : card (type r) = #α := rfl
@[simp] lemma card_typein {r : α → α → Prop} [wo : is_well_order α r] (x : α) :
#{y // r y x} = (typein r x).card :=
rfl
theorem card_le_card {o₁ o₂ : ordinal} : o₁ ≤ o₂ → card o₁ ≤ card o₂ :=
induction_on o₁ $ λ α r _, induction_on o₂ $ λ β s _ ⟨⟨⟨f, _⟩, _⟩⟩, ⟨f⟩
@[simp] theorem card_zero : card 0 = 0 := rfl
@[simp] theorem card_eq_zero {o} : card o = 0 ↔ o = 0 :=
⟨induction_on o $ λ α r _ h, begin
haveI := cardinal.mk_eq_zero_iff.1 h,
apply type_eq_zero_of_empty
end, λ e, by simp only [e, card_zero]⟩
@[simp] theorem card_one : card 1 = 1 := rfl
/-! ### Lifting ordinals to a higher universe -/
/-- The universe lift operation for ordinals, which embeds `ordinal.{u}` as
a proper initial segment of `ordinal.{v}` for `v > u`. For the initial segment version,
see `lift.initial_seg`. -/
def lift (o : ordinal.{v}) : ordinal.{max v u} :=
quotient.lift_on o (λ w, type $ ulift.down ⁻¹'o w.r) $
λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨f⟩, quot.sound ⟨(rel_iso.preimage equiv.ulift r).trans $
f.trans (rel_iso.preimage equiv.ulift s).symm⟩
@[simp] theorem type_ulift (r : α → α → Prop) [is_well_order α r] :
type (ulift.down ⁻¹'o r) = lift.{v} (type r) :=
rfl
theorem _root_.rel_iso.ordinal_lift_type_eq {α : Type u} {β : Type v}
{r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : r ≃r s) :
lift.{v} (type r) = lift.{u} (type s) :=
((rel_iso.preimage equiv.ulift r).trans $
f.trans (rel_iso.preimage equiv.ulift s).symm).ordinal_type_eq
@[simp] theorem type_lift_preimage {α : Type u} {β : Type v} (r : α → α → Prop) [is_well_order α r]
(f : β ≃ α) : lift.{u} (type (f ⁻¹'o r)) = lift.{v} (type r) :=
(rel_iso.preimage f r).ordinal_lift_type_eq
/-- `lift.{(max u v) u}` equals `lift.{v u}`. Using `set_option pp.universes true` will make it much
easier to understand what's happening when using this lemma. -/
@[simp] theorem lift_umax : lift.{(max u v) u} = lift.{v u} :=
funext $ λ a, induction_on a $ λ α r _,
quotient.sound ⟨(rel_iso.preimage equiv.ulift r).trans (rel_iso.preimage equiv.ulift r).symm⟩
/-- `lift.{(max v u) u}` equals `lift.{v u}`. Using `set_option pp.universes true` will make it much
easier to understand what's happening when using this lemma. -/
@[simp] theorem lift_umax' : lift.{(max v u) u} = lift.{v u} := lift_umax
/-- An ordinal lifted to a lower or equal universe equals itself. -/
@[simp] theorem lift_id' (a : ordinal) : lift a = a :=
induction_on a $ λ α r _, quotient.sound ⟨rel_iso.preimage equiv.ulift r⟩
/-- An ordinal lifted to the same universe equals itself. -/
@[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u}
/-- An ordinal lifted to the zero universe equals itself. -/
@[simp] theorem lift_uzero (a : ordinal.{u}) : lift.{0} a = a := lift_id'.{0 u} a
@[simp] theorem lift_lift (a : ordinal) : lift.{w} (lift.{v} a) = lift.{max v w} a :=
induction_on a $ λ α r _,
quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans $
(rel_iso.preimage equiv.ulift _).trans (rel_iso.preimage equiv.ulift _).symm⟩
theorem lift_type_le {α : Type u} {β : Type v} {r s} [is_well_order α r] [is_well_order β s] :
lift.{max v w} (type r) ≤ lift.{max u w} (type s) ↔ nonempty (r ≼i s) :=
⟨λ ⟨f⟩, ⟨(initial_seg.of_iso (rel_iso.preimage equiv.ulift r).symm).trans $
f.trans (initial_seg.of_iso (rel_iso.preimage equiv.ulift s))⟩,
λ ⟨f⟩, ⟨(initial_seg.of_iso (rel_iso.preimage equiv.ulift r)).trans $
f.trans (initial_seg.of_iso (rel_iso.preimage equiv.ulift s).symm)⟩⟩
theorem lift_type_eq {α : Type u} {β : Type v} {r s} [is_well_order α r] [is_well_order β s] :
lift.{max v w} (type r) = lift.{max u w} (type s) ↔ nonempty (r ≃r s) :=
quotient.eq.trans
⟨λ ⟨f⟩, ⟨(rel_iso.preimage equiv.ulift r).symm.trans $
f.trans (rel_iso.preimage equiv.ulift s)⟩,
λ ⟨f⟩, ⟨(rel_iso.preimage equiv.ulift r).trans $
f.trans (rel_iso.preimage equiv.ulift s).symm⟩⟩
theorem lift_type_lt {α : Type u} {β : Type v} {r s} [is_well_order α r] [is_well_order β s] :
lift.{max v w} (type r) < lift.{max u w} (type s) ↔ nonempty (r ≺i s) :=
by haveI := @rel_embedding.is_well_order _ _ (@equiv.ulift.{max v w} α ⁻¹'o r)
r (rel_iso.preimage equiv.ulift.{max v w} r) _;
haveI := @rel_embedding.is_well_order _ _ (@equiv.ulift.{max u w} β ⁻¹'o s)
s (rel_iso.preimage equiv.ulift.{max u w} s) _; exact
⟨λ ⟨f⟩, ⟨(f.equiv_lt (rel_iso.preimage equiv.ulift r).symm).lt_le
(initial_seg.of_iso (rel_iso.preimage equiv.ulift s))⟩,
λ ⟨f⟩, ⟨(f.equiv_lt (rel_iso.preimage equiv.ulift r)).lt_le
(initial_seg.of_iso (rel_iso.preimage equiv.ulift s).symm)⟩⟩
@[simp] theorem lift_le {a b : ordinal} : lift.{u v} a ≤ lift b ↔ a ≤ b :=
induction_on a $ λ α r _, induction_on b $ λ β s _, by { rw ← lift_umax, exactI lift_type_le }
@[simp] theorem lift_inj {a b : ordinal} : lift a = lift b ↔ a = b :=
by simp only [le_antisymm_iff, lift_le]
@[simp] theorem lift_lt {a b : ordinal} : lift a < lift b ↔ a < b :=
by simp only [lt_iff_le_not_le, lift_le]
@[simp] theorem lift_zero : lift 0 = 0 := type_eq_zero_of_empty _
@[simp] theorem lift_one : lift 1 = 1 := type_eq_one_of_unique _
@[simp] theorem lift_card (a) : (card a).lift = card (lift a) :=
induction_on a $ λ α r _, rfl
theorem lift_down' {a : cardinal.{u}} {b : ordinal.{max u v}}
(h : card b ≤ a.lift) : ∃ a', lift a' = b :=
let ⟨c, e⟩ := cardinal.lift_down h in
cardinal.induction_on c (λ α, induction_on b $ λ β s _ e', begin
resetI,
rw [card_type, ← cardinal.lift_id'.{(max u v) u} (#β),
← cardinal.lift_umax.{u v}, lift_mk_eq.{u (max u v) (max u v)}] at e',
cases e' with f,
have g := rel_iso.preimage f s,
haveI := (g : ⇑f ⁻¹'o s ↪r s).is_well_order,
have := lift_type_eq.{u (max u v) (max u v)}.2 ⟨g⟩,
rw [lift_id, lift_umax.{u v}] at this,
exact ⟨_, this⟩
end) e
theorem lift_down {a : ordinal.{u}} {b : ordinal.{max u v}}
(h : b ≤ lift a) : ∃ a', lift a' = b :=
@lift_down' (card a) _ (by rw lift_card; exact card_le_card h)
theorem le_lift_iff {a : ordinal.{u}} {b : ordinal.{max u v}} :
b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a :=
⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩,
λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩
theorem lt_lift_iff {a : ordinal.{u}} {b : ordinal.{max u v}} :
b < lift a ↔ ∃ a', lift a' = b ∧ a' < a :=
⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in
⟨a', e, lift_lt.1 $ e.symm ▸ h⟩,
λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩
/-- Initial segment version of the lift operation on ordinals, embedding `ordinal.{u}` in
`ordinal.{v}` as an initial segment when `u ≤ v`. -/
def lift.initial_seg : @initial_seg ordinal.{u} ordinal.{max u v} (<) (<) :=
⟨⟨⟨lift.{v}, λ a b, lift_inj.1⟩, λ a b, lift_lt⟩,
λ a b h, lift_down (le_of_lt h)⟩
@[simp] theorem lift.initial_seg_coe : (lift.initial_seg : ordinal → ordinal) = lift := rfl
/-! ### The first infinite ordinal `omega` -/
/-- `ω` is the first infinite ordinal, defined as the order type of `ℕ`. -/
def omega : ordinal.{u} := lift $ @type ℕ (<) _
localized "notation (name := ordinal.omega) `ω` := ordinal.omega" in ordinal
/-- Note that the presence of this lemma makes `simp [omega]` form a loop. -/
@[simp] theorem type_nat_lt : @type ℕ (<) _ = ω := (lift_id _).symm
@[simp] theorem card_omega : card ω = ℵ₀ := rfl
@[simp] theorem lift_omega : lift ω = ω := lift_lift _
/-!
### Definition and first properties of addition on ordinals
In this paragraph, we introduce the addition on ordinals, and prove just enough properties to
deduce that the order on ordinals is total (and therefore well-founded). Further properties of
the addition, together with properties of the other operations, are proved in
`ordinal_arithmetic.lean`.
-/
/-- `o₁ + o₂` is the order on the disjoint union of `o₁` and `o₂` obtained by declaring that
every element of `o₁` is smaller than every element of `o₂`. -/
instance : has_add ordinal.{u} :=
⟨λ o₁ o₂, quotient.lift_on₂ o₁ o₂
(λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, by exactI type (sum.lex r s)) $
λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩,
quot.sound ⟨rel_iso.sum_lex_congr f g⟩⟩
instance : add_monoid_with_one ordinal.{u} :=
{ add := (+),
zero := 0,
one := 1,
zero_add := λ o, induction_on o $ λ α r _, eq.symm $ quotient.sound
⟨⟨(empty_sum pempty α).symm, λ a b, sum.lex_inr_inr⟩⟩,
add_zero := λ o, induction_on o $ λ α r _, eq.symm $ quotient.sound
⟨⟨(sum_empty α pempty).symm, λ a b, sum.lex_inl_inl⟩⟩,
add_assoc := λ o₁ o₂ o₃, quotient.induction_on₃ o₁ o₂ o₃ $
λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩, quot.sound
⟨⟨sum_assoc _ _ _, λ a b,
begin rcases a with ⟨a|a⟩|a; rcases b with ⟨b|b⟩|b;
simp only [sum_assoc_apply_inl_inl, sum_assoc_apply_inl_inr, sum_assoc_apply_inr,
sum.lex_inl_inl, sum.lex_inr_inr, sum.lex.sep, sum.lex_inr_inl] end⟩⟩ }
@[simp] theorem card_add (o₁ o₂ : ordinal) : card (o₁ + o₂) = card o₁ + card o₂ :=
induction_on o₁ $ λ α r _, induction_on o₂ $ λ β s _, rfl
@[simp] theorem type_sum_lex {α β : Type u} (r : α → α → Prop) (s : β → β → Prop)
[is_well_order α r] [is_well_order β s] : type (sum.lex r s) = type r + type s := rfl
@[simp] theorem card_nat (n : ℕ) : card.{u} n = n :=
by induction n; [refl, simp only [card_add, card_one, nat.cast_succ, *]]
instance add_covariant_class_le : covariant_class ordinal.{u} ordinal.{u} (+) (≤) :=
⟨λ c a b h, begin
revert h c, exact (
induction_on a $ λ α₁ r₁ _, induction_on b $ λ α₂ r₂ _ ⟨⟨⟨f, fo⟩, fi⟩⟩ c,
induction_on c $ λ β s _,
⟨⟨⟨(embedding.refl _).sum_map f,
λ a b, match a, b with
| sum.inl a, sum.inl b := sum.lex_inl_inl.trans sum.lex_inl_inl.symm
| sum.inl a, sum.inr b := by apply iff_of_true; apply sum.lex.sep
| sum.inr a, sum.inl b := by apply iff_of_false; exact sum.lex_inr_inl
| sum.inr a, sum.inr b := sum.lex_inr_inr.trans $ fo.trans sum.lex_inr_inr.symm
end⟩,
λ a b H, match a, b, H with
| _, sum.inl b, _ := ⟨sum.inl b, rfl⟩
| sum.inl a, sum.inr b, H := (sum.lex_inr_inl H).elim
| sum.inr a, sum.inr b, H := let ⟨w, h⟩ := fi _ _ (sum.lex_inr_inr.1 H) in
⟨sum.inr w, congr_arg sum.inr h⟩
end⟩⟩)
end⟩
instance add_swap_covariant_class_le : covariant_class ordinal.{u} ordinal.{u} (swap (+)) (≤) :=
⟨λ c a b h, begin
revert h c, exact (
induction_on a $ λ α₁ r₁ hr₁, induction_on b $ λ α₂ r₂ hr₂ ⟨⟨⟨f, fo⟩, fi⟩⟩ c,
induction_on c $ λ β s hs, by exactI
@rel_embedding.ordinal_type_le _ _ (sum.lex r₁ s) (sum.lex r₂ s) _ _
⟨f.sum_map (embedding.refl _), λ a b, begin
split; intro H,
{ cases a with a a; cases b with b b; cases H; constructor; [rwa ← fo, assumption] },
{ cases H; constructor; [rwa fo, assumption] }
end⟩)
end⟩
theorem le_add_right (a b : ordinal) : a ≤ a + b :=
by simpa only [add_zero] using add_le_add_left (ordinal.zero_le b) a
theorem le_add_left (a b : ordinal) : a ≤ b + a :=
by simpa only [zero_add] using add_le_add_right (ordinal.zero_le b) a
instance : linear_order ordinal :=
{ le_total := λ a b,
match lt_or_eq_of_le (le_add_left b a), lt_or_eq_of_le (le_add_right a b) with
| or.inr h, _ := by rw h; exact or.inl (le_add_right _ _)
| _, or.inr h := by rw h; exact or.inr (le_add_left _ _)
| or.inl h₁, or.inl h₂ := induction_on a (λ α₁ r₁ _,
induction_on b $ λ α₂ r₂ _ ⟨f⟩ ⟨g⟩, begin
resetI,
rw [← typein_top f, ← typein_top g, le_iff_lt_or_eq,
le_iff_lt_or_eq, typein_lt_typein, typein_lt_typein],
rcases trichotomous_of (sum.lex r₁ r₂) g.top f.top with h|h|h;
[exact or.inl (or.inl h), {left, right, rw h}, exact or.inr (or.inl h)]
end) h₁ h₂
end,
decidable_le := classical.dec_rel _,
..ordinal.partial_order }
instance : well_founded_lt ordinal := ⟨lt_wf⟩
instance : is_well_order ordinal (<) := { }
instance : conditionally_complete_linear_order_bot ordinal :=
is_well_order.conditionally_complete_linear_order_bot _
@[simp] lemma max_zero_left : ∀ a : ordinal, max 0 a = a := max_bot_left
@[simp] lemma max_zero_right : ∀ a : ordinal, max a 0 = a := max_bot_right
@[simp] lemma max_eq_zero {a b : ordinal} : max a b = 0 ↔ a = 0 ∧ b = 0 := max_eq_bot
@[simp] theorem Inf_empty : Inf (∅ : set ordinal) = 0 :=
dif_neg not_nonempty_empty
/- ### Successor order properties -/
private theorem succ_le_iff' {a b : ordinal} : a + 1 ≤ b ↔ a < b :=
⟨lt_of_lt_of_le (induction_on a $ λ α r _, ⟨⟨⟨⟨λ x, sum.inl x, λ _ _, sum.inl.inj⟩,
λ _ _, sum.lex_inl_inl⟩,
sum.inr punit.star, λ b, sum.rec_on b
(λ x, ⟨λ _, ⟨x, rfl⟩, λ _, sum.lex.sep _ _⟩)
(λ x, sum.lex_inr_inr.trans ⟨false.elim, λ ⟨x, H⟩, sum.inl_ne_inr H⟩)⟩⟩),
induction_on a $ λ α r hr, induction_on b $ λ β s hs ⟨⟨f, t, hf⟩⟩, begin
haveI := hs,
refine ⟨⟨@rel_embedding.of_monotone (α ⊕ punit) β _ _ _ _ (sum.rec _ _) (λ a b, _), λ a b, _⟩⟩,
{ exact f }, { exact λ _, t },
{ rcases a with a|_; rcases b with b|_,
{ simpa only [sum.lex_inl_inl] using f.map_rel_iff.2 },
{ intro _, rw hf, exact ⟨_, rfl⟩ },
{ exact false.elim ∘ sum.lex_inr_inl },
{ exact false.elim ∘ sum.lex_inr_inr.1 } },
{ rcases a with a|_,
{ intro h, have := @principal_seg.init _ _ _ _ _ ⟨f, t, hf⟩ _ _ h,
cases this with w h, exact ⟨sum.inl w, h⟩ },
{ intro h, cases (hf b).1 h with w h, exact ⟨sum.inl w, h⟩ } }
end⟩
instance : no_max_order ordinal := ⟨λ a, ⟨_, succ_le_iff'.1 le_rfl⟩⟩
instance : succ_order ordinal.{u} := succ_order.of_succ_le_iff (λ o, o + 1) (λ a b, succ_le_iff')
@[simp] theorem add_one_eq_succ (o : ordinal) : o + 1 = succ o := rfl
@[simp] theorem succ_zero : succ (0 : ordinal) = 1 := zero_add 1
@[simp] theorem succ_one : succ (1 : ordinal) = 2 := rfl
theorem add_succ (o₁ o₂ : ordinal) : o₁ + succ o₂ = succ (o₁ + o₂) :=
(add_assoc _ _ _).symm
theorem one_le_iff_pos {o : ordinal} : 1 ≤ o ↔ 0 < o :=
by rw [← succ_zero, succ_le_iff]
theorem one_le_iff_ne_zero {o : ordinal} : 1 ≤ o ↔ o ≠ 0 :=
by rw [one_le_iff_pos, ordinal.pos_iff_ne_zero]
theorem succ_pos (o : ordinal) : 0 < succ o := bot_lt_succ o
theorem succ_ne_zero (o : ordinal) : succ o ≠ 0 := ne_of_gt $ succ_pos o
theorem lt_one_iff_zero {a : ordinal} : a < 1 ↔ a = 0 := by simpa using @lt_succ_bot_iff _ _ _ a _ _
theorem le_one_iff {a : ordinal} : a ≤ 1 ↔ a = 0 ∨ a = 1 :=
by simpa using @le_succ_bot_iff _ _ _ a _
@[simp] theorem card_succ (o : ordinal) : card (succ o) = card o + 1 :=
by simp only [←add_one_eq_succ, card_add, card_one]
theorem nat_cast_succ (n : ℕ) : ↑n.succ = succ (n : ordinal) := rfl
instance unique_Iio_one : unique (Iio (1 : ordinal)) :=
{ default := ⟨0, zero_lt_one⟩,
uniq := λ a, subtype.ext $ lt_one_iff_zero.1 a.prop }
instance unique_out_one : unique (1 : ordinal).out.α :=
{ default := enum (<) 0 (by simp),
uniq := λ a, begin
rw ←enum_typein (<) a,
unfold default,
congr,
rw ←lt_one_iff_zero,
apply typein_lt_self
end }
theorem one_out_eq (x : (1 : ordinal).out.α) : x = enum (<) 0 (by simp) := unique.eq_default x
/-! ### Extra properties of typein and enum -/
@[simp] theorem typein_one_out (x : (1 : ordinal).out.α) : typein (<) x = 0 :=
by rw [one_out_eq x, typein_enum]
@[simp] lemma typein_le_typein (r : α → α → Prop) [is_well_order α r] {x x' : α} :
typein r x ≤ typein r x' ↔ ¬r x' x :=
by rw [←not_lt, typein_lt_typein]
@[simp] lemma typein_le_typein' (o : ordinal) {x x' : o.out.α} :
typein (<) x ≤ typein (<) x' ↔ x ≤ x' :=
by { rw typein_le_typein, exact not_lt }
@[simp] lemma enum_le_enum (r : α → α → Prop) [is_well_order α r] {o o' : ordinal}
(ho : o < type r) (ho' : o' < type r) : ¬r (enum r o' ho') (enum r o ho) ↔ o ≤ o' :=
by rw [←@not_lt _ _ o' o, enum_lt_enum ho']
@[simp] lemma enum_le_enum' (a : ordinal) {o o' : ordinal}
(ho : o < type (<)) (ho' : o' < type (<)) : enum (<) o ho ≤ @enum a.out.α (<) _ o' ho' ↔ o ≤ o' :=
by rw [←enum_le_enum (<), ←not_lt]
theorem enum_zero_le {r : α → α → Prop} [is_well_order α r] (h0 : 0 < type r) (a : α) :
¬ r a (enum r 0 h0) :=
by { rw [←enum_typein r a, enum_le_enum r], apply ordinal.zero_le }
theorem enum_zero_le' {o : ordinal} (h0 : 0 < o) (a : o.out.α) :
@enum o.out.α (<) _ 0 (by rwa type_lt) ≤ a :=
by { rw ←not_lt, apply enum_zero_le }
theorem le_enum_succ {o : ordinal} (a : (succ o).out.α) :
a ≤ @enum (succ o).out.α (<) _ o (by { rw type_lt, exact lt_succ o }) :=
by { rw [←enum_typein (<) a, enum_le_enum', ←lt_succ_iff], apply typein_lt_self }
@[simp] theorem enum_inj {r : α → α → Prop} [is_well_order α r] {o₁ o₂ : ordinal} (h₁ : o₁ < type r)
(h₂ : o₂ < type r) : enum r o₁ h₁ = enum r o₂ h₂ ↔ o₁ = o₂ :=
⟨λ h, begin
by_contra hne,
cases lt_or_gt_of_ne hne with hlt hlt;
apply (is_well_order.is_irrefl r).1,
{ rwa [←@enum_lt_enum α r _ o₁ o₂ h₁ h₂, h] at hlt },
{ change _ < _ at hlt, rwa [←@enum_lt_enum α r _ o₂ o₁ h₂ h₁, h] at hlt }
end, λ h, by simp_rw h⟩
/-- A well order `r` is order isomorphic to the set of ordinals smaller than `type r`. -/
@[simps] def enum_iso (r : α → α → Prop) [is_well_order α r] : subrel (<) (< type r) ≃r r :=
{ to_fun := λ x, enum r x.1 x.2,
inv_fun := λ x, ⟨typein r x, typein_lt_type r x⟩,
left_inv := λ ⟨o, h⟩, subtype.ext_val (typein_enum _ _),
right_inv := λ h, enum_typein _ _,
map_rel_iff' := by { rintros ⟨a, _⟩ ⟨b, _⟩, apply enum_lt_enum } }
/-- The order isomorphism between ordinals less than `o` and `o.out.α`. -/
@[simps] noncomputable def enum_iso_out (o : ordinal) : set.Iio o ≃o o.out.α :=
{ to_fun := λ x, enum (<) x.1 $ by { rw type_lt, exact x.2 },
inv_fun := λ x, ⟨typein (<) x, typein_lt_self x⟩,
left_inv := λ ⟨o', h⟩, subtype.ext_val (typein_enum _ _),
right_inv := λ h, enum_typein _ _,
map_rel_iff' := by { rintros ⟨a, _⟩ ⟨b, _⟩, apply enum_le_enum' } }
/-- `o.out.α` is an `order_bot` whenever `0 < o`. -/
def out_order_bot_of_pos {o : ordinal} (ho : 0 < o) : order_bot o.out.α :=
⟨_, enum_zero_le' ho⟩
theorem enum_zero_eq_bot {o : ordinal} (ho : 0 < o) :
enum (<) 0 (by rwa type_lt) = by { haveI H := out_order_bot_of_pos ho, exact ⊥ } :=
rfl
/-! ### Universal ordinal -/
/-- `univ.{u v}` is the order type of the ordinals of `Type u` as a member
of `ordinal.{v}` (when `u < v`). It is an inaccessible cardinal. -/
@[nolint check_univs] -- intended to be used with explicit universe parameters
def univ : ordinal.{max (u + 1) v} := lift.{v (u+1)} (@type ordinal (<) _)
theorem univ_id : univ.{u (u+1)} = @type ordinal (<) _ := lift_id _
@[simp] theorem lift_univ : lift.{w} univ.{u v} = univ.{u (max v w)} := lift_lift _
theorem univ_umax : univ.{u (max (u+1) v)} = univ.{u v} := congr_fun lift_umax _
/-- Principal segment version of the lift operation on ordinals, embedding `ordinal.{u}` in
`ordinal.{v}` as a principal segment when `u < v`. -/
def lift.principal_seg : @principal_seg ordinal.{u} ordinal.{max (u+1) v} (<) (<) :=
⟨↑lift.initial_seg.{u (max (u+1) v)}, univ.{u v}, begin
refine λ b, induction_on b _, introsI β s _,
rw [univ, ← lift_umax], split; intro h,
{ rw ← lift_id (type s) at h ⊢,
cases lift_type_lt.1 h with f, cases f with f a hf,
existsi a, revert hf,
apply induction_on a, introsI α r _ hf,
refine lift_type_eq.{u (max (u+1) v) (max (u+1) v)}.2
⟨(rel_iso.of_surjective (rel_embedding.of_monotone _ _) _).symm⟩,
{ exact λ b, enum r (f b) ((hf _).2 ⟨_, rfl⟩) },
{ refine λ a b h, (typein_lt_typein r).1 _,
rw [typein_enum, typein_enum],
exact f.map_rel_iff.2 h },
{ intro a', cases (hf _).1 (typein_lt_type _ a') with b e,
existsi b, simp, simp [e] } },
{ cases h with a e, rw [← e],
apply induction_on a, introsI α r _,
exact lift_type_lt.{u (u+1) (max (u+1) v)}.2
⟨typein.principal_seg r⟩ }
end⟩
@[simp] theorem lift.principal_seg_coe :
(lift.principal_seg.{u v} : ordinal → ordinal) = lift.{max (u+1) v} := rfl
@[simp] theorem lift.principal_seg_top : lift.principal_seg.top = univ := rfl
theorem lift.principal_seg_top' :
lift.principal_seg.{u (u+1)}.top = @type ordinal (<) _ :=
by simp only [lift.principal_seg_top, univ_id]
end ordinal
/-! ### Representing a cardinal with an ordinal -/
namespace cardinal
open ordinal
@[simp] theorem mk_ordinal_out (o : ordinal) : #(o.out.α) = o.card :=
(ordinal.card_type _).symm.trans $ by rw ordinal.type_lt
/-- The ordinal corresponding to a cardinal `c` is the least ordinal
whose cardinal is `c`. For the order-embedding version, see `ord.order_embedding`. -/
def ord (c : cardinal) : ordinal :=
let F := λ α : Type u, ⨅ r : {r // is_well_order α r}, @type α r.1 r.2 in
quot.lift_on c F
begin
suffices : ∀ {α β}, α ≈ β → F α ≤ F β,
from λ α β h, (this h).antisymm (this (setoid.symm h)),
rintros α β ⟨f⟩,
refine le_cinfi_iff'.2 (λ i, _),
haveI := @rel_embedding.is_well_order _ _ (f ⁻¹'o i.1) _ ↑(rel_iso.preimage f i.1) i.2,
exact (cinfi_le' _ (subtype.mk (⇑f ⁻¹'o i.val)
(@rel_embedding.is_well_order _ _ _ _ ↑(rel_iso.preimage f i.1) i.2))).trans_eq
(quot.sound ⟨rel_iso.preimage f i.1⟩)
end
lemma ord_eq_Inf (α : Type u) : ord (#α) = ⨅ r : {r // is_well_order α r}, @type α r.1 r.2 :=
rfl
theorem ord_eq (α) : ∃ (r : α → α → Prop) [wo : is_well_order α r], ord (#α) = @type α r wo :=
let ⟨r, wo⟩ := infi_mem (λ r : {r // is_well_order α r}, @type α r.1 r.2) in ⟨r.1, r.2, wo.symm⟩
theorem ord_le_type (r : α → α → Prop) [h : is_well_order α r] : ord (#α) ≤ type r :=
cinfi_le' _ (subtype.mk r h)
theorem ord_le {c o} : ord c ≤ o ↔ c ≤ o.card :=
induction_on c $ λ α, ordinal.induction_on o $ λ β s _,
let ⟨r, _, e⟩ := ord_eq α in begin
resetI, simp only [card_type], split; intro h,
{ rw e at h, exact let ⟨f⟩ := h in ⟨f.to_embedding⟩ },
{ cases h with f,
have g := rel_embedding.preimage f s,
haveI := rel_embedding.is_well_order g,
exact le_trans (ord_le_type _) g.ordinal_type_le }
end
theorem gc_ord_card : galois_connection ord card := λ _ _, ord_le
theorem lt_ord {c o} : o < ord c ↔ o.card < c := gc_ord_card.lt_iff_lt
@[simp] theorem card_ord (c) : (ord c).card = c :=
quotient.induction_on c $ λ α,
let ⟨r, _, e⟩ := ord_eq α in by simp only [mk_def, e, card_type]
/-- Galois coinsertion between `cardinal.ord` and `ordinal.card`. -/
def gci_ord_card : galois_coinsertion ord card :=
gc_ord_card.to_galois_coinsertion $ λ c, c.card_ord.le
theorem ord_card_le (o : ordinal) : o.card.ord ≤ o := gc_ord_card.l_u_le _
lemma lt_ord_succ_card (o : ordinal) : o < (succ o.card).ord := lt_ord.2 $ lt_succ _
@[mono] theorem ord_strict_mono : strict_mono ord := gci_ord_card.strict_mono_l
@[mono] theorem ord_mono : monotone ord := gc_ord_card.monotone_l
@[simp] theorem ord_le_ord {c₁ c₂} : ord c₁ ≤ ord c₂ ↔ c₁ ≤ c₂ := gci_ord_card.l_le_l_iff
@[simp] theorem ord_lt_ord {c₁ c₂} : ord c₁ < ord c₂ ↔ c₁ < c₂ := ord_strict_mono.lt_iff_lt
@[simp] theorem ord_zero : ord 0 = 0 := gc_ord_card.l_bot
@[simp] theorem ord_nat (n : ℕ) : ord n = n :=
(ord_le.2 (card_nat n).ge).antisymm begin
induction n with n IH,
{ apply ordinal.zero_le },
{ exact succ_le_of_lt (IH.trans_lt $ ord_lt_ord.2 $ nat_cast_lt.2 (nat.lt_succ_self n)) }
end
@[simp] theorem ord_one : ord 1 = 1 :=
by simpa using ord_nat 1
@[simp] theorem lift_ord (c) : (ord c).lift = ord (lift c) :=
begin
refine le_antisymm (le_of_forall_lt (λ a ha, _)) _,
{ rcases ordinal.lt_lift_iff.1 ha with ⟨a, rfl, h⟩,
rwa [lt_ord, ← lift_card, lift_lt, ← lt_ord, ← ordinal.lift_lt] },
{ rw [ord_le, ← lift_card, card_ord] }
end
lemma mk_ord_out (c : cardinal) : #c.ord.out.α = c := by simp
lemma card_typein_lt (r : α → α → Prop) [is_well_order α r] (x : α)
(h : ord (#α) = type r) : card (typein r x) < #α :=
by { rw [←lt_ord, h], apply typein_lt_type }
lemma card_typein_out_lt (c : cardinal) (x : c.ord.out.α) : card (typein (<) x) < c :=
by { rw ←lt_ord, apply typein_lt_self }
lemma ord_injective : injective ord :=
by { intros c c' h, rw [←card_ord c, ←card_ord c', h] }
/-- The ordinal corresponding to a cardinal `c` is the least ordinal
whose cardinal is `c`. This is the order-embedding version. For the regular function, see `ord`.
-/
def ord.order_embedding : cardinal ↪o ordinal :=
rel_embedding.order_embedding_of_lt_embedding
(rel_embedding.of_monotone cardinal.ord $ λ a b, cardinal.ord_lt_ord.2)
@[simp] theorem ord.order_embedding_coe :
(ord.order_embedding : cardinal → ordinal) = ord := rfl
/-- The cardinal `univ` is the cardinality of ordinal `univ`, or
equivalently the cardinal of `ordinal.{u}`, or `cardinal.{u}`,
as an element of `cardinal.{v}` (when `u < v`). -/
@[nolint check_univs] -- intended to be used with explicit universe parameters
def univ := lift.{v (u+1)} (#ordinal)
theorem univ_id : univ.{u (u+1)} = #ordinal := lift_id _
@[simp] theorem lift_univ : lift.{w} univ.{u v} = univ.{u (max v w)} := lift_lift _
theorem univ_umax : univ.{u (max (u+1) v)} = univ.{u v} := congr_fun lift_umax _
theorem lift_lt_univ (c : cardinal) : lift.{(u+1) u} c < univ.{u (u+1)} :=
by simpa only [lift.principal_seg_coe, lift_ord, lift_succ, ord_le, succ_le_iff] using le_of_lt
(lift.principal_seg.{u (u+1)}.lt_top (succ c).ord)
theorem lift_lt_univ' (c : cardinal) : lift.{(max (u+1) v) u} c < univ.{u v} :=
by simpa only [lift_lift, lift_univ, univ_umax] using
lift_lt.{_ (max (u+1) v)}.2 (lift_lt_univ c)
@[simp] theorem ord_univ : ord univ.{u v} = ordinal.univ.{u v} :=
le_antisymm (ord_card_le _) $ le_of_forall_lt $ λ o h,
lt_ord.2 begin
rcases lift.principal_seg.{u v}.down.1
(by simpa only [lift.principal_seg_coe] using h) with ⟨o', rfl⟩,
simp only [lift.principal_seg_coe], rw [← lift_card],
apply lift_lt_univ'
end
theorem lt_univ {c} : c < univ.{u (u+1)} ↔ ∃ c', c = lift.{(u+1) u} c' :=
⟨λ h, begin
have := ord_lt_ord.2 h,
rw ord_univ at this,
cases lift.principal_seg.{u (u+1)}.down.1
(by simpa only [lift.principal_seg_top]) with o e,
have := card_ord c,
rw [← e, lift.principal_seg_coe, ← lift_card] at this,
exact ⟨_, this.symm⟩
end, λ ⟨c', e⟩, e.symm ▸ lift_lt_univ _⟩
theorem lt_univ' {c} : c < univ.{u v} ↔ ∃ c', c = lift.{(max (u+1) v) u} c' :=
⟨λ h, let ⟨a, e, h'⟩ := lt_lift_iff.1 h in begin
rw [← univ_id] at h',
rcases lt_univ.{u}.1 h' with ⟨c', rfl⟩,
exact ⟨c', by simp only [e.symm, lift_lift]⟩
end, λ ⟨c', e⟩, e.symm ▸ lift_lt_univ' _⟩
theorem small_iff_lift_mk_lt_univ {α : Type u} :
small.{v} α ↔ cardinal.lift (#α) < univ.{v (max u (v + 1))} :=
begin
rw lt_univ',
split,
{ rintro ⟨β, e⟩,
exact ⟨#β, lift_mk_eq.{u _ (v + 1)}.2 e⟩ },
{ rintro ⟨c, hc⟩,
exact ⟨⟨c.out, lift_mk_eq.{u _ (v + 1)}.1 (hc.trans (congr rfl c.mk_out.symm))⟩⟩ }
end
end cardinal
namespace ordinal
@[simp] theorem card_univ : card univ = cardinal.univ := rfl
@[simp] theorem nat_le_card {o} {n : ℕ} : (n : cardinal) ≤ card o ↔ (n : ordinal) ≤ o :=
by rw [← cardinal.ord_le, cardinal.ord_nat]
@[simp] theorem nat_lt_card {o} {n : ℕ} : (n : cardinal) < card o ↔ (n : ordinal) < o :=
by { rw [←succ_le_iff, ←succ_le_iff, ←nat_succ, nat_le_card], refl }
@[simp] theorem card_lt_nat {o} {n : ℕ} : card o < n ↔ o < n :=
lt_iff_lt_of_le_iff_le nat_le_card
@[simp] theorem card_le_nat {o} {n : ℕ} : card o ≤ n ↔ o ≤ n :=
le_iff_le_iff_lt_iff_lt.2 nat_lt_card
@[simp] theorem card_eq_nat {o} {n : ℕ} : card o = n ↔ o = n :=
by simp only [le_antisymm_iff, card_le_nat, nat_le_card]
@[simp] theorem type_fintype (r : α → α → Prop) [is_well_order α r] [fintype α] :
type r = fintype.card α :=
by rw [←card_eq_nat, card_type, mk_fintype]
theorem type_fin (n : ℕ) : @type (fin n) (<) _ = n := by simp
end ordinal
|
499bf583da386e323cd74faab659a9e444e23ec7 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/recInfo1.lean | fa38cb19fc25b44a0ad74dcc501ae71762680f97 | [
"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 | 638 | lean | import Lean.Meta
open Lean
open Lean.Meta
def print (msg : MessageData) : MetaM Unit := do
trace[Meta.debug] msg
def showRecInfo (declName : Name) (majorPos? : Option Nat := none) : MetaM Unit := do
let info ← mkRecursorInfo declName majorPos?
print (toString info)
theorem Iff.elim {a b c} (h₁ : (a → b) → (b → a) → c) (h₂ : a ↔ b) : c :=
h₁ h₂.1 h₂.2
set_option trace.Meta true
set_option trace.Meta.isDefEq false
#eval showRecInfo `Acc.recOn
#eval showRecInfo `Prod.casesOn
#eval showRecInfo `List.recOn
#eval showRecInfo `List.casesOn
#eval showRecInfo `List.brecOn
#eval showRecInfo `Iff.elim (some 4)
|
70c5e773ece295a81d42db115046b0044dfa4d80 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/order/monoid/with_top.lean | 616d4148549cb0c9c5e30f2e929d155d64aeca27 | [
"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 | 21,428 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl
-/
import algebra.hom.group
import algebra.order.monoid.order_dual
import algebra.order.monoid.with_zero.basic
import data.nat.cast.defs
/-! # Adjoining top/bottom elements to ordered monoids.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
-/
universes u v
variables {α : Type u} {β : Type v}
open function
namespace with_top
section has_one
variables [has_one α]
@[to_additive] instance : has_one (with_top α) := ⟨(1 : α)⟩
@[simp, norm_cast, to_additive] lemma coe_one : ((1 : α) : with_top α) = 1 := rfl
@[simp, norm_cast, to_additive] lemma coe_eq_one {a : α} : (a : with_top α) = 1 ↔ a = 1 :=
coe_eq_coe
@[simp, to_additive] lemma untop_one : (1 : with_top α).untop coe_ne_top = 1 := rfl
@[simp, to_additive] lemma untop_one' (d : α) : (1 : with_top α).untop' d = 1 := rfl
@[simp, norm_cast, to_additive coe_nonneg]
lemma one_le_coe [has_le α] {a : α} : 1 ≤ (a : with_top α) ↔ 1 ≤ a := coe_le_coe
@[simp, norm_cast, to_additive coe_le_zero]
lemma coe_le_one [has_le α] {a : α} : (a : with_top α) ≤ 1 ↔ a ≤ 1 := coe_le_coe
@[simp, norm_cast, to_additive coe_pos]
lemma one_lt_coe [has_lt α] {a : α} : 1 < (a : with_top α) ↔ 1 < a := coe_lt_coe
@[simp, norm_cast, to_additive coe_lt_zero]
lemma coe_lt_one [has_lt α] {a : α} : (a : with_top α) < 1 ↔ a < 1 := coe_lt_coe
@[simp, to_additive] protected lemma map_one {β} (f : α → β) :
(1 : with_top α).map f = (f 1 : with_top β) := rfl
@[simp, norm_cast, to_additive] theorem one_eq_coe {a : α} : 1 = (a : with_top α) ↔ a = 1 :=
trans eq_comm coe_eq_one
@[simp, to_additive] theorem top_ne_one : ⊤ ≠ (1 : with_top α) .
@[simp, to_additive] theorem one_ne_top : (1 : with_top α) ≠ ⊤ .
instance [has_zero α] [has_le α] [zero_le_one_class α] : zero_le_one_class (with_top α) :=
⟨some_le_some.2 zero_le_one⟩
end has_one
section has_add
variables [has_add α] {a b c d : with_top α} {x y : α}
instance : has_add (with_top α) := ⟨option.map₂ (+)⟩
@[norm_cast] lemma coe_add : ((x + y : α) : with_top α) = x + y := rfl
@[norm_cast] lemma coe_bit0 : ((bit0 x : α) : with_top α) = bit0 x := rfl
@[norm_cast] lemma coe_bit1 [has_one α] {a : α} : ((bit1 a : α) : with_top α) = bit1 a := rfl
@[simp] lemma top_add (a : with_top α) : ⊤ + a = ⊤ := rfl
@[simp] lemma add_top (a : with_top α) : a + ⊤ = ⊤ := by cases a; refl
@[simp] lemma add_eq_top : a + b = ⊤ ↔ a = ⊤ ∨ b = ⊤ :=
by cases a; cases b; simp [none_eq_top, some_eq_coe, ←with_top.coe_add]
lemma add_ne_top : a + b ≠ ⊤ ↔ a ≠ ⊤ ∧ b ≠ ⊤ := add_eq_top.not.trans not_or_distrib
lemma add_lt_top [has_lt α] {a b : with_top α} : a + b < ⊤ ↔ a < ⊤ ∧ b < ⊤ :=
by simp_rw [with_top.lt_top_iff_ne_top, add_ne_top]
lemma add_eq_coe : ∀ {a b : with_top α} {c : α},
a + b = c ↔ ∃ (a' b' : α), ↑a' = a ∧ ↑b' = b ∧ a' + b' = c
| none b c := by simp [none_eq_top]
| (some a) none c := by simp [none_eq_top]
| (some a) (some b) c :=
by simp only [some_eq_coe, ← coe_add, coe_eq_coe, exists_and_distrib_left, exists_eq_left]
@[simp] lemma add_coe_eq_top_iff {x : with_top α} {y : α} : x + y = ⊤ ↔ x = ⊤ :=
by { induction x using with_top.rec_top_coe; simp [← coe_add] }
@[simp] lemma coe_add_eq_top_iff {y : with_top α} : ↑x + y = ⊤ ↔ y = ⊤ :=
by { induction y using with_top.rec_top_coe; simp [← coe_add] }
instance covariant_class_add_le [has_le α] [covariant_class α α (+) (≤)] :
covariant_class (with_top α) (with_top α) (+) (≤) :=
⟨λ a b c h, begin
cases a; cases c; try { exact le_top },
rcases le_coe_iff.1 h with ⟨b, rfl, h'⟩,
exact coe_le_coe.2 (add_le_add_left (coe_le_coe.1 h) _)
end⟩
instance covariant_class_swap_add_le [has_le α] [covariant_class α α (swap (+)) (≤)] :
covariant_class (with_top α) (with_top α) (swap (+)) (≤) :=
⟨λ a b c h, begin
cases a; cases c; try { exact le_top },
rcases le_coe_iff.1 h with ⟨b, rfl, h'⟩,
exact coe_le_coe.2 (add_le_add_right (coe_le_coe.1 h) _)
end⟩
instance contravariant_class_add_lt [has_lt α] [contravariant_class α α (+) (<)] :
contravariant_class (with_top α) (with_top α) (+) (<) :=
⟨λ a b c h, begin
induction a using with_top.rec_top_coe, { exact (not_none_lt _ h).elim },
induction b using with_top.rec_top_coe, { exact (not_none_lt _ h).elim },
induction c using with_top.rec_top_coe,
{ exact coe_lt_top _ },
{ exact coe_lt_coe.2 (lt_of_add_lt_add_left $ coe_lt_coe.1 h) }
end⟩
instance contravariant_class_swap_add_lt [has_lt α] [contravariant_class α α (swap (+)) (<)] :
contravariant_class (with_top α) (with_top α) (swap (+)) (<) :=
⟨λ a b c h, begin
cases a; cases b; try { exact (not_none_lt _ h).elim },
cases c,
{ exact coe_lt_top _ },
{ exact coe_lt_coe.2 (lt_of_add_lt_add_right $ coe_lt_coe.1 h) }
end⟩
protected lemma le_of_add_le_add_left [has_le α] [contravariant_class α α (+) (≤)] (ha : a ≠ ⊤)
(h : a + b ≤ a + c) : b ≤ c :=
begin
lift a to α using ha,
induction c using with_top.rec_top_coe, { exact le_top },
induction b using with_top.rec_top_coe, { exact (not_top_le_coe _ h).elim },
simp only [← coe_add, coe_le_coe] at h ⊢,
exact le_of_add_le_add_left h
end
protected lemma le_of_add_le_add_right [has_le α] [contravariant_class α α (swap (+)) (≤)]
(ha : a ≠ ⊤) (h : b + a ≤ c + a) : b ≤ c :=
begin
lift a to α using ha,
cases c,
{ exact le_top },
cases b,
{ exact (not_top_le_coe _ h).elim },
{ exact coe_le_coe.2 (le_of_add_le_add_right $ coe_le_coe.1 h) }
end
protected lemma add_lt_add_left [has_lt α] [covariant_class α α (+) (<)] (ha : a ≠ ⊤) (h : b < c) :
a + b < a + c :=
begin
lift a to α using ha,
rcases lt_iff_exists_coe.1 h with ⟨b, rfl, h'⟩,
cases c,
{ exact coe_lt_top _ },
{ exact coe_lt_coe.2 (add_lt_add_left (coe_lt_coe.1 h) _) }
end
protected lemma add_lt_add_right [has_lt α] [covariant_class α α (swap (+)) (<)]
(ha : a ≠ ⊤) (h : b < c) :
b + a < c + a :=
begin
lift a to α using ha,
rcases lt_iff_exists_coe.1 h with ⟨b, rfl, h'⟩,
cases c,
{ exact coe_lt_top _ },
{ exact coe_lt_coe.2 (add_lt_add_right (coe_lt_coe.1 h) _) }
end
protected lemma add_le_add_iff_left [has_le α] [covariant_class α α (+) (≤)]
[contravariant_class α α (+) (≤)]
(ha : a ≠ ⊤) : a + b ≤ a + c ↔ b ≤ c :=
⟨with_top.le_of_add_le_add_left ha, λ h, add_le_add_left h a⟩
protected lemma add_le_add_iff_right [has_le α] [covariant_class α α (swap (+)) (≤)]
[contravariant_class α α (swap (+)) (≤)] (ha : a ≠ ⊤) : b + a ≤ c + a ↔ b ≤ c :=
⟨with_top.le_of_add_le_add_right ha, λ h, add_le_add_right h a⟩
protected lemma add_lt_add_iff_left [has_lt α] [covariant_class α α (+) (<)]
[contravariant_class α α (+) (<)] (ha : a ≠ ⊤) : a + b < a + c ↔ b < c :=
⟨lt_of_add_lt_add_left, with_top.add_lt_add_left ha⟩
protected lemma add_lt_add_iff_right [has_lt α] [covariant_class α α (swap (+)) (<)]
[contravariant_class α α (swap (+)) (<)] (ha : a ≠ ⊤) : b + a < c + a ↔ b < c :=
⟨lt_of_add_lt_add_right, with_top.add_lt_add_right ha⟩
protected lemma add_lt_add_of_le_of_lt [preorder α] [covariant_class α α (+) (<)]
[covariant_class α α (swap (+)) (≤)] (ha : a ≠ ⊤) (hab : a ≤ b) (hcd : c < d) : a + c < b + d :=
(with_top.add_lt_add_left ha hcd).trans_le $ add_le_add_right hab _
protected lemma add_lt_add_of_lt_of_le [preorder α] [covariant_class α α (+) (≤)]
[covariant_class α α (swap (+)) (<)] (hc : c ≠ ⊤) (hab : a < b) (hcd : c ≤ d) : a + c < b + d :=
(with_top.add_lt_add_right hc hab).trans_le $ add_le_add_left hcd _
/- There is no `with_top.map_mul_of_mul_hom`, since `with_top` does not have a multiplication. -/
@[simp] protected lemma map_add {F} [has_add β] [add_hom_class F α β] (f : F) (a b : with_top α) :
(a + b).map f = a.map f + b.map f :=
begin
induction a using with_top.rec_top_coe,
{ exact (top_add _).symm },
{ induction b using with_top.rec_top_coe,
{ exact (add_top _).symm },
{ rw [map_coe, map_coe, ← coe_add, ← coe_add, ← map_add],
refl } },
end
end has_add
instance [add_semigroup α] : add_semigroup (with_top α) :=
{ add_assoc := λ _ _ _, option.map₂_assoc add_assoc,
..with_top.has_add }
instance [add_comm_semigroup α] : add_comm_semigroup (with_top α) :=
{ add_comm := λ _ _, option.map₂_comm add_comm,
..with_top.add_semigroup }
instance [add_zero_class α] : add_zero_class (with_top α) :=
{ zero_add := option.map₂_left_identity zero_add,
add_zero := option.map₂_right_identity add_zero,
..with_top.has_zero,
..with_top.has_add }
instance [add_monoid α] : add_monoid (with_top α) :=
{ ..with_top.add_zero_class,
..with_top.has_zero,
..with_top.add_semigroup }
instance [add_comm_monoid α] : add_comm_monoid (with_top α) :=
{ ..with_top.add_monoid, ..with_top.add_comm_semigroup }
instance [add_monoid_with_one α] : add_monoid_with_one (with_top α) :=
{ nat_cast := λ n, ↑(n : α),
nat_cast_zero := by rw [nat.cast_zero, with_top.coe_zero],
nat_cast_succ := λ n, by rw [nat.cast_add_one, with_top.coe_add, with_top.coe_one],
.. with_top.has_one, .. with_top.add_monoid }
instance [add_comm_monoid_with_one α] : add_comm_monoid_with_one (with_top α) :=
{ .. with_top.add_monoid_with_one, .. with_top.add_comm_monoid }
instance [ordered_add_comm_monoid α] : ordered_add_comm_monoid (with_top α) :=
{ add_le_add_left :=
begin
rintros a b h (_|c), { simp [none_eq_top] },
rcases b with (_|b), { simp [none_eq_top] },
rcases le_coe_iff.1 h with ⟨a, rfl, h⟩,
simp only [some_eq_coe, ← coe_add, coe_le_coe] at h ⊢,
exact add_le_add_left h c
end,
..with_top.partial_order, ..with_top.add_comm_monoid }
instance [linear_ordered_add_comm_monoid α] :
linear_ordered_add_comm_monoid_with_top (with_top α) :=
{ top_add' := with_top.top_add,
..with_top.order_top,
..with_top.linear_order,
..with_top.ordered_add_comm_monoid,
..option.nontrivial }
instance [has_le α] [has_add α] [has_exists_add_of_le α] : has_exists_add_of_le (with_top α) :=
⟨λ a b, match a, b with
| ⊤, ⊤ := by simp
| (a : α), ⊤ := λ _, ⟨⊤, rfl⟩
| (a : α), (b : α) := λ h, begin
obtain ⟨c, rfl⟩ := exists_add_of_le (with_top.coe_le_coe.1 h),
exact ⟨c, rfl⟩
end
| ⊤, (b : α) := λ h, (not_top_le_coe _ h).elim
end⟩
instance [canonically_ordered_add_monoid α] : canonically_ordered_add_monoid (with_top α) :=
{ le_self_add := λ a b, match a, b with
| ⊤, ⊤ := le_rfl
| (a : α), ⊤ := le_top
| (a : α), (b : α) := with_top.coe_le_coe.2 le_self_add
| ⊤, (b : α) := le_rfl
end,
..with_top.order_bot, ..with_top.ordered_add_comm_monoid, ..with_top.has_exists_add_of_le }
instance [canonically_linear_ordered_add_monoid α] :
canonically_linear_ordered_add_monoid (with_top α) :=
{ ..with_top.canonically_ordered_add_monoid, ..with_top.linear_order }
@[simp, norm_cast] lemma coe_nat [add_monoid_with_one α] (n : ℕ) : ((n : α) : with_top α) = n := rfl
@[simp] lemma nat_ne_top [add_monoid_with_one α] (n : ℕ) : (n : with_top α) ≠ ⊤ := coe_ne_top
@[simp] lemma top_ne_nat [add_monoid_with_one α] (n : ℕ) : (⊤ : with_top α) ≠ n := top_ne_coe
/-- Coercion from `α` to `with_top α` as an `add_monoid_hom`. -/
def coe_add_hom [add_monoid α] : α →+ with_top α :=
⟨coe, rfl, λ _ _, rfl⟩
@[simp] lemma coe_coe_add_hom [add_monoid α] : ⇑(coe_add_hom : α →+ with_top α) = coe := rfl
@[simp] lemma zero_lt_top [ordered_add_comm_monoid α] : (0 : with_top α) < ⊤ :=
coe_lt_top 0
@[simp, norm_cast] lemma zero_lt_coe [ordered_add_comm_monoid α] (a : α) :
(0 : with_top α) < a ↔ 0 < a :=
coe_lt_coe
/-- A version of `with_top.map` for `one_hom`s. -/
@[to_additive "A version of `with_top.map` for `zero_hom`s", simps { fully_applied := ff }]
protected def _root_.one_hom.with_top_map {M N : Type*} [has_one M] [has_one N] (f : one_hom M N) :
one_hom (with_top M) (with_top N) :=
{ to_fun := with_top.map f,
map_one' := by rw [with_top.map_one, map_one, coe_one] }
/-- A version of `with_top.map` for `add_hom`s. -/
@[simps { fully_applied := ff }] protected def _root_.add_hom.with_top_map
{M N : Type*} [has_add M] [has_add N] (f : add_hom M N) :
add_hom (with_top M) (with_top N) :=
{ to_fun := with_top.map f,
map_add' := with_top.map_add f }
/-- A version of `with_top.map` for `add_monoid_hom`s. -/
@[simps { fully_applied := ff }] protected def _root_.add_monoid_hom.with_top_map
{M N : Type*} [add_zero_class M] [add_zero_class N] (f : M →+ N) :
with_top M →+ with_top N :=
{ to_fun := with_top.map f,
.. f.to_zero_hom.with_top_map, .. f.to_add_hom.with_top_map }
end with_top
namespace with_bot
@[to_additive] instance [has_one α] : has_one (with_bot α) := with_top.has_one
instance [has_add α] : has_add (with_bot α) := with_top.has_add
instance [add_semigroup α] : add_semigroup (with_bot α) := with_top.add_semigroup
instance [add_comm_semigroup α] : add_comm_semigroup (with_bot α) := with_top.add_comm_semigroup
instance [add_zero_class α] : add_zero_class (with_bot α) := with_top.add_zero_class
instance [add_monoid α] : add_monoid (with_bot α) := with_top.add_monoid
instance [add_comm_monoid α] : add_comm_monoid (with_bot α) := with_top.add_comm_monoid
instance [add_monoid_with_one α] : add_monoid_with_one (with_bot α) := with_top.add_monoid_with_one
instance [add_comm_monoid_with_one α] : add_comm_monoid_with_one (with_bot α) :=
with_top.add_comm_monoid_with_one
instance [has_zero α] [has_one α] [has_le α] [zero_le_one_class α] :
zero_le_one_class (with_bot α) :=
⟨some_le_some.2 zero_le_one⟩
-- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast`
@[to_additive]
lemma coe_one [has_one α] : ((1 : α) : with_bot α) = 1 := rfl
-- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast`
@[to_additive]
lemma coe_eq_one [has_one α] {a : α} : (a : with_bot α) = 1 ↔ a = 1 :=
with_top.coe_eq_one
@[simp, to_additive] lemma unbot_one [has_one α] : (1 : with_bot α).unbot coe_ne_bot = 1 := rfl
@[simp, to_additive] lemma unbot_one' [has_one α] (d : α) : (1 : with_bot α).unbot' d = 1 := rfl
@[simp, norm_cast, to_additive coe_nonneg]
lemma one_le_coe [has_one α] [has_le α] {a : α} : 1 ≤ (a : with_bot α) ↔ 1 ≤ a := coe_le_coe
@[simp, norm_cast, to_additive coe_le_zero]
lemma coe_le_one [has_one α] [has_le α] {a : α} : (a : with_bot α) ≤ 1 ↔ a ≤ 1 := coe_le_coe
@[simp, norm_cast, to_additive coe_pos]
lemma one_lt_coe [has_one α] [has_lt α] {a : α} : 1 < (a : with_bot α) ↔ 1 < a := coe_lt_coe
@[simp, norm_cast, to_additive coe_lt_zero]
lemma coe_lt_one [has_one α] [has_lt α] {a : α} : (a : with_bot α) < 1 ↔ a < 1 := coe_lt_coe
@[simp, to_additive] protected lemma map_one {β} [has_one α] (f : α → β) :
(1 : with_bot α).map f = (f 1 : with_bot β) := rfl
@[norm_cast] lemma coe_nat [add_monoid_with_one α] (n : ℕ) : ((n : α) : with_bot α) = n := rfl
@[simp] lemma nat_ne_bot [add_monoid_with_one α] (n : ℕ) : (n : with_bot α) ≠ ⊥ := coe_ne_bot
@[simp] lemma bot_ne_nat [add_monoid_with_one α] (n : ℕ) : (⊥ : with_bot α) ≠ n := bot_ne_coe
section has_add
variables [has_add α] {a b c d : with_bot α} {x y : α}
-- `norm_cast` proves those lemmas, because `with_top`/`with_bot` are reducible
lemma coe_add (a b : α) : ((a + b : α) : with_bot α) = a + b := rfl
lemma coe_bit0 : ((bit0 x : α) : with_bot α) = bit0 x := rfl
lemma coe_bit1 [has_one α] {a : α} : ((bit1 a : α) : with_bot α) = bit1 a := rfl
@[simp] lemma bot_add (a : with_bot α) : ⊥ + a = ⊥ := rfl
@[simp] lemma add_bot (a : with_bot α) : a + ⊥ = ⊥ := by cases a; refl
@[simp] lemma add_eq_bot : a + b = ⊥ ↔ a = ⊥ ∨ b = ⊥ := with_top.add_eq_top
lemma add_ne_bot : a + b ≠ ⊥ ↔ a ≠ ⊥ ∧ b ≠ ⊥ := with_top.add_ne_top
lemma bot_lt_add [has_lt α] {a b : with_bot α} : ⊥ < a + b ↔ ⊥ < a ∧ ⊥ < b :=
@with_top.add_lt_top αᵒᵈ _ _ _ _
lemma add_eq_coe : a + b = x ↔ ∃ (a' b' : α), ↑a' = a ∧ ↑b' = b ∧ a' + b' = x := with_top.add_eq_coe
@[simp] lemma add_coe_eq_bot_iff : a + y = ⊥ ↔ a = ⊥ := with_top.add_coe_eq_top_iff
@[simp] lemma coe_add_eq_bot_iff : ↑x + b = ⊥ ↔ b = ⊥ := with_top.coe_add_eq_top_iff
/- There is no `with_bot.map_mul_of_mul_hom`, since `with_bot` does not have a multiplication. -/
@[simp] protected lemma map_add {F} [has_add β] [add_hom_class F α β] (f : F) (a b : with_bot α) :
(a + b).map f = a.map f + b.map f :=
with_top.map_add f a b
/-- A version of `with_bot.map` for `one_hom`s. -/
@[to_additive "A version of `with_bot.map` for `zero_hom`s", simps { fully_applied := ff }]
protected def _root_.one_hom.with_bot_map {M N : Type*} [has_one M] [has_one N] (f : one_hom M N) :
one_hom (with_bot M) (with_bot N) :=
{ to_fun := with_bot.map f,
map_one' := by rw [with_bot.map_one, map_one, coe_one] }
/-- A version of `with_bot.map` for `add_hom`s. -/
@[simps { fully_applied := ff }] protected def _root_.add_hom.with_bot_map
{M N : Type*} [has_add M] [has_add N] (f : add_hom M N) :
add_hom (with_bot M) (with_bot N) :=
{ to_fun := with_bot.map f,
map_add' := with_bot.map_add f }
/-- A version of `with_bot.map` for `add_monoid_hom`s. -/
@[simps { fully_applied := ff }] protected def _root_.add_monoid_hom.with_bot_map
{M N : Type*} [add_zero_class M] [add_zero_class N] (f : M →+ N) :
with_bot M →+ with_bot N :=
{ to_fun := with_bot.map f,
.. f.to_zero_hom.with_bot_map, .. f.to_add_hom.with_bot_map }
variables [preorder α]
instance covariant_class_add_le [covariant_class α α (+) (≤)] :
covariant_class (with_bot α) (with_bot α) (+) (≤) :=
@order_dual.covariant_class_add_le (with_top αᵒᵈ) _ _ _
instance covariant_class_swap_add_le [covariant_class α α (swap (+)) (≤)] :
covariant_class (with_bot α) (with_bot α) (swap (+)) (≤) :=
@order_dual.covariant_class_swap_add_le (with_top αᵒᵈ) _ _ _
instance contravariant_class_add_lt [contravariant_class α α (+) (<)] :
contravariant_class (with_bot α) (with_bot α) (+) (<) :=
@order_dual.contravariant_class_add_lt (with_top αᵒᵈ) _ _ _
instance contravariant_class_swap_add_lt [contravariant_class α α (swap (+)) (<)] :
contravariant_class (with_bot α) (with_bot α) (swap (+)) (<) :=
@order_dual.contravariant_class_swap_add_lt (with_top αᵒᵈ) _ _ _
protected lemma le_of_add_le_add_left [contravariant_class α α (+) (≤)] (ha : a ≠ ⊥)
(h : a + b ≤ a + c) : b ≤ c :=
@with_top.le_of_add_le_add_left αᵒᵈ _ _ _ _ _ _ ha h
protected lemma le_of_add_le_add_right [contravariant_class α α (swap (+)) (≤)] (ha : a ≠ ⊥)
(h : b + a ≤ c + a) : b ≤ c :=
@with_top.le_of_add_le_add_right αᵒᵈ _ _ _ _ _ _ ha h
protected lemma add_lt_add_left [covariant_class α α (+) (<)] (ha : a ≠ ⊥) (h : b < c) :
a + b < a + c :=
@with_top.add_lt_add_left αᵒᵈ _ _ _ _ _ _ ha h
protected lemma add_lt_add_right [covariant_class α α (swap (+)) (<)] (ha : a ≠ ⊥) (h : b < c) :
b + a < c + a :=
@with_top.add_lt_add_right αᵒᵈ _ _ _ _ _ _ ha h
protected lemma add_le_add_iff_left [covariant_class α α (+) (≤)] [contravariant_class α α (+) (≤)]
(ha : a ≠ ⊥) : a + b ≤ a + c ↔ b ≤ c :=
⟨with_bot.le_of_add_le_add_left ha, λ h, add_le_add_left h a⟩
protected lemma add_le_add_iff_right [covariant_class α α (swap (+)) (≤)]
[contravariant_class α α (swap (+)) (≤)] (ha : a ≠ ⊥) : b + a ≤ c + a ↔ b ≤ c :=
⟨with_bot.le_of_add_le_add_right ha, λ h, add_le_add_right h a⟩
protected lemma add_lt_add_iff_left [covariant_class α α (+) (<)] [contravariant_class α α (+) (<)]
(ha : a ≠ ⊥) : a + b < a + c ↔ b < c :=
⟨lt_of_add_lt_add_left, with_bot.add_lt_add_left ha⟩
protected lemma add_lt_add_iff_right [covariant_class α α (swap (+)) (<)]
[contravariant_class α α (swap (+)) (<)] (ha : a ≠ ⊥) : b + a < c + a ↔ b < c :=
⟨lt_of_add_lt_add_right, with_bot.add_lt_add_right ha⟩
protected lemma add_lt_add_of_le_of_lt [covariant_class α α (+) (<)]
[covariant_class α α (swap (+)) (≤)] (hb : b ≠ ⊥) (hab : a ≤ b) (hcd : c < d) : a + c < b + d :=
@with_top.add_lt_add_of_le_of_lt αᵒᵈ _ _ _ _ _ _ _ _ hb hab hcd
protected lemma add_lt_add_of_lt_of_le [covariant_class α α (+) (≤)]
[covariant_class α α (swap (+)) (<)] (hd : d ≠ ⊥) (hab : a < b) (hcd : c ≤ d) : a + c < b + d :=
@with_top.add_lt_add_of_lt_of_le αᵒᵈ _ _ _ _ _ _ _ _ hd hab hcd
end has_add
instance [ordered_add_comm_monoid α] : ordered_add_comm_monoid (with_bot α) :=
{ add_le_add_left := λ a b h c, add_le_add_left h c,
..with_bot.partial_order,
..with_bot.add_comm_monoid }
instance [linear_ordered_add_comm_monoid α] : linear_ordered_add_comm_monoid (with_bot α) :=
{ ..with_bot.linear_order, ..with_bot.ordered_add_comm_monoid }
end with_bot
|
8cb77c10452c2f9f4d20160d04b1c0ff2baa1125 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/geometry/manifold/local_invariant_properties.lean | fedd470ff9b59ae342f6bde3163b2d06122d33d4 | [
"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 | 34,748 | lean | /-
Copyright (c) 2020 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel, Floris van Doorn
-/
import geometry.manifold.charted_space
/-!
# Local properties invariant under a groupoid
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We study properties of a triple `(g, s, x)` where `g` is a function between two spaces `H` and `H'`,
`s` is a subset of `H` and `x` is a point of `H`. Our goal is to register how such a property
should behave to make sense in charted spaces modelled on `H` and `H'`.
The main examples we have in mind are the properties "`g` is differentiable at `x` within `s`", or
"`g` is smooth at `x` within `s`". We want to develop general results that, when applied in these
specific situations, say that the notion of smooth function in a manifold behaves well under
restriction, intersection, is local, and so on.
## Main definitions
* `local_invariant_prop G G' P` says that a property `P` of a triple `(g, s, x)` is local, and
invariant under composition by elements of the groupoids `G` and `G'` of `H` and `H'`
respectively.
* `charted_space.lift_prop_within_at` (resp. `lift_prop_at`, `lift_prop_on` and `lift_prop`):
given a property `P` of `(g, s, x)` where `g : H → H'`, define the corresponding property
for functions `M → M'` where `M` and `M'` are charted spaces modelled respectively on `H` and
`H'`. We define these properties within a set at a point, or at a point, or on a set, or in the
whole space. This lifting process (obtained by restricting to suitable chart domains) can always
be done, but it only behaves well under locality and invariance assumptions.
Given `hG : local_invariant_prop G G' P`, we deduce many properties of the lifted property on the
charted spaces. For instance, `hG.lift_prop_within_at_inter` says that `P g s x` is equivalent to
`P g (s ∩ t) x` whenever `t` is a neighborhood of `x`.
## Implementation notes
We do not use dot notation for properties of the lifted property. For instance, we have
`hG.lift_prop_within_at_congr` saying that if `lift_prop_within_at P g s x` holds, and `g` and `g'`
coincide on `s`, then `lift_prop_within_at P g' s x` holds. We can't call it
`lift_prop_within_at.congr` as it is in the namespace associated to `local_invariant_prop`, not
in the one for `lift_prop_within_at`.
-/
noncomputable theory
open_locale classical manifold topology
open set filter topological_space
variables {H M H' M' X : Type*}
variables [topological_space H] [topological_space M] [charted_space H M]
variables [topological_space H'] [topological_space M'] [charted_space H' M']
variables [topological_space X]
namespace structure_groupoid
variables (G : structure_groupoid H) (G' : structure_groupoid H')
/-- Structure recording good behavior of a property of a triple `(f, s, x)` where `f` is a function,
`s` a set and `x` a point. Good behavior here means locality and invariance under given groupoids
(both in the source and in the target). Given such a good behavior, the lift of this property
to charted spaces admitting these groupoids will inherit the good behavior. -/
structure local_invariant_prop (P : (H → H') → (set H) → H → Prop) : Prop :=
(is_local : ∀ {s x u} {f : H → H'}, is_open u → x ∈ u → (P f s x ↔ P f (s ∩ u) x))
(right_invariance' : ∀ {s x f} {e : local_homeomorph H H}, e ∈ G → x ∈ e.source → P f s x →
P (f ∘ e.symm) (e.symm ⁻¹' s) (e x))
(congr_of_forall : ∀ {s x} {f g : H → H'}, (∀ y ∈ s, f y = g y) → f x = g x → P f s x → P g s x)
(left_invariance' : ∀ {s x f} {e' : local_homeomorph H' H'}, e' ∈ G' → s ⊆ f ⁻¹' e'.source →
f x ∈ e'.source → P f s x → P (e' ∘ f) s x)
variables {G G'} {P : (H → H') → (set H) → H → Prop} {s t u : set H} {x : H}
variable (hG : G.local_invariant_prop G' P)
include hG
namespace local_invariant_prop
lemma congr_set {s t : set H} {x : H} {f : H → H'} (hu : s =ᶠ[𝓝 x] t) :
P f s x ↔ P f t x :=
begin
obtain ⟨o, host, ho, hxo⟩ := mem_nhds_iff.mp hu.mem_iff,
simp_rw [subset_def, mem_set_of, ← and.congr_left_iff, ← mem_inter_iff, ← set.ext_iff] at host,
rw [hG.is_local ho hxo, host, ← hG.is_local ho hxo]
end
lemma is_local_nhds {s u : set H} {x : H} {f : H → H'} (hu : u ∈ 𝓝[s] x) :
P f s x ↔ P f (s ∩ u) x :=
hG.congr_set $ mem_nhds_within_iff_eventually_eq.mp hu
lemma congr_iff_nhds_within {s : set H} {x : H} {f g : H → H'} (h1 : f =ᶠ[𝓝[s] x] g)
(h2 : f x = g x) : P f s x ↔ P g s x :=
by { simp_rw [hG.is_local_nhds h1],
exact ⟨hG.congr_of_forall (λ y hy, hy.2) h2, hG.congr_of_forall (λ y hy, hy.2.symm) h2.symm⟩ }
lemma congr_nhds_within {s : set H} {x : H} {f g : H → H'} (h1 : f =ᶠ[𝓝[s] x] g) (h2 : f x = g x)
(hP : P f s x) : P g s x :=
(hG.congr_iff_nhds_within h1 h2).mp hP
lemma congr_nhds_within' {s : set H} {x : H} {f g : H → H'} (h1 : f =ᶠ[𝓝[s] x] g) (h2 : f x = g x)
(hP : P g s x) : P f s x :=
(hG.congr_iff_nhds_within h1 h2).mpr hP
lemma congr_iff {s : set H} {x : H} {f g : H → H'} (h : f =ᶠ[𝓝 x] g) : P f s x ↔ P g s x :=
hG.congr_iff_nhds_within (mem_nhds_within_of_mem_nhds h) (mem_of_mem_nhds h : _)
lemma congr {s : set H} {x : H} {f g : H → H'} (h : f =ᶠ[𝓝 x] g) (hP : P f s x) : P g s x :=
(hG.congr_iff h).mp hP
lemma congr' {s : set H} {x : H} {f g : H → H'} (h : f =ᶠ[𝓝 x] g) (hP : P g s x) : P f s x :=
hG.congr h.symm hP
lemma left_invariance {s : set H} {x : H} {f : H → H'} {e' : local_homeomorph H' H'}
(he' : e' ∈ G') (hfs : continuous_within_at f s x) (hxe' : f x ∈ e'.source) :
P (e' ∘ f) s x ↔ P f s x :=
begin
have h2f := hfs.preimage_mem_nhds_within (e'.open_source.mem_nhds hxe'),
have h3f := (((e'.continuous_at hxe').comp_continuous_within_at hfs).preimage_mem_nhds_within $
e'.symm.open_source.mem_nhds $ e'.maps_to hxe'),
split,
{ intro h,
rw [hG.is_local_nhds h3f] at h,
have h2 := hG.left_invariance' (G'.symm he') (inter_subset_right _ _)
(by exact e'.maps_to hxe') h,
rw [← hG.is_local_nhds h3f] at h2,
refine hG.congr_nhds_within _ (e'.left_inv hxe') h2,
exact eventually_of_mem h2f (λ x', e'.left_inv) },
{ simp_rw [hG.is_local_nhds h2f],
exact hG.left_invariance' he' (inter_subset_right _ _) hxe' }
end
lemma right_invariance {s : set H} {x : H} {f : H → H'} {e : local_homeomorph H H}
(he : e ∈ G) (hxe : x ∈ e.source) : P (f ∘ e.symm) (e.symm ⁻¹' s) (e x) ↔ P f s x :=
begin
refine ⟨λ h, _, hG.right_invariance' he hxe⟩,
have := hG.right_invariance' (G.symm he) (e.maps_to hxe) h,
rw [e.symm_symm, e.left_inv hxe] at this,
refine hG.congr _ ((hG.congr_set _).mp this),
{ refine eventually_of_mem (e.open_source.mem_nhds hxe) (λ x' hx', _),
simp_rw [function.comp_apply, e.left_inv hx'] },
{ rw [eventually_eq_set],
refine eventually_of_mem (e.open_source.mem_nhds hxe) (λ x' hx', _),
simp_rw [mem_preimage, e.left_inv hx'] },
end
end local_invariant_prop
end structure_groupoid
namespace charted_space
/-- Given a property of germs of functions and sets in the model space, then one defines
a corresponding property in a charted space, by requiring that it holds at the preferred chart at
this point. (When the property is local and invariant, it will in fact hold using any chart, see
`lift_prop_within_at_indep_chart`). We require continuity in the lifted property, as otherwise one
single chart might fail to capture the behavior of the function.
-/
def lift_prop_within_at (P : (H → H') → set H → H → Prop)
(f : M → M') (s : set M) (x : M) : Prop :=
continuous_within_at f s x ∧
P (chart_at H' (f x) ∘ f ∘ (chart_at H x).symm) ((chart_at H x).symm ⁻¹' s) (chart_at H x x)
/-- Given a property of germs of functions and sets in the model space, then one defines
a corresponding property of functions on sets in a charted space, by requiring that it holds
around each point of the set, in the preferred charts. -/
def lift_prop_on (P : (H → H') → set H → H → Prop) (f : M → M') (s : set M) :=
∀ x ∈ s, lift_prop_within_at P f s x
/-- Given a property of germs of functions and sets in the model space, then one defines
a corresponding property of a function at a point in a charted space, by requiring that it holds
in the preferred chart. -/
def lift_prop_at (P : (H → H') → set H → H → Prop) (f : M → M') (x : M) :=
lift_prop_within_at P f univ x
lemma lift_prop_at_iff {P : (H → H') → set H → H → Prop} {f : M → M'} {x : M} :
lift_prop_at P f x ↔ continuous_at f x ∧
P (chart_at H' (f x) ∘ f ∘ (chart_at H x).symm) univ (chart_at H x x) :=
by rw [lift_prop_at, lift_prop_within_at, continuous_within_at_univ, preimage_univ]
/-- Given a property of germs of functions and sets in the model space, then one defines
a corresponding property of a function in a charted space, by requiring that it holds
in the preferred chart around every point. -/
def lift_prop (P : (H → H') → set H → H → Prop) (f : M → M') :=
∀ x, lift_prop_at P f x
lemma lift_prop_iff {P : (H → H') → set H → H → Prop} {f : M → M'} :
lift_prop P f ↔ continuous f ∧
∀ x, P (chart_at H' (f x) ∘ f ∘ (chart_at H x).symm) univ (chart_at H x x) :=
by simp_rw [lift_prop, lift_prop_at_iff, forall_and_distrib, continuous_iff_continuous_at]
end charted_space
open charted_space
namespace structure_groupoid
variables {G : structure_groupoid H} {G' : structure_groupoid H'}
{e e' : local_homeomorph M H} {f f' : local_homeomorph M' H'}
{P : (H → H') → set H → H → Prop} {g g' : M → M'} {s t : set M} {x : M}
{Q : (H → H) → set H → H → Prop}
lemma lift_prop_within_at_univ : lift_prop_within_at P g univ x ↔ lift_prop_at P g x :=
iff.rfl
lemma lift_prop_on_univ : lift_prop_on P g univ ↔ lift_prop P g :=
by simp [lift_prop_on, lift_prop, lift_prop_at]
lemma lift_prop_within_at_self {f : H → H'} {s : set H} {x : H} :
lift_prop_within_at P f s x ↔ continuous_within_at f s x ∧ P f s x :=
iff.rfl
lemma lift_prop_within_at_self_source {f : H → M'} {s : set H} {x : H} :
lift_prop_within_at P f s x ↔ continuous_within_at f s x ∧ P (chart_at H' (f x) ∘ f) s x :=
iff.rfl
lemma lift_prop_within_at_self_target {f : M → H'} :
lift_prop_within_at P f s x ↔
continuous_within_at f s x ∧
P (f ∘ (chart_at H x).symm) ((chart_at H x).symm ⁻¹' s) (chart_at H x x) :=
iff.rfl
namespace local_invariant_prop
variable (hG : G.local_invariant_prop G' P)
include hG
/-- `lift_prop_within_at P f s x` is equivalent to a definition where we restrict the set we are
considering to the domain of the charts at `x` and `f x`. -/
lemma lift_prop_within_at_iff {f : M → M'} :
lift_prop_within_at P f s x ↔
continuous_within_at f s x ∧ P ((chart_at H' (f x)) ∘ f ∘ (chart_at H x).symm)
((chart_at H x).target ∩ (chart_at H x).symm ⁻¹' (s ∩ f ⁻¹' (chart_at H' (f x)).source))
(chart_at H x x) :=
begin
refine and_congr_right (λ hf, hG.congr_set _),
exact local_homeomorph.preimage_eventually_eq_target_inter_preimage_inter hf
(mem_chart_source H x) (chart_source_mem_nhds H' (f x))
end
lemma lift_prop_within_at_indep_chart_source_aux (g : M → H')
(he : e ∈ G.maximal_atlas M) (xe : x ∈ e.source)
(he' : e' ∈ G.maximal_atlas M) (xe' : x ∈ e'.source) :
P (g ∘ e.symm) (e.symm ⁻¹' s) (e x) ↔ P (g ∘ e'.symm) (e'.symm ⁻¹' s) (e' x) :=
begin
rw [← hG.right_invariance (compatible_of_mem_maximal_atlas he he')],
swap, { simp only [xe, xe'] with mfld_simps },
simp_rw [local_homeomorph.trans_apply, e.left_inv xe],
rw [hG.congr_iff],
{ refine hG.congr_set _,
refine (eventually_of_mem _ $ λ y (hy : y ∈ e'.symm ⁻¹' e.source), _).set_eq,
{ refine (e'.symm.continuous_at $ e'.maps_to xe').preimage_mem_nhds (e.open_source.mem_nhds _),
simp_rw [e'.left_inv xe', xe] },
simp_rw [mem_preimage, local_homeomorph.coe_trans_symm, local_homeomorph.symm_symm,
function.comp_apply, e.left_inv hy] },
{ refine ((e'.eventually_nhds' _ xe').mpr $ e.eventually_left_inverse xe).mono (λ y hy, _),
simp only with mfld_simps,
rw [hy] },
end
lemma lift_prop_within_at_indep_chart_target_aux2 (g : H → M') {x : H} {s : set H}
(hf : f ∈ G'.maximal_atlas M') (xf : g x ∈ f.source)
(hf' : f' ∈ G'.maximal_atlas M') (xf' : g x ∈ f'.source)
(hgs : continuous_within_at g s x) :
P (f ∘ g) s x ↔ P (f' ∘ g) s x :=
begin
have hcont : continuous_within_at (f ∘ g) s x :=
(f.continuous_at xf).comp_continuous_within_at hgs,
rw [← hG.left_invariance (compatible_of_mem_maximal_atlas hf hf') hcont
(by simp only [xf, xf'] with mfld_simps)],
refine hG.congr_iff_nhds_within _ (by simp only [xf] with mfld_simps),
exact (hgs.eventually $ f.eventually_left_inverse xf).mono (λ y, congr_arg f')
end
lemma lift_prop_within_at_indep_chart_target_aux {g : X → M'} {e : local_homeomorph X H} {x : X}
{s : set X} (xe : x ∈ e.source)
(hf : f ∈ G'.maximal_atlas M') (xf : g x ∈ f.source)
(hf' : f' ∈ G'.maximal_atlas M') (xf' : g x ∈ f'.source)
(hgs : continuous_within_at g s x) :
P (f ∘ g ∘ e.symm) (e.symm ⁻¹' s) (e x) ↔ P (f' ∘ g ∘ e.symm) (e.symm ⁻¹' s) (e x) :=
begin
rw [← e.left_inv xe] at xf xf' hgs,
refine hG.lift_prop_within_at_indep_chart_target_aux2 (g ∘ e.symm) hf xf hf' xf' _,
exact hgs.comp (e.symm.continuous_at $ e.maps_to xe).continuous_within_at subset.rfl
end
/-- If a property of a germ of function `g` on a pointed set `(s, x)` is invariant under the
structure groupoid (by composition in the source space and in the target space), then
expressing it in charted spaces does not depend on the element of the maximal atlas one uses
both in the source and in the target manifolds, provided they are defined around `x` and `g x`
respectively, and provided `g` is continuous within `s` at `x` (otherwise, the local behavior
of `g` at `x` can not be captured with a chart in the target). -/
lemma lift_prop_within_at_indep_chart_aux
(he : e ∈ G.maximal_atlas M) (xe : x ∈ e.source)
(he' : e' ∈ G.maximal_atlas M) (xe' : x ∈ e'.source)
(hf : f ∈ G'.maximal_atlas M') (xf : g x ∈ f.source)
(hf' : f' ∈ G'.maximal_atlas M') (xf' : g x ∈ f'.source)
(hgs : continuous_within_at g s x) :
P (f ∘ g ∘ e.symm) (e.symm ⁻¹' s) (e x) ↔ P (f' ∘ g ∘ e'.symm) (e'.symm ⁻¹' s) (e' x) :=
by rw [hG.lift_prop_within_at_indep_chart_source_aux (f ∘ g) he xe he' xe',
hG.lift_prop_within_at_indep_chart_target_aux xe' hf xf hf' xf' hgs]
lemma lift_prop_within_at_indep_chart [has_groupoid M G] [has_groupoid M' G']
(he : e ∈ G.maximal_atlas M) (xe : x ∈ e.source)
(hf : f ∈ G'.maximal_atlas M') (xf : g x ∈ f.source) :
lift_prop_within_at P g s x ↔
continuous_within_at g s x ∧ P (f ∘ g ∘ e.symm) (e.symm ⁻¹' s) (e x) :=
and_congr_right $ hG.lift_prop_within_at_indep_chart_aux (chart_mem_maximal_atlas _ _)
(mem_chart_source _ _) he xe (chart_mem_maximal_atlas _ _) (mem_chart_source _ _) hf xf
/-- A version of `lift_prop_within_at_indep_chart`, only for the source. -/
lemma lift_prop_within_at_indep_chart_source [has_groupoid M G]
(he : e ∈ G.maximal_atlas M) (xe : x ∈ e.source) :
lift_prop_within_at P g s x ↔ lift_prop_within_at P (g ∘ e.symm) (e.symm ⁻¹' s) (e x) :=
begin
have := e.symm.continuous_within_at_iff_continuous_within_at_comp_right xe,
rw [e.symm_symm] at this,
rw [lift_prop_within_at_self_source, lift_prop_within_at, ← this],
simp_rw [function.comp_app, e.left_inv xe],
refine and_congr iff.rfl _,
rw hG.lift_prop_within_at_indep_chart_source_aux (chart_at H' (g x) ∘ g)
(chart_mem_maximal_atlas G x) (mem_chart_source H x) he xe,
end
/-- A version of `lift_prop_within_at_indep_chart`, only for the target. -/
lemma lift_prop_within_at_indep_chart_target [has_groupoid M' G']
(hf : f ∈ G'.maximal_atlas M') (xf : g x ∈ f.source) :
lift_prop_within_at P g s x ↔ continuous_within_at g s x ∧ lift_prop_within_at P (f ∘ g) s x :=
begin
rw [lift_prop_within_at_self_target, lift_prop_within_at, and.congr_right_iff],
intro hg,
simp_rw [(f.continuous_at xf).comp_continuous_within_at hg, true_and],
exact hG.lift_prop_within_at_indep_chart_target_aux (mem_chart_source _ _)
(chart_mem_maximal_atlas _ _) (mem_chart_source _ _) hf xf hg
end
/-- A version of `lift_prop_within_at_indep_chart`, that uses `lift_prop_within_at` on both sides.
-/
lemma lift_prop_within_at_indep_chart' [has_groupoid M G] [has_groupoid M' G']
(he : e ∈ G.maximal_atlas M) (xe : x ∈ e.source)
(hf : f ∈ G'.maximal_atlas M') (xf : g x ∈ f.source) :
lift_prop_within_at P g s x ↔
continuous_within_at g s x ∧ lift_prop_within_at P (f ∘ g ∘ e.symm) (e.symm ⁻¹' s) (e x) :=
begin
rw [hG.lift_prop_within_at_indep_chart he xe hf xf, lift_prop_within_at_self, and.left_comm,
iff.comm, and_iff_right_iff_imp],
intro h,
have h1 := (e.symm.continuous_within_at_iff_continuous_within_at_comp_right xe).mp h.1,
have : continuous_at f ((g ∘ e.symm) (e x)),
{ simp_rw [function.comp, e.left_inv xe, f.continuous_at xf] },
exact this.comp_continuous_within_at h1,
end
lemma lift_prop_on_indep_chart [has_groupoid M G] [has_groupoid M' G']
(he : e ∈ G.maximal_atlas M) (hf : f ∈ G'.maximal_atlas M') (h : lift_prop_on P g s)
{y : H} (hy : y ∈ e.target ∩ e.symm ⁻¹' (s ∩ g ⁻¹' f.source)) :
P (f ∘ g ∘ e.symm) (e.symm ⁻¹' s) y :=
begin
convert ((hG.lift_prop_within_at_indep_chart he (e.symm_maps_to hy.1) hf hy.2.2).1
(h _ hy.2.1)).2,
rw [e.right_inv hy.1],
end
lemma lift_prop_within_at_inter' (ht : t ∈ 𝓝[s] x) :
lift_prop_within_at P g (s ∩ t) x ↔ lift_prop_within_at P g s x :=
begin
rw [lift_prop_within_at, lift_prop_within_at, continuous_within_at_inter' ht, hG.congr_set],
simp_rw [eventually_eq_set, mem_preimage,
(chart_at H x).eventually_nhds' (λ x, x ∈ s ∩ t ↔ x ∈ s) (mem_chart_source H x)],
exact (mem_nhds_within_iff_eventually_eq.mp ht).symm.mem_iff
end
lemma lift_prop_within_at_inter (ht : t ∈ 𝓝 x) :
lift_prop_within_at P g (s ∩ t) x ↔ lift_prop_within_at P g s x :=
hG.lift_prop_within_at_inter' (mem_nhds_within_of_mem_nhds ht)
lemma lift_prop_at_of_lift_prop_within_at (h : lift_prop_within_at P g s x) (hs : s ∈ 𝓝 x) :
lift_prop_at P g x :=
by rwa [← univ_inter s, hG.lift_prop_within_at_inter hs] at h
lemma lift_prop_within_at_of_lift_prop_at_of_mem_nhds (h : lift_prop_at P g x) (hs : s ∈ 𝓝 x) :
lift_prop_within_at P g s x :=
by rwa [← univ_inter s, hG.lift_prop_within_at_inter hs]
lemma lift_prop_on_of_locally_lift_prop_on
(h : ∀ x ∈ s, ∃ u, is_open u ∧ x ∈ u ∧ lift_prop_on P g (s ∩ u)) :
lift_prop_on P g s :=
begin
assume x hx,
rcases h x hx with ⟨u, u_open, xu, hu⟩,
have := hu x ⟨hx, xu⟩,
rwa hG.lift_prop_within_at_inter at this,
exact is_open.mem_nhds u_open xu,
end
lemma lift_prop_of_locally_lift_prop_on (h : ∀ x, ∃ u, is_open u ∧ x ∈ u ∧ lift_prop_on P g u) :
lift_prop P g :=
begin
rw ← lift_prop_on_univ,
apply hG.lift_prop_on_of_locally_lift_prop_on (λ x hx, _),
simp [h x],
end
lemma lift_prop_within_at_congr_of_eventually_eq
(h : lift_prop_within_at P g s x) (h₁ : g' =ᶠ[𝓝[s] x] g) (hx : g' x = g x) :
lift_prop_within_at P g' s x :=
begin
refine ⟨h.1.congr_of_eventually_eq h₁ hx, _⟩,
refine hG.congr_nhds_within' _ (by simp_rw [function.comp_apply,
(chart_at H x).left_inv (mem_chart_source H x), hx]) h.2,
simp_rw [eventually_eq, function.comp_app, (chart_at H x).eventually_nhds_within'
(λ y, chart_at H' (g' x) (g' y) = chart_at H' (g x) (g y))
(mem_chart_source H x)],
exact h₁.mono (λ y hy, by rw [hx, hy])
end
lemma lift_prop_within_at_congr_iff_of_eventually_eq (h₁ : g' =ᶠ[𝓝[s] x] g) (hx : g' x = g x) :
lift_prop_within_at P g' s x ↔ lift_prop_within_at P g s x :=
⟨λ h, hG.lift_prop_within_at_congr_of_eventually_eq h h₁.symm hx.symm,
λ h, hG.lift_prop_within_at_congr_of_eventually_eq h h₁ hx⟩
lemma lift_prop_within_at_congr_iff
(h₁ : ∀ y ∈ s, g' y = g y) (hx : g' x = g x) :
lift_prop_within_at P g' s x ↔ lift_prop_within_at P g s x :=
hG.lift_prop_within_at_congr_iff_of_eventually_eq (eventually_nhds_within_of_forall h₁) hx
lemma lift_prop_within_at_congr
(h : lift_prop_within_at P g s x) (h₁ : ∀ y ∈ s, g' y = g y) (hx : g' x = g x) :
lift_prop_within_at P g' s x :=
(hG.lift_prop_within_at_congr_iff h₁ hx).mpr h
lemma lift_prop_at_congr_iff_of_eventually_eq
(h₁ : g' =ᶠ[𝓝 x] g) : lift_prop_at P g' x ↔ lift_prop_at P g x :=
hG.lift_prop_within_at_congr_iff_of_eventually_eq (by simp_rw [nhds_within_univ, h₁]) h₁.eq_of_nhds
lemma lift_prop_at_congr_of_eventually_eq (h : lift_prop_at P g x) (h₁ : g' =ᶠ[𝓝 x] g) :
lift_prop_at P g' x :=
(hG.lift_prop_at_congr_iff_of_eventually_eq h₁).mpr h
lemma lift_prop_on_congr (h : lift_prop_on P g s) (h₁ : ∀ y ∈ s, g' y = g y) :
lift_prop_on P g' s :=
λ x hx, hG.lift_prop_within_at_congr (h x hx) h₁ (h₁ x hx)
lemma lift_prop_on_congr_iff (h₁ : ∀ y ∈ s, g' y = g y) :
lift_prop_on P g' s ↔ lift_prop_on P g s :=
⟨λ h, hG.lift_prop_on_congr h (λ y hy, (h₁ y hy).symm), λ h, hG.lift_prop_on_congr h h₁⟩
omit hG
lemma lift_prop_within_at_mono_of_mem
(mono_of_mem : ∀ ⦃s x t⦄ ⦃f : H → H'⦄, s ∈ 𝓝[t] x → P f s x → P f t x)
(h : lift_prop_within_at P g s x) (hst : s ∈ 𝓝[t] x) :
lift_prop_within_at P g t x :=
begin
refine ⟨h.1.mono_of_mem hst, mono_of_mem _ h.2⟩,
simp_rw [← mem_map, (chart_at H x).symm.map_nhds_within_preimage_eq (mem_chart_target H x),
(chart_at H x).left_inv (mem_chart_source H x), hst]
end
lemma lift_prop_within_at_mono
(mono : ∀ ⦃s x t⦄ ⦃f : H → H'⦄, t ⊆ s → P f s x → P f t x)
(h : lift_prop_within_at P g s x) (hts : t ⊆ s) :
lift_prop_within_at P g t x :=
begin
refine ⟨h.1.mono hts, _⟩,
apply mono (λ y hy, _) h.2,
simp only with mfld_simps at hy,
simp only [hy, hts _] with mfld_simps,
end
lemma lift_prop_within_at_of_lift_prop_at
(mono : ∀ ⦃s x t⦄ ⦃f : H → H'⦄, t ⊆ s → P f s x → P f t x) (h : lift_prop_at P g x) :
lift_prop_within_at P g s x :=
begin
rw ← lift_prop_within_at_univ at h,
exact lift_prop_within_at_mono mono h (subset_univ _),
end
lemma lift_prop_on_mono (mono : ∀ ⦃s x t⦄ ⦃f : H → H'⦄, t ⊆ s → P f s x → P f t x)
(h : lift_prop_on P g t) (hst : s ⊆ t) :
lift_prop_on P g s :=
λ x hx, lift_prop_within_at_mono mono (h x (hst hx)) hst
lemma lift_prop_on_of_lift_prop
(mono : ∀ ⦃s x t⦄ ⦃f : H → H'⦄, t ⊆ s → P f s x → P f t x) (h : lift_prop P g) :
lift_prop_on P g s :=
begin
rw ← lift_prop_on_univ at h,
exact lift_prop_on_mono mono h (subset_univ _)
end
lemma lift_prop_at_of_mem_maximal_atlas [has_groupoid M G]
(hG : G.local_invariant_prop G Q) (hQ : ∀ y, Q id univ y)
(he : e ∈ maximal_atlas M G) (hx : x ∈ e.source) : lift_prop_at Q e x :=
begin
simp_rw [lift_prop_at,
hG.lift_prop_within_at_indep_chart he hx G.id_mem_maximal_atlas (mem_univ _),
(e.continuous_at hx).continuous_within_at, true_and],
exact hG.congr' (e.eventually_right_inverse' hx) (hQ _)
end
lemma lift_prop_on_of_mem_maximal_atlas [has_groupoid M G]
(hG : G.local_invariant_prop G Q) (hQ : ∀ y, Q id univ y) (he : e ∈ maximal_atlas M G) :
lift_prop_on Q e e.source :=
begin
assume x hx,
apply hG.lift_prop_within_at_of_lift_prop_at_of_mem_nhds
(hG.lift_prop_at_of_mem_maximal_atlas hQ he hx),
exact is_open.mem_nhds e.open_source hx,
end
lemma lift_prop_at_symm_of_mem_maximal_atlas [has_groupoid M G] {x : H}
(hG : G.local_invariant_prop G Q) (hQ : ∀ y, Q id univ y)
(he : e ∈ maximal_atlas M G) (hx : x ∈ e.target) : lift_prop_at Q e.symm x :=
begin
suffices h : Q (e ∘ e.symm) univ x,
{ have A : e.symm ⁻¹' e.source ∩ e.target = e.target,
by mfld_set_tac,
have : e.symm x ∈ e.source, by simp only [hx] with mfld_simps,
rw [lift_prop_at,
hG.lift_prop_within_at_indep_chart G.id_mem_maximal_atlas (mem_univ _) he this],
refine ⟨(e.symm.continuous_at hx).continuous_within_at, _⟩,
simp only [h] with mfld_simps },
exact hG.congr' (e.eventually_right_inverse hx) (hQ x)
end
lemma lift_prop_on_symm_of_mem_maximal_atlas [has_groupoid M G]
(hG : G.local_invariant_prop G Q) (hQ : ∀ y, Q id univ y) (he : e ∈ maximal_atlas M G) :
lift_prop_on Q e.symm e.target :=
begin
assume x hx,
apply hG.lift_prop_within_at_of_lift_prop_at_of_mem_nhds
(hG.lift_prop_at_symm_of_mem_maximal_atlas hQ he hx),
exact is_open.mem_nhds e.open_target hx,
end
lemma lift_prop_at_chart [has_groupoid M G]
(hG : G.local_invariant_prop G Q) (hQ : ∀ y, Q id univ y) : lift_prop_at Q (chart_at H x) x :=
hG.lift_prop_at_of_mem_maximal_atlas hQ (chart_mem_maximal_atlas G x) (mem_chart_source H x)
lemma lift_prop_on_chart [has_groupoid M G]
(hG : G.local_invariant_prop G Q) (hQ : ∀ y, Q id univ y) :
lift_prop_on Q (chart_at H x) (chart_at H x).source :=
hG.lift_prop_on_of_mem_maximal_atlas hQ (chart_mem_maximal_atlas G x)
lemma lift_prop_at_chart_symm [has_groupoid M G]
(hG : G.local_invariant_prop G Q) (hQ : ∀ y, Q id univ y) :
lift_prop_at Q (chart_at H x).symm ((chart_at H x) x) :=
hG.lift_prop_at_symm_of_mem_maximal_atlas hQ (chart_mem_maximal_atlas G x) (by simp)
lemma lift_prop_on_chart_symm [has_groupoid M G]
(hG : G.local_invariant_prop G Q) (hQ : ∀ y, Q id univ y) :
lift_prop_on Q (chart_at H x).symm (chart_at H x).target :=
hG.lift_prop_on_symm_of_mem_maximal_atlas hQ (chart_mem_maximal_atlas G x)
lemma lift_prop_at_of_mem_groupoid (hG : G.local_invariant_prop G Q) (hQ : ∀ y, Q id univ y)
{f : local_homeomorph H H} (hf : f ∈ G) {x : H} (hx : x ∈ f.source) :
lift_prop_at Q f x :=
lift_prop_at_of_mem_maximal_atlas hG hQ (G.mem_maximal_atlas_of_mem_groupoid hf) hx
lemma lift_prop_on_of_mem_groupoid (hG : G.local_invariant_prop G Q) (hQ : ∀ y, Q id univ y)
{f : local_homeomorph H H} (hf : f ∈ G) :
lift_prop_on Q f f.source :=
lift_prop_on_of_mem_maximal_atlas hG hQ (G.mem_maximal_atlas_of_mem_groupoid hf)
lemma lift_prop_id (hG : G.local_invariant_prop G Q) (hQ : ∀ y, Q id univ y) :
lift_prop Q (id : M → M) :=
begin
simp_rw [lift_prop_iff, continuous_id, true_and],
exact λ x, hG.congr' ((chart_at H x).eventually_right_inverse $ mem_chart_target H x) (hQ _)
end
lemma lift_prop_at_iff_comp_inclusion (hG : local_invariant_prop G G' P) {U V : opens M}
(hUV : U ≤ V) (f : V → M') (x : U) :
lift_prop_at P f (set.inclusion hUV x) ↔ lift_prop_at P (f ∘ set.inclusion hUV : U → M') x :=
begin
congrm _ ∧ _,
{ simp [continuous_within_at_univ,
(topological_space.opens.open_embedding_of_le hUV).continuous_at_iff] },
{ apply hG.congr_iff,
exact (topological_space.opens.chart_at_inclusion_symm_eventually_eq hUV).fun_comp
(chart_at H' (f (set.inclusion hUV x)) ∘ f) },
end
lemma lift_prop_inclusion {Q : (H → H) → (set H) → H → Prop} (hG : local_invariant_prop G G Q)
(hQ : ∀ y, Q id univ y) {U V : opens M} (hUV : U ≤ V) :
lift_prop Q (set.inclusion hUV : U → V) :=
begin
intro x,
show lift_prop_at Q (id ∘ inclusion hUV) x,
rw ← hG.lift_prop_at_iff_comp_inclusion hUV,
apply hG.lift_prop_id hQ,
end
end local_invariant_prop
section local_structomorph
variables (G)
open local_homeomorph
/-- A function from a model space `H` to itself is a local structomorphism, with respect to a
structure groupoid `G` for `H`, relative to a set `s` in `H`, if for all points `x` in the set, the
function agrees with a `G`-structomorphism on `s` in a neighbourhood of `x`. -/
def is_local_structomorph_within_at (f : H → H) (s : set H) (x : H) : Prop :=
x ∈ s → ∃ (e : local_homeomorph H H), e ∈ G ∧ eq_on f e.to_fun (s ∩ e.source) ∧ x ∈ e.source
/-- For a groupoid `G` which is `closed_under_restriction`, being a local structomorphism is a local
invariant property. -/
lemma is_local_structomorph_within_at_local_invariant_prop [closed_under_restriction G] :
local_invariant_prop G G (is_local_structomorph_within_at G) :=
{ is_local := begin
intros s x u f hu hux,
split,
{ rintros h hx,
rcases h hx.1 with ⟨e, heG, hef, hex⟩,
have : s ∩ u ∩ e.source ⊆ s ∩ e.source := by mfld_set_tac,
exact ⟨e, heG, hef.mono this, hex⟩ },
{ rintros h hx,
rcases h ⟨hx, hux⟩ with ⟨e, heG, hef, hex⟩,
refine ⟨e.restr (interior u), _, _, _⟩,
{ exact closed_under_restriction' heG (is_open_interior) },
{ have : s ∩ u ∩ e.source = s ∩ (e.source ∩ u) := by mfld_set_tac,
simpa only [this, interior_interior, hu.interior_eq] with mfld_simps using hef },
{ simp only [*, interior_interior, hu.interior_eq] with mfld_simps } }
end,
right_invariance' := begin
intros s x f e' he'G he'x h hx,
have hxs : x ∈ s := by simpa only [e'.left_inv he'x] with mfld_simps using hx,
rcases h hxs with ⟨e, heG, hef, hex⟩,
refine ⟨e'.symm.trans e, G.trans (G.symm he'G) heG, _, _⟩,
{ intros y hy,
simp only with mfld_simps at hy,
simp only [hef ⟨hy.1, hy.2.2⟩] with mfld_simps },
{ simp only [hex, he'x] with mfld_simps }
end,
congr_of_forall := begin
intros s x f g hfgs hfg' h hx,
rcases h hx with ⟨e, heG, hef, hex⟩,
refine ⟨e, heG, _, hex⟩,
intros y hy,
rw [← hef hy, hfgs y hy.1]
end,
left_invariance' := begin
intros s x f e' he'G he' hfx h hx,
rcases h hx with ⟨e, heG, hef, hex⟩,
refine ⟨e.trans e', G.trans heG he'G, _, _⟩,
{ intros y hy,
simp only with mfld_simps at hy,
simp only [hef ⟨hy.1, hy.2.1⟩] with mfld_simps },
{ simpa only [hex, hef ⟨hx, hex⟩] with mfld_simps using hfx }
end }
/-- A slight reformulation of `is_local_structomorph_within_at` when `f` is a local homeomorph.
This gives us an `e` that is defined on a subset of `f.source`. -/
lemma _root_.local_homeomorph.is_local_structomorph_within_at_iff {G : structure_groupoid H}
[closed_under_restriction G]
(f : local_homeomorph H H) {s : set H} {x : H} (hx : x ∈ f.source ∪ sᶜ) :
G.is_local_structomorph_within_at ⇑f s x ↔
x ∈ s → ∃ (e : local_homeomorph H H), e ∈ G ∧ e.source ⊆ f.source ∧
eq_on f ⇑e (s ∩ e.source) ∧ x ∈ e.source :=
begin
split,
{ intros hf h2x,
obtain ⟨e, he, hfe, hxe⟩ := hf h2x,
refine ⟨e.restr f.source, closed_under_restriction' he f.open_source, _, _, hxe, _⟩,
{ simp_rw [local_homeomorph.restr_source],
refine (inter_subset_right _ _).trans interior_subset },
{ intros x' hx', exact hfe ⟨hx'.1, hx'.2.1⟩ },
{ rw [f.open_source.interior_eq], exact or.resolve_right hx (not_not.mpr h2x) } },
{ intros hf hx, obtain ⟨e, he, h2e, hfe, hxe⟩ := hf hx, exact ⟨e, he, hfe, hxe⟩ }
end
/-- A slight reformulation of `is_local_structomorph_within_at` when `f` is a local homeomorph and
the set we're considering is a superset of `f.source`. -/
lemma _root_.local_homeomorph.is_local_structomorph_within_at_iff' {G : structure_groupoid H}
[closed_under_restriction G]
(f : local_homeomorph H H) {s : set H} {x : H} (hs : f.source ⊆ s) (hx : x ∈ f.source ∪ sᶜ) :
G.is_local_structomorph_within_at ⇑f s x ↔
x ∈ s → ∃ (e : local_homeomorph H H), e ∈ G ∧ e.source ⊆ f.source ∧
eq_on f ⇑e e.source ∧ x ∈ e.source :=
begin
simp_rw [f.is_local_structomorph_within_at_iff hx],
refine imp_congr_right (λ hx, exists_congr $ λ e, and_congr_right $ λ he, _),
refine and_congr_right (λ h2e, _),
rw [inter_eq_right_iff_subset.mpr (h2e.trans hs)],
end
/-- A slight reformulation of `is_local_structomorph_within_at` when `f` is a local homeomorph and
the set we're considering is `f.source`. -/
lemma _root_.local_homeomorph.is_local_structomorph_within_at_source_iff {G : structure_groupoid H}
[closed_under_restriction G]
(f : local_homeomorph H H) {x : H} :
G.is_local_structomorph_within_at ⇑f f.source x ↔
x ∈ f.source → ∃ (e : local_homeomorph H H), e ∈ G ∧ e.source ⊆ f.source ∧
eq_on f ⇑e e.source ∧ x ∈ e.source :=
begin
have : x ∈ f.source ∪ f.sourceᶜ, { simp_rw [union_compl_self] },
exact f.is_local_structomorph_within_at_iff' subset.rfl this,
end
variables {H₁ : Type*} [topological_space H₁] {H₂ : Type*} [topological_space H₂]
{H₃ : Type*} [topological_space H₃] [charted_space H₁ H₂] [charted_space H₂ H₃]
{G₁ : structure_groupoid H₁} [has_groupoid H₂ G₁] [closed_under_restriction G₁]
(G₂ : structure_groupoid H₂) [has_groupoid H₃ G₂]
variables (G₂)
lemma has_groupoid.comp
(H : ∀ e ∈ G₂, lift_prop_on (is_local_structomorph_within_at G₁) (e : H₂ → H₂) e.source) :
@has_groupoid H₁ _ H₃ _ (charted_space.comp H₁ H₂ H₃) G₁ :=
{ compatible := begin
rintros _ _ ⟨e, f, he, hf, rfl⟩ ⟨e', f', he', hf', rfl⟩,
apply G₁.locality,
intros x hx,
simp only with mfld_simps at hx,
have hxs : x ∈ f.symm ⁻¹' (e.symm ≫ₕ e').source,
{ simp only [hx] with mfld_simps },
have hxs' : x ∈ f.target ∩ (f.symm) ⁻¹' ((e.symm ≫ₕ e').source ∩ (e.symm ≫ₕ e') ⁻¹' f'.source),
{ simp only [hx] with mfld_simps },
obtain ⟨φ, hφG₁, hφ, hφ_dom⟩ := local_invariant_prop.lift_prop_on_indep_chart
(is_local_structomorph_within_at_local_invariant_prop G₁) (G₁.subset_maximal_atlas hf)
(G₁.subset_maximal_atlas hf') (H _ (G₂.compatible he he')) hxs' hxs,
simp_rw [← local_homeomorph.coe_trans, local_homeomorph.trans_assoc] at hφ,
simp_rw [local_homeomorph.trans_symm_eq_symm_trans_symm, local_homeomorph.trans_assoc],
have hs : is_open (f.symm ≫ₕ e.symm ≫ₕ e' ≫ₕ f').source :=
(f.symm ≫ₕ e.symm ≫ₕ e' ≫ₕ f').open_source,
refine ⟨_, hs.inter φ.open_source, _, _⟩,
{ simp only [hx, hφ_dom] with mfld_simps, },
{ refine G₁.eq_on_source (closed_under_restriction' hφG₁ hs) _,
rw local_homeomorph.restr_source_inter,
refine (hφ.mono _).restr_eq_on_source,
mfld_set_tac },
end }
end local_structomorph
end structure_groupoid
|
9396adefca6892e07fdfec82462278d3e60150c5 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/fold.lean | 8f83d0a4818699ab85ca2419a923fd0101b3389a | [
"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 | 991 | lean | prelude
definition Prop := Type.{0} inductive true : Prop := intro : true inductive false : Prop constant num : Type
inductive prod (A B : Type) := mk : A → B → prod A B infixl ` × `:30 := prod
variables a b c : num
section
local notation `(` t:(foldr `, ` (e r, prod.mk e r)) `)` := t
check (a, false, b, true, c)
set_option pp.notation false
check (a, false, b, true, c)
end
section
local notation `(` t:(foldr `, ` (e r, prod.mk r e)) `)` := t
set_option pp.notation true
check (a, false, b, true, c)
set_option pp.notation false
check (a, false, b, true, c)
end
section
local notation `(` t:(foldl `, ` (e r, prod.mk r e)) `)` := t
set_option pp.notation true
check (a, false, b, true, c)
set_option pp.notation false
check (a, false, b, true, c)
end
section
local notation `(` t:(foldl `, ` (e r, prod.mk e r)) `)` := t
set_option pp.notation true
check (a, false, b, true, c)
set_option pp.notation false
check (a, false, b, true, c)
end
|
6f89ca8ecb92d234c68c70ba2f87d6a3df65dc52 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/probability/process/filtration.lean | 9bcf5a38d2a62a5e0893085d19e58a37b32f63ed | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 13,183 | lean | /-
Copyright (c) 2021 Kexing Ying. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kexing Ying, Rémy Degenne
-/
import measure_theory.function.conditional_expectation.real
/-!
# Filtrations
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines filtrations of a measurable space and σ-finite filtrations.
## Main definitions
* `measure_theory.filtration`: a filtration on a measurable space. That is, a monotone sequence of
sub-σ-algebras.
* `measure_theory.sigma_finite_filtration`: a filtration `f` is σ-finite with respect to a measure
`μ` if for all `i`, `μ.trim (f.le i)` is σ-finite.
* `measure_theory.filtration.natural`: the smallest filtration that makes a process adapted. That
notion `adapted` is not defined yet in this file. See `measure_theory.adapted`.
## Main results
* `measure_theory.filtration.complete_lattice`: filtrations are a complete lattice.
## Tags
filtration, stochastic process
-/
open filter order topological_space
open_locale classical measure_theory nnreal ennreal topology big_operators
namespace measure_theory
/-- A `filtration` on a measurable space `Ω` with σ-algebra `m` is a monotone
sequence of sub-σ-algebras of `m`. -/
structure filtration {Ω : Type*} (ι : Type*) [preorder ι] (m : measurable_space Ω) :=
(seq : ι → measurable_space Ω)
(mono' : monotone seq)
(le' : ∀ i : ι, seq i ≤ m)
variables {Ω β ι : Type*} {m : measurable_space Ω}
instance [preorder ι] : has_coe_to_fun (filtration ι m) (λ _, ι → measurable_space Ω) :=
⟨λ f, f.seq⟩
namespace filtration
variables [preorder ι]
protected lemma mono {i j : ι} (f : filtration ι m) (hij : i ≤ j) : f i ≤ f j := f.mono' hij
protected lemma le (f : filtration ι m) (i : ι) : f i ≤ m := f.le' i
@[ext] protected lemma ext {f g : filtration ι m} (h : (f : ι → measurable_space Ω) = g) : f = g :=
by { cases f, cases g, simp only, exact h, }
variable (ι)
/-- The constant filtration which is equal to `m` for all `i : ι`. -/
def const (m' : measurable_space Ω) (hm' : m' ≤ m) : filtration ι m :=
⟨λ _, m', monotone_const, λ _, hm'⟩
variable {ι}
@[simp]
lemma const_apply {m' : measurable_space Ω} {hm' : m' ≤ m} (i : ι) : const ι m' hm' i = m' := rfl
instance : inhabited (filtration ι m) := ⟨const ι m le_rfl⟩
instance : has_le (filtration ι m) := ⟨λ f g, ∀ i, f i ≤ g i⟩
instance : has_bot (filtration ι m) := ⟨const ι ⊥ bot_le⟩
instance : has_top (filtration ι m) := ⟨const ι m le_rfl⟩
instance : has_sup (filtration ι m) := ⟨λ f g,
{ seq := λ i, f i ⊔ g i,
mono' := λ i j hij, sup_le ((f.mono hij).trans le_sup_left) ((g.mono hij).trans le_sup_right),
le' := λ i, sup_le (f.le i) (g.le i) }⟩
@[norm_cast] lemma coe_fn_sup {f g : filtration ι m} : ⇑(f ⊔ g) = f ⊔ g := rfl
instance : has_inf (filtration ι m) := ⟨λ f g,
{ seq := λ i, f i ⊓ g i,
mono' := λ i j hij, le_inf (inf_le_left.trans (f.mono hij)) (inf_le_right.trans (g.mono hij)),
le' := λ i, inf_le_left.trans (f.le i) }⟩
@[norm_cast] lemma coe_fn_inf {f g : filtration ι m} : ⇑(f ⊓ g) = f ⊓ g := rfl
instance : has_Sup (filtration ι m) := ⟨λ s,
{ seq := λ i, Sup ((λ f : filtration ι m, f i) '' s),
mono' := λ i j hij,
begin
refine Sup_le (λ m' hm', _),
rw [set.mem_image] at hm',
obtain ⟨f, hf_mem, hfm'⟩ := hm',
rw ← hfm',
refine (f.mono hij).trans _,
have hfj_mem : f j ∈ ((λ g : filtration ι m, g j) '' s), from ⟨f, hf_mem, rfl⟩,
exact le_Sup hfj_mem,
end,
le' := λ i,
begin
refine Sup_le (λ m' hm', _),
rw [set.mem_image] at hm',
obtain ⟨f, hf_mem, hfm'⟩ := hm',
rw ← hfm',
exact f.le i,
end, }⟩
lemma Sup_def (s : set (filtration ι m)) (i : ι) :
Sup s i = Sup ((λ f : filtration ι m, f i) '' s) :=
rfl
noncomputable
instance : has_Inf (filtration ι m) := ⟨λ s,
{ seq := λ i, if set.nonempty s then Inf ((λ f : filtration ι m, f i) '' s) else m,
mono' := λ i j hij,
begin
by_cases h_nonempty : set.nonempty s,
swap, { simp only [h_nonempty, set.nonempty_image_iff, if_false, le_refl], },
simp only [h_nonempty, if_true, le_Inf_iff, set.mem_image, forall_exists_index, and_imp,
forall_apply_eq_imp_iff₂],
refine λ f hf_mem, le_trans _ (f.mono hij),
have hfi_mem : f i ∈ ((λ g : filtration ι m, g i) '' s), from ⟨f, hf_mem, rfl⟩,
exact Inf_le hfi_mem,
end,
le' := λ i,
begin
by_cases h_nonempty : set.nonempty s,
swap, { simp only [h_nonempty, if_false, le_refl], },
simp only [h_nonempty, if_true],
obtain ⟨f, hf_mem⟩ := h_nonempty,
exact le_trans (Inf_le ⟨f, hf_mem, rfl⟩) (f.le i),
end, }⟩
lemma Inf_def (s : set (filtration ι m)) (i : ι) :
Inf s i = if set.nonempty s then Inf ((λ f : filtration ι m, f i) '' s) else m :=
rfl
noncomputable
instance : complete_lattice (filtration ι m) :=
{ le := (≤),
le_refl := λ f i, le_rfl,
le_trans := λ f g h h_fg h_gh i, (h_fg i).trans (h_gh i),
le_antisymm := λ f g h_fg h_gf, filtration.ext $ funext $ λ i, (h_fg i).antisymm (h_gf i),
sup := (⊔),
le_sup_left := λ f g i, le_sup_left,
le_sup_right := λ f g i, le_sup_right,
sup_le := λ f g h h_fh h_gh i, sup_le (h_fh i) (h_gh _),
inf := (⊓),
inf_le_left := λ f g i, inf_le_left,
inf_le_right := λ f g i, inf_le_right,
le_inf := λ f g h h_fg h_fh i, le_inf (h_fg i) (h_fh i),
Sup := Sup,
le_Sup := λ s f hf_mem i, le_Sup ⟨f, hf_mem, rfl⟩,
Sup_le := λ s f h_forall i, Sup_le $ λ m' hm',
begin
obtain ⟨g, hg_mem, hfm'⟩ := hm',
rw ← hfm',
exact h_forall g hg_mem i,
end,
Inf := Inf,
Inf_le := λ s f hf_mem i,
begin
have hs : s.nonempty := ⟨f, hf_mem⟩,
simp only [Inf_def, hs, if_true],
exact Inf_le ⟨f, hf_mem, rfl⟩,
end,
le_Inf := λ s f h_forall i,
begin
by_cases hs : s.nonempty,
swap, { simp only [Inf_def, hs, if_false], exact f.le i, },
simp only [Inf_def, hs, if_true, le_Inf_iff, set.mem_image, forall_exists_index, and_imp,
forall_apply_eq_imp_iff₂],
exact λ g hg_mem, h_forall g hg_mem i,
end,
top := ⊤,
bot := ⊥,
le_top := λ f i, f.le' i,
bot_le := λ f i, bot_le, }
end filtration
lemma measurable_set_of_filtration [preorder ι] {f : filtration ι m} {s : set Ω} {i : ι}
(hs : measurable_set[f i] s) : measurable_set[m] s :=
f.le i s hs
/-- A measure is σ-finite with respect to filtration if it is σ-finite with respect
to all the sub-σ-algebra of the filtration. -/
class sigma_finite_filtration [preorder ι] (μ : measure Ω) (f : filtration ι m) : Prop :=
(sigma_finite : ∀ i : ι, sigma_finite (μ.trim (f.le i)))
instance sigma_finite_of_sigma_finite_filtration [preorder ι] (μ : measure Ω) (f : filtration ι m)
[hf : sigma_finite_filtration μ f] (i : ι) :
sigma_finite (μ.trim (f.le i)) :=
by apply hf.sigma_finite -- can't exact here
@[priority 100]
instance is_finite_measure.sigma_finite_filtration [preorder ι] (μ : measure Ω) (f : filtration ι m)
[is_finite_measure μ] :
sigma_finite_filtration μ f :=
⟨λ n, by apply_instance⟩
/-- Given a integrable function `g`, the conditional expectations of `g` with respect to a
filtration is uniformly integrable. -/
lemma integrable.uniform_integrable_condexp_filtration
[preorder ι] {μ : measure Ω} [is_finite_measure μ] {f : filtration ι m}
{g : Ω → ℝ} (hg : integrable g μ) :
uniform_integrable (λ i, μ[g | f i]) 1 μ :=
hg.uniform_integrable_condexp f.le
section of_set
variables [preorder ι]
/-- Given a sequence of measurable sets `(sₙ)`, `filtration_of_set` is the smallest filtration
such that `sₙ` is measurable with respect to the `n`-the sub-σ-algebra in `filtration_of_set`. -/
def filtration_of_set {s : ι → set Ω} (hsm : ∀ i, measurable_set (s i)) : filtration ι m :=
{ seq := λ i, measurable_space.generate_from {t | ∃ j ≤ i, s j = t},
mono' := λ n m hnm, measurable_space.generate_from_mono
(λ t ⟨k, hk₁, hk₂⟩, ⟨k, hk₁.trans hnm, hk₂⟩),
le' := λ n, measurable_space.generate_from_le (λ t ⟨k, hk₁, hk₂⟩, hk₂ ▸ hsm k) }
lemma measurable_set_filtration_of_set {s : ι → set Ω}
(hsm : ∀ i, measurable_set[m] (s i)) (i : ι) {j : ι} (hj : j ≤ i) :
measurable_set[filtration_of_set hsm i] (s j) :=
measurable_space.measurable_set_generate_from ⟨j, hj, rfl⟩
lemma measurable_set_filtration_of_set' {s : ι → set Ω}
(hsm : ∀ n, measurable_set[m] (s n)) (i : ι) :
measurable_set[filtration_of_set hsm i] (s i) :=
measurable_set_filtration_of_set hsm i le_rfl
end of_set
namespace filtration
variables [topological_space β] [metrizable_space β] [mβ : measurable_space β] [borel_space β]
[preorder ι]
include mβ
/-- Given a sequence of functions, the natural filtration is the smallest sequence
of σ-algebras such that that sequence of functions is measurable with respect to
the filtration. -/
def natural (u : ι → Ω → β) (hum : ∀ i, strongly_measurable (u i)) : filtration ι m :=
{ seq := λ i, ⨆ j ≤ i, measurable_space.comap (u j) mβ,
mono' := λ i j hij, bsupr_mono $ λ k, ge_trans hij,
le' := λ i,
begin
refine supr₂_le _,
rintros j hj s ⟨t, ht, rfl⟩,
exact (hum j).measurable ht,
end }
section
open measurable_space
lemma filtration_of_set_eq_natural [mul_zero_one_class β] [nontrivial β]
{s : ι → set Ω} (hsm : ∀ i, measurable_set[m] (s i)) :
filtration_of_set hsm = natural (λ i, (s i).indicator (λ ω, 1 : Ω → β))
(λ i, strongly_measurable_one.indicator (hsm i)) :=
begin
simp only [natural, filtration_of_set, measurable_space_supr_eq],
ext1 i,
refine le_antisymm (generate_from_le _) (generate_from_le _),
{ rintro _ ⟨j, hij, rfl⟩,
refine measurable_set_generate_from ⟨j, measurable_set_generate_from ⟨hij, _⟩⟩,
rw comap_eq_generate_from,
refine measurable_set_generate_from ⟨{1}, measurable_set_singleton 1, _⟩,
ext x,
simp [set.indicator_const_preimage_eq_union] },
{ rintro t ⟨n, ht⟩,
suffices : measurable_space.generate_from
{t | ∃ (H : n ≤ i), measurable_set[(measurable_space.comap
((s n).indicator (λ ω, 1 : Ω → β)) mβ)] t}
≤ generate_from {t | ∃ (j : ι) (H : j ≤ i), s j = t},
{ exact this _ ht },
refine generate_from_le _,
rintro t ⟨hn, u, hu, hu'⟩,
obtain heq | heq | heq | heq := set.indicator_const_preimage (s n) u (1 : β),
swap 4, rw set.mem_singleton_iff at heq,
all_goals { rw heq at hu', rw ← hu' },
exacts [measurable_set_empty _, measurable_set.univ, measurable_set_generate_from ⟨n, hn, rfl⟩,
measurable_set.compl (measurable_set_generate_from ⟨n, hn, rfl⟩)] }
end
end
section limit
omit mβ
variables {E : Type*} [has_zero E] [topological_space E]
{ℱ : filtration ι m} {f : ι → Ω → E} {μ : measure Ω}
/-- Given a process `f` and a filtration `ℱ`, if `f` converges to some `g` almost everywhere and
`g` is `⨆ n, ℱ n`-measurable, then `limit_process f ℱ μ` chooses said `g`, else it returns 0.
This definition is used to phrase the a.e. martingale convergence theorem
`submartingale.ae_tendsto_limit_process` where an L¹-bounded submartingale `f` adapted to `ℱ`
converges to `limit_process f ℱ μ` `μ`-almost everywhere. -/
noncomputable
def limit_process (f : ι → Ω → E) (ℱ : filtration ι m) (μ : measure Ω . volume_tac) :=
if h : ∃ g : Ω → E, strongly_measurable[⨆ n, ℱ n] g ∧
∀ᵐ ω ∂μ, tendsto (λ n, f n ω) at_top (𝓝 (g ω)) then classical.some h else 0
lemma strongly_measurable_limit_process :
strongly_measurable[⨆ n, ℱ n] (limit_process f ℱ μ) :=
begin
rw limit_process,
split_ifs with h h,
exacts [(classical.some_spec h).1, strongly_measurable_zero]
end
lemma strongly_measurable_limit_process' :
strongly_measurable[m] (limit_process f ℱ μ) :=
strongly_measurable_limit_process.mono (Sup_le (λ m ⟨n, hn⟩, hn ▸ ℱ.le _))
lemma mem_ℒp_limit_process_of_snorm_bdd {R : ℝ≥0} {p : ℝ≥0∞}
{F : Type*} [normed_add_comm_group F] {ℱ : filtration ℕ m} {f : ℕ → Ω → F}
(hfm : ∀ n, ae_strongly_measurable (f n) μ) (hbdd : ∀ n, snorm (f n) p μ ≤ R) :
mem_ℒp (limit_process f ℱ μ) p μ :=
begin
rw limit_process,
split_ifs with h,
{ refine ⟨strongly_measurable.ae_strongly_measurable
((classical.some_spec h).1.mono (Sup_le (λ m ⟨n, hn⟩, hn ▸ ℱ.le _))),
lt_of_le_of_lt (Lp.snorm_lim_le_liminf_snorm hfm _ (classical.some_spec h).2)
(lt_of_le_of_lt _ (ennreal.coe_lt_top : ↑R < ∞))⟩,
simp_rw [liminf_eq, eventually_at_top],
exact Sup_le (λ b ⟨a, ha⟩, (ha a le_rfl).trans (hbdd _)) },
{ exact zero_mem_ℒp }
end
end limit
end filtration
end measure_theory
|
b8c3a4e0532f4cca3807349d8b102b052afca00e | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Util/PtrSet.lean | 38bc51ea7d05a516b1a3d2ce39a0bd116af9c04d | [
"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 | 876 | lean | /-
Copyright (c) 2023 Leonardo de Moura. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Data.HashSet
namespace Lean
structure Ptr (α : Type u) where
value : α
unsafe instance : Hashable (Ptr α) where
hash a := hash64 (ptrAddrUnsafe a).toUInt64
unsafe instance : BEq (Ptr α) where
beq a b := ptrAddrUnsafe a == ptrAddrUnsafe b
/--
Set of pointers. It is a low-level auxiliary datastructure used for traversing DAGs.
-/
unsafe def PtrSet (α : Type) :=
HashSet (Ptr α)
unsafe def mkPtrSet {α : Type} (capacity : Nat := 64) : PtrSet α :=
mkHashSet capacity
unsafe abbrev PtrSet.insert (s : PtrSet α) (a : α) : PtrSet α :=
HashSet.insert s { value := a }
unsafe abbrev PtrSet.contains (s : PtrSet α) (a : α) : Bool :=
HashSet.contains s { value := a }
end Lean
|
e5d4e5cb692bf4b24fdf2d5099f67e1586874d17 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/analysis/normed_space/indicator_function.lean | 42b01e95ff6e771806a2ddae84f9aa2af88952f8 | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 1,340 | lean | /-
Copyright (c) 2020 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou, Yury Kudryashov
-/
import algebra.indicator_function
import analysis.normed_space.basic
/-!
# Indicator function and norm
This file contains a few simple lemmas about `set.indicator` and `norm`.
## Tags
indicator, norm
-/
variables {α E : Type*} [normed_group E] {s t : set α} (f : α → E) (a : α)
open set
lemma norm_indicator_eq_indicator_norm :
∥indicator s f a∥ = indicator s (λa, ∥f a∥) a :=
flip congr_fun a (indicator_comp_of_zero norm_zero).symm
lemma nnnorm_indicator_eq_indicator_nnnorm :
nnnorm (indicator s f a) = indicator s (λa, nnnorm (f a)) a :=
flip congr_fun a (indicator_comp_of_zero nnnorm_zero).symm
lemma norm_indicator_le_of_subset (h : s ⊆ t) (f : α → E) (a : α) :
∥indicator s f a∥ ≤ ∥indicator t f a∥ :=
begin
simp only [norm_indicator_eq_indicator_norm],
exact indicator_le_indicator_of_subset ‹_› (λ _, norm_nonneg _) _
end
lemma indicator_norm_le_norm_self : indicator s (λa, ∥f a∥) a ≤ ∥f a∥ :=
indicator_le_self' (λ _ _, norm_nonneg _) a
lemma norm_indicator_le_norm_self : ∥indicator s f a∥ ≤ ∥f a∥ :=
by { rw norm_indicator_eq_indicator_norm, apply indicator_norm_le_norm_self }
|
ece38db9e218692d1efe128e544ef2995c71b423 | df561f413cfe0a88b1056655515399c546ff32a5 | /5-advanced-proposition-world/l8.lean | 3f53aacf892ac9de9f23ac78550c03d6d5d59c8f | [] | no_license | nicholaspun/natural-number-game-solutions | 31d5158415c6f582694680044c5c6469032c2a06 | 1e2aed86d2e76a3f4a275c6d99e795ad30cf6df0 | refs/heads/main | 1,675,123,625,012 | 1,607,633,548,000 | 1,607,633,548,000 | 318,933,860 | 3 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 377 | lean | lemma and_or_distrib_left (P Q R : Prop) : P ∧ (Q ∨ R) ↔ (P ∧ Q) ∨ (P ∧ R) :=
begin
split,
intro paqor,
cases paqor with p qor,
cases qor with q r,
left,
split,
exact p,
exact q,
right,
split,
exact p,
exact r,
intro long,
split,
cases long with paq par,
exact paq.left,
exact par.left,
cases long with paq par,
left,
exact paq.right,
right,
exact par.right,
end |
d6e184da76e9ceb9edb893532932da64a010e872 | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/algebra/char_zero.lean | 8484e6cbb8ea941f536235ba46cc127d6ec7276a | [
"Apache-2.0"
] | permissive | ChrisHughes24/mathlib | 98322577c460bc6b1fe5c21f42ce33ad1c3e5558 | a2a867e827c2a6702beb9efc2b9282bd801d5f9a | refs/heads/master | 1,583,848,251,477 | 1,565,164,247,000 | 1,565,164,247,000 | 129,409,993 | 0 | 1 | Apache-2.0 | 1,565,164,817,000 | 1,523,628,059,000 | Lean | UTF-8 | Lean | false | false | 3,118 | lean | /-
Copyright (c) 2014 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
Natural homomorphism from the natural numbers into a monoid with one.
-/
import data.nat.cast algebra.group algebra.field
/-- Typeclass for monoids with characteristic zero.
(This is usually stated on fields but it makes sense for any additive monoid with 1.) -/
class char_zero (α : Type*) [add_monoid α] [has_one α] : Prop :=
(cast_inj : ∀ {m n : ℕ}, (m : α) = n ↔ m = n)
theorem char_zero_of_inj_zero {α : Type*} [add_monoid α] [has_one α]
(add_left_cancel : ∀ a b c : α, a + b = a + c → b = c)
(H : ∀ n:ℕ, (n:α) = 0 → n = 0) : char_zero α :=
⟨λ m n, ⟨suffices ∀ {m n : ℕ}, (m:α) = n → m ≤ n,
from λ h, le_antisymm (this h) (this h.symm),
λ m n h, (le_total m n).elim id $ λ h2, le_of_eq $ begin
cases nat.le.dest h2 with k e,
suffices : k = 0, {rw [← e, this, add_zero]},
apply H, apply add_left_cancel n,
rw [← nat.cast_add, e, add_zero, h]
end,
congr_arg _⟩⟩
theorem add_group.char_zero_of_inj_zero {α : Type*} [add_group α] [has_one α]
(H : ∀ n:ℕ, (n:α) = 0 → n = 0) : char_zero α :=
char_zero_of_inj_zero (@add_left_cancel _ _) H
theorem ordered_cancel_comm_monoid.char_zero_of_inj_zero {α : Type*}
[ordered_cancel_comm_monoid α] [has_one α]
(H : ∀ n:ℕ, (n:α) = 0 → n = 0) : char_zero α :=
char_zero_of_inj_zero (@add_left_cancel _ _) H
instance linear_ordered_semiring.to_char_zero {α : Type*}
[linear_ordered_semiring α] : char_zero α :=
ordered_cancel_comm_monoid.char_zero_of_inj_zero $
λ n h, nat.eq_zero_of_le_zero $
(@nat.cast_le α _ _ _).1 (le_of_eq h)
namespace nat
variables {α : Type*} [add_monoid α] [has_one α] [char_zero α]
@[simp, elim_cast] theorem cast_inj {m n : ℕ} : (m : α) = n ↔ m = n :=
char_zero.cast_inj _
theorem cast_injective : function.injective (coe : ℕ → α)
| m n := cast_inj.1
@[simp] theorem cast_eq_zero {n : ℕ} : (n : α) = 0 ↔ n = 0 :=
by rw [← cast_zero, cast_inj]
@[simp] theorem cast_ne_zero {n : ℕ} : (n : α) ≠ 0 ↔ n ≠ 0 :=
not_congr cast_eq_zero
end nat
lemma two_ne_zero' {α : Type*} [add_monoid α] [has_one α] [char_zero α] : (2:α) ≠ 0 :=
have ((2:ℕ):α) ≠ 0, from nat.cast_ne_zero.2 dec_trivial,
by rwa [nat.cast_succ, nat.cast_one] at this
section
variables {α : Type*} [domain α] [char_zero α]
lemma add_self_eq_zero {a : α} : a + a = 0 ↔ a = 0 :=
by simp only [(two_mul a).symm, mul_eq_zero, two_ne_zero', false_or]
lemma bit0_eq_zero {a : α} : bit0 a = 0 ↔ a = 0 := add_self_eq_zero
end
section
variables {α : Type*} [division_ring α] [char_zero α]
@[simp] lemma half_add_self (a : α) : (a + a) / 2 = a :=
by rw [← mul_two, mul_div_cancel a two_ne_zero']
@[simp] lemma add_halves' (a : α) : a / 2 + a / 2 = a :=
by rw [← add_div, half_add_self]
lemma sub_half (a : α) : a - a / 2 = a / 2 :=
by rw [sub_eq_iff_eq_add, add_halves']
lemma half_sub (a : α) : a / 2 - a = - (a / 2) :=
by rw [← neg_sub, sub_half]
end
|
514960990a2e16545e94ca8a59eed3eaf496234d | 94e33a31faa76775069b071adea97e86e218a8ee | /src/ring_theory/finiteness.lean | b90466397fd90bc5a5a4b8af831afe0f249ea468 | [
"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 | 38,574 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import group_theory.finiteness
import ring_theory.algebra_tower
import ring_theory.ideal.quotient
import ring_theory.noetherian
/-!
# Finiteness conditions in commutative algebra
In this file we define several notions of finiteness that are common in commutative algebra.
## Main declarations
- `module.finite`, `algebra.finite`, `ring_hom.finite`, `alg_hom.finite`
all of these express that some object is finitely generated *as module* over some base ring.
- `algebra.finite_type`, `ring_hom.finite_type`, `alg_hom.finite_type`
all of these express that some object is finitely generated *as algebra* over some base ring.
- `algebra.finite_presentation`, `ring_hom.finite_presentation`, `alg_hom.finite_presentation`
all of these express that some object is finitely presented *as algebra* over some base ring.
-/
open function (surjective)
open_locale big_operators polynomial
section module_and_algebra
variables (R A B M N : Type*)
/-- A module over a semiring is `finite` if it is finitely generated as a module. -/
class module.finite [semiring R] [add_comm_monoid M] [module R M] :
Prop := (out : (⊤ : submodule R M).fg)
/-- An algebra over a commutative semiring is of `finite_type` if it is finitely generated
over the base ring as algebra. -/
class algebra.finite_type [comm_semiring R] [semiring A] [algebra R A] : Prop :=
(out : (⊤ : subalgebra R A).fg)
/-- An algebra over a commutative semiring is `finite_presentation` if it is the quotient of a
polynomial ring in `n` variables by a finitely generated ideal. -/
def algebra.finite_presentation [comm_semiring R] [semiring A] [algebra R A] : Prop :=
∃ (n : ℕ) (f : mv_polynomial (fin n) R →ₐ[R] A),
surjective f ∧ f.to_ring_hom.ker.fg
namespace module
variables [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid N] [module R N]
lemma finite_def {R M} [semiring R] [add_comm_monoid M] [module R M] :
finite R M ↔ (⊤ : submodule R M).fg := ⟨λ h, h.1, λ h, ⟨h⟩⟩
@[priority 100] -- see Note [lower instance priority]
instance is_noetherian.finite [is_noetherian R M] : finite R M :=
⟨is_noetherian.noetherian ⊤⟩
namespace finite
open _root_.submodule set
lemma iff_add_monoid_fg {M : Type*} [add_comm_monoid M] : module.finite ℕ M ↔ add_monoid.fg M :=
⟨λ h, add_monoid.fg_def.2 $ (fg_iff_add_submonoid_fg ⊤).1 (finite_def.1 h),
λ h, finite_def.2 $ (fg_iff_add_submonoid_fg ⊤).2 (add_monoid.fg_def.1 h)⟩
lemma iff_add_group_fg {G : Type*} [add_comm_group G] : module.finite ℤ G ↔ add_group.fg G :=
⟨λ h, add_group.fg_def.2 $ (fg_iff_add_subgroup_fg ⊤).1 (finite_def.1 h),
λ h, finite_def.2 $ (fg_iff_add_subgroup_fg ⊤).2 (add_group.fg_def.1 h)⟩
variables {R M N}
lemma exists_fin [finite R M] : ∃ (n : ℕ) (s : fin n → M), span R (range s) = ⊤ :=
submodule.fg_iff_exists_fin_generating_family.mp out
lemma of_surjective [hM : finite R M] (f : M →ₗ[R] N) (hf : surjective f) :
finite R N :=
⟨begin
rw [← linear_map.range_eq_top.2 hf, ← submodule.map_top],
exact hM.1.map f
end⟩
lemma of_injective [is_noetherian R N] (f : M →ₗ[R] N)
(hf : function.injective f) : finite R M :=
⟨fg_of_injective f hf⟩
variables (R)
instance self : finite R R :=
⟨⟨{1}, by simpa only [finset.coe_singleton] using ideal.span_singleton_one⟩⟩
variable (M)
lemma of_restrict_scalars_finite (R A M : Type*) [comm_semiring R] [semiring A] [add_comm_monoid M]
[module R M] [module A M] [algebra R A] [is_scalar_tower R A M] [hM : finite R M] :
finite A M :=
begin
rw [finite_def, fg_def] at hM ⊢,
obtain ⟨S, hSfin, hSgen⟩ := hM,
refine ⟨S, hSfin, eq_top_iff.2 _⟩,
have := submodule.span_le_restrict_scalars R A S,
rw hSgen at this,
exact this
end
variables {R M}
instance prod [hM : finite R M] [hN : finite R N] : finite R (M × N) :=
⟨begin
rw ← submodule.prod_top,
exact hM.1.prod hN.1
end⟩
instance pi {ι : Type*} {M : ι → Type*} [fintype ι] [Π i, add_comm_monoid (M i)]
[Π i, module R (M i)] [h : ∀ i, finite R (M i)] : finite R (Π i, M i) :=
⟨begin
rw ← submodule.pi_top,
exact submodule.fg_pi (λ i, (h i).1),
end⟩
lemma equiv [hM : finite R M] (e : M ≃ₗ[R] N) : finite R N :=
of_surjective (e : M →ₗ[R] N) e.surjective
section algebra
lemma trans {R : Type*} (A B : Type*) [comm_semiring R] [comm_semiring A] [algebra R A]
[semiring B] [algebra R B] [algebra A B] [is_scalar_tower R A B] :
∀ [finite R A] [finite A B], finite R B
| ⟨⟨s, hs⟩⟩ ⟨⟨t, ht⟩⟩ := ⟨submodule.fg_def.2
⟨set.image2 (•) (↑s : set A) (↑t : set B),
set.finite.image2 _ s.finite_to_set t.finite_to_set,
by rw [set.image2_smul, submodule.span_smul hs (↑t : set B),
ht, submodule.restrict_scalars_top]⟩⟩
@[priority 100] -- see Note [lower instance priority]
instance finite_type {R : Type*} (A : Type*) [comm_semiring R] [semiring A]
[algebra R A] [hRA : finite R A] : algebra.finite_type R A :=
⟨subalgebra.fg_of_submodule_fg hRA.1⟩
end algebra
end finite
end module
instance module.finite.tensor_product [comm_semiring R]
[add_comm_monoid M] [module R M] [add_comm_monoid N] [module R N]
[hM : module.finite R M] [hN : module.finite R N] : module.finite R (tensor_product R M N) :=
{ out := (tensor_product.map₂_mk_top_top_eq_top R M N).subst (hM.out.map₂ _ hN.out) }
namespace algebra
variables [comm_ring R] [comm_ring A] [algebra R A] [comm_ring B] [algebra R B]
variables [add_comm_group M] [module R M]
variables [add_comm_group N] [module R N]
namespace finite_type
lemma self : finite_type R R := ⟨⟨{1}, subsingleton.elim _ _⟩⟩
section
open_locale classical
protected lemma mv_polynomial (ι : Type*) [fintype ι] : finite_type R (mv_polynomial ι R) :=
⟨⟨finset.univ.image mv_polynomial.X, begin
rw eq_top_iff, refine λ p, mv_polynomial.induction_on' p
(λ u x, finsupp.induction u (subalgebra.algebra_map_mem _ x)
(λ i n f hif hn ih, _))
(λ p q ihp ihq, subalgebra.add_mem _ ihp ihq),
rw [add_comm, mv_polynomial.monomial_add_single],
exact subalgebra.mul_mem _ ih
(subalgebra.pow_mem _ (subset_adjoin $ finset.mem_image_of_mem _ $ finset.mem_univ _) _)
end⟩⟩
end
lemma of_restrict_scalars_finite_type [algebra A B] [is_scalar_tower R A B] [hB : finite_type R B] :
finite_type A B :=
begin
obtain ⟨S, hS⟩ := hB.out,
refine ⟨⟨S, eq_top_iff.2 (λ b, _)⟩⟩,
have le : adjoin R (S : set B) ≤ subalgebra.restrict_scalars R (adjoin A S),
{ apply (algebra.adjoin_le _ : _ ≤ (subalgebra.restrict_scalars R (adjoin A ↑S))),
simp only [subalgebra.coe_restrict_scalars],
exact algebra.subset_adjoin, },
exact le (eq_top_iff.1 hS b),
end
variables {R A B}
lemma of_surjective (hRA : finite_type R A) (f : A →ₐ[R] B) (hf : surjective f) :
finite_type R B :=
⟨begin
convert hRA.1.map f,
simpa only [map_top f, @eq_comm _ ⊤, eq_top_iff, alg_hom.mem_range] using hf
end⟩
lemma equiv (hRA : finite_type R A) (e : A ≃ₐ[R] B) : finite_type R B :=
hRA.of_surjective e e.surjective
lemma trans [algebra A B] [is_scalar_tower R A B] (hRA : finite_type R A) (hAB : finite_type A B) :
finite_type R B :=
⟨fg_trans' hRA.1 hAB.1⟩
/-- An algebra is finitely generated if and only if it is a quotient
of a polynomial ring whose variables are indexed by a finset. -/
lemma iff_quotient_mv_polynomial : (finite_type R A) ↔ ∃ (s : finset A)
(f : (mv_polynomial {x // x ∈ s} R) →ₐ[R] A), (surjective f) :=
begin
split,
{ rintro ⟨s, hs⟩,
use [s, mv_polynomial.aeval coe],
intro x,
have hrw : (↑s : set A) = (λ (x : A), x ∈ s.val) := rfl,
rw [← set.mem_range, ← alg_hom.coe_range, ← adjoin_eq_range, ← hrw, hs],
exact set.mem_univ x },
{ rintro ⟨s, ⟨f, hsur⟩⟩,
exact finite_type.of_surjective (finite_type.mv_polynomial R {x // x ∈ s}) f hsur }
end
/-- An algebra is finitely generated if and only if it is a quotient
of a polynomial ring whose variables are indexed by a fintype. -/
lemma iff_quotient_mv_polynomial' : (finite_type R A) ↔ ∃ (ι : Type u_2) (_ : fintype ι)
(f : (mv_polynomial ι R) →ₐ[R] A), (surjective f) :=
begin
split,
{ rw iff_quotient_mv_polynomial,
rintro ⟨s, ⟨f, hsur⟩⟩,
use [{x // x ∈ s}, by apply_instance, f, hsur] },
{ rintro ⟨ι, ⟨hfintype, ⟨f, hsur⟩⟩⟩,
letI : fintype ι := hfintype,
exact finite_type.of_surjective (finite_type.mv_polynomial R ι) f hsur }
end
/-- An algebra is finitely generated if and only if it is a quotient of a polynomial ring in `n`
variables. -/
lemma iff_quotient_mv_polynomial'' : (finite_type R A) ↔ ∃ (n : ℕ)
(f : (mv_polynomial (fin n) R) →ₐ[R] A), (surjective f) :=
begin
split,
{ rw iff_quotient_mv_polynomial',
rintro ⟨ι, hfintype, ⟨f, hsur⟩⟩,
resetI,
have equiv := mv_polynomial.rename_equiv R (fintype.equiv_fin ι),
exact ⟨fintype.card ι, alg_hom.comp f equiv.symm, function.surjective.comp hsur
(alg_equiv.symm equiv).surjective⟩ },
{ rintro ⟨n, ⟨f, hsur⟩⟩,
exact finite_type.of_surjective (finite_type.mv_polynomial R (fin n)) f hsur }
end
/-- A finitely presented algebra is of finite type. -/
lemma of_finite_presentation : finite_presentation R A → finite_type R A :=
begin
rintro ⟨n, f, hf⟩,
apply (finite_type.iff_quotient_mv_polynomial'').2,
exact ⟨n, f, hf.1⟩
end
instance prod [hA : finite_type R A] [hB : finite_type R B] : finite_type R (A × B) :=
⟨begin
rw ← subalgebra.prod_top,
exact hA.1.prod hB.1
end⟩
lemma is_noetherian_ring (R S : Type*) [comm_ring R] [comm_ring S] [algebra R S]
[h : algebra.finite_type R S] [is_noetherian_ring R] : is_noetherian_ring S :=
begin
obtain ⟨s, hs⟩ := h.1,
apply is_noetherian_ring_of_surjective
(mv_polynomial s R) S (mv_polynomial.aeval coe : mv_polynomial s R →ₐ[R] S),
rw [← set.range_iff_surjective, alg_hom.coe_to_ring_hom, ← alg_hom.coe_range,
← algebra.adjoin_range_eq_range_aeval, subtype.range_coe_subtype, finset.set_of_mem, hs],
refl
end
lemma _root_.subalgebra.fg_iff_finite_type {R A : Type*} [comm_semiring R] [semiring A]
[algebra R A] (S : subalgebra R A) : S.fg ↔ algebra.finite_type R S :=
S.fg_top.symm.trans ⟨λ h, ⟨h⟩, λ h, h.out⟩
end finite_type
namespace finite_presentation
variables {R A B}
/-- An algebra over a Noetherian ring is finitely generated if and only if it is finitely
presented. -/
lemma of_finite_type [is_noetherian_ring R] : finite_type R A ↔ finite_presentation R A :=
begin
refine ⟨λ h, _, algebra.finite_type.of_finite_presentation⟩,
obtain ⟨n, f, hf⟩ := algebra.finite_type.iff_quotient_mv_polynomial''.1 h,
refine ⟨n, f, hf, _⟩,
have hnoet : is_noetherian_ring (mv_polynomial (fin n) R) := by apply_instance,
replace hnoet := (is_noetherian_ring_iff.1 hnoet).noetherian,
exact hnoet f.to_ring_hom.ker,
end
/-- If `e : A ≃ₐ[R] B` and `A` is finitely presented, then so is `B`. -/
lemma equiv (hfp : finite_presentation R A) (e : A ≃ₐ[R] B) : finite_presentation R B :=
begin
obtain ⟨n, f, hf⟩ := hfp,
use [n, alg_hom.comp ↑e f],
split,
{ exact function.surjective.comp e.surjective hf.1 },
suffices hker : (alg_hom.comp ↑e f).to_ring_hom.ker = f.to_ring_hom.ker,
{ rw hker, exact hf.2 },
{ have hco : (alg_hom.comp ↑e f).to_ring_hom = ring_hom.comp ↑e.to_ring_equiv f.to_ring_hom,
{ have h : (alg_hom.comp ↑e f).to_ring_hom = e.to_alg_hom.to_ring_hom.comp f.to_ring_hom := rfl,
have h1 : ↑(e.to_ring_equiv) = (e.to_alg_hom).to_ring_hom := rfl,
rw [h, h1] },
rw [ring_hom.ker_eq_comap_bot, hco, ← ideal.comap_comap, ← ring_hom.ker_eq_comap_bot,
ring_hom.ker_coe_equiv (alg_equiv.to_ring_equiv e), ring_hom.ker_eq_comap_bot] }
end
variable (R)
/-- The ring of polynomials in finitely many variables is finitely presented. -/
protected lemma mv_polynomial (ι : Type u_2) [fintype ι] :
finite_presentation R (mv_polynomial ι R) :=
begin
have equiv := mv_polynomial.rename_equiv R (fintype.equiv_fin ι),
refine ⟨_, alg_equiv.to_alg_hom equiv.symm, _⟩,
split,
{ exact (alg_equiv.symm equiv).surjective },
suffices hinj : function.injective equiv.symm.to_alg_hom.to_ring_hom,
{ rw [(ring_hom.injective_iff_ker_eq_bot _).1 hinj],
exact submodule.fg_bot },
exact (alg_equiv.symm equiv).injective
end
/-- `R` is finitely presented as `R`-algebra. -/
lemma self : finite_presentation R R :=
equiv (finite_presentation.mv_polynomial R pempty) (mv_polynomial.is_empty_alg_equiv R pempty)
variable {R}
/-- The quotient of a finitely presented algebra by a finitely generated ideal is finitely
presented. -/
protected lemma quotient {I : ideal A} (h : I.fg) (hfp : finite_presentation R A) :
finite_presentation R (A ⧸ I) :=
begin
obtain ⟨n, f, hf⟩ := hfp,
refine ⟨n, (ideal.quotient.mkₐ R I).comp f, _, _⟩,
{ exact (ideal.quotient.mkₐ_surjective R I).comp hf.1 },
{ refine ideal.fg_ker_comp _ _ hf.2 _ hf.1,
simp [h] }
end
/-- If `f : A →ₐ[R] B` is surjective with finitely generated kernel and `A` is finitely presented,
then so is `B`. -/
lemma of_surjective {f : A →ₐ[R] B} (hf : function.surjective f) (hker : f.to_ring_hom.ker.fg)
(hfp : finite_presentation R A) : finite_presentation R B :=
equiv (hfp.quotient hker) (ideal.quotient_ker_alg_equiv_of_surjective hf)
lemma iff : finite_presentation R A ↔
∃ n (I : ideal (mv_polynomial (fin n) R)) (e : (_ ⧸ I) ≃ₐ[R] A), I.fg :=
begin
split,
{ rintros ⟨n, f, hf⟩,
exact ⟨n, f.to_ring_hom.ker, ideal.quotient_ker_alg_equiv_of_surjective hf.1, hf.2⟩ },
{ rintros ⟨n, I, e, hfg⟩,
exact equiv ((finite_presentation.mv_polynomial R _).quotient hfg) e }
end
/-- An algebra is finitely presented if and only if it is a quotient of a polynomial ring whose
variables are indexed by a fintype by a finitely generated ideal. -/
lemma iff_quotient_mv_polynomial' : finite_presentation R A ↔ ∃ (ι : Type u_2) (_ : fintype ι)
(f : mv_polynomial ι R →ₐ[R] A), surjective f ∧ f.to_ring_hom.ker.fg :=
begin
split,
{ rintro ⟨n, f, hfs, hfk⟩,
set ulift_var := mv_polynomial.rename_equiv R equiv.ulift,
refine ⟨ulift (fin n), infer_instance, f.comp ulift_var.to_alg_hom,
hfs.comp ulift_var.surjective,
ideal.fg_ker_comp _ _ _ hfk ulift_var.surjective⟩,
convert submodule.fg_bot,
exact ring_hom.ker_coe_equiv ulift_var.to_ring_equiv, },
{ rintro ⟨ι, hfintype, f, hf⟩,
resetI,
have equiv := mv_polynomial.rename_equiv R (fintype.equiv_fin ι),
refine ⟨fintype.card ι, f.comp equiv.symm,
hf.1.comp (alg_equiv.symm equiv).surjective,
ideal.fg_ker_comp _ f _ hf.2 equiv.symm.surjective⟩,
convert submodule.fg_bot,
exact ring_hom.ker_coe_equiv (equiv.symm.to_ring_equiv), }
end
/-- If `A` is a finitely presented `R`-algebra, then `mv_polynomial (fin n) A` is finitely presented
as `R`-algebra. -/
lemma mv_polynomial_of_finite_presentation (hfp : finite_presentation R A) (ι : Type*)
[fintype ι] : finite_presentation R (mv_polynomial ι A) :=
begin
rw iff_quotient_mv_polynomial' at hfp ⊢,
classical,
obtain ⟨ι', _, f, hf_surj, hf_ker⟩ := hfp,
resetI,
let g := (mv_polynomial.map_alg_hom f).comp (mv_polynomial.sum_alg_equiv R ι ι').to_alg_hom,
refine ⟨ι ⊕ ι', by apply_instance, g,
(mv_polynomial.map_surjective f.to_ring_hom hf_surj).comp (alg_equiv.surjective _),
ideal.fg_ker_comp _ _ _ _ (alg_equiv.surjective _)⟩,
{ convert submodule.fg_bot,
exact ring_hom.ker_coe_equiv (mv_polynomial.sum_alg_equiv R ι ι').to_ring_equiv },
{ rw [alg_hom.to_ring_hom_eq_coe, mv_polynomial.map_alg_hom_coe_ring_hom, mv_polynomial.ker_map],
exact hf_ker.map mv_polynomial.C, }
end
/-- If `A` is an `R`-algebra and `S` is an `A`-algebra, both finitely presented, then `S` is
finitely presented as `R`-algebra. -/
lemma trans [algebra A B] [is_scalar_tower R A B] (hfpA : finite_presentation R A)
(hfpB : finite_presentation A B) : finite_presentation R B :=
begin
obtain ⟨n, I, e, hfg⟩ := iff.1 hfpB,
exact equiv ((mv_polynomial_of_finite_presentation hfpA _).quotient hfg) (e.restrict_scalars R)
end
end finite_presentation
end algebra
end module_and_algebra
namespace ring_hom
variables {A B C : Type*} [comm_ring A] [comm_ring B] [comm_ring C]
/-- A ring morphism `A →+* B` is `finite` if `B` is finitely generated as `A`-module. -/
def finite (f : A →+* B) : Prop :=
by letI : algebra A B := f.to_algebra; exact module.finite A B
/-- A ring morphism `A →+* B` is of `finite_type` if `B` is finitely generated as `A`-algebra. -/
def finite_type (f : A →+* B) : Prop := @algebra.finite_type A B _ _ f.to_algebra
/-- A ring morphism `A →+* B` is of `finite_presentation` if `B` is finitely presented as
`A`-algebra. -/
def finite_presentation (f : A →+* B) : Prop := @algebra.finite_presentation A B _ _ f.to_algebra
namespace finite
variables (A)
lemma id : finite (ring_hom.id A) := module.finite.self A
variables {A}
lemma of_surjective (f : A →+* B) (hf : surjective f) : f.finite :=
begin
letI := f.to_algebra,
exact module.finite.of_surjective (algebra.of_id A B).to_linear_map hf
end
lemma comp {g : B →+* C} {f : A →+* B} (hg : g.finite) (hf : f.finite) : (g.comp f).finite :=
@module.finite.trans A B C _ _ f.to_algebra _ (g.comp f).to_algebra g.to_algebra
begin
fconstructor,
intros a b c,
simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc],
refl
end
hf hg
lemma finite_type {f : A →+* B} (hf : f.finite) : finite_type f :=
@module.finite.finite_type _ _ _ _ f.to_algebra hf
lemma of_comp_finite {f : A →+* B} {g : B →+* C} (h : (g.comp f).finite) : g.finite :=
begin
letI := f.to_algebra,
letI := g.to_algebra,
letI := (g.comp f).to_algebra,
letI : is_scalar_tower A B C := restrict_scalars.is_scalar_tower A B C,
letI : module.finite A C := h,
exact module.finite.of_restrict_scalars_finite A B C
end
end finite
namespace finite_type
variables (A)
lemma id : finite_type (ring_hom.id A) := algebra.finite_type.self A
variables {A}
lemma comp_surjective {f : A →+* B} {g : B →+* C} (hf : f.finite_type) (hg : surjective g) :
(g.comp f).finite_type :=
@algebra.finite_type.of_surjective A B C _ _ f.to_algebra _ (g.comp f).to_algebra hf
{ to_fun := g, commutes' := λ a, rfl, .. g } hg
lemma of_surjective (f : A →+* B) (hf : surjective f) : f.finite_type :=
by { rw ← f.comp_id, exact (id A).comp_surjective hf }
lemma comp {g : B →+* C} {f : A →+* B} (hg : g.finite_type) (hf : f.finite_type) :
(g.comp f).finite_type :=
@algebra.finite_type.trans A B C _ _ f.to_algebra _ (g.comp f).to_algebra g.to_algebra
begin
fconstructor,
intros a b c,
simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc],
refl
end
hf hg
lemma of_finite_presentation {f : A →+* B} (hf : f.finite_presentation) : f.finite_type :=
@algebra.finite_type.of_finite_presentation A B _ _ f.to_algebra hf
lemma of_comp_finite_type {f : A →+* B} {g : B →+* C} (h : (g.comp f).finite_type) :
g.finite_type :=
begin
letI := f.to_algebra,
letI := g.to_algebra,
letI := (g.comp f).to_algebra,
letI : is_scalar_tower A B C := restrict_scalars.is_scalar_tower A B C,
letI : algebra.finite_type A C := h,
exact algebra.finite_type.of_restrict_scalars_finite_type A B C
end
end finite_type
namespace finite_presentation
variables (A)
lemma id : finite_presentation (ring_hom.id A) := algebra.finite_presentation.self A
variables {A}
lemma comp_surjective {f : A →+* B} {g : B →+* C} (hf : f.finite_presentation) (hg : surjective g)
(hker : g.ker.fg) : (g.comp f).finite_presentation :=
@algebra.finite_presentation.of_surjective A B C _ _ f.to_algebra _ (g.comp f).to_algebra
{ to_fun := g, commutes' := λ a, rfl, .. g } hg hker hf
lemma of_surjective (f : A →+* B) (hf : surjective f) (hker : f.ker.fg) : f.finite_presentation :=
by { rw ← f.comp_id, exact (id A).comp_surjective hf hker}
lemma of_finite_type [is_noetherian_ring A] {f : A →+* B} : f.finite_type ↔ f.finite_presentation :=
@algebra.finite_presentation.of_finite_type A B _ _ f.to_algebra _
lemma comp {g : B →+* C} {f : A →+* B} (hg : g.finite_presentation) (hf : f.finite_presentation) :
(g.comp f).finite_presentation :=
@algebra.finite_presentation.trans A B C _ _ f.to_algebra _ (g.comp f).to_algebra g.to_algebra
{ smul_assoc := λ a b c, begin
simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc],
refl
end }
hf hg
end finite_presentation
end ring_hom
namespace alg_hom
variables {R A B C : Type*} [comm_ring R]
variables [comm_ring A] [comm_ring B] [comm_ring C]
variables [algebra R A] [algebra R B] [algebra R C]
/-- An algebra morphism `A →ₐ[R] B` is finite if it is finite as ring morphism.
In other words, if `B` is finitely generated as `A`-module. -/
def finite (f : A →ₐ[R] B) : Prop := f.to_ring_hom.finite
/-- An algebra morphism `A →ₐ[R] B` is of `finite_type` if it is of finite type as ring morphism.
In other words, if `B` is finitely generated as `A`-algebra. -/
def finite_type (f : A →ₐ[R] B) : Prop := f.to_ring_hom.finite_type
/-- An algebra morphism `A →ₐ[R] B` is of `finite_presentation` if it is of finite presentation as
ring morphism. In other words, if `B` is finitely presented as `A`-algebra. -/
def finite_presentation (f : A →ₐ[R] B) : Prop := f.to_ring_hom.finite_presentation
namespace finite
variables (R A)
lemma id : finite (alg_hom.id R A) := ring_hom.finite.id A
variables {R A}
lemma comp {g : B →ₐ[R] C} {f : A →ₐ[R] B} (hg : g.finite) (hf : f.finite) : (g.comp f).finite :=
ring_hom.finite.comp hg hf
lemma of_surjective (f : A →ₐ[R] B) (hf : surjective f) : f.finite :=
ring_hom.finite.of_surjective f hf
lemma finite_type {f : A →ₐ[R] B} (hf : f.finite) : finite_type f :=
ring_hom.finite.finite_type hf
lemma of_comp_finite {f : A →ₐ[R] B} {g : B →ₐ[R] C} (h : (g.comp f).finite) : g.finite :=
ring_hom.finite.of_comp_finite h
end finite
namespace finite_type
variables (R A)
lemma id : finite_type (alg_hom.id R A) := ring_hom.finite_type.id A
variables {R A}
lemma comp {g : B →ₐ[R] C} {f : A →ₐ[R] B} (hg : g.finite_type) (hf : f.finite_type) :
(g.comp f).finite_type :=
ring_hom.finite_type.comp hg hf
lemma comp_surjective {f : A →ₐ[R] B} {g : B →ₐ[R] C} (hf : f.finite_type) (hg : surjective g) :
(g.comp f).finite_type :=
ring_hom.finite_type.comp_surjective hf hg
lemma of_surjective (f : A →ₐ[R] B) (hf : surjective f) : f.finite_type :=
ring_hom.finite_type.of_surjective f hf
lemma of_finite_presentation {f : A →ₐ[R] B} (hf : f.finite_presentation) : f.finite_type :=
ring_hom.finite_type.of_finite_presentation hf
lemma of_comp_finite_type {f : A →ₐ[R] B} {g : B →ₐ[R] C} (h : (g.comp f).finite_type) :
g.finite_type :=
ring_hom.finite_type.of_comp_finite_type h
end finite_type
namespace finite_presentation
variables (R A)
lemma id : finite_presentation (alg_hom.id R A) := ring_hom.finite_presentation.id A
variables {R A}
lemma comp {g : B →ₐ[R] C} {f : A →ₐ[R] B} (hg : g.finite_presentation)
(hf : f.finite_presentation) : (g.comp f).finite_presentation :=
ring_hom.finite_presentation.comp hg hf
lemma comp_surjective {f : A →ₐ[R] B} {g : B →ₐ[R] C} (hf : f.finite_presentation)
(hg : surjective g) (hker : g.to_ring_hom.ker.fg) : (g.comp f).finite_presentation :=
ring_hom.finite_presentation.comp_surjective hf hg hker
lemma of_surjective (f : A →ₐ[R] B) (hf : surjective f) (hker : f.to_ring_hom.ker.fg) :
f.finite_presentation :=
ring_hom.finite_presentation.of_surjective f hf hker
lemma of_finite_type [is_noetherian_ring A] {f : A →ₐ[R] B} :
f.finite_type ↔ f.finite_presentation :=
ring_hom.finite_presentation.of_finite_type
end finite_presentation
end alg_hom
section monoid_algebra
variables {R : Type*} {M : Type*}
namespace add_monoid_algebra
open algebra add_submonoid submodule
section span
section semiring
variables [comm_semiring R] [add_monoid M]
/-- An element of `add_monoid_algebra R M` is in the subalgebra generated by its support. -/
lemma mem_adjoin_support (f : add_monoid_algebra R M) : f ∈ adjoin R (of' R M '' f.support) :=
begin
suffices : span R (of' R M '' f.support) ≤ (adjoin R (of' R M '' f.support)).to_submodule,
{ exact this (mem_span_support f) },
rw submodule.span_le,
exact subset_adjoin
end
/-- If a set `S` generates, as algebra, `add_monoid_algebra R M`, then the set of supports of
elements of `S` generates `add_monoid_algebra R M`. -/
lemma support_gen_of_gen {S : set (add_monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) :
algebra.adjoin R (⋃ f ∈ S, (of' R M '' (f.support : set M))) = ⊤ :=
begin
refine le_antisymm le_top _,
rw [← hS, adjoin_le_iff],
intros f hf,
have hincl : of' R M '' f.support ⊆
⋃ (g : add_monoid_algebra R M) (H : g ∈ S), of' R M '' g.support,
{ intros s hs,
exact set.mem_Union₂.2 ⟨f, ⟨hf, hs⟩⟩ },
exact adjoin_mono hincl (mem_adjoin_support f)
end
/-- If a set `S` generates, as algebra, `add_monoid_algebra R M`, then the image of the union of
the supports of elements of `S` generates `add_monoid_algebra R M`. -/
lemma support_gen_of_gen' {S : set (add_monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) :
algebra.adjoin R (of' R M '' (⋃ f ∈ S, (f.support : set M))) = ⊤ :=
begin
suffices : of' R M '' (⋃ f ∈ S, (f.support : set M)) = ⋃ f ∈ S, (of' R M '' (f.support : set M)),
{ rw this,
exact support_gen_of_gen hS },
simp only [set.image_Union]
end
end semiring
section ring
variables [comm_ring R] [add_comm_monoid M]
/-- If `add_monoid_algebra R M` is of finite type, there there is a `G : finset M` such that its
image generates, as algera, `add_monoid_algebra R M`. -/
lemma exists_finset_adjoin_eq_top [h : finite_type R (add_monoid_algebra R M)] :
∃ G : finset M, algebra.adjoin R (of' R M '' G) = ⊤ :=
begin
unfreezingI { obtain ⟨S, hS⟩ := h },
letI : decidable_eq M := classical.dec_eq M,
use finset.bUnion S (λ f, f.support),
have : (finset.bUnion S (λ f, f.support) : set M) = ⋃ f ∈ S, (f.support : set M),
{ simp only [finset.set_bUnion_coe, finset.coe_bUnion] },
rw [this],
exact support_gen_of_gen' hS
end
/-- The image of an element `m : M` in `add_monoid_algebra R M` belongs the submodule generated by
`S : set M` if and only if `m ∈ S`. -/
lemma of'_mem_span [nontrivial R] {m : M} {S : set M} :
of' R M m ∈ span R (of' R M '' S) ↔ m ∈ S :=
begin
refine ⟨λ h, _, λ h, submodule.subset_span $ set.mem_image_of_mem (of R M) h⟩,
rw [of', ← finsupp.supported_eq_span_single, finsupp.mem_supported,
finsupp.support_single_ne_zero _ (@one_ne_zero R _ (by apply_instance))] at h,
simpa using h
end
/--If the image of an element `m : M` in `add_monoid_algebra R M` belongs the submodule generated by
the closure of some `S : set M` then `m ∈ closure S`. -/
lemma mem_closure_of_mem_span_closure [nontrivial R] {m : M} {S : set M}
(h : of' R M m ∈ span R (submonoid.closure (of' R M '' S) : set (add_monoid_algebra R M))) :
m ∈ closure S :=
begin
suffices : multiplicative.of_add m ∈ submonoid.closure (multiplicative.to_add ⁻¹' S),
{ simpa [← to_submonoid_closure] },
let S' := @submonoid.closure M multiplicative.mul_one_class S,
have h' : submonoid.map (of R M) S' = submonoid.closure ((λ (x : M), (of R M) x) '' S) :=
monoid_hom.map_mclosure _ _,
rw [set.image_congr' (show ∀ x, of' R M x = of R M x, from λ x, of'_eq_of x), ← h'] at h,
simpa using of'_mem_span.1 h
end
end ring
end span
variables [add_comm_monoid M]
/-- If a set `S` generates an additive monoid `M`, then the image of `M` generates, as algebra,
`add_monoid_algebra R M`. -/
lemma mv_polynomial_aeval_of_surjective_of_closure [comm_semiring R] {S : set M}
(hS : closure S = ⊤) : function.surjective (mv_polynomial.aeval
(λ (s : S), of' R M ↑s) : mv_polynomial S R → add_monoid_algebra R M) :=
begin
refine λ f, induction_on f (λ m, _) _ _,
{ have : m ∈ closure S := hS.symm ▸ mem_top _,
refine closure_induction this (λ m hm, _) _ _,
{ exact ⟨mv_polynomial.X ⟨m, hm⟩, mv_polynomial.aeval_X _ _⟩ },
{ exact ⟨1, alg_hom.map_one _⟩ },
{ rintro m₁ m₂ ⟨P₁, hP₁⟩ ⟨P₂, hP₂⟩,
exact ⟨P₁ * P₂, by rw [alg_hom.map_mul, hP₁, hP₂, of_apply, of_apply, of_apply,
single_mul_single, one_mul]; refl⟩ } },
{ rintro f g ⟨P, rfl⟩ ⟨Q, rfl⟩,
exact ⟨P + Q, alg_hom.map_add _ _ _⟩ },
{ rintro r f ⟨P, rfl⟩,
exact ⟨r • P, alg_hom.map_smul _ _ _⟩ }
end
variables (R M)
/-- If an additive monoid `M` is finitely generated then `add_monoid_algebra R M` is of finite
type. -/
instance finite_type_of_fg [comm_ring R] [h : add_monoid.fg M] :
finite_type R (add_monoid_algebra R M) :=
begin
obtain ⟨S, hS⟩ := h.out,
exact (finite_type.mv_polynomial R (S : set M)).of_surjective (mv_polynomial.aeval
(λ (s : (S : set M)), of' R M ↑s)) (mv_polynomial_aeval_of_surjective_of_closure hS)
end
variables {R M}
/-- An additive monoid `M` is finitely generated if and only if `add_monoid_algebra R M` is of
finite type. -/
lemma finite_type_iff_fg [comm_ring R] [nontrivial R] :
finite_type R (add_monoid_algebra R M) ↔ add_monoid.fg M :=
begin
refine ⟨λ h, _, λ h, @add_monoid_algebra.finite_type_of_fg _ _ _ _ h⟩,
obtain ⟨S, hS⟩ := @exists_finset_adjoin_eq_top R M _ _ h,
refine add_monoid.fg_def.2 ⟨S, (eq_top_iff' _).2 (λ m, _)⟩,
have hm : of' R M m ∈ (adjoin R (of' R M '' ↑S)).to_submodule,
{ simp only [hS, top_to_submodule, submodule.mem_top], },
rw [adjoin_eq_span] at hm,
exact mem_closure_of_mem_span_closure hm
end
/-- If `add_monoid_algebra R M` is of finite type then `M` is finitely generated. -/
lemma fg_of_finite_type [comm_ring R] [nontrivial R] [h : finite_type R (add_monoid_algebra R M)] :
add_monoid.fg M :=
finite_type_iff_fg.1 h
/-- An additive group `G` is finitely generated if and only if `add_monoid_algebra R G` is of
finite type. -/
lemma finite_type_iff_group_fg {G : Type*} [add_comm_group G] [comm_ring R] [nontrivial R] :
finite_type R (add_monoid_algebra R G) ↔ add_group.fg G :=
by simpa [add_group.fg_iff_add_monoid.fg] using finite_type_iff_fg
end add_monoid_algebra
namespace monoid_algebra
open algebra submonoid submodule
section span
section semiring
variables [comm_semiring R] [monoid M]
/-- An element of `monoid_algebra R M` is in the subalgebra generated by its support. -/
lemma mem_adjoint_support (f : monoid_algebra R M) : f ∈ adjoin R (of R M '' f.support) :=
begin
suffices : span R (of R M '' f.support) ≤ (adjoin R (of R M '' f.support)).to_submodule,
{ exact this (mem_span_support f) },
rw submodule.span_le,
exact subset_adjoin
end
/-- If a set `S` generates, as algebra, `monoid_algebra R M`, then the set of supports of elements
of `S` generates `monoid_algebra R M`. -/
lemma support_gen_of_gen {S : set (monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) :
algebra.adjoin R (⋃ f ∈ S, (of R M '' (f.support : set M))) = ⊤ :=
begin
refine le_antisymm le_top _,
rw [← hS, adjoin_le_iff],
intros f hf,
have hincl : (of R M) '' f.support ⊆
⋃ (g : monoid_algebra R M) (H : g ∈ S), of R M '' g.support,
{ intros s hs,
exact set.mem_Union₂.2 ⟨f, ⟨hf, hs⟩⟩ },
exact adjoin_mono hincl (mem_adjoint_support f)
end
/-- If a set `S` generates, as algebra, `monoid_algebra R M`, then the image of the union of the
supports of elements of `S` generates `monoid_algebra R M`. -/
lemma support_gen_of_gen' {S : set (monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) :
algebra.adjoin R (of R M '' (⋃ f ∈ S, (f.support : set M))) = ⊤ :=
begin
suffices : of R M '' (⋃ f ∈ S, (f.support : set M)) = ⋃ f ∈ S, (of R M '' (f.support : set M)),
{ rw this,
exact support_gen_of_gen hS },
simp only [set.image_Union]
end
end semiring
section ring
variables [comm_ring R] [comm_monoid M]
/-- If `monoid_algebra R M` is of finite type, there there is a `G : finset M` such that its image
generates, as algera, `monoid_algebra R M`. -/
lemma exists_finset_adjoin_eq_top [h :finite_type R (monoid_algebra R M)] :
∃ G : finset M, algebra.adjoin R (of R M '' G) = ⊤ :=
begin
unfreezingI { obtain ⟨S, hS⟩ := h },
letI : decidable_eq M := classical.dec_eq M,
use finset.bUnion S (λ f, f.support),
have : (finset.bUnion S (λ f, f.support) : set M) = ⋃ f ∈ S, (f.support : set M),
{ simp only [finset.set_bUnion_coe, finset.coe_bUnion] },
rw [this],
exact support_gen_of_gen' hS
end
/-- The image of an element `m : M` in `monoid_algebra R M` belongs the submodule generated by
`S : set M` if and only if `m ∈ S`. -/
lemma of_mem_span_of_iff [nontrivial R] {m : M} {S : set M} :
of R M m ∈ span R (of R M '' S) ↔ m ∈ S :=
begin
refine ⟨λ h, _, λ h, submodule.subset_span $ set.mem_image_of_mem (of R M) h⟩,
rw [of, monoid_hom.coe_mk, ← finsupp.supported_eq_span_single, finsupp.mem_supported,
finsupp.support_single_ne_zero _ (@one_ne_zero R _ (by apply_instance))] at h,
simpa using h
end
/--If the image of an element `m : M` in `monoid_algebra R M` belongs the submodule generated by the
closure of some `S : set M` then `m ∈ closure S`. -/
lemma mem_closure_of_mem_span_closure [nontrivial R] {m : M} {S : set M}
(h : of R M m ∈ span R (submonoid.closure (of R M '' S) : set (monoid_algebra R M))) :
m ∈ closure S :=
begin
rw ← monoid_hom.map_mclosure at h,
simpa using of_mem_span_of_iff.1 h
end
end ring
end span
variables [comm_monoid M]
/-- If a set `S` generates a monoid `M`, then the image of `M` generates, as algebra,
`monoid_algebra R M`. -/
lemma mv_polynomial_aeval_of_surjective_of_closure [comm_semiring R] {S : set M}
(hS : closure S = ⊤) : function.surjective (mv_polynomial.aeval
(λ (s : S), of R M ↑s) : mv_polynomial S R → monoid_algebra R M) :=
begin
refine λ f, induction_on f (λ m, _) _ _,
{ have : m ∈ closure S := hS.symm ▸ mem_top _,
refine closure_induction this (λ m hm, _) _ _,
{ exact ⟨mv_polynomial.X ⟨m, hm⟩, mv_polynomial.aeval_X _ _⟩ },
{ exact ⟨1, alg_hom.map_one _⟩ },
{ rintro m₁ m₂ ⟨P₁, hP₁⟩ ⟨P₂, hP₂⟩,
exact ⟨P₁ * P₂, by rw [alg_hom.map_mul, hP₁, hP₂, of_apply, of_apply, of_apply,
single_mul_single, one_mul]⟩ } },
{ rintro f g ⟨P, rfl⟩ ⟨Q, rfl⟩,
exact ⟨P + Q, alg_hom.map_add _ _ _⟩ },
{ rintro r f ⟨P, rfl⟩,
exact ⟨r • P, alg_hom.map_smul _ _ _⟩ }
end
/-- If a monoid `M` is finitely generated then `monoid_algebra R M` is of finite type. -/
instance finite_type_of_fg [comm_ring R] [monoid.fg M] : finite_type R (monoid_algebra R M) :=
(add_monoid_algebra.finite_type_of_fg R (additive M)).equiv (to_additive_alg_equiv R M).symm
/-- A monoid `M` is finitely generated if and only if `monoid_algebra R M` is of finite type. -/
lemma finite_type_iff_fg [comm_ring R] [nontrivial R] :
finite_type R (monoid_algebra R M) ↔ monoid.fg M :=
⟨λ h, monoid.fg_iff_add_fg.2 $ add_monoid_algebra.finite_type_iff_fg.1 $ h.equiv $
to_additive_alg_equiv R M, λ h, @monoid_algebra.finite_type_of_fg _ _ _ _ h⟩
/-- If `monoid_algebra R M` is of finite type then `M` is finitely generated. -/
lemma fg_of_finite_type [comm_ring R] [nontrivial R] [h : finite_type R (monoid_algebra R M)] :
monoid.fg M :=
finite_type_iff_fg.1 h
/-- A group `G` is finitely generated if and only if `add_monoid_algebra R G` is of finite type. -/
lemma finite_type_iff_group_fg {G : Type*} [comm_group G] [comm_ring R] [nontrivial R] :
finite_type R (monoid_algebra R G) ↔ group.fg G :=
by simpa [group.fg_iff_monoid.fg] using finite_type_iff_fg
end monoid_algebra
end monoid_algebra
section vasconcelos
variables {R : Type*} [comm_ring R] {M : Type*} [add_comm_group M] [module R M] (f : M →ₗ[R] M)
noncomputable theory
/-- The structure of a module `M` over a ring `R` as a module over `polynomial R` when given a
choice of how `X` acts by choosing a linear map `f : M →ₗ[R] M` -/
@[simps]
def module_polynomial_of_endo : module R[X] M :=
module.comp_hom M (polynomial.aeval f).to_ring_hom
include f
lemma module_polynomial_of_endo.is_scalar_tower : @is_scalar_tower R R[X] M _
(by { letI := module_polynomial_of_endo f, apply_instance }) _ :=
begin
letI := module_polynomial_of_endo f,
constructor,
intros x y z,
simp,
end
open polynomial module
/-- A theorem/proof by Vasconcelos, given a finite module `M` over a commutative ring, any
surjective endomorphism of `M` is also injective. Based on,
https://math.stackexchange.com/a/239419/31917,
https://www.ams.org/journals/tran/1969-138-00/S0002-9947-1969-0238839-5/.
This is similar to `is_noetherian.injective_of_surjective_endomorphism` but only applies in the
commutative case, but does not use a Noetherian hypothesis. -/
theorem module.finite.injective_of_surjective_endomorphism [hfg : finite R M]
(f_surj : function.surjective f) : function.injective f :=
begin
letI := module_polynomial_of_endo f,
haveI : is_scalar_tower R R[X] M := module_polynomial_of_endo.is_scalar_tower f,
have hfgpoly : finite R[X] M, from finite.of_restrict_scalars_finite R _ _,
have X_mul : ∀ o, (X : R[X]) • o = f o,
{ intro,
simp, },
have : (⊤ : submodule R[X] M) ≤ ideal.span {X} • ⊤,
{ intros a ha,
obtain ⟨y, rfl⟩ := f_surj a,
rw [← X_mul y],
exact submodule.smul_mem_smul (ideal.mem_span_singleton.mpr (dvd_refl _)) trivial, },
obtain ⟨F, hFa, hFb⟩ := submodule.exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul _
(⊤ : submodule R[X] M) (finite_def.mp hfgpoly) this,
rw [← linear_map.ker_eq_bot, linear_map.ker_eq_bot'],
intros m hm,
rw ideal.mem_span_singleton' at hFa,
obtain ⟨G, hG⟩ := hFa,
suffices : (F - 1) • m = 0,
{ have Fmzero := hFb m (by simp),
rwa [← sub_add_cancel F 1, add_smul, one_smul, this, zero_add] at Fmzero, },
rw [← hG, mul_smul, X_mul m, hm, smul_zero],
end
end vasconcelos
|
2df3b613eb2260cd5a1eb3e2595bcbfe575a705b | 968e2f50b755d3048175f176376eff7139e9df70 | /examples/prop_logic_theory/unnamed_196.lean | 399eff0231f10a40e6fa6f185f9f5858e55ed8af | [] | no_license | gihanmarasingha/mth1001_sphinx | 190a003269ba5e54717b448302a27ca26e31d491 | 05126586cbf5786e521be1ea2ef5b4ba3c44e74a | refs/heads/master | 1,672,913,933,677 | 1,604,516,583,000 | 1,604,516,583,000 | 309,245,750 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 149 | lean | variables p q r : Prop
-- BEGIN
example (h : (p ∧ q) ∧ r ) : q :=
begin
have h₂ : p ∧ q, from h.left,
show q, from h₂.right,
end
-- END |
b562d90c0f2244dacb797a268b52564f070613bd | c777c32c8e484e195053731103c5e52af26a25d1 | /src/data/real/golden_ratio.lean | 4c0ef8fec16ca893766c659ecc1b740ae5a64dd1 | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 5,678 | lean | /-
Copyright (c) 2020 Anatole Dedecker. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anatole Dedecker, Alexey Soloyev, Junyan Xu
-/
import data.real.irrational
import data.nat.fib
import data.nat.prime_norm_num
import data.fin.vec_notation
import tactic.ring_exp
import algebra.linear_recurrence
/-!
# The golden ratio and its conjugate
This file defines the golden ratio `φ := (1 + √5)/2` and its conjugate
`ψ := (1 - √5)/2`, which are the two real roots of `X² - X - 1`.
Along with various computational facts about them, we prove their
irrationality, and we link them to the Fibonacci sequence by proving
Binet's formula.
-/
noncomputable theory
open_locale polynomial
/-- The golden ratio `φ := (1 + √5)/2`. -/
@[reducible] def golden_ratio := (1 + real.sqrt 5)/2
/-- The conjugate of the golden ratio `ψ := (1 - √5)/2`. -/
@[reducible] def golden_conj := (1 - real.sqrt 5)/2
localized "notation (name := golden_ratio) `φ` := golden_ratio" in real
localized "notation (name := golden_conj) `ψ` := golden_conj" in real
/-- The inverse of the golden ratio is the opposite of its conjugate. -/
lemma inv_gold : φ⁻¹ = -ψ :=
begin
have : 1 + real.sqrt 5 ≠ 0,
from ne_of_gt (add_pos (by norm_num) $ real.sqrt_pos.mpr (by norm_num)),
field_simp [sub_mul, mul_add],
norm_num
end
/-- The opposite of the golden ratio is the inverse of its conjugate. -/
lemma inv_gold_conj : ψ⁻¹ = -φ :=
begin
rw [inv_eq_iff_eq_inv, ← neg_inv, ← neg_eq_iff_eq_neg],
exact inv_gold.symm,
end
@[simp] lemma gold_mul_gold_conj : φ * ψ = -1 :=
by {field_simp, rw ← sq_sub_sq, norm_num}
@[simp] lemma gold_conj_mul_gold : ψ * φ = -1 :=
by {rw mul_comm, exact gold_mul_gold_conj}
@[simp] lemma gold_add_gold_conj : φ + ψ = 1 := by {rw [golden_ratio, golden_conj], ring}
lemma one_sub_gold_conj : 1 - φ = ψ := by linarith [gold_add_gold_conj]
lemma one_sub_gold : 1 - ψ = φ := by linarith [gold_add_gold_conj]
@[simp] lemma gold_sub_gold_conj : φ - ψ = real.sqrt 5 := by {rw [golden_ratio, golden_conj], ring}
@[simp] lemma gold_sq : φ^2 = φ + 1 :=
begin
rw [golden_ratio, ←sub_eq_zero],
ring_exp,
rw real.sq_sqrt; norm_num,
end
@[simp] lemma gold_conj_sq : ψ^2 = ψ + 1 :=
begin
rw [golden_conj, ←sub_eq_zero],
ring_exp,
rw real.sq_sqrt; norm_num,
end
lemma gold_pos : 0 < φ :=
mul_pos (by apply add_pos; norm_num) $ inv_pos.2 zero_lt_two
lemma gold_ne_zero : φ ≠ 0 := ne_of_gt gold_pos
lemma one_lt_gold : 1 < φ :=
begin
refine lt_of_mul_lt_mul_left _ (le_of_lt gold_pos),
simp [← sq, gold_pos, zero_lt_one]
end
lemma gold_conj_neg : ψ < 0 := by linarith [one_sub_gold_conj, one_lt_gold]
lemma gold_conj_ne_zero : ψ ≠ 0 := ne_of_lt gold_conj_neg
lemma neg_one_lt_gold_conj : -1 < ψ :=
begin
rw [neg_lt, ← inv_gold],
exact inv_lt_one one_lt_gold,
end
/-!
## Irrationality
-/
/-- The golden ratio is irrational. -/
theorem gold_irrational : irrational φ :=
begin
have := nat.prime.irrational_sqrt (show nat.prime 5, by norm_num),
have := this.rat_add 1,
have := this.rat_mul (show (0.5 : ℚ) ≠ 0, by norm_num),
convert this,
field_simp
end
/-- The conjugate of the golden ratio is irrational. -/
theorem gold_conj_irrational : irrational ψ :=
begin
have := nat.prime.irrational_sqrt (show nat.prime 5, by norm_num),
have := this.rat_sub 1,
have := this.rat_mul (show (0.5 : ℚ) ≠ 0, by norm_num),
convert this,
field_simp
end
/-!
## Links with Fibonacci sequence
-/
section fibrec
variables {α : Type*} [comm_semiring α]
/-- The recurrence relation satisfied by the Fibonacci sequence. -/
def fib_rec : linear_recurrence α :=
{ order := 2,
coeffs := ![1, 1]}
section poly
open polynomial
/-- The characteristic polynomial of `fib_rec` is `X² - (X + 1)`. -/
lemma fib_rec_char_poly_eq {β : Type*} [comm_ring β] :
fib_rec.char_poly = X^2 - (X + (1 : β[X])) :=
begin
rw [fib_rec, linear_recurrence.char_poly],
simp [finset.sum_fin_eq_sum_range, finset.sum_range_succ', ← smul_X_eq_monomial]
end
end poly
/-- As expected, the Fibonacci sequence is a solution of `fib_rec`. -/
lemma fib_is_sol_fib_rec : fib_rec.is_solution (λ x, x.fib : ℕ → α) :=
begin
rw fib_rec,
intros n,
simp only,
rw [nat.fib_add_two, add_comm],
simp [finset.sum_fin_eq_sum_range, finset.sum_range_succ'],
end
/-- The geometric sequence `λ n, φ^n` is a solution of `fib_rec`. -/
lemma geom_gold_is_sol_fib_rec : fib_rec.is_solution (pow φ) :=
begin
rw [fib_rec.geom_sol_iff_root_char_poly, fib_rec_char_poly_eq],
simp [sub_eq_zero]
end
/-- The geometric sequence `λ n, ψ^n` is a solution of `fib_rec`. -/
lemma geom_gold_conj_is_sol_fib_rec : fib_rec.is_solution (pow ψ) :=
begin
rw [fib_rec.geom_sol_iff_root_char_poly, fib_rec_char_poly_eq],
simp [sub_eq_zero]
end
end fibrec
/-- Binet's formula as a function equality. -/
theorem real.coe_fib_eq' : (λ n, nat.fib n : ℕ → ℝ) = λ n, (φ^n - ψ^n) / real.sqrt 5 :=
begin
rw fib_rec.sol_eq_of_eq_init,
{ intros i hi,
fin_cases hi,
{ simp },
{ simp only [golden_ratio, golden_conj], ring_exp, rw mul_inv_cancel; norm_num } },
{ exact fib_is_sol_fib_rec },
{ ring_nf,
exact (@fib_rec ℝ _).sol_space.sub_mem
(submodule.smul_mem fib_rec.sol_space (real.sqrt 5)⁻¹ geom_gold_is_sol_fib_rec)
(submodule.smul_mem fib_rec.sol_space (real.sqrt 5)⁻¹ geom_gold_conj_is_sol_fib_rec) }
end
/-- Binet's formula as a dependent equality. -/
theorem real.coe_fib_eq : ∀ n, (nat.fib n : ℝ) = (φ^n - ψ^n) / real.sqrt 5 :=
by rw [← function.funext_iff, real.coe_fib_eq']
|
22ce3b092cb6579dc097ab2b8b3fd6948b963d5c | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/order/lexicographic.lean | 7083507dfe515d5c413aa98ffaf9a2668ccc1db1 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,145 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Scott Morrison, Minchao Wu
Lexicographic preorder / partial_order / linear_order / linear_order,
for pairs and dependent pairs.
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.basic
import Mathlib.PostPort
universes u v
namespace Mathlib
/-- The cartesian product, equipped with the lexicographic order. -/
def lex (α : Type u) (β : Type v) :=
α × β
protected instance lex.decidable_eq {α : Type u} {β : Type v} [DecidableEq α] [DecidableEq β] : DecidableEq (lex α β) :=
prod.decidable_eq
protected instance lex.inhabited {α : Type u} {β : Type v} [Inhabited α] [Inhabited β] : Inhabited (lex α β) :=
prod.inhabited
/-- Dictionary / lexicographic ordering on pairs. -/
protected instance lex_has_le {α : Type u} {β : Type v} [preorder α] [preorder β] : HasLessEq (lex α β) :=
{ LessEq := prod.lex Less LessEq }
protected instance lex_has_lt {α : Type u} {β : Type v} [preorder α] [preorder β] : HasLess (lex α β) :=
{ Less := prod.lex Less Less }
/-- Dictionary / lexicographic preorder for pairs. -/
protected instance lex_preorder {α : Type u} {β : Type v} [preorder α] [preorder β] : preorder (lex α β) :=
preorder.mk LessEq Less sorry sorry
/-- Dictionary / lexicographic partial_order for pairs. -/
protected instance lex_partial_order {α : Type u} {β : Type v} [partial_order α] [partial_order β] : partial_order (lex α β) :=
partial_order.mk preorder.le preorder.lt sorry sorry sorry
/-- Dictionary / lexicographic linear_order for pairs. -/
protected instance lex_linear_order {α : Type u} {β : Type v} [linear_order α] [linear_order β] : linear_order (lex α β) :=
linear_order.mk partial_order.le partial_order.lt sorry sorry sorry sorry
(id
fun (a b : lex α β) =>
prod.cases_on a
fun (a₁ : α) (b₁ : β) =>
prod.cases_on b
fun (a₂ : α) (b₂ : β) =>
decidable.cases_on (linear_order.decidable_le a₁ a₂) (fun (a_lt : ¬a₁ ≤ a₂) => isFalse sorry)
fun (a_le : a₁ ≤ a₂) =>
dite (a₁ = a₂)
(fun (h : a₁ = a₂) =>
eq.mpr sorry
(decidable.cases_on (linear_order.decidable_le b₁ b₂) (fun (b_lt : ¬b₁ ≤ b₂) => isFalse sorry)
fun (b_le : b₁ ≤ b₂) => is_true sorry))
fun (h : ¬a₁ = a₂) => is_true sorry)
Mathlib.decidable_eq_of_decidable_le Mathlib.decidable_lt_of_decidable_le
/--
Dictionary / lexicographic ordering on dependent pairs.
The 'pointwise' partial order `prod.has_le` doesn't make
sense for dependent pairs, so it's safe to mark these as
instances here.
-/
protected instance dlex_has_le {α : Type u} {Z : α → Type v} [preorder α] [(a : α) → preorder (Z a)] : HasLessEq (psigma fun (a : α) => Z a) :=
{ LessEq := psigma.lex Less fun (a : α) => LessEq }
protected instance dlex_has_lt {α : Type u} {Z : α → Type v} [preorder α] [(a : α) → preorder (Z a)] : HasLess (psigma fun (a : α) => Z a) :=
{ Less := psigma.lex Less fun (a : α) => Less }
/-- Dictionary / lexicographic preorder on dependent pairs. -/
protected instance dlex_preorder {α : Type u} {Z : α → Type v} [preorder α] [(a : α) → preorder (Z a)] : preorder (psigma fun (a : α) => Z a) :=
preorder.mk LessEq Less sorry sorry
/-- Dictionary / lexicographic partial_order for dependent pairs. -/
protected instance dlex_partial_order {α : Type u} {Z : α → Type v} [partial_order α] [(a : α) → partial_order (Z a)] : partial_order (psigma fun (a : α) => Z a) :=
partial_order.mk preorder.le preorder.lt sorry sorry sorry
/-- Dictionary / lexicographic linear_order for pairs. -/
protected instance dlex_linear_order {α : Type u} {Z : α → Type v} [linear_order α] [(a : α) → linear_order (Z a)] : linear_order (psigma fun (a : α) => Z a) :=
linear_order.mk partial_order.le partial_order.lt sorry sorry sorry sorry
(id
fun (a b : psigma fun (a : α) => Z a) =>
psigma.cases_on a
fun (a₁ : α) (b₁ : Z a₁) =>
psigma.cases_on b
fun (a₂ : α) (b₂ : Z a₂) =>
decidable.cases_on (linear_order.decidable_le a₁ a₂) (fun (a_lt : ¬a₁ ≤ a₂) => isFalse sorry)
fun (a_le : a₁ ≤ a₂) =>
dite (a₁ = a₂)
(fun (h : a₁ = a₂) =>
Eq._oldrec
(fun (b₂ : Z a₁) (a_le : a₁ ≤ a₁) =>
decidable.cases_on (linear_order.decidable_le b₁ b₂) (fun (b_lt : ¬b₁ ≤ b₂) => isFalse sorry)
fun (b_le : b₁ ≤ b₂) => is_true sorry)
h b₂ a_le)
fun (h : ¬a₁ = a₂) => is_true sorry)
Mathlib.decidable_eq_of_decidable_le Mathlib.decidable_lt_of_decidable_le
|
4c0b90cb8b840401298597dcdf1963d0a99d65a4 | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /library/hott/funext_from_ua.lean | 94cca2b3deff662eb38c9ad5976be97e870eefab | [
"Apache-2.0"
] | permissive | codyroux/lean | 7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3 | 0cca265db19f7296531e339192e9b9bae4a31f8b | refs/heads/master | 1,610,909,964,159 | 1,407,084,399,000 | 1,416,857,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,353 | lean | -- Copyright (c) 2014 Jakob von Raumer. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Author: Jakob von Raumer
-- Ported from Coq HoTT
import hott.equiv hott.funext_varieties hott.axioms.ua hott.axioms.funext
import data.prod data.sigma data.unit
open path function prod sigma truncation Equiv IsEquiv unit ua_type
context
universe variables l
parameter [UA : ua_type.{l+1}]
protected theorem ua_isequiv_postcompose {A B : Type.{l+1}} {C : Type}
{w : A → B} {H0 : IsEquiv w} : IsEquiv (@compose C A B w) :=
let w' := Equiv.mk w H0 in
let eqinv : A ≈ B := ((@IsEquiv.inv _ _ _ (@ua_type.inst UA A B)) w') in
let eq' := equiv_path eqinv in
IsEquiv.adjointify (@compose C A B w)
(@compose C B A (IsEquiv.inv w))
(λ (x : C → B),
have eqretr : eq' ≈ w',
from (@retr _ _ (@equiv_path A B) (@ua_type.inst UA A B) w'),
have invs_eq : (equiv_fun eq')⁻¹ ≈ (equiv_fun w')⁻¹,
from inv_eq eq' w' eqretr,
have eqfin : (equiv_fun eq') ∘ ((equiv_fun eq')⁻¹ ∘ x) ≈ x,
from (λ p,
(@path.rec_on Type.{l+1} A
(λ B' p', Π (x' : C → B'), (equiv_fun (equiv_path p'))
∘ ((equiv_fun (equiv_path p'))⁻¹ ∘ x') ≈ x')
B p (λ x', idp))
) eqinv x,
have eqfin' : (equiv_fun w') ∘ ((equiv_fun eq')⁻¹ ∘ x) ≈ x,
from eqretr ▹ eqfin,
have eqfin'' : (equiv_fun w') ∘ ((equiv_fun w')⁻¹ ∘ x) ≈ x,
from invs_eq ▹ eqfin',
eqfin''
)
(λ (x : C → A),
have eqretr : eq' ≈ w',
from (@retr _ _ (@equiv_path A B) ua_type.inst w'),
have invs_eq : (equiv_fun eq')⁻¹ ≈ (equiv_fun w')⁻¹,
from inv_eq eq' w' eqretr,
have eqfin : (equiv_fun eq')⁻¹ ∘ ((equiv_fun eq') ∘ x) ≈ x,
from (λ p, path.rec_on p idp) eqinv,
have eqfin' : (equiv_fun eq')⁻¹ ∘ ((equiv_fun w') ∘ x) ≈ x,
from eqretr ▹ eqfin,
have eqfin'' : (equiv_fun w')⁻¹ ∘ ((equiv_fun w') ∘ x) ≈ x,
from invs_eq ▹ eqfin',
eqfin''
)
-- We are ready to prove functional extensionality,
-- starting with the naive non-dependent version.
protected definition diagonal [reducible] (B : Type) : Type
:= Σ xy : B × B, pr₁ xy ≈ pr₂ xy
protected definition isequiv_src_compose {A B : Type}
: @IsEquiv (A → diagonal B)
(A → B)
(compose (pr₁ ∘ dpr1)) :=
@ua_isequiv_postcompose _ _ _ (pr₁ ∘ dpr1)
(IsEquiv.adjointify (pr₁ ∘ dpr1)
(λ x, dpair (x , x) idp) (λx, idp)
(λ x, sigma.rec_on x
(λ xy, prod.rec_on xy
(λ b c p, path.rec_on p idp))))
protected definition isequiv_tgt_compose {A B : Type}
: @IsEquiv (A → diagonal B)
(A → B)
(compose (pr₂ ∘ dpr1)) :=
@ua_isequiv_postcompose _ _ _ (pr2 ∘ dpr1)
(IsEquiv.adjointify (pr2 ∘ dpr1)
(λ x, dpair (x , x) idp) (λx, idp)
(λ x, sigma.rec_on x
(λ xy, prod.rec_on xy
(λ b c p, path.rec_on p idp))))
theorem ua_implies_funext_nondep {A : Type} {B : Type.{l+1}}
: Π {f g : A → B}, f ∼ g → f ≈ g :=
(λ (f g : A → B) (p : f ∼ g),
let d := λ (x : A), dpair (f x , f x) idp in
let e := λ (x : A), dpair (f x , g x) (p x) in
let precomp1 := compose (pr₁ ∘ dpr1) in
have equiv1 [visible] : IsEquiv precomp1,
from @isequiv_src_compose A B,
have equiv2 [visible] : Π x y, IsEquiv (ap precomp1),
from IsEquiv.ap_closed precomp1,
have H' : Π (x y : A → diagonal B),
pr₁ ∘ dpr1 ∘ x ≈ pr₁ ∘ dpr1 ∘ y → x ≈ y,
from (λ x y, IsEquiv.inv (ap precomp1)),
have eq2 : pr₁ ∘ dpr1 ∘ d ≈ pr₁ ∘ dpr1 ∘ e,
from idp,
have eq0 : d ≈ e,
from H' d e eq2,
have eq1 : (pr₂ ∘ dpr1) ∘ d ≈ (pr₂ ∘ dpr1) ∘ e,
from ap _ eq0,
eq1
)
end
-- Now we use this to prove weak funext, which as we know
-- implies (with dependent eta) also the strong dependent funext.
universe variables l k
theorem ua_implies_weak_funext [ua3 : ua_type.{k+1}] [ua4 : ua_type.{k+2}] : weak_funext.{l+1 k+1} :=
(λ (A : Type) (P : A → Type) allcontr,
let U := (λ (x : A), unit) in
have pequiv : Π (x : A), P x ≃ U x,
from (λ x, @equiv_contr_unit(P x) (allcontr x)),
have psim : Π (x : A), P x ≈ U x,
from (λ x, @IsEquiv.inv _ _
equiv_path ua_type.inst (pequiv x)),
have p : P ≈ U,
from @ua_implies_funext_nondep _ A Type P U psim,
have tU' : is_contr (A → unit),
from is_contr.mk (λ x, ⋆)
(λ f, @ua_implies_funext_nondep _ A unit (λ x, ⋆) f
(λ x, unit.rec_on (f x) idp)),
have tU : is_contr (Π x, U x),
from tU',
have tlast : is_contr (Πx, P x),
from path.transport _ (p⁻¹) tU,
tlast
)
-- In the following we will proof function extensionality using the univalence axiom
definition ua_implies_funext [instance] [ua ua2 : ua_type] : funext :=
weak_funext_implies_funext (@ua_implies_weak_funext ua ua2)
|
41df024e1b029254ff8ce73a6c932673300e6c1d | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/algebra/lie/weights.lean | 7556a23d2de0230d2f770c7264f25b2c84bb6da4 | [
"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 | 21,189 | lean | /-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import algebra.lie.nilpotent
import algebra.lie.tensor_product
import algebra.lie.character
import algebra.lie.cartan_subalgebra
import linear_algebra.eigenspace
import ring_theory.tensor_product
/-!
# Weights and roots of Lie modules and Lie algebras
Just as a key tool when studying the behaviour of a linear operator is to decompose the space on
which it acts into a sum of (generalised) eigenspaces, a key tool when studying a representation `M`
of Lie algebra `L` is to decompose `M` into a sum of simultaneous eigenspaces of `x` as `x` ranges
over `L`. These simultaneous generalised eigenspaces are known as the weight spaces of `M`.
When `L` is nilpotent, it follows from the binomial theorem that weight spaces are Lie submodules.
Even when `L` is not nilpotent, it may be useful to study its representations by restricting them
to a nilpotent subalgebra (e.g., a Cartan subalgebra). In the particular case when we view `L` as a
module over itself via the adjoint action, the weight spaces of `L` restricted to a nilpotent
subalgebra are known as root spaces.
Basic definitions and properties of the above ideas are provided in this file.
## Main definitions
* `lie_module.weight_space`
* `lie_module.is_weight`
* `lie_algebra.root_space`
* `lie_algebra.is_root`
* `lie_algebra.root_space_weight_space_product`
* `lie_algebra.root_space_product`
## References
* [N. Bourbaki, *Lie Groups and Lie Algebras, Chapters 7--9*](bourbaki1975b)
## Tags
lie character, eigenvalue, eigenspace, weight, weight vector, root, root vector
-/
universes u v w w₁ w₂ w₃
variables {R : Type u} {L : Type v} [comm_ring R] [lie_ring L] [lie_algebra R L]
variables (H : lie_subalgebra R L) [lie_algebra.is_nilpotent R H]
variables (M : Type w) [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M]
namespace lie_module
open lie_algebra
open tensor_product
open tensor_product.lie_module
open_locale big_operators
open_locale tensor_product
/-- Given a Lie module `M` over a Lie algebra `L`, the pre-weight space of `M` with respect to a
map `χ : L → R` is the simultaneous generalized eigenspace of the action of all `x : L` on `M`,
with eigenvalues `χ x`.
See also `lie_module.weight_space`. -/
def pre_weight_space (χ : L → R) : submodule R M :=
⨅ (x : L), (to_endomorphism R L M x).maximal_generalized_eigenspace (χ x)
lemma mem_pre_weight_space (χ : L → R) (m : M) :
m ∈ pre_weight_space M χ ↔ ∀ x, ∃ (k : ℕ), ((to_endomorphism R L M x - (χ x) • 1)^k) m = 0 :=
by simp [pre_weight_space, -linear_map.pow_apply]
variables (L)
/-- See also `bourbaki1975b` Chapter VII §1.1, Proposition 2 (ii). -/
protected lemma weight_vector_multiplication (M₁ : Type w₁) (M₂ : Type w₂) (M₃ : Type w₃)
[add_comm_group M₁] [module R M₁] [lie_ring_module L M₁] [lie_module R L M₁]
[add_comm_group M₂] [module R M₂] [lie_ring_module L M₂] [lie_module R L M₂]
[add_comm_group M₃] [module R M₃] [lie_ring_module L M₃] [lie_module R L M₃]
(g : M₁ ⊗[R] M₂ →ₗ⁅R,L⁆ M₃) (χ₁ χ₂ : L → R) :
((g : M₁ ⊗[R] M₂ →ₗ[R] M₃).comp
(map_incl (pre_weight_space M₁ χ₁) (pre_weight_space M₂ χ₂))).range ≤
pre_weight_space M₃ (χ₁ + χ₂) :=
begin
/- Unpack the statement of the goal. -/
intros m₃,
simp only [lie_module_hom.coe_to_linear_map, pi.add_apply, function.comp_app,
mem_pre_weight_space, linear_map.coe_comp, tensor_product.map_incl, exists_imp_distrib,
linear_map.mem_range],
rintros t rfl x,
/- Set up some notation. -/
let F : module.End R M₃ := (to_endomorphism R L M₃ x) - (χ₁ x + χ₂ x) • 1,
change ∃ k, (F^k) (g _) = 0,
/- The goal is linear in `t` so use induction to reduce to the case that `t` is a pure tensor. -/
apply t.induction_on,
{ use 0, simp only [linear_map.map_zero, lie_module_hom.map_zero], },
swap,
{ rintros t₁ t₂ ⟨k₁, hk₁⟩ ⟨k₂, hk₂⟩, use max k₁ k₂,
simp only [lie_module_hom.map_add, linear_map.map_add,
linear_map.pow_map_zero_of_le (le_max_left k₁ k₂) hk₁,
linear_map.pow_map_zero_of_le (le_max_right k₁ k₂) hk₂, add_zero], },
/- Now the main argument: pure tensors. -/
rintros ⟨m₁, hm₁⟩ ⟨m₂, hm₂⟩,
change ∃ k, (F^k) ((g : M₁ ⊗[R] M₂ →ₗ[R] M₃) (m₁ ⊗ₜ m₂)) = 0,
/- Eliminate `g` from the picture. -/
let f₁ : module.End R (M₁ ⊗[R] M₂) := (to_endomorphism R L M₁ x - (χ₁ x) • 1).rtensor M₂,
let f₂ : module.End R (M₁ ⊗[R] M₂) := (to_endomorphism R L M₂ x - (χ₂ x) • 1).ltensor M₁,
have h_comm_square : F.comp ↑g = (g : M₁ ⊗[R] M₂ →ₗ[R] M₃).comp (f₁ + f₂),
{ ext m₁ m₂, simp only [← g.map_lie x (m₁ ⊗ₜ m₂), add_smul, sub_tmul, tmul_sub, smul_tmul,
lie_tmul_right, tmul_smul, to_endomorphism_apply_apply, lie_module_hom.map_smul,
linear_map.one_apply, lie_module_hom.coe_to_linear_map, linear_map.smul_apply,
function.comp_app, linear_map.coe_comp, linear_map.rtensor_tmul, lie_module_hom.map_add,
linear_map.add_apply, lie_module_hom.map_sub, linear_map.sub_apply, linear_map.ltensor_tmul,
algebra_tensor_module.curry_apply, curry_apply, linear_map.to_fun_eq_coe,
linear_map.coe_restrict_scalars_eq_coe], abel, },
suffices : ∃ k, ((f₁ + f₂)^k) (m₁ ⊗ₜ m₂) = 0,
{ obtain ⟨k, hk⟩ := this, use k,
rw [← linear_map.comp_apply, linear_map.commute_pow_left_of_commute h_comm_square,
linear_map.comp_apply, hk, linear_map.map_zero], },
/- Unpack the information we have about `m₁`, `m₂`. -/
simp only [mem_pre_weight_space] at hm₁ hm₂,
obtain ⟨k₁, hk₁⟩ := hm₁ x,
obtain ⟨k₂, hk₂⟩ := hm₂ x,
have hf₁ : (f₁^k₁) (m₁ ⊗ₜ m₂) = 0,
{ simp only [hk₁, zero_tmul, linear_map.rtensor_tmul, linear_map.rtensor_pow], },
have hf₂ : (f₂^k₂) (m₁ ⊗ₜ m₂) = 0,
{ simp only [hk₂, tmul_zero, linear_map.ltensor_tmul, linear_map.ltensor_pow], },
/- It's now just an application of the binomial theorem. -/
use k₁ + k₂ - 1,
have hf_comm : commute f₁ f₂,
{ ext m₁ m₂, simp only [linear_map.mul_apply, linear_map.rtensor_tmul, linear_map.ltensor_tmul,
algebra_tensor_module.curry_apply, linear_map.to_fun_eq_coe, linear_map.ltensor_tmul,
curry_apply, linear_map.coe_restrict_scalars_eq_coe], },
rw hf_comm.add_pow',
simp only [tensor_product.map_incl, submodule.subtype_apply, finset.sum_apply,
submodule.coe_mk, linear_map.coe_fn_sum, tensor_product.map_tmul, linear_map.smul_apply],
/- The required sum is zero because each individual term is zero. -/
apply finset.sum_eq_zero,
rintros ⟨i, j⟩ hij,
/- Eliminate the binomial coefficients from the picture. -/
suffices : (f₁^i * f₂^j) (m₁ ⊗ₜ m₂) = 0, { rw this, apply smul_zero, },
/- Finish off with appropriate case analysis. -/
cases nat.le_or_le_of_add_eq_add_pred (finset.nat.mem_antidiagonal.mp hij) with hi hj,
{ rw [(hf_comm.pow_pow i j).eq, linear_map.mul_apply, linear_map.pow_map_zero_of_le hi hf₁,
linear_map.map_zero], },
{ rw [linear_map.mul_apply, linear_map.pow_map_zero_of_le hj hf₂, linear_map.map_zero], },
end
variables {L M}
lemma lie_mem_pre_weight_space_of_mem_pre_weight_space {χ₁ χ₂ : L → R} {x : L} {m : M}
(hx : x ∈ pre_weight_space L χ₁) (hm : m ∈ pre_weight_space M χ₂) :
⁅x, m⁆ ∈ pre_weight_space M (χ₁ + χ₂) :=
begin
apply lie_module.weight_vector_multiplication L L M M (to_module_hom R L M) χ₁ χ₂,
simp only [lie_module_hom.coe_to_linear_map, function.comp_app, linear_map.coe_comp,
tensor_product.map_incl, linear_map.mem_range],
use [⟨x, hx⟩ ⊗ₜ ⟨m, hm⟩],
simp only [submodule.subtype_apply, to_module_hom_apply, tensor_product.map_tmul],
refl,
end
variables (M)
/-- If a Lie algebra is nilpotent, then pre-weight spaces are Lie submodules. -/
def weight_space [lie_algebra.is_nilpotent R L] (χ : L → R) : lie_submodule R L M :=
{ lie_mem := λ x m hm,
begin
rw ← zero_add χ,
refine lie_mem_pre_weight_space_of_mem_pre_weight_space _ hm,
suffices : pre_weight_space L (0 : L → R) = ⊤, { simp only [this, submodule.mem_top], },
exact lie_algebra.infi_max_gen_zero_eigenspace_eq_top_of_nilpotent R L,
end,
.. pre_weight_space M χ }
lemma mem_weight_space [lie_algebra.is_nilpotent R L] (χ : L → R) (m : M) :
m ∈ weight_space M χ ↔ m ∈ pre_weight_space M χ :=
iff.rfl
/-- See also the more useful form `lie_module.zero_weight_space_eq_top_of_nilpotent`. -/
@[simp] lemma zero_weight_space_eq_top_of_nilpotent'
[lie_algebra.is_nilpotent R L] [is_nilpotent R L M] :
weight_space M (0 : L → R) = ⊤ :=
begin
rw [← lie_submodule.coe_to_submodule_eq_iff, lie_submodule.top_coe_submodule],
exact infi_max_gen_zero_eigenspace_eq_top_of_nilpotent R L M,
end
lemma coe_weight_space_of_top [lie_algebra.is_nilpotent R L] (χ : L → R) :
(weight_space M (χ ∘ (⊤ : lie_subalgebra R L).incl) : submodule R M) = weight_space M χ :=
begin
ext m,
simp only [weight_space, lie_submodule.coe_to_submodule_mk, lie_subalgebra.coe_bracket_of_module,
function.comp_app, mem_pre_weight_space],
split; intros h x,
{ obtain ⟨k, hk⟩ := h ⟨x, set.mem_univ x⟩, use k, exact hk, },
{ obtain ⟨k, hk⟩ := h x, use k, exact hk, },
end
@[simp] lemma zero_weight_space_eq_top_of_nilpotent
[lie_algebra.is_nilpotent R L] [is_nilpotent R L M] :
weight_space M (0 : (⊤ : lie_subalgebra R L) → R) = ⊤ :=
begin
/- We use `coe_weight_space_of_top` as a trick to circumvent the fact that we don't (yet) know
`is_nilpotent R (⊤ : lie_subalgebra R L) M` is equivalent to `is_nilpotent R L M`. -/
have h₀ : (0 : L → R) ∘ (⊤ : lie_subalgebra R L).incl = 0, { ext, refl, },
rw [← lie_submodule.coe_to_submodule_eq_iff, lie_submodule.top_coe_submodule, ← h₀,
coe_weight_space_of_top, ← infi_max_gen_zero_eigenspace_eq_top_of_nilpotent R L M],
refl,
end
/-- Given a Lie module `M` of a Lie algebra `L`, a weight of `M` with respect to a nilpotent
subalgebra `H ⊆ L` is a Lie character whose corresponding weight space is non-empty. -/
def is_weight (χ : lie_character R H) : Prop := weight_space M χ ≠ ⊥
/-- For a non-trivial nilpotent Lie module over a nilpotent Lie algebra, the zero character is a
weight with respect to the `⊤` Lie subalgebra. -/
lemma is_weight_zero_of_nilpotent
[nontrivial M] [lie_algebra.is_nilpotent R L] [is_nilpotent R L M] :
is_weight (⊤ : lie_subalgebra R L) M 0 :=
by { rw [is_weight, lie_hom.coe_zero, zero_weight_space_eq_top_of_nilpotent], exact top_ne_bot, }
end lie_module
namespace lie_algebra
open_locale tensor_product
open tensor_product.lie_module
open lie_module
/-- Given a nilpotent Lie subalgebra `H ⊆ L`, the root space of a map `χ : H → R` is the weight
space of `L` regarded as a module of `H` via the adjoint action. -/
abbreviation root_space (χ : H → R) : lie_submodule R H L := weight_space L χ
@[simp] lemma zero_root_space_eq_top_of_nilpotent [h : is_nilpotent R L] :
root_space (⊤ : lie_subalgebra R L) 0 = ⊤ :=
zero_weight_space_eq_top_of_nilpotent L
/-- A root of a Lie algebra `L` with respect to a nilpotent subalgebra `H ⊆ L` is a weight of `L`,
regarded as a module of `H` via the adjoint action. -/
abbreviation is_root := is_weight H L
@[simp] lemma root_space_comap_eq_weight_space (χ : H → R) :
(root_space H χ).comap H.incl' = weight_space H χ :=
begin
ext x,
let f : H → module.End R L := λ y, to_endomorphism R H L y - (χ y) • 1,
let g : H → module.End R H := λ y, to_endomorphism R H H y - (χ y) • 1,
suffices : (∀ (y : H), ∃ (k : ℕ), ((f y)^k).comp (H.incl : H →ₗ[R] L) x = 0) ↔
∀ (y : H), ∃ (k : ℕ), (H.incl : H →ₗ[R] L).comp ((g y)^k) x = 0,
{ simp only [lie_hom.coe_to_linear_map, lie_subalgebra.coe_incl, function.comp_app,
linear_map.coe_comp, submodule.coe_eq_zero] at this,
simp only [mem_weight_space, mem_pre_weight_space,
lie_subalgebra.coe_incl', lie_submodule.mem_comap, this], },
have hfg : ∀ (y : H), (f y).comp (H.incl : H →ₗ[R] L) = (H.incl : H →ₗ[R] L).comp (g y),
{ rintros ⟨y, hz⟩, ext ⟨z, hz⟩,
simp only [submodule.coe_sub, to_endomorphism_apply_apply, lie_hom.coe_to_linear_map,
linear_map.one_apply, lie_subalgebra.coe_incl, lie_subalgebra.coe_bracket_of_module,
lie_subalgebra.coe_bracket, linear_map.smul_apply, function.comp_app,
submodule.coe_smul_of_tower, linear_map.coe_comp, linear_map.sub_apply], },
simp_rw [linear_map.commute_pow_left_of_commute (hfg _)],
end
variables {H M}
lemma lie_mem_weight_space_of_mem_weight_space {χ₁ χ₂ : H → R} {x : L} {m : M}
(hx : x ∈ root_space H χ₁) (hm : m ∈ weight_space M χ₂) : ⁅x, m⁆ ∈ weight_space M (χ₁ + χ₂) :=
begin
apply lie_module.weight_vector_multiplication
H L M M ((to_module_hom R L M).restrict_lie H) χ₁ χ₂,
simp only [lie_module_hom.coe_to_linear_map, function.comp_app, linear_map.coe_comp,
tensor_product.map_incl, linear_map.mem_range],
use [⟨x, hx⟩ ⊗ₜ ⟨m, hm⟩],
simp only [submodule.subtype_apply, to_module_hom_apply, submodule.coe_mk,
lie_module_hom.coe_restrict_lie, tensor_product.map_tmul],
end
variables (R L H M)
/-- Given a nilpotent Lie subalgebra `H ⊆ L` together with `χ₁ χ₂ : H → R`, there is a natural
`R`-bilinear product of root vectors and weight vectors, compatible with the actions of `H`. -/
def root_space_weight_space_product (χ₁ χ₂ χ₃ : H → R) (hχ : χ₁ + χ₂ = χ₃) :
(root_space H χ₁) ⊗[R] (weight_space M χ₂) →ₗ⁅R,H⁆ weight_space M χ₃ :=
lift_lie R H (root_space H χ₁) (weight_space M χ₂) (weight_space M χ₃)
{ to_fun := λ x,
{ to_fun :=
λ m, ⟨⁅(x : L), (m : M)⁆,
hχ ▸ (lie_mem_weight_space_of_mem_weight_space x.property m.property) ⟩,
map_add' := λ m n, by { simp only [lie_submodule.coe_add, lie_add], refl, },
map_smul' := λ t m, by { conv_lhs { congr, rw [lie_submodule.coe_smul, lie_smul], }, refl, }, },
map_add' := λ x y, by ext m; rw [linear_map.add_apply, linear_map.coe_mk, linear_map.coe_mk,
linear_map.coe_mk, subtype.coe_mk, lie_submodule.coe_add, lie_submodule.coe_add, add_lie,
subtype.coe_mk, subtype.coe_mk],
map_smul' := λ t x, by ext m; rw [linear_map.smul_apply, linear_map.coe_mk, linear_map.coe_mk,
subtype.coe_mk, lie_submodule.coe_smul, smul_lie, lie_submodule.coe_smul, subtype.coe_mk],
map_lie' := λ x y, by ext m; rw [lie_hom.lie_apply, lie_submodule.coe_sub, linear_map.coe_mk,
linear_map.coe_mk, subtype.coe_mk, subtype.coe_mk, lie_submodule.coe_bracket,
lie_submodule.coe_bracket, subtype.coe_mk, lie_subalgebra.coe_bracket_of_module,
lie_subalgebra.coe_bracket_of_module, lie_submodule.coe_bracket,
lie_subalgebra.coe_bracket_of_module, lie_lie], }
@[simp] lemma coe_root_space_weight_space_product_tmul
(χ₁ χ₂ χ₃ : H → R) (hχ : χ₁ + χ₂ = χ₃) (x : root_space H χ₁) (m : weight_space M χ₂) :
(root_space_weight_space_product R L H M χ₁ χ₂ χ₃ hχ (x ⊗ₜ m) : M) = ⁅(x : L), (m : M)⁆ :=
by simp only [root_space_weight_space_product, lift_apply, lie_module_hom.coe_to_linear_map,
coe_lift_lie_eq_lift_coe, submodule.coe_mk, linear_map.coe_mk, lie_module_hom.coe_mk]
/-- Given a nilpotent Lie subalgebra `H ⊆ L` together with `χ₁ χ₂ : H → R`, there is a natural
`R`-bilinear product of root vectors, compatible with the actions of `H`. -/
def root_space_product (χ₁ χ₂ χ₃ : H → R) (hχ : χ₁ + χ₂ = χ₃) :
(root_space H χ₁) ⊗[R] (root_space H χ₂) →ₗ⁅R,H⁆ root_space H χ₃ :=
root_space_weight_space_product R L H L χ₁ χ₂ χ₃ hχ
@[simp] lemma root_space_product_def :
root_space_product R L H = root_space_weight_space_product R L H L :=
rfl
lemma root_space_product_tmul
(χ₁ χ₂ χ₃ : H → R) (hχ : χ₁ + χ₂ = χ₃) (x : root_space H χ₁) (y : root_space H χ₂) :
(root_space_product R L H χ₁ χ₂ χ₃ hχ (x ⊗ₜ y) : L) = ⁅(x : L), (y : L)⁆ :=
by simp only [root_space_product_def, coe_root_space_weight_space_product_tmul]
/-- Given a nilpotent Lie subalgebra `H ⊆ L`, the root space of the zero map `0 : H → R` is a Lie
subalgebra of `L`. -/
def zero_root_subalgebra : lie_subalgebra R L :=
{ lie_mem' := λ x y hx hy, by
{ let xy : (root_space H 0) ⊗[R] (root_space H 0) := ⟨x, hx⟩ ⊗ₜ ⟨y, hy⟩,
suffices : (root_space_product R L H 0 0 0 (add_zero 0) xy : L) ∈ root_space H 0,
{ rwa [root_space_product_tmul, subtype.coe_mk, subtype.coe_mk] at this, },
exact (root_space_product R L H 0 0 0 (add_zero 0) xy).property, },
.. (root_space H 0 : submodule R L) }
@[simp] lemma coe_zero_root_subalgebra :
(zero_root_subalgebra R L H : submodule R L) = root_space H 0 :=
rfl
lemma mem_zero_root_subalgebra (x : L) :
x ∈ zero_root_subalgebra R L H ↔ ∀ (y : H), ∃ (k : ℕ), ((to_endomorphism R H L y)^k) x = 0 :=
by simp only [zero_root_subalgebra, mem_weight_space, mem_pre_weight_space, pi.zero_apply, sub_zero,
set_like.mem_coe, zero_smul, lie_submodule.mem_coe_submodule, submodule.mem_carrier,
lie_subalgebra.mem_mk_iff]
lemma to_lie_submodule_le_root_space_zero : H.to_lie_submodule ≤ root_space H 0 :=
begin
intros x hx,
simp only [lie_subalgebra.mem_to_lie_submodule] at hx,
simp only [mem_weight_space, mem_pre_weight_space, pi.zero_apply, sub_zero, zero_smul],
intros y,
unfreezingI { obtain ⟨k, hk⟩ := (infer_instance : is_nilpotent R H) },
use k,
let f : module.End R H := to_endomorphism R H H y,
let g : module.End R L := to_endomorphism R H L y,
have hfg : g.comp (H : submodule R L).subtype = (H : submodule R L).subtype.comp f,
{ ext z, simp only [to_endomorphism_apply_apply, submodule.subtype_apply,
lie_subalgebra.coe_bracket_of_module, lie_subalgebra.coe_bracket, function.comp_app,
linear_map.coe_comp], },
change (g^k).comp (H : submodule R L).subtype ⟨x, hx⟩ = 0,
rw linear_map.commute_pow_left_of_commute hfg k,
have h := iterate_to_endomorphism_mem_lower_central_series R H H y ⟨x, hx⟩ k,
rw [hk, lie_submodule.mem_bot] at h,
simp only [submodule.subtype_apply, function.comp_app, linear_map.pow_apply, linear_map.coe_comp,
submodule.coe_eq_zero],
exact h,
end
lemma le_zero_root_subalgebra : H ≤ zero_root_subalgebra R L H :=
begin
rw [← lie_subalgebra.coe_submodule_le_coe_submodule, ← H.coe_to_lie_submodule,
coe_zero_root_subalgebra, lie_submodule.coe_submodule_le_coe_submodule],
exact to_lie_submodule_le_root_space_zero R L H,
end
@[simp] lemma zero_root_subalgebra_normalizer_eq_self :
(zero_root_subalgebra R L H).normalizer = zero_root_subalgebra R L H :=
begin
refine le_antisymm _ (lie_subalgebra.le_normalizer _),
intros x hx,
rw lie_subalgebra.mem_normalizer_iff at hx,
rw mem_zero_root_subalgebra,
rintros ⟨y, hy⟩,
specialize hx y (le_zero_root_subalgebra R L H hy),
rw mem_zero_root_subalgebra at hx,
obtain ⟨k, hk⟩ := hx ⟨y, hy⟩,
rw [← lie_skew, linear_map.map_neg, neg_eq_zero] at hk,
use k + 1,
rw [linear_map.iterate_succ, linear_map.coe_comp, function.comp_app, to_endomorphism_apply_apply,
lie_subalgebra.coe_bracket_of_module, submodule.coe_mk, hk],
end
/-- In finite dimensions over a field (and possibly more generally) Engel's theorem shows that
the converse of this is also true, i.e.,
`zero_root_subalgebra R L H = H ↔ lie_subalgebra.is_cartan_subalgebra H`. -/
lemma zero_root_subalgebra_is_cartan_of_eq (h : zero_root_subalgebra R L H = H) :
lie_subalgebra.is_cartan_subalgebra H :=
{ nilpotent := infer_instance,
self_normalizing := by { rw ← h, exact zero_root_subalgebra_normalizer_eq_self R L H, } }
end lie_algebra
namespace lie_module
open lie_algebra
variables {R L H}
/-- A priori, weight spaces are Lie submodules over the Lie subalgebra `H` used to define them.
However they are naturally Lie submodules over the (in general larger) Lie subalgebra
`zero_root_subalgebra R L H`. Even though it is often the case that
`zero_root_subalgebra R L H = H`, it is likely to be useful to have the flexibility not to have
to invoke this equality (as well as to work more generally). -/
def weight_space' (χ : H → R) : lie_submodule R (zero_root_subalgebra R L H) M :=
{ lie_mem := λ x m hm, by
{ have hx : (x : L) ∈ root_space H 0,
{ rw [← lie_submodule.mem_coe_submodule, ← coe_zero_root_subalgebra], exact x.property, },
rw ← zero_add χ,
exact lie_mem_weight_space_of_mem_weight_space hx hm, },
.. (weight_space M χ : submodule R M) }
@[simp] lemma coe_weight_space' (χ : H → R) :
(weight_space' M χ : submodule R M) = weight_space M χ :=
rfl
end lie_module
|
e4f279011633999f5af40c5554fe7998dac65ccc | 98beff2e97d91a54bdcee52f922c4e1866a6c9b9 | /src/opens.lean | dd41d3a897882c8d85200ac6b8a40ff90afe5d1e | [] | no_license | b-mehta/topos | c3fc43fb04ba16bae1965ce5c26c6461172e5bc6 | c9032b11789e36038bc841a1e2b486972421b983 | refs/heads/master | 1,629,609,492,867 | 1,609,907,263,000 | 1,609,907,263,000 | 240,943,034 | 43 | 3 | null | 1,598,210,062,000 | 1,581,877,668,000 | Lean | UTF-8 | Lean | false | false | 4,169 | lean | import topology.category.Top.opens
import grothendieck
import tactic.equiv_rw
universes u
open category_theory topological_space category_theory.limits
namespace topological_space.opens
section
variables (X : Type u) [topological_space X]
section
variables {X} (U V : opens X)
@[derive partial_order]
def opens_sieve' := {s : set (opens X) // ∀ V ∈ s, V ≤ U ∧ ∀ W ≤ V, W ∈ s }
@[simps]
def equivalence' : opens_sieve' U ≃o sieve U :=
{ inv_fun := λ S,
{ val := λ V, ∃ (h : V ≤ U), S.arrows (over.mk (hom_of_le h)),
property := by { rintro V ⟨VU, hVU⟩, exact ⟨VU, λ W WV, ⟨_, S.downward_closed hVU (hom_of_le WV)⟩⟩ } },
to_fun := λ S,
{ arrows := λ f, f.left ∈ S.1,
subs := λ V W VU WV hVU, ((S.2 V) hVU).2 W (le_of_hom WV) },
right_inv := λ S, sieve.ext_iff $ λ V VU,
⟨by { rintro ⟨_, q⟩, convert q }, by { rintro hf, refine ⟨le_of_hom VU, _⟩, convert hf }⟩,
left_inv := λ S, subtype.ext_val $ funext $ λ V,
propext ⟨by {rintro ⟨_, q⟩, exact q}, λ hV, ⟨(S.2 V hV).1, hV⟩⟩,
map_rel_iff' := λ a b, ⟨λ h V VU hVU, h hVU, λ h V hV, h _ (hom_of_le (a.2 _ hV).1) hV⟩ }
instance : order_top (opens_sieve' U) :=
{ top := ⟨λ V, V ≤ U, by tidy⟩,
le_top := λ S V hV, (S.2 V hV).1,
..topological_space.opens.opens_sieve'.partial_order _ }
def is_covering' (s : opens_sieve' U) : Prop := ∀ x ∈ U, ∃ V, V ∈ s.1 ∧ x ∈ V
def restrict' {U : opens X} (V : opens X) (s : opens_sieve' U) : opens_sieve' V :=
begin
refine subtype.map (set.image (⊓ V)) _ s,
rintros S hS _ ⟨W', hW', rfl⟩,
refine ⟨lattice.inf_le_right _ _, λ V' hV', ⟨V' ⊓ W', _, _⟩⟩,
apply (hS _ hW').2,
refine lattice.inf_le_right _ _,
simp only [],
rw inf_assoc,
apply inf_of_le_left hV',
end
lemma restrict_equivalence {U V : opens X} (VU : V ⟶ U) (s : opens_sieve' U) :
equivalence' _ (restrict' V s) = sieve.pullback (equivalence' _ s) VU :=
sieve.ext_iff $ λ W WV,
⟨ by {rintro ⟨W, h, q⟩, cases q, exact (s.2 _ h).2 _ (lattice.inf_le_left _ _)},
λ hW, ⟨_, hW, inf_of_le_left (le_of_hom WV)⟩⟩
lemma covering'_trans (r s : opens_sieve' U) (hs : is_covering' U s)
(hr : ∀ {Y : opens X} (a : Y ≤ U), s.1 Y → is_covering' _ (restrict' Y r)) :
is_covering' U r :=
begin
intros x hx,
obtain ⟨V, Vs, xV⟩ := hs x hx,
obtain ⟨_, ⟨W, Wr, rfl⟩, xW⟩ :=
hr (lattice.inf_le_left U V) ((s.2 _ Vs).2 _ (lattice.inf_le_right _ _)) x ⟨hx, xV⟩,
exact ⟨_, Wr, xW.1⟩,
end
end
def covering : sieve_set (opens X) := λ U S, is_covering' _ ((equivalence' _).symm S)
lemma covering_sieve (U : opens X) (S : sieve U) :
S ∈ covering X U ↔ ∀ x ∈ U, ∃ V, x ∈ V ∧ ∃ (f : V ≤ U), over.mk (hom_of_le f) ∈ S.arrows :=
ball_congr (λ x hx, exists_congr (λ V, and_comm _ _))
instance : grothendieck (covering X) :=
{ max := λ U,
begin
change U.is_covering' _,
rw order_iso.map_top (equivalence' U).symm,
intros x hx,
exact ⟨U, le_refl _, hx⟩,
end,
stab := λ U V s hs f x hx,
begin
equiv_rw (equivalence' U).to_equiv.symm at s,
change ∀ (x ∈ U), _ at hs,
simp only [rel_iso.coe_fn_to_equiv, equiv.symm_symm, order_iso.symm_apply_apply] at hs,
simp only [rel_iso.coe_fn_to_equiv],
rw ← restrict_equivalence,
simp only [order_iso.symm_apply_apply],
dsimp [restrict', subtype.map],
obtain ⟨W, hW₁, hW₂⟩ := hs x (le_of_hom f hx),
refine ⟨_ ⊓ _, ⟨W, hW₁, rfl⟩, hW₂, hx⟩,
end,
trans := λ U s hs r h,
begin
equiv_rw (equivalence' U).to_equiv.symm at s,
equiv_rw (equivalence' U).to_equiv.symm at r,
change is_covering' _ _,
change is_covering' _ _ at hs,
simp only [rel_iso.coe_fn_to_equiv, order_iso.symm_apply_apply, equiv.symm_symm] at ⊢ hs h,
refine U.covering'_trans r s hs _,
intros V VU Vs,
specialize h (hom_of_le VU) _,
rw ← restrict_equivalence at h,
change is_covering' _ _ at h,
simp only [rel_iso.coe_fn_to_equiv, order_iso.symm_apply_apply, equiv.symm_symm] at h,
apply h,
apply Vs,
end }
end
end topological_space.opens
|
4af5988c417b0c73b2570f326e38b1ac0cd3ebd1 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/probability/independence.lean | 4adcf7ed67e6369fb3e44076d444158e822e2996 | [
"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 | 18,403 | lean | /-
Copyright (c) 2021 Rémy Degenne. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Rémy Degenne
-/
import algebra.big_operators.intervals
import measure_theory.measure.measure_space
import measure_theory.pi_system
/-!
# Independence of sets of sets and measure spaces (σ-algebras)
* A family of sets of sets `π : ι → set (set α)` is independent with respect to a measure `μ` if for
any finite set of indices `s = {i_1, ..., i_n}`, for any sets `f i_1 ∈ π i_1, ..., f i_n ∈ π i_n`,
`μ (⋂ i in s, f i) = ∏ i in s, μ (f i) `. It will be used for families of π-systems.
* A family of measurable space structures (i.e. of σ-algebras) is independent with respect to a
measure `μ` (typically defined on a finer σ-algebra) if the family of sets of measurable sets they
define is independent. I.e., `m : ι → measurable_space α` is independent with respect to a
measure `μ` if for any finite set of indices `s = {i_1, ..., i_n}`, for any sets
`f i_1 ∈ m i_1, ..., f i_n ∈ m i_n`, then `μ (⋂ i in s, f i) = ∏ i in s, μ (f i)`.
* Independence of sets (or events in probabilistic parlance) is defined as independence of the
measurable space structures they generate: a set `s` generates the measurable space structure with
measurable sets `∅, s, sᶜ, univ`.
* Independence of functions (or random variables) is also defined as independence of the measurable
space structures they generate: a function `f` for which we have a measurable space `m` on the
codomain generates `measurable_space.comap f m`.
## Main statements
* TODO: `Indep_of_Indep_sets`: if π-systems are independent as sets of sets, then the
measurable space structures they generate are independent.
* `indep_of_indep_sets`: variant with two π-systems.
## Implementation notes
We provide one main definition of independence:
* `Indep_sets`: independence of a family of sets of sets `pi : ι → set (set α)`.
Three other independence notions are defined using `Indep_sets`:
* `Indep`: independence of a family of measurable space structures `m : ι → measurable_space α`,
* `Indep_set`: independence of a family of sets `s : ι → set α`,
* `Indep_fun`: independence of a family of functions. For measurable spaces
`m : Π (i : ι), measurable_space (β i)`, we consider functions `f : Π (i : ι), α → β i`.
Additionally, we provide four corresponding statements for two measurable space structures (resp.
sets of sets, sets, functions) instead of a family. These properties are denoted by the same names
as for a family, but without a capital letter, for example `indep_fun` is the version of `Indep_fun`
for two functions.
The definition of independence for `Indep_sets` uses finite sets (`finset`). An alternative and
equivalent way of defining independence would have been to use countable sets.
TODO: prove that equivalence.
Most of the definitions and lemma in this file list all variables instead of using the `variables`
keyword at the beginning of a section, for example
`lemma indep.symm {α} {m₁ m₂ : measurable_space α} [measurable_space α] {μ : measure α} ...` .
This is intentional, to be able to control the order of the `measurable_space` variables. Indeed
when defining `μ` in the example above, the measurable space used is the last one defined, here
`[measurable_space α]`, and not `m₁` or `m₂`.
## References
* Williams, David. Probability with martingales. Cambridge university press, 1991.
Part A, Chapter 4.
-/
open measure_theory measurable_space
open_locale big_operators classical measure_theory
namespace probability_theory
section definitions
/-- A family of sets of sets `π : ι → set (set α)` is independent with respect to a measure `μ` if
for any finite set of indices `s = {i_1, ..., i_n}`, for any sets
`f i_1 ∈ π i_1, ..., f i_n ∈ π i_n`, then `μ (⋂ i in s, f i) = ∏ i in s, μ (f i) `.
It will be used for families of pi_systems. -/
def Indep_sets {α ι} [measurable_space α] (π : ι → set (set α)) (μ : measure α . volume_tac) :
Prop :=
∀ (s : finset ι) {f : ι → set α} (H : ∀ i, i ∈ s → f i ∈ π i), μ (⋂ i ∈ s, f i) = ∏ i in s, μ (f i)
/-- Two sets of sets `s₁, s₂` are independent with respect to a measure `μ` if for any sets
`t₁ ∈ p₁, t₂ ∈ s₂`, then `μ (t₁ ∩ t₂) = μ (t₁) * μ (t₂)` -/
def indep_sets {α} [measurable_space α] (s1 s2 : set (set α)) (μ : measure α . volume_tac) : Prop :=
∀ t1 t2 : set α, t1 ∈ s1 → t2 ∈ s2 → μ (t1 ∩ t2) = μ t1 * μ t2
/-- A family of measurable space structures (i.e. of σ-algebras) is independent with respect to a
measure `μ` (typically defined on a finer σ-algebra) if the family of sets of measurable sets they
define is independent. `m : ι → measurable_space α` is independent with respect to measure `μ` if
for any finite set of indices `s = {i_1, ..., i_n}`, for any sets
`f i_1 ∈ m i_1, ..., f i_n ∈ m i_n`, then `μ (⋂ i in s, f i) = ∏ i in s, μ (f i) `. -/
def Indep {α ι} (m : ι → measurable_space α) [measurable_space α] (μ : measure α . volume_tac) :
Prop :=
Indep_sets (λ x, {s | measurable_set[m x] s}) μ
/-- Two measurable space structures (or σ-algebras) `m₁, m₂` are independent with respect to a
measure `μ` (defined on a third σ-algebra) if for any sets `t₁ ∈ m₁, t₂ ∈ m₂`,
`μ (t₁ ∩ t₂) = μ (t₁) * μ (t₂)` -/
def indep {α} (m₁ m₂ : measurable_space α) [measurable_space α] (μ : measure α . volume_tac) :
Prop :=
indep_sets ({s | measurable_set[m₁] s}) ({s | measurable_set[m₂] s}) μ
/-- A family of sets is independent if the family of measurable space structures they generate is
independent. For a set `s`, the generated measurable space has measurable sets `∅, s, sᶜ, univ`. -/
def Indep_set {α ι} [measurable_space α] (s : ι → set α) (μ : measure α . volume_tac) : Prop :=
Indep (λ i, generate_from {s i}) μ
/-- Two sets are independent if the two measurable space structures they generate are independent.
For a set `s`, the generated measurable space structure has measurable sets `∅, s, sᶜ, univ`. -/
def indep_set {α} [measurable_space α] (s t : set α) (μ : measure α . volume_tac) : Prop :=
indep (generate_from {s}) (generate_from {t}) μ
/-- A family of functions defined on the same space `α` and taking values in possibly different
spaces, each with a measurable space structure, is independent if the family of measurable space
structures they generate on `α` is independent. For a function `g` with codomain having measurable
space structure `m`, the generated measurable space structure is `measurable_space.comap g m`. -/
def Indep_fun {α ι} [measurable_space α] {β : ι → Type*} (m : Π (x : ι), measurable_space (β x))
(f : Π (x : ι), α → β x) (μ : measure α . volume_tac) : Prop :=
Indep (λ x, measurable_space.comap (f x) (m x)) μ
/-- Two functions are independent if the two measurable space structures they generate are
independent. For a function `f` with codomain having measurable space structure `m`, the generated
measurable space structure is `measurable_space.comap f m`. -/
def indep_fun {α β γ} [measurable_space α] [mβ : measurable_space β] [mγ : measurable_space γ]
(f : α → β) (g : α → γ) (μ : measure α . volume_tac) : Prop :=
indep (measurable_space.comap f mβ) (measurable_space.comap g mγ) μ
end definitions
section indep
lemma indep_sets.symm {α} {s₁ s₂ : set (set α)} [measurable_space α] {μ : measure α}
(h : indep_sets s₁ s₂ μ) :
indep_sets s₂ s₁ μ :=
by { intros t1 t2 ht1 ht2, rw [set.inter_comm, mul_comm], exact h t2 t1 ht2 ht1, }
lemma indep.symm {α} {m₁ m₂ : measurable_space α} [measurable_space α] {μ : measure α}
(h : indep m₁ m₂ μ) :
indep m₂ m₁ μ :=
indep_sets.symm h
lemma indep_sets_of_indep_sets_of_le_left {α} {s₁ s₂ s₃: set (set α)} [measurable_space α]
{μ : measure α} (h_indep : indep_sets s₁ s₂ μ) (h31 : s₃ ⊆ s₁) :
indep_sets s₃ s₂ μ :=
λ t1 t2 ht1 ht2, h_indep t1 t2 (set.mem_of_subset_of_mem h31 ht1) ht2
lemma indep_sets_of_indep_sets_of_le_right {α} {s₁ s₂ s₃: set (set α)} [measurable_space α]
{μ : measure α} (h_indep : indep_sets s₁ s₂ μ) (h32 : s₃ ⊆ s₂) :
indep_sets s₁ s₃ μ :=
λ t1 t2 ht1 ht2, h_indep t1 t2 ht1 (set.mem_of_subset_of_mem h32 ht2)
lemma indep_of_indep_of_le_left {α} {m₁ m₂ m₃: measurable_space α} [measurable_space α]
{μ : measure α} (h_indep : indep m₁ m₂ μ) (h31 : m₃ ≤ m₁) :
indep m₃ m₂ μ :=
λ t1 t2 ht1 ht2, h_indep t1 t2 (h31 _ ht1) ht2
lemma indep_of_indep_of_le_right {α} {m₁ m₂ m₃: measurable_space α} [measurable_space α]
{μ : measure α} (h_indep : indep m₁ m₂ μ) (h32 : m₃ ≤ m₂) :
indep m₁ m₃ μ :=
λ t1 t2 ht1 ht2, h_indep t1 t2 ht1 (h32 _ ht2)
lemma indep_sets.union {α} [measurable_space α] {s₁ s₂ s' : set (set α)} {μ : measure α}
(h₁ : indep_sets s₁ s' μ) (h₂ : indep_sets s₂ s' μ) :
indep_sets (s₁ ∪ s₂) s' μ :=
begin
intros t1 t2 ht1 ht2,
cases (set.mem_union _ _ _).mp ht1 with ht1₁ ht1₂,
{ exact h₁ t1 t2 ht1₁ ht2, },
{ exact h₂ t1 t2 ht1₂ ht2, },
end
@[simp] lemma indep_sets.union_iff {α} [measurable_space α] {s₁ s₂ s' : set (set α)}
{μ : measure α} :
indep_sets (s₁ ∪ s₂) s' μ ↔ indep_sets s₁ s' μ ∧ indep_sets s₂ s' μ :=
⟨λ h, ⟨indep_sets_of_indep_sets_of_le_left h (set.subset_union_left s₁ s₂),
indep_sets_of_indep_sets_of_le_left h (set.subset_union_right s₁ s₂)⟩,
λ h, indep_sets.union h.left h.right⟩
lemma indep_sets.Union {α ι} [measurable_space α] {s : ι → set (set α)} {s' : set (set α)}
{μ : measure α} (hyp : ∀ n, indep_sets (s n) s' μ) :
indep_sets (⋃ n, s n) s' μ :=
begin
intros t1 t2 ht1 ht2,
rw set.mem_Union at ht1,
cases ht1 with n ht1,
exact hyp n t1 t2 ht1 ht2,
end
lemma indep_sets.inter {α} [measurable_space α] {s₁ s' : set (set α)} (s₂ : set (set α))
{μ : measure α} (h₁ : indep_sets s₁ s' μ) :
indep_sets (s₁ ∩ s₂) s' μ :=
λ t1 t2 ht1 ht2, h₁ t1 t2 ((set.mem_inter_iff _ _ _).mp ht1).left ht2
lemma indep_sets.Inter {α ι} [measurable_space α] {s : ι → set (set α)} {s' : set (set α)}
{μ : measure α} (h : ∃ n, indep_sets (s n) s' μ) :
indep_sets (⋂ n, s n) s' μ :=
by {intros t1 t2 ht1 ht2, cases h with n h, exact h t1 t2 (set.mem_Inter.mp ht1 n) ht2 }
lemma indep_sets_singleton_iff {α} [measurable_space α] {s t : set α} {μ : measure α} :
indep_sets {s} {t} μ ↔ μ (s ∩ t) = μ s * μ t :=
⟨λ h, h s t rfl rfl,
λ h s1 t1 hs1 ht1, by rwa [set.mem_singleton_iff.mp hs1, set.mem_singleton_iff.mp ht1]⟩
end indep
/-! ### Deducing `indep` from `Indep` -/
section from_Indep_to_indep
lemma Indep_sets.indep_sets {α ι} {s : ι → set (set α)} [measurable_space α] {μ : measure α}
(h_indep : Indep_sets s μ) {i j : ι} (hij : i ≠ j) :
indep_sets (s i) (s j) μ :=
begin
intros t₁ t₂ ht₁ ht₂,
have hf_m : ∀ (x : ι), x ∈ {i, j} → (ite (x=i) t₁ t₂) ∈ s x,
{ intros x hx,
cases finset.mem_insert.mp hx with hx hx,
{ simp [hx, ht₁], },
{ simp [finset.mem_singleton.mp hx, hij.symm, ht₂], }, },
have h1 : t₁ = ite (i = i) t₁ t₂, by simp only [if_true, eq_self_iff_true],
have h2 : t₂ = ite (j = i) t₁ t₂, by simp only [hij.symm, if_false],
have h_inter : (⋂ (t : ι) (H : t ∈ ({i, j} : finset ι)), ite (t = i) t₁ t₂)
= (ite (i = i) t₁ t₂) ∩ (ite (j = i) t₁ t₂),
by simp only [finset.set_bInter_singleton, finset.set_bInter_insert],
have h_prod : (∏ (t : ι) in ({i, j} : finset ι), μ (ite (t = i) t₁ t₂))
= μ (ite (i = i) t₁ t₂) * μ (ite (j = i) t₁ t₂),
by simp only [hij, finset.prod_singleton, finset.prod_insert, not_false_iff,
finset.mem_singleton],
rw h1,
nth_rewrite 1 h2,
nth_rewrite 3 h2,
rw [←h_inter, ←h_prod, h_indep {i, j} hf_m],
end
lemma Indep.indep {α ι} {m : ι → measurable_space α} [measurable_space α] {μ : measure α}
(h_indep : Indep m μ) {i j : ι} (hij : i ≠ j) :
indep (m i) (m j) μ :=
begin
change indep_sets ((λ x, (m x).measurable_set') i) ((λ x, (m x).measurable_set') j) μ,
exact Indep_sets.indep_sets h_indep hij,
end
end from_Indep_to_indep
/-!
## π-system lemma
Independence of measurable spaces is equivalent to independence of generating π-systems.
-/
section from_measurable_spaces_to_sets_of_sets
/-! ### Independence of measurable space structures implies independence of generating π-systems -/
lemma Indep.Indep_sets {α ι} [measurable_space α] {μ : measure α} {m : ι → measurable_space α}
{s : ι → set (set α)} (hms : ∀ n, m n = generate_from (s n))
(h_indep : Indep m μ) :
Indep_sets s μ :=
λ S f hfs, h_indep S $ λ x hxS,
((hms x).symm ▸ measurable_set_generate_from (hfs x hxS) : measurable_set[m x] (f x))
lemma indep.indep_sets {α} [measurable_space α] {μ : measure α} {s1 s2 : set (set α)}
(h_indep : indep (generate_from s1) (generate_from s2) μ) :
indep_sets s1 s2 μ :=
λ t1 t2 ht1 ht2, h_indep t1 t2 (measurable_set_generate_from ht1) (measurable_set_generate_from ht2)
end from_measurable_spaces_to_sets_of_sets
section from_pi_systems_to_measurable_spaces
/-! ### Independence of generating π-systems implies independence of measurable space structures -/
private lemma indep_sets.indep_aux {α} {m2 : measurable_space α}
{m : measurable_space α} {μ : measure α} [is_probability_measure μ] {p1 p2 : set (set α)}
(h2 : m2 ≤ m) (hp2 : is_pi_system p2) (hpm2 : m2 = generate_from p2)
(hyp : indep_sets p1 p2 μ) {t1 t2 : set α} (ht1 : t1 ∈ p1) (ht2m : m2.measurable_set' t2) :
μ (t1 ∩ t2) = μ t1 * μ t2 :=
begin
let μ_inter := μ.restrict t1,
let ν := (μ t1) • μ,
have h_univ : μ_inter set.univ = ν set.univ,
by rw [measure.restrict_apply_univ, measure.smul_apply, smul_eq_mul, measure_univ, mul_one],
haveI : is_finite_measure μ_inter := @restrict.is_finite_measure α _ t1 μ ⟨measure_lt_top μ t1⟩,
rw [set.inter_comm, ←@measure.restrict_apply α _ μ t1 t2 (h2 t2 ht2m)],
refine ext_on_measurable_space_of_generate_finite m p2 (λ t ht, _) h2 hpm2 hp2 h_univ ht2m,
have ht2 : m.measurable_set' t,
{ refine h2 _ _,
rw hpm2,
exact measurable_set_generate_from ht, },
rw [measure.restrict_apply ht2, measure.smul_apply, set.inter_comm],
exact hyp t1 t ht1 ht,
end
lemma indep_sets.indep {α} {m1 m2 : measurable_space α} {m : measurable_space α}
{μ : measure α} [is_probability_measure μ] {p1 p2 : set (set α)} (h1 : m1 ≤ m) (h2 : m2 ≤ m)
(hp1 : is_pi_system p1) (hp2 : is_pi_system p2) (hpm1 : m1 = generate_from p1)
(hpm2 : m2 = generate_from p2) (hyp : indep_sets p1 p2 μ) :
indep m1 m2 μ :=
begin
intros t1 t2 ht1 ht2,
let μ_inter := μ.restrict t2,
let ν := (μ t2) • μ,
have h_univ : μ_inter set.univ = ν set.univ,
by rw [measure.restrict_apply_univ, measure.smul_apply, smul_eq_mul, measure_univ, mul_one],
haveI : is_finite_measure μ_inter := @restrict.is_finite_measure α _ t2 μ ⟨measure_lt_top μ t2⟩,
rw [mul_comm, ←@measure.restrict_apply α _ μ t2 t1 (h1 t1 ht1)],
refine ext_on_measurable_space_of_generate_finite m p1 (λ t ht, _) h1 hpm1 hp1 h_univ ht1,
have ht1 : m.measurable_set' t,
{ refine h1 _ _,
rw hpm1,
exact measurable_set_generate_from ht, },
rw [measure.restrict_apply ht1, measure.smul_apply, smul_eq_mul, mul_comm],
exact indep_sets.indep_aux h2 hp2 hpm2 hyp ht ht2,
end
end from_pi_systems_to_measurable_spaces
section indep_set
/-! ### Independence of measurable sets
We prove the following equivalences on `indep_set`, for measurable sets `s, t`.
* `indep_set s t μ ↔ μ (s ∩ t) = μ s * μ t`,
* `indep_set s t μ ↔ indep_sets {s} {t} μ`.
-/
variables {α : Type*} [measurable_space α] {s t : set α} (S T : set (set α))
lemma indep_set_iff_indep_sets_singleton (hs_meas : measurable_set s) (ht_meas : measurable_set t)
(μ : measure α . volume_tac) [is_probability_measure μ] :
indep_set s t μ ↔ indep_sets {s} {t} μ :=
⟨indep.indep_sets, λ h, indep_sets.indep
(generate_from_le (λ u hu, by rwa set.mem_singleton_iff.mp hu))
(generate_from_le (λ u hu, by rwa set.mem_singleton_iff.mp hu)) (is_pi_system.singleton s)
(is_pi_system.singleton t) rfl rfl h⟩
lemma indep_set_iff_measure_inter_eq_mul (hs_meas : measurable_set s) (ht_meas : measurable_set t)
(μ : measure α . volume_tac) [is_probability_measure μ] :
indep_set s t μ ↔ μ (s ∩ t) = μ s * μ t :=
(indep_set_iff_indep_sets_singleton hs_meas ht_meas μ).trans indep_sets_singleton_iff
lemma indep_sets.indep_set_of_mem (hs : s ∈ S) (ht : t ∈ T) (hs_meas : measurable_set s)
(ht_meas : measurable_set t) (μ : measure α . volume_tac) [is_probability_measure μ]
(h_indep : indep_sets S T μ) :
indep_set s t μ :=
(indep_set_iff_measure_inter_eq_mul hs_meas ht_meas μ).mpr (h_indep s t hs ht)
end indep_set
section indep_fun
variables {α β β' γ γ' : Type*} {mα : measurable_space α} {μ : measure α}
lemma indep_fun.ae_eq {mβ : measurable_space β} {f g f' g' : α → β}
(hfg : indep_fun f g μ) (hf : f =ᵐ[μ] f') (hg : g =ᵐ[μ] g') :
indep_fun f' g' μ :=
begin
rintro _ _ ⟨A, hA, rfl⟩ ⟨B, hB, rfl⟩,
have h1 : f ⁻¹' A =ᵐ[μ] f' ⁻¹' A := hf.fun_comp A,
have h2 : g ⁻¹' B =ᵐ[μ] g' ⁻¹' B := hg.fun_comp B,
rw [←measure_congr h1, ←measure_congr h2, ←measure_congr (h1.inter h2)],
exact hfg _ _ ⟨_, hA, rfl⟩ ⟨_, hB, rfl⟩
end
lemma indep_fun.comp {mβ : measurable_space β} {mβ' : measurable_space β'}
{mγ : measurable_space γ} {mγ' : measurable_space γ'}
{f : α → β} {g : α → β'} {φ : β → γ} {ψ : β' → γ'}
(hfg : indep_fun f g μ) (hφ : measurable φ) (hψ : measurable ψ) :
indep_fun (φ ∘ f) (ψ ∘ g) μ :=
begin
rintro _ _ ⟨A, hA, rfl⟩ ⟨B, hB, rfl⟩,
apply hfg,
{ exact ⟨φ ⁻¹' A, hφ hA, set.preimage_comp.symm⟩ },
{ exact ⟨ψ ⁻¹' B, hψ hB, set.preimage_comp.symm⟩ }
end
end indep_fun
end probability_theory
|
35209d323989fd054ee8e33c6eb1eaf7e2df5e81 | 572fb32b6f5b7c2bf26921ffa2abea054cce881a | /src/week_1/Part_D_relations.lean | 69c992e29e09c9762fc8c6f1e54091dd15648b01 | [
"Apache-2.0"
] | permissive | kgeorgiy/lean-formalising-mathematics | 2deb30756d5a54bee1cfa64873e86f641c59c7dc | 73429a8ded68f641c896b6ba9342450d4d3ae50f | refs/heads/master | 1,683,029,640,682 | 1,621,403,041,000 | 1,621,403,041,000 | 367,790,347 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,415 | lean | import tactic
/-!
# Equivalence relations are the same as partitions
In this file we prove that there's a bijection between
the equivalence relations on a type, and the partitions of a type.
Three sections:
1) partitions
2) equivalence classes
3) the proof
## Overview
Say `α` is a type, and `R : α → α → Prop` 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 lemmas about partitions. Some
I prove myself (not always using tactics) and some I leave for you.
## 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
Here's the way notation works. If `α` is a type (i.e. a set)
then a term `P` of type `partition α` is a partition of `α`,
that is, a set of disjoint nonempty subsets of `α` whose union is `α`.
The collection of sets underlying `P` is `P.C`, the proof that
they're all nonempty is `P.Hnonempty` and so on.
-/
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 :=
-- Proof: follows immediately from the disjointness hypothesis.
P.Hdisjoint _ _ hX hY ⟨a, haX, haY⟩
/-- 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
rwa ← (eq_of_mem hX hY haX haY),
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 :=
let ⟨X, ⟨hX, haX⟩⟩ := P.Hcover a in ⟨X, ⟨hX, haX⟩⟩
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 mem_cl_iff {a b : α} : b ∈ cl R a ↔ R b a := by refl
-- Assume now that R is an equivalence relation.
variables {R} (hR : equivalence R)
include hR
/-- x is in cl(x) -/
lemma mem_cl_self (a : α) : a ∈ cl R a := hR.1 a
lemma cl_sub_cl_of_mem_cl {a b : α} : a ∈ cl R b → cl R a ⊆ cl R b :=
λ ha c hc, hR.2.2 hc ha -- trans
lemma cl_eq_cl_of_mem_cl {a b : α} : a ∈ cl R b → cl R a = cl R b :=
-- remember `set.subset.antisymm` says `X ⊆ Y → Y ⊆ X → X = Y`
λ ah, set.subset.antisymm
(cl_sub_cl_of_mem_cl hR ah)
(cl_sub_cl_of_mem_cl hR (hR.2.1 ah))
end equivalence_classes -- section
/-!
# 3) The theorem
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,
rintros X ⟨a, rfl⟩,
exact ⟨a, hR.1 a⟩, -- hrefl
end,
Hcover := begin
cases R with R hR,
-- The equivalence classes cover α
show ∀ (a : α), ∃ (X : set α) (H : ∃ (b : α), X = cl R b), a ∈ X,
exact λ a, ⟨cl R a, ⟨⟨a, rfl⟩, hR.1 a⟩⟩,
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 _ b) → (X ∩ Y).nonempty → X = Y,
rintros X Y ⟨x, rfl⟩ ⟨y, rfl⟩ ⟨z, hzX, hzY⟩,
exact cl_eq_cl_of_mem_cl hR (hR.2.2 (hR.2.1 hzX) hzY),
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,
exact λ a X hxP haX, haX
},
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,
intros a b hA X hXP hbX,
obtain ⟨Y, hYP, aY⟩ := P.Hcover a,
rwa (let hbY := hA Y hYP aY in eq_of_mem hXP hYP hbX hbY),
},
{ -- 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,
exact λ a b c hab hbc X hXP haX, hbc X hXP (hab X hXP haX),
}
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,
exact let ⟨hRefl, hSymm, hTrans⟩ := hR in ⟨
λ h, hSymm (h a (hRefl a)),
λ hab c hca, hTrans (hSymm hab) hca,
⟩
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,
split, {
rintro ⟨a, ha⟩,
obtain ⟨Y, hY, aY⟩ := P.Hcover a,
have q : X = Y := begin
subst ha,
ext b,
split, {
intro hb,
simp only [cl, set.mem_set_of_eq] at hb,
obtain ⟨Z, hZ, bZ⟩ := P.Hcover b,
rwa let aZ := hb Z hZ bZ in eq_of_mem hY hZ aY aZ,
}, {
simp only [cl, set.mem_set_of_eq],
intros bY X hX bX,
rwa eq_of_mem hX hY bX bY,
}
end,
rwa q,
}, {
intro hX,
obtain ⟨a, aX⟩ := P.Hnonempty X hX,
use a,
--obtain ⟨Y, hY, bY⟩ := P.Hcover a,
ext b,
simp [cl],
split, {
intros bX Y hY bY,
have q : X = Y := eq_of_mem hX hY bX bY,
rwa ← q,
}, {
intros h,
obtain ⟨Y, hY, bY⟩ := P.Hcover b,
have aY := h Y hY bY,
exact mem_of_mem hY hX aY aX bY,
}
},
end }
|
e2f55e50fcc8a2665f55d18ad00aacd39ef92744 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/ring_theory/dedekind_domain/dvr.lean | 4e4592bbdea2244824bdd77050987f3327ad0ebc | [
"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,444 | lean | /-
Copyright (c) 2020 Kenji Nakagawa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenji Nakagawa, Anne Baanen, Filippo A. E. Nuccio
-/
import ring_theory.localization.localization_localization
import ring_theory.localization.submodule
import ring_theory.discrete_valuation_ring.tfae
/-!
# Dedekind domains
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines an equivalent notion of a Dedekind domain (or Dedekind ring),
namely a Noetherian integral domain where the localization at all nonzero prime ideals is a DVR
(TODO: and shows that implies the main definition).
## Main definitions
- `is_dedekind_domain_dvr` alternatively defines a Dedekind domain as an integral domain that
is Noetherian, and the localization at every nonzero prime ideal is a DVR.
## Main results
- `is_localization.at_prime.discrete_valuation_ring_of_dedekind_domain` shows that
`is_dedekind_domain` implies the localization at each nonzero prime ideal is a DVR.
- `is_dedekind_domain.is_dedekind_domain_dvr` is one direction of the equivalence of definitions
of a Dedekind domain
## Implementation notes
The definitions that involve a field of fractions choose a canonical field of fractions,
but are independent of that choice. The `..._iff` lemmas express this independence.
Often, definitions assume that Dedekind domains are not fields. We found it more practical
to add a `(h : ¬ is_field A)` assumption whenever this is explicitly needed.
## References
* [D. Marcus, *Number Fields*][marcus1977number]
* [J.W.S. Cassels, A. Frölich, *Algebraic Number Theory*][cassels1967algebraic]
* [J. Neukirch, *Algebraic Number Theory*][Neukirch1992]
## Tags
dedekind domain, dedekind ring
-/
variables (R A K : Type*) [comm_ring R] [comm_ring A] [is_domain A] [field K]
open_locale non_zero_divisors polynomial
/--
A Dedekind domain is an integral domain that is Noetherian, and the
localization at every nonzero prime is a discrete valuation ring.
This is equivalent to `is_dedekind_domain`.
TODO: prove the equivalence.
-/
structure is_dedekind_domain_dvr : Prop :=
(is_noetherian_ring : is_noetherian_ring A)
(is_dvr_at_nonzero_prime : ∀ P ≠ (⊥ : ideal A), P.is_prime →
discrete_valuation_ring (localization.at_prime P))
/-- Localizing a domain of Krull dimension `≤ 1` gives another ring of Krull dimension `≤ 1`.
Note that the same proof can/should be generalized to preserving any Krull dimension,
once we have a suitable definition.
-/
lemma ring.dimension_le_one.localization {R : Type*} (Rₘ : Type*) [comm_ring R] [is_domain R]
[comm_ring Rₘ] [algebra R Rₘ] {M : submonoid R} [is_localization M Rₘ] (hM : M ≤ R⁰)
(h : ring.dimension_le_one R) : ring.dimension_le_one Rₘ :=
begin
introsI p hp0 hpp,
refine ideal.is_maximal_def.mpr ⟨hpp.ne_top, ideal.maximal_of_no_maximal (λ P hpP hPm, _)⟩,
have hpP' : (⟨p, hpp⟩ : {p : ideal Rₘ // p.is_prime}) < ⟨P, hPm.is_prime⟩ := hpP,
rw ← (is_localization.order_iso_of_prime M Rₘ).lt_iff_lt at hpP',
haveI : ideal.is_prime (ideal.comap (algebra_map R Rₘ) p) :=
((is_localization.order_iso_of_prime M Rₘ) ⟨p, hpp⟩).2.1,
haveI : ideal.is_prime (ideal.comap (algebra_map R Rₘ) P) :=
((is_localization.order_iso_of_prime M Rₘ) ⟨P, hPm.is_prime⟩).2.1,
have hlt : ideal.comap (algebra_map R Rₘ) p < ideal.comap (algebra_map R Rₘ) P := hpP',
refine h.not_lt_lt ⊥ (ideal.comap _ _) (ideal.comap _ _) ⟨_, hpP'⟩,
exact is_localization.bot_lt_comap_prime _ _ hM _ hp0
end
/-- The localization of a Dedekind domain is a Dedekind domain. -/
lemma is_localization.is_dedekind_domain [is_dedekind_domain A] {M : submonoid A} (hM : M ≤ A⁰)
(Aₘ : Type*) [comm_ring Aₘ] [is_domain Aₘ] [algebra A Aₘ]
[is_localization M Aₘ] : is_dedekind_domain Aₘ :=
begin
have : ∀ (y : M), is_unit (algebra_map A (fraction_ring A) y),
{ rintros ⟨y, hy⟩,
exact is_unit.mk0 _ (mt is_fraction_ring.to_map_eq_zero_iff.mp (non_zero_divisors.ne_zero
(hM hy))) },
letI : algebra Aₘ (fraction_ring A) := ring_hom.to_algebra (is_localization.lift this),
haveI : is_scalar_tower A Aₘ (fraction_ring A) := is_scalar_tower.of_algebra_map_eq
(λ x, (is_localization.lift_eq this x).symm),
haveI : is_fraction_ring Aₘ (fraction_ring A) :=
is_fraction_ring.is_fraction_ring_of_is_domain_of_is_localization M _ _,
refine (is_dedekind_domain_iff _ (fraction_ring A)).mpr ⟨_, _, _⟩,
{ exact is_localization.is_noetherian_ring M _ (by apply_instance) },
{ exact is_dedekind_domain.dimension_le_one.localization Aₘ hM },
{ intros x hx,
obtain ⟨⟨y, y_mem⟩, hy⟩ := hx.exists_multiple_integral_of_is_localization M _,
obtain ⟨z, hz⟩ := (is_integrally_closed_iff _).mp is_dedekind_domain.is_integrally_closed hy,
refine ⟨is_localization.mk' Aₘ z ⟨y, y_mem⟩, (is_localization.lift_mk'_spec _ _ _ _).mpr _⟩,
rw [hz, set_like.coe_mk, ← algebra.smul_def],
refl },
end
/-- The localization of a Dedekind domain at every nonzero prime ideal is a Dedekind domain. -/
lemma is_localization.at_prime.is_dedekind_domain [is_dedekind_domain A]
(P : ideal A) [P.is_prime] (Aₘ : Type*) [comm_ring Aₘ] [is_domain Aₘ] [algebra A Aₘ]
[is_localization.at_prime Aₘ P] : is_dedekind_domain Aₘ :=
is_localization.is_dedekind_domain A P.prime_compl_le_non_zero_divisors Aₘ
lemma is_localization.at_prime.not_is_field
{P : ideal A} (hP : P ≠ ⊥) [pP : P.is_prime]
(Aₘ : Type*) [comm_ring Aₘ] [algebra A Aₘ] [is_localization.at_prime Aₘ P] :
¬ (is_field Aₘ) :=
begin
intro h,
letI := h.to_field,
obtain ⟨x, x_mem, x_ne⟩ := P.ne_bot_iff.mp hP,
exact (local_ring.maximal_ideal.is_maximal _).ne_top (ideal.eq_top_of_is_unit_mem _
((is_localization.at_prime.to_map_mem_maximal_iff Aₘ P _).mpr x_mem)
(is_unit_iff_ne_zero.mpr ((map_ne_zero_iff (algebra_map A Aₘ)
(is_localization.injective Aₘ P.prime_compl_le_non_zero_divisors)).mpr x_ne))),
end
/-- In a Dedekind domain, the localization at every nonzero prime ideal is a DVR. -/
lemma is_localization.at_prime.discrete_valuation_ring_of_dedekind_domain [is_dedekind_domain A]
{P : ideal A} (hP : P ≠ ⊥) [pP : P.is_prime]
(Aₘ : Type*) [comm_ring Aₘ] [is_domain Aₘ] [algebra A Aₘ] [is_localization.at_prime Aₘ P] :
discrete_valuation_ring Aₘ :=
begin
classical,
letI : is_noetherian_ring Aₘ := is_localization.is_noetherian_ring P.prime_compl _
is_dedekind_domain.is_noetherian_ring,
letI : local_ring Aₘ := is_localization.at_prime.local_ring Aₘ P,
have hnf := is_localization.at_prime.not_is_field A hP Aₘ,
exact ((discrete_valuation_ring.tfae Aₘ hnf).out 0 2).mpr
(is_localization.at_prime.is_dedekind_domain A P _)
end
/-- Dedekind domains, in the sense of Noetherian integrally closed domains of Krull dimension ≤ 1,
are also Dedekind domains in the sense of Noetherian domains where the localization at every
nonzero prime ideal is a DVR. -/
theorem is_dedekind_domain.is_dedekind_domain_dvr [is_dedekind_domain A] :
is_dedekind_domain_dvr A :=
{ is_noetherian_ring := is_dedekind_domain.is_noetherian_ring,
is_dvr_at_nonzero_prime := λ P hP pP, by exactI
is_localization.at_prime.discrete_valuation_ring_of_dedekind_domain A hP _ }
|
88b78bfacea85638a5ee1e0025b53b432b183364 | d642a6b1261b2cbe691e53561ac777b924751b63 | /src/topology/uniform_space/complete_separated.lean | 64bb7ddb18d1821b8ab315a1049385e28dc1fcd2 | [
"Apache-2.0"
] | permissive | cipher1024/mathlib | fee56b9954e969721715e45fea8bcb95f9dc03fe | d077887141000fefa5a264e30fa57520e9f03522 | refs/heads/master | 1,651,806,490,504 | 1,573,508,694,000 | 1,573,508,694,000 | 107,216,176 | 0 | 0 | Apache-2.0 | 1,647,363,136,000 | 1,508,213,014,000 | Lean | UTF-8 | Lean | false | false | 1,327 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
Theory of complete separated uniform spaces.
This file is for elementary lemmas that depend on both Cauchy filters and separation.
-/
import topology.uniform_space.cauchy topology.uniform_space.separation
import topology.dense_embedding
open filter
variables {α : Type*}
/-In a separated space, a complete set is closed -/
lemma is_closed_of_is_complete [uniform_space α] [separated α] {s : set α} (h : is_complete s) :
is_closed s :=
is_closed_iff_nhds.2 $ λ a ha, begin
let f := nhds a ⊓ principal s,
have : cauchy f := cauchy_downwards (cauchy_nhds) ha (lattice.inf_le_left),
rcases h f this (lattice.inf_le_right) with ⟨y, ys, fy⟩,
rwa (tendsto_nhds_unique ha lattice.inf_le_left fy : a = y)
end
namespace dense_inducing
open filter
variables [topological_space α] {β : Type*} [topological_space β]
variables {γ : Type*} [uniform_space γ] [complete_space γ] [separated γ]
lemma continuous_extend_of_cauchy {e : α → β} {f : α → γ}
(de : dense_inducing e) (h : ∀ b : β, cauchy (map f (comap e $ nhds b))) :
continuous (de.extend f) :=
de.continuous_extend $ λ b, complete_space.complete (h b)
end dense_inducing
|
fba405ec569245a86f6ba6f66d9bac808269a00b | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/ring_theory/polynomial/tower.lean | d781e40d379b3037d9bea5971756a7e39024d65a | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 2,681 | lean | /-
Copyright (c) 2020 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import algebra.algebra.tower
import data.polynomial.algebra_map
/-!
# Algebra towers for polynomial
This file defines the algebra tower structure for the type `polynomial R`,
and proves some basic results.
-/
universes u v w u₁
variables (R : Type u) (S : Type v) (A : Type w) (B : Type u₁)
namespace is_scalar_tower
section semiring
variables [comm_semiring R] [comm_semiring S] [semiring A] [semiring B]
variables [algebra R S] [algebra S A] [algebra S B] [algebra R A] [algebra R B]
variables [is_scalar_tower R S A] [is_scalar_tower R S B]
variables (R) {S A B}
instance polynomial : is_scalar_tower R S (polynomial A) :=
of_algebra_map_eq $ λ x, congr_arg polynomial.C $ algebra_map_apply R S A x
variables (R S A)
theorem aeval_apply (x : A) (p : polynomial R) : polynomial.aeval x p =
polynomial.aeval x (polynomial.map (algebra_map R S) p) :=
by rw [polynomial.aeval_def, polynomial.aeval_def, polynomial.eval₂_map, algebra_map_eq R S A]
end semiring
section comm_semiring
variables [comm_semiring R] [comm_semiring A] [comm_semiring B]
variables [algebra R A] [algebra A B] [algebra R B] [is_scalar_tower R A B]
lemma algebra_map_aeval (x : A) (p : polynomial R) :
algebra_map A B (polynomial.aeval x p) = polynomial.aeval (algebra_map A B x) p :=
by rw [polynomial.aeval_def, polynomial.aeval_def, polynomial.hom_eval₂,
←is_scalar_tower.algebra_map_eq]
lemma aeval_eq_zero_of_aeval_algebra_map_eq_zero {x : A} {p : polynomial R}
(h : function.injective (algebra_map A B)) (hp : polynomial.aeval (algebra_map A B x) p = 0) :
polynomial.aeval x p = 0 :=
begin
rw [← algebra_map_aeval, ← (algebra_map A B).map_zero] at hp,
exact h hp,
end
lemma aeval_eq_zero_of_aeval_algebra_map_eq_zero_field {R A B : Type*} [comm_semiring R] [field A]
[comm_semiring B] [nontrivial B] [algebra R A] [algebra R B] [algebra A B] [is_scalar_tower R A B]
{x : A} {p : polynomial R} (h : polynomial.aeval (algebra_map A B x) p = 0) :
polynomial.aeval x p = 0 :=
aeval_eq_zero_of_aeval_algebra_map_eq_zero R A B (algebra_map A B).injective h
end comm_semiring
end is_scalar_tower
namespace subalgebra
open is_scalar_tower
section comm_semiring
variables (R) {S A} [comm_semiring R] [comm_semiring S] [comm_semiring A]
variables [algebra R S] [algebra S A] [algebra R A] [is_scalar_tower R S A]
@[simp] lemma aeval_coe {S : subalgebra R A} {x : S} {p : polynomial R} :
polynomial.aeval (x : A) p = polynomial.aeval x p :=
(algebra_map_aeval R S A x p).symm
end comm_semiring
end subalgebra
|
4172c3101a29b68d72462cdbf2255265bc4117f0 | 0845ae2ca02071debcfd4ac24be871236c01784f | /tests/bench/qsort.lean | 69ab3ca9da33ee827584fe438319d3c5205586db | [
"Apache-2.0"
] | permissive | GaloisInc/lean4 | 74c267eb0e900bfaa23df8de86039483ecbd60b7 | 228ddd5fdcd98dd4e9c009f425284e86917938aa | refs/heads/master | 1,643,131,356,301 | 1,562,715,572,000 | 1,562,715,572,000 | 192,390,898 | 0 | 0 | null | 1,560,792,750,000 | 1,560,792,749,000 | null | UTF-8 | Lean | false | false | 2,395 | lean | abbreviation Elem := UInt32
def badRand (seed : Elem) : Elem :=
seed * 1664525 + 1013904223
def mkRandomArray : Nat → Elem → Array Elem → Array Elem
| 0 seed as := as
| (i+1) seed as := mkRandomArray i (badRand seed) (as.push seed)
partial def checkSortedAux (a : Array Elem) : Nat → IO Unit
| i :=
if i < a.size - 1 then do
unless (a.get i <= a.get (i+1)) $ throw (IO.userError "array is not sorted");
checkSortedAux (i+1)
else
pure ()
-- copied from stdlib, but with `UInt32` indices instead of `Nat` (which is more comparable to the other versions)
abbreviation Idx := UInt32
instance : HasLift UInt32 Nat := ⟨UInt32.toNat⟩
prefix `↑`:max := coe
@[specialize] private partial def partitionAux {α : Type} [Inhabited α] (lt : α → α → Bool) (hi : Idx) (pivot : α) : Array α → Idx → Idx → Idx × Array α
| as i j :=
if j < hi then
if lt (as.get ↑j) pivot then
let as := as.swap ↑i ↑j;
partitionAux as (i+1) (j+1)
else
partitionAux as i (j+1)
else
let as := as.swap ↑i ↑hi;
(i, as)
@[inline] def partition {α : Type} [Inhabited α] (as : Array α) (lt : α → α → Bool) (lo hi : Idx) : Idx × Array α :=
let mid := (lo + hi) / 2;
let as := if lt (as.get ↑mid) (as.get ↑lo) then as.swap ↑lo ↑mid else as;
let as := if lt (as.get ↑hi) (as.get ↑lo) then as.swap ↑lo ↑hi else as;
let as := if lt (as.get ↑mid) (as.get ↑hi) then as.swap ↑mid ↑hi else as;
let pivot := as.get ↑hi;
partitionAux lt hi pivot as lo lo
@[specialize] partial def qsortAux {α : Type} [Inhabited α] (lt : α → α → Bool) : Array α → Idx → Idx → Array α
| as low high :=
if low < high then
let p := partition as lt low high;
-- TODO: fix `partial` support in the equation compiler, it breaks if we use `let (mid, as) := partition as lt low high`
let mid := p.1;
let as := p.2;
let as := qsortAux as low mid;
qsortAux as (mid+1) high
else as
@[inline] def qsort {α : Type} [Inhabited α] (as : Array α) (lt : α → α → Bool) : Array α :=
qsortAux lt as 0 (UInt32.ofNat (as.size - 1))
def main (xs : List String) : IO Unit :=
do
let n := xs.head.toNat;
n.mfor $ fun _ =>
n.mfor $ fun i => do
let xs := mkRandomArray i (UInt32.ofNat i) Array.empty;
let xs := qsort xs (fun a b => a < b);
--IO.println xs;
checkSortedAux xs 0
|
ec7194b0b3188d23b17ae19061eb60ed27ffc91a | 8f0ea954c1cc4f4cda83826954d6186c68fc9536 | /hott/homotopy/connectedness.hlean | 975bb3f11a33477893b11a4fd37630b28aba970c | [
"Apache-2.0"
] | permissive | piyush-kurur/lean | fb3cbd339dfa8c70c49559fbea88ac0d3102b8ca | a8db8bc61a0b00379b3d0be8ecaf0d0858dc82ee | refs/heads/master | 1,594,387,140,961 | 1,457,548,608,000 | 1,457,909,538,000 | 53,615,930 | 0 | 0 | null | 1,457,642,939,000 | 1,457,642,939,000 | null | UTF-8 | Lean | false | false | 11,443 | hlean | /-
Copyright (c) 2015 Ulrik Buchholtz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Ulrik Buchholtz, Floris van Doorn
-/
import types.trunc types.arrow_2 .sphere
open eq is_trunc is_equiv nat equiv trunc function fiber funext pi
namespace homotopy
definition is_conn [reducible] (n : ℕ₋₂) (A : Type) : Type :=
is_contr (trunc n A)
definition is_conn_equiv_closed (n : ℕ₋₂) {A B : Type}
: A ≃ B → is_conn n A → is_conn n B :=
begin
intros H C,
fapply @is_contr_equiv_closed (trunc n A) _,
apply trunc_equiv_trunc,
assumption
end
definition is_conn_fun [reducible] (n : ℕ₋₂) {A B : Type} (f : A → B) : Type :=
Πb : B, is_conn n (fiber f b)
theorem is_conn_of_le (A : Type) {n k : ℕ₋₂} (H : n ≤ k) [is_conn k A] : is_conn n A :=
begin
apply is_contr_equiv_closed,
apply trunc_trunc_equiv_left _ n k H
end
theorem is_conn_fun_of_le {A B : Type} (f : A → B) {n k : ℕ₋₂} (H : n ≤ k)
[is_conn_fun k f] : is_conn_fun n f :=
λb, is_conn_of_le _ H
namespace is_conn_fun
section
parameters (n : ℕ₋₂) {A B : Type} {h : A → B}
(H : is_conn_fun n h) (P : B → Type) [Πb, is_trunc n (P b)]
private definition rec.helper : (Πa : A, P (h a)) → Πb : B, trunc n (fiber h b) → P b :=
λt b, trunc.rec (λx, point_eq x ▸ t (point x))
private definition rec.g : (Πa : A, P (h a)) → (Πb : B, P b) :=
λt b, rec.helper t b (@center (trunc n (fiber h b)) (H b))
-- induction principle for n-connected maps (Lemma 7.5.7)
protected definition rec : is_equiv (λs : Πb : B, P b, λa : A, s (h a)) :=
adjointify (λs a, s (h a)) rec.g
begin
intro t, apply eq_of_homotopy, intro a, unfold rec.g, unfold rec.helper,
rewrite [@center_eq _ (H (h a)) (tr (fiber.mk a idp))],
end
begin
intro k, apply eq_of_homotopy, intro b, unfold rec.g,
generalize (@center _ (H b)), apply trunc.rec, apply fiber.rec,
intros a p, induction p, reflexivity
end
protected definition elim : (Πa : A, P (h a)) → (Πb : B, P b) :=
@is_equiv.inv _ _ (λs a, s (h a)) rec
protected definition elim_β : Πf : (Πa : A, P (h a)), Πa : A, elim f (h a) = f a :=
λf, apd10 (@is_equiv.right_inv _ _ (λs a, s (h a)) rec f)
end
section
parameters (n k : ℕ₋₂) {A B : Type} {f : A → B}
(H : is_conn_fun n f) (P : B → Type) [HP : Πb, is_trunc (n +2+ k) (P b)]
include H HP
-- Lemma 8.6.1
proposition elim_general : is_trunc_fun k (pi_functor_left f P) :=
begin
revert P HP,
induction k with k IH: intro P HP t,
{ apply is_contr_fiber_of_is_equiv, apply is_conn_fun.rec, exact H, exact HP},
{ apply is_trunc_succ_intro,
intros x y, cases x with g p, cases y with h q,
have e : fiber (λr : g ~ h, (λa, r (f a))) (apd10 (p ⬝ q⁻¹))
≃ (fiber.mk g p = fiber.mk h q
:> fiber (λs : (Πb, P b), (λa, s (f a))) t),
begin
apply equiv.trans !fiber.sigma_char,
have e' : Πr : g ~ h,
((λa, r (f a)) = apd10 (p ⬝ q⁻¹))
≃ (ap (λv, (λa, v (f a))) (eq_of_homotopy r) ⬝ q = p),
begin
intro r,
refine equiv.trans _ (eq_con_inv_equiv_con_eq q p
(ap (λv a, v (f a)) (eq_of_homotopy r))),
rewrite [-(ap (λv a, v (f a)) (apd10_eq_of_homotopy r))],
rewrite [-(apd10_ap_precompose_dependent f (eq_of_homotopy r))],
apply equiv.symm,
apply eq_equiv_fn_eq (@apd10 A (λa, P (f a)) (λa, g (f a)) (λa, h (f a)))
end,
apply equiv.trans (sigma.sigma_equiv_sigma_right e'), clear e',
apply equiv.trans (equiv.symm (sigma.sigma_equiv_sigma_left
eq_equiv_homotopy)),
apply equiv.symm, apply equiv.trans !fiber_eq_equiv,
apply sigma.sigma_equiv_sigma_right, intro r,
apply eq_equiv_eq_symm
end,
apply @is_trunc_equiv_closed _ _ k e, clear e,
apply IH (λb : B, (g b = h b)) (λb, @is_trunc_eq (P b) (n +2+ k) (HP b) (g b) (h b))}
end
end
section
universe variables u v
parameters (n : ℕ₋₂) {A : Type.{u}} {B : Type.{v}} {h : A → B}
parameter sec : ΠP : B → trunctype.{max u v} n,
is_retraction (λs : (Πb : B, P b), λ a, s (h a))
private definition s := sec (λb, trunctype.mk' n (trunc n (fiber h b)))
include sec
-- the other half of Lemma 7.5.7
definition intro : is_conn_fun n h :=
begin
intro b,
apply is_contr.mk (@is_retraction.sect _ _ _ s (λa, tr (fiber.mk a idp)) b),
esimp, apply trunc.rec, apply fiber.rec, intros a p,
apply transport
(λz : (Σy, h a = y), @sect _ _ _ s (λa, tr (mk a idp)) (sigma.pr1 z) =
tr (fiber.mk a (sigma.pr2 z)))
(@center_eq _ (is_contr_sigma_eq (h a)) (sigma.mk b p)),
exact apd10 (@right_inverse _ _ _ s (λa, tr (fiber.mk a idp))) a
end
end
end is_conn_fun
-- Connectedness is related to maps to and from the unit type, first to
section
parameters (n : ℕ₋₂) (A : Type)
definition is_conn_of_map_to_unit
: is_conn_fun n (const A unit.star) → is_conn n A :=
begin
intro H, unfold is_conn_fun at H,
rewrite [-(ua (fiber.fiber_star_equiv A))],
exact (H unit.star)
end
-- now maps from unit
definition is_conn_of_map_from_unit (a₀ : A) (H : is_conn_fun n (const unit a₀))
: is_conn n .+1 A :=
is_contr.mk (tr a₀)
begin
apply trunc.rec, intro a,
exact trunc.elim (λz : fiber (const unit a₀) a, ap tr (point_eq z))
(@center _ (H a))
end
definition is_conn_fun_from_unit (a₀ : A) [H : is_conn n .+1 A]
: is_conn_fun n (const unit a₀) :=
begin
intro a,
apply is_conn_equiv_closed n (equiv.symm (fiber_const_equiv A a₀ a)),
apply @is_contr_equiv_closed _ _ (tr_eq_tr_equiv n a₀ a),
end
end
-- as special case we get elimination principles for pointed connected types
namespace is_conn
open pointed unit
section
parameters (n : ℕ₋₂) {A : Type*}
[H : is_conn n .+1 A] (P : A → Type) [Πa, is_trunc n (P a)]
include H
protected definition rec : is_equiv (λs : Πa : A, P a, s (Point A)) :=
@is_equiv_compose
(Πa : A, P a) (unit → P (Point A)) (P (Point A))
(λs x, s (Point A)) (λf, f unit.star)
(is_conn_fun.rec n (is_conn_fun_from_unit n A (Point A)) P)
(to_is_equiv (arrow_unit_left (P (Point A))))
protected definition elim : P (Point A) → (Πa : A, P a) :=
@is_equiv.inv _ _ (λs, s (Point A)) rec
protected definition elim_β (p : P (Point A)) : elim p (Point A) = p :=
@is_equiv.right_inv _ _ (λs, s (Point A)) rec p
end
section
parameters (n k : ℕ₋₂) {A : Type*}
[H : is_conn n .+1 A] (P : A → Type) [Πa, is_trunc (n +2+ k) (P a)]
include H
proposition elim_general (p : P (Point A))
: is_trunc k (fiber (λs : (Πa : A, P a), s (Point A)) p) :=
@is_trunc_equiv_closed
(fiber (λs x, s (Point A)) (λx, p))
(fiber (λs, s (Point A)) p)
k
(equiv.symm (fiber.equiv_postcompose (to_fun (arrow_unit_left (P (Point A))))))
(is_conn_fun.elim_general n k (is_conn_fun_from_unit n A (Point A)) P (λx, p))
end
end is_conn
-- Lemma 7.5.2
definition minus_one_conn_of_surjective {A B : Type} (f : A → B)
: is_surjective f → is_conn_fun -1 f :=
begin
intro H, intro b,
exact @is_contr_of_inhabited_prop (∥fiber f b∥) (is_trunc_trunc -1 (fiber f b)) (H b),
end
definition is_surjection_of_minus_one_conn {A B : Type} (f : A → B)
: is_conn_fun -1 f → is_surjective f :=
begin
intro H, intro b,
exact @center (∥fiber f b∥) (H b),
end
definition merely_of_minus_one_conn {A : Type} : is_conn -1 A → ∥A∥ :=
λH, @center (∥A∥) H
definition minus_one_conn_of_merely {A : Type} : ∥A∥ → is_conn -1 A :=
@is_contr_of_inhabited_prop (∥A∥) (is_trunc_trunc -1 A)
section
open arrow
variables {f g : arrow}
-- Lemma 7.5.4
definition retract_of_conn_is_conn [instance] (r : arrow_hom f g) [H : is_retraction r]
(n : ℕ₋₂) [K : is_conn_fun n f] : is_conn_fun n g :=
begin
intro b, unfold is_conn,
apply is_contr_retract (trunc_functor n (retraction_on_fiber r b)),
exact K (on_cod (arrow.is_retraction.sect r) b)
end
end
-- Corollary 7.5.5
definition is_conn_homotopy (n : ℕ₋₂) {A B : Type} {f g : A → B}
(p : f ~ g) (H : is_conn_fun n f) : is_conn_fun n g :=
@retract_of_conn_is_conn _ _ (arrow.arrow_hom_of_homotopy p) (arrow.is_retraction_arrow_hom_of_homotopy p) n H
-- all types are -2-connected
definition is_conn_minus_two (A : Type) : is_conn -2 A :=
_
-- Theorem 8.2.1
open susp
theorem is_conn_susp [instance] (n : ℕ₋₂) (A : Type)
[H : is_conn n A] : is_conn (n .+1) (susp A) :=
is_contr.mk (tr north)
begin
apply trunc.rec,
fapply susp.rec,
{ reflexivity },
{ exact (trunc.rec (λa, ap tr (merid a)) (center (trunc n A))) },
{ intro a,
generalize (center (trunc n A)),
apply trunc.rec,
intro a',
apply pathover_of_tr_eq,
rewrite [transport_eq_Fr,idp_con],
revert H, induction n with [n, IH],
{ intro H, apply is_prop.elim },
{ intros H,
change ap (@tr n .+2 (susp A)) (merid a) = ap tr (merid a'),
generalize a',
apply is_conn_fun.elim n
(is_conn_fun_from_unit n A a)
(λx : A, trunctype.mk' n (ap (@tr n .+2 (susp A)) (merid a) = ap tr (merid x))),
intros,
change ap (@tr n .+2 (susp A)) (merid a) = ap tr (merid a),
reflexivity
}
}
end
-- Lemma 7.5.14
theorem is_equiv_trunc_functor_of_is_conn_fun {A B : Type} (n : ℕ₋₂) (f : A → B)
[H : is_conn_fun n f] : is_equiv (trunc_functor n f) :=
begin
fapply adjointify,
{ intro b, induction b with b, exact trunc_functor n point (center (trunc n (fiber f b)))},
{ intro b, induction b with b, esimp, generalize center (trunc n (fiber f b)), intro v,
induction v with v, induction v with a p, esimp, exact ap tr p},
{ intro a, induction a with a, esimp, rewrite [center_eq (tr (fiber.mk a idp))]}
end
theorem trunc_equiv_trunc_of_is_conn_fun {A B : Type} (n : ℕ₋₂) (f : A → B)
[H : is_conn_fun n f] : trunc n A ≃ trunc n B :=
equiv.mk (trunc_functor n f) (is_equiv_trunc_functor_of_is_conn_fun n f)
open trunc_index pointed sphere.ops
-- Corollary 8.2.2
theorem is_conn_sphere [instance] (n : ℕ₋₁) : is_conn (n..-1) (S n) :=
begin
induction n with n IH,
{ apply is_conn_minus_two},
{ rewrite [succ_sub_one, sphere.sphere_succ], apply is_conn_susp}
end
section
open sphere_index
theorem is_conn_psphere [instance] (n : ℕ) : is_conn (n.-1) (S. n) :=
transport (λx, is_conn x (sphere n)) (of_nat_sub_one n) (is_conn_sphere n)
end
end homotopy
|
fd8db7d4a5ea4710c606d49acb7f2928bb7142f5 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/data/mv_polynomial/equiv.lean | 2ec5e18d0e10c5a6680ea3383cc480d809b8ea07 | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 10,162 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Johan Commelin, Mario Carneiro
-/
import data.mv_polynomial.rename
import data.equiv.fin
/-!
# Equivalences between polynomial rings
This file establishes a number of equivalences between polynomial rings,
based on equivalences between the underlying types.
## Notation
As in other polynomial files, we typically use the notation:
+ `σ : Type*` (indexing the variables)
+ `R : Type*` `[comm_semiring R]` (the coefficients)
+ `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set.
This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s`
+ `a : R`
+ `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians
+ `p : mv_polynomial σ R`
## Tags
equivalence, isomorphism, morphism, ring hom, hom
-/
noncomputable theory
open_locale classical big_operators
open set function finsupp add_monoid_algebra
universes u v w x
variables {R : Type u} {S₁ : Type v} {S₂ : Type w} {S₃ : Type x}
namespace mv_polynomial
variables {σ : Type*} {a a' a₁ a₂ : R} {e : ℕ} {n m : σ} {s : σ →₀ ℕ}
section equiv
variables (R) [comm_semiring R]
/-- The ring isomorphism between multivariable polynomials in no variables and the ground ring. -/
@[simps]
def pempty_ring_equiv : mv_polynomial pempty R ≃+* R :=
{ to_fun := mv_polynomial.eval₂ (ring_hom.id _) $ pempty.elim,
inv_fun := C,
left_inv := is_id (C.comp (eval₂_hom (ring_hom.id _) pempty.elim))
(assume a : R, by { dsimp, rw [eval₂_C], refl }) (assume a, a.elim),
right_inv := λ r, eval₂_C _ _ _,
map_mul' := λ _ _, eval₂_mul _ _,
map_add' := λ _ _, eval₂_add _ _ }
/--
The ring isomorphism between multivariable polynomials in a single variable and
polynomials over the ground ring.
-/
@[simps]
def punit_ring_equiv : mv_polynomial punit R ≃+* polynomial R :=
{ to_fun := eval₂ polynomial.C (λu:punit, polynomial.X),
inv_fun := polynomial.eval₂ mv_polynomial.C (X punit.star),
left_inv :=
begin
let f : polynomial R →+* mv_polynomial punit R :=
ring_hom.of (polynomial.eval₂ mv_polynomial.C (X punit.star)),
let g : mv_polynomial punit R →+* polynomial R :=
ring_hom.of (eval₂ polynomial.C (λu:punit, polynomial.X)),
show ∀ p, f.comp g p = p,
apply is_id,
{ assume a, dsimp, rw [eval₂_C, polynomial.eval₂_C] },
{ rintros ⟨⟩, dsimp, 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]),
map_mul' := λ _ _, eval₂_mul _ _,
map_add' := λ _ _, eval₂_add _ _ }
/-- The ring isomorphism between multivariable polynomials induced by an equivalence of the variables. -/
@[simps]
def ring_equiv_of_equiv (e : S₁ ≃ S₂) : mv_polynomial S₁ R ≃+* mv_polynomial S₂ R :=
{ 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,
map_mul' := (rename e).map_mul,
map_add' := (rename e).map_add }
/-- The ring isomorphism between multivariable polynomials induced by a ring isomorphism of the ground ring. -/
@[simps]
def ring_equiv_congr [comm_semiring S₂] (e : R ≃+* S₂) : mv_polynomial S₁ R ≃+* mv_polynomial S₁ S₂ :=
{ to_fun := map (e : R →+* S₂),
inv_fun := map (e.symm : S₂ →+* R),
left_inv := assume p,
have (e.symm : S₂ →+* R).comp (e : R →+* S₂) = ring_hom.id _,
{ ext a, exact e.symm_apply_apply a },
by simp only [map_map, this, map_id],
right_inv := assume p,
have (e : R →+* S₂).comp (e.symm : S₂ →+* R) = ring_hom.id _,
{ ext a, exact e.apply_symm_apply a },
by simp only [map_map, this, map_id],
map_mul' := ring_hom.map_mul _,
map_add' := ring_hom.map_add _ }
section
variables (S₁ S₂ S₃)
/--
The function from multivariable polynomials in a sum of two types,
to multivariable polynomials in one of the types,
with coefficents in multivariable polynomials in the other type.
See `sum_ring_equiv` for the ring isomorphism.
-/
def sum_to_iter : mv_polynomial (S₁ ⊕ S₂) R →+* mv_polynomial S₁ (mv_polynomial S₂ R) :=
eval₂_hom (C.comp C) (λbc, sum.rec_on bc X (C ∘ X))
instance is_semiring_hom_sum_to_iter : is_semiring_hom (sum_to_iter R S₁ S₂) :=
eval₂.is_semiring_hom _ _
@[simp]
lemma sum_to_iter_C (a : R) : sum_to_iter R S₁ S₂ (C a) = C (C a) :=
eval₂_C _ _ a
@[simp]
lemma sum_to_iter_Xl (b : S₁) : sum_to_iter R S₁ S₂ (X (sum.inl b)) = X b :=
eval₂_X _ _ (sum.inl b)
@[simp]
lemma sum_to_iter_Xr (c : S₂) : sum_to_iter R S₁ S₂ (X (sum.inr c)) = C (X c) :=
eval₂_X _ _ (sum.inr c)
/--
The function from multivariable polynomials in one type,
with coefficents in multivariable polynomials in another type,
to multivariable polynomials in the sum of the two types.
See `sum_ring_equiv` for the ring isomorphism.
-/
def iter_to_sum : mv_polynomial S₁ (mv_polynomial S₂ R) →+* mv_polynomial (S₁ ⊕ S₂) R :=
eval₂_hom (ring_hom.of (eval₂ C (X ∘ sum.inr))) (X ∘ sum.inl)
lemma iter_to_sum_C_C (a : R) : iter_to_sum R S₁ S₂ (C (C a)) = C a :=
eq.trans (eval₂_C _ _ (C a)) (eval₂_C _ _ _)
lemma iter_to_sum_X (b : S₁) : iter_to_sum R S₁ S₂ (X b) = X (sum.inl b) :=
eval₂_X _ _ _
lemma iter_to_sum_C_X (c : S₂) : iter_to_sum R S₁ S₂ (C (X c)) = X (sum.inr c) :=
eq.trans (eval₂_C _ _ (X c)) (eval₂_X _ _ _)
/-- A helper function for `sum_ring_equiv`. -/
@[simps]
def mv_polynomial_equiv_mv_polynomial [comm_semiring S₃]
(f : mv_polynomial S₁ R →+* mv_polynomial S₂ S₃)
(g : mv_polynomial S₂ S₃ →+* mv_polynomial S₁ R)
(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 S₁ R ≃+* mv_polynomial S₂ S₃ :=
{ to_fun := f, inv_fun := g,
left_inv := is_id (ring_hom.comp _ _) hgfC hgfX,
right_inv := is_id (ring_hom.comp _ _) hfgC hfgX,
map_mul' := f.map_mul,
map_add' := f.map_add }
/--
The ring isomorphism between multivariable polynomials in a sum of two types,
and multivariable polynomials in one of the types,
with coefficents in multivariable polynomials in the other type.
-/
def sum_ring_equiv : mv_polynomial (S₁ ⊕ S₂) R ≃+* mv_polynomial S₁ (mv_polynomial S₂ R) :=
begin
apply @mv_polynomial_equiv_mv_polynomial R (S₁ ⊕ S₂) _ _ _ _
(sum_to_iter R S₁ S₂) (iter_to_sum R S₁ S₂),
{ assume p,
convert hom_eq_hom ((sum_to_iter R S₁ S₂).comp ((iter_to_sum R S₁ S₂).comp C)) C _ _ p,
{ assume a, dsimp, rw [iter_to_sum_C_C R S₁ S₂, sum_to_iter_C R S₁ S₂] },
{ assume c, dsimp, rw [iter_to_sum_C_X R S₁ S₂, sum_to_iter_Xr R S₁ S₂] } },
{ assume b, rw [iter_to_sum_X R S₁ S₂, sum_to_iter_Xl R S₁ S₂] },
{ assume a, rw [sum_to_iter_C R S₁ S₂, iter_to_sum_C_C R S₁ S₂] },
{ 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] } },
end
/--
The ring isomorphism between multivariable polynomials in `option S₁` and
polynomials with coefficients in `mv_polynomial S₁ R`.
-/
def option_equiv_left : mv_polynomial (option S₁) R ≃+* polynomial (mv_polynomial S₁ R) :=
(ring_equiv_of_equiv R $ (equiv.option_equiv_sum_punit.{0} S₁).trans (equiv.sum_comm _ _)).trans $
(sum_ring_equiv R _ _).trans $
punit_ring_equiv _
/--
The ring isomorphism between multivariable polynomials in `option S₁` and
multivariable polynomials with coefficients in polynomials.
-/
def option_equiv_right : mv_polynomial (option S₁) R ≃+* mv_polynomial S₁ (polynomial R) :=
(ring_equiv_of_equiv R $ equiv.option_equiv_sum_punit.{0} S₁).trans $
(sum_ring_equiv R S₁ unit).trans $
ring_equiv_congr (mv_polynomial unit R) (punit_ring_equiv R)
/--
The ring isomorphism between multivariable polynomials in `fin (n + 1)` and
polynomials over multivariable polynomials in `fin n`.
-/
def fin_succ_equiv (n : ℕ) :
mv_polynomial (fin (n + 1)) R ≃+* polynomial (mv_polynomial (fin n) R) :=
(ring_equiv_of_equiv R (fin_succ_equiv n)).trans
(option_equiv_left R (fin n))
lemma fin_succ_equiv_eq (n : ℕ) :
(fin_succ_equiv R n : mv_polynomial (fin (n + 1)) R →+* polynomial (mv_polynomial (fin n) R)) =
eval₂_hom (polynomial.C.comp (C : R →+* mv_polynomial (fin n) R))
(λ i : fin (n+1), fin.cases polynomial.X (λ k, polynomial.C (X k)) i) :=
begin
apply ring_hom_ext,
{ intro r,
dsimp [ring_equiv.coe_ring_hom, fin_succ_equiv, option_equiv_left, sum_ring_equiv],
simp only [sum_to_iter_C, eval₂_C, rename_C, ring_hom.coe_comp] },
{ intro i,
dsimp [ring_equiv.coe_ring_hom, fin_succ_equiv, option_equiv_left, sum_ring_equiv, _root_.fin_succ_equiv],
by_cases hi : i = 0,
{ simp only [hi, fin.cases_zero, sum.swap, rename_X, equiv.option_equiv_sum_punit_none,
equiv.sum_comm_apply, comp_app, sum_to_iter_Xl, eval₂_X] },
{ rw [← fin.succ_pred i hi],
simp only [rename_X, equiv.sum_comm_apply, comp_app, eval₂_X,
equiv.option_equiv_sum_punit_some, sum.swap, fin.cases_succ, sum_to_iter_Xr, eval₂_C] } }
end
@[simp] lemma fin_succ_equiv_apply (n : ℕ) (p : mv_polynomial (fin (n + 1)) R) :
fin_succ_equiv R n p =
eval₂_hom (polynomial.C.comp (C : R →+* mv_polynomial (fin n) R))
(λ i : fin (n+1), fin.cases polynomial.X (λ k, polynomial.C (X k)) i) p :=
by { rw ← fin_succ_equiv_eq, refl }
end
end equiv
end mv_polynomial
|
e7d5398e21dc1b0d5f0bf875b14a21b69a11555f | 6ae186a0c6ab366b39397ec9250541c9d5aeb023 | /src/category_theory/currying.lean | a7425040a16755cf173a0efdc8f08a0ad74ddf80 | [] | no_license | ThanhPhamPhuong/lean-category-theory | 0d5c4fe1137866b4fe29ec2753d99aa0d0667881 | 968a29fe7c0b20e10d8a27e120aca8ddc184e1ea | refs/heads/master | 1,587,206,682,489 | 1,544,045,056,000 | 1,544,045,056,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,864 | lean | -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison
import category_theory.products.bifunctors
import category_theory.equivalence
-- FIXME why do we need this here?
-- @[obviously] meta def obviously_2 := tactic.tidy { tactics := extended_tidy_tactics }
namespace category_theory
universes u₁ v₁ u₂ v₂ u₃ v₃
variables {C : Type u₁} [𝒞 : category.{u₁ v₁} C] {D : Type u₂} [𝒟 : category.{u₂ v₂} D] {E : Type u₃} [ℰ : category.{u₃ v₃} E]
include 𝒞 𝒟 ℰ
def uncurry : (C ⥤ (D ⥤ E)) ⥤ ((C × D) ⥤ E) :=
{ obj := λ F, { obj := λ X, (F.obj X.1).obj X.2,
map := λ X Y f, ((F.map f.1).app X.2) ≫ ((F.obj Y.1).map f.2) },
map := λ F G T, { app := λ X, (T.app X.1).app X.2 } }.
def curry : ((C × D) ⥤ E) ⥤ (C ⥤ (D ⥤ E)) :=
{ obj := λ F, { obj := λ X, { obj := λ Y, F.obj (X, Y),
map := λ Y Y' g, F.map (𝟙 X, g) },
map := λ X X' f, { app := λ Y, F.map (f, 𝟙 Y) } },
map := λ F G T, { app := λ X, { app := λ Y, T.app (X, Y) } } }.
@[simp] lemma uncurry.obj_map {F : C ⥤ (D ⥤ E)} {X Y : C × D} {f : X ⟶ Y} : (uncurry.obj F).map f = ((F.map f.1).app X.2) ≫ ((F.obj Y.1).map f.2) := rfl
@[simp] lemma curry.obj_obj_map {F : (C × D) ⥤ E} {X : C} {Y Y' : D} {g : Y ⟶ Y'} : ((curry.obj F).obj X).map g = F.map (𝟙 X, g) := rfl
@[simp] lemma curry.obj_map_app {F : (C × D) ⥤ E} {X X' : C} {f : X ⟶ X'} {Y} : ((curry.obj F).map f).app Y = F.map (f, 𝟙 Y) := rfl
-- local attribute [back] category.id -- this is usually a bad idea, but just what we needed here
-- def currying : equivalence (C ⥤ (D ⥤ E)) ((C × D) ⥤ E) :=
-- { functor := uncurry,
-- inverse := curry }
end category_theory |
787f616f72cca14cdde50771e884d316ac0e3086 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/770.lean | 7c7b41a87cba9cf91a83750a0d29d64625a22a80 | [
"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 | 86 | lean | def u (x : Nat) : Nat := do
let y := x + x
y * (if y > 100 then 1 else (5 : Nat))
|
d8b6b8f95875fdd0a3b6a742abaa121dcb012aa2 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/hott/noc.hlean | 50eaa5fa9dc9f74eca46a59e97038d8f3e96b647 | [
"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 | 446 | hlean | set_option pp.beta true
structure foo :=
mk :: (A : Type) (B : A → Type) (a : A) (b : B a)
namespace foo
definition foo.inj₁
{A₁ : Type} {B₁ : A₁ → Type} {a₁ : A₁} {b₁ : B₁ a₁}
{A₂ : Type} {B₂ : A₂ → Type} {a₂ : A₂} {b₂ : B₂ a₂}
(H : foo.mk A₁ B₁ a₁ b₁ = foo.mk A₂ B₂ a₂ b₂)
: A₁ = A₂
:= lift.down (foo.no_confusion H (λ e₁ e₂ e₃ e₄, e₁))
end foo
|
f7e42914b23759fa6044ad1cae7e8a01408f13b0 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/algebra/group_with_zero/defs_auto.lean | cab0827dab4644503f23b3c5a499589d6d565fe6 | [] | 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,445 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.group.defs
import Mathlib.logic.nontrivial
import Mathlib.PostPort
universes u_4 l u_1 u
namespace Mathlib
/-!
# Typeclasses for groups with an adjoined zero element
This file provides just the typeclass definitions, and the projection lemmas that expose their
members.
## Main definitions
* `group_with_zero`
* `comm_group_with_zero`
-/
-- We have to fix the universe of `G₀` here, since the default argument to
-- `group_with_zero.div'` cannot contain a universe metavariable.
/-- Typeclass for expressing that a type `M₀` with multiplication and a zero satisfies
`0 * a = 0` and `a * 0 = 0` for all `a : M₀`. -/
class mul_zero_class (M₀ : Type u_4) extends Mul M₀, HasZero M₀ where
zero_mul : ∀ (a : M₀), 0 * a = 0
mul_zero : ∀ (a : M₀), a * 0 = 0
@[simp] theorem zero_mul {M₀ : Type u_1} [mul_zero_class M₀] (a : M₀) : 0 * a = 0 :=
mul_zero_class.zero_mul a
@[simp] theorem mul_zero {M₀ : Type u_1} [mul_zero_class M₀] (a : M₀) : a * 0 = 0 :=
mul_zero_class.mul_zero a
/-- Predicate typeclass for expressing that `a * b = 0` implies `a = 0` or `b = 0`
for all `a` and `b` of type `G₀`. -/
class no_zero_divisors (M₀ : Type u_4) [Mul M₀] [HasZero M₀] where
eq_zero_or_eq_zero_of_mul_eq_zero : ∀ {a b : M₀}, a * b = 0 → a = 0 ∨ b = 0
/-- A type `M` is a “monoid with zero” if it is a monoid with zero element, and `0` is left
and right absorbing. -/
class monoid_with_zero (M₀ : Type u_4) extends mul_zero_class M₀, monoid M₀ where
/-- A type `M` is a `cancel_monoid_with_zero` if it is a monoid with zero element, `0` is left
and right absorbing, and left/right multiplication by a non-zero element is injective. -/
class cancel_monoid_with_zero (M₀ : Type u_4) extends monoid_with_zero M₀ where
mul_left_cancel_of_ne_zero : ∀ {a b c : M₀}, a ≠ 0 → a * b = a * c → b = c
mul_right_cancel_of_ne_zero : ∀ {a b c : M₀}, b ≠ 0 → a * b = c * b → a = c
theorem mul_left_cancel' {M₀ : Type u_1} [cancel_monoid_with_zero M₀] {a : M₀} {b : M₀} {c : M₀}
(ha : a ≠ 0) (h : a * b = a * c) : b = c :=
cancel_monoid_with_zero.mul_left_cancel_of_ne_zero ha h
theorem mul_right_cancel' {M₀ : Type u_1} [cancel_monoid_with_zero M₀] {a : M₀} {b : M₀} {c : M₀}
(hb : b ≠ 0) (h : a * b = c * b) : a = c :=
cancel_monoid_with_zero.mul_right_cancel_of_ne_zero hb h
/-- A type `M` is a commutative “monoid with zero” if it is a commutative monoid with zero
element, and `0` is left and right absorbing. -/
class comm_monoid_with_zero (M₀ : Type u_4) extends comm_monoid M₀, monoid_with_zero M₀ where
/-- A type `M` is a `comm_cancel_monoid_with_zero` if it is a commutative monoid with zero element,
`0` is left and right absorbing,
and left/right multiplication by a non-zero element is injective. -/
class comm_cancel_monoid_with_zero (M₀ : Type u_4)
extends comm_monoid_with_zero M₀, cancel_monoid_with_zero M₀ where
/-- A type `G₀` is a “group with zero” if it is a monoid with zero element (distinct from `1`)
such that every nonzero element is invertible.
The type is required to come with an “inverse” function, and the inverse of `0` must be `0`.
Examples include division rings and the ordered monoids that are the
target of valuations in general valuation theory.-/
class group_with_zero (G₀ : Type u) extends div_inv_monoid G₀, nontrivial G₀, monoid_with_zero G₀
where
inv_zero : 0⁻¹ = 0
mul_inv_cancel : ∀ (a : G₀), a ≠ 0 → a * (a⁻¹) = 1
@[simp] theorem inv_zero {G₀ : Type u} [group_with_zero G₀] : 0⁻¹ = 0 := group_with_zero.inv_zero
@[simp] theorem mul_inv_cancel {G₀ : Type u} [group_with_zero G₀] {a : G₀} (h : a ≠ 0) :
a * (a⁻¹) = 1 :=
group_with_zero.mul_inv_cancel a h
/-- A type `G₀` is a commutative “group with zero”
if it is a commutative monoid with zero element (distinct from `1`)
such that every nonzero element is invertible.
The type is required to come with an “inverse” function, and the inverse of `0` must be `0`. -/
class comm_group_with_zero (G₀ : Type u_4) extends comm_monoid_with_zero G₀, group_with_zero G₀
where
end Mathlib |
b52e0c8437fef09f83da04f509634cc35c9ad440 | d0f9af2b0ace5ce352570d61b09019c8ef4a3b96 | /hw3/dm_prod_test.lean | 4e47f07fdaf540e087138338e40d19ee8652d8a1 | [] | no_license | jngo13/Discrete-Mathematics | 8671540ef2da7c75915d32332dd20c02f001474e | bf674a866e61f60e6e6d128df85fa73819091787 | refs/heads/master | 1,675,615,657,924 | 1,609,142,011,000 | 1,609,142,011,000 | 267,190,341 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,229 | lean | -- Justin Ngo
-- jmn4fms
-- 2/3/20
-- Sullivan 2102-001
/-Then, in a second file called dm_prod_test.lean,
write test cases for your implementation. You
will have to import your dm_prod.lean file into
this test file so that it has access to your
dm_prod definitions.
Your test cases should include (1) the definitions
of three ordered pairs, p1, p2, and p3, with elements
types of ℕ and ℕ, ℕ and bool, and bool and bool,
respectively; (2) the use of #eval or #reduce to
confirm that your functions operate as expected,
at least for these test cases.
-/
import .dm_prod
def p1 := dm_prod.mk 5 3
def p2 := dm_prod.mk 4 tt
def p3 := dm_prod.mk tt ff
#reduce fst p1
#reduce fst p2
#reduce fst p3
#reduce snd p1
#reduce snd p2
#reduce snd p3
#reduce set_fst p1 6
#reduce set_fst p2 5
#reduce set_fst p3 ff
#reduce set_snd p1
#reduce set_snd p2
#reduce set_snd p3
#reduce swap p1
#reduce swap p2
#reduce swap p3
-- C-style
def fst' {S T: Type} (p : dm_prod S T):=
match p with
|(dm_prod.mk x _) := x
end
def snd' {S T: Type} (p : dm_prod S T):=
match p with
|(dm_prod.mk _ y) := y
end
def set_fst' {S T : Type} (p: dm_prod S T) (s : S):=
match p with
|dm_prod.mk x y := dm_prod.mk s y
end
def set_snd' {S T : Type} (p: dm_prod S T) (t : T) :=
match p with
|dm_prod.mk x y := dm_prod.mk x t
end
def swap' {S T: Type} (p: dm_prod S T):=
match p with
|dm_prod.mk x y := dm_prod.mk y x
end
-- By case
def fst'' {S T: Type}: (dm_prod S T) → S
|(dm_prod.mk x _) := x
def snd'' {S T: Type}: (dm_prod S T) → T
|(dm_prod.mk _ y) := y
def set_fst'' {S T : Type} : (dm_prod S T) → S → dm_prod S T
|(dm_prod.mk x y) (s:S) := dm_prod.mk s y
def set_snd'' {S T : Type}: (dm_prod S T) → T → dm_prod S T
|(dm_prod.mk x y) (t:T) := dm_prod.mk x t
def swap'' {S T: Type}: (dm_prod S T) → dm_prod T S
|(dm_prod.mk x y) := dm_prod.mk y x
#reduce fst'' p1
#reduce fst'' p2
#reduce fst'' p3
#reduce snd'' p1
#reduce snd'' p2
#reduce snd'' p3
#reduce set_fst'' p1 6
#reduce set_fst'' p2 5
#reduce set_fst'' p3 ff
#reduce set_snd'' p1 4
#reduce set_snd'' p2 ff
#reduce set_snd'' p3 tt
#reduce swap'' p1
#reduce swap'' p2
#reduce swap'' p3 |
e6d9eb5e8c4cd9c8728dc59c9ae02f70feaba116 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/dynamics/omega_limit.lean | 8a9c50a52a212bcd8e361791e46cf91ba1cd6a69 | [
"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 | 16,560 | lean | /-
Copyright (c) 2020 Jean Lo. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jean Lo
-/
import dynamics.flow
/-!
# ω-limits
For a function `ϕ : τ → α → β` where `β` is a topological space, we
define the ω-limit under `ϕ` of a set `s` in `α` with respect to
filter `f` on `τ`: an element `y : β` is in the ω-limit of `s` if the
forward images of `s` intersect arbitrarily small neighbourhoods of
`y` frequently "in the direction of `f`".
In practice `ϕ` is often a continuous monoid-act, but the definition
requires only that `ϕ` has a coercion to the appropriate function
type. In the case where `τ` is `ℕ` or `ℝ` and `f` is `at_top`, we
recover the usual definition of the ω-limit set as the set of all `y`
such that there exist sequences `(tₙ)`, `(xₙ)` such that `ϕ tₙ xₙ ⟶ y`
as `n ⟶ ∞`.
## Notations
The `omega_limit` locale provides the localised notation `ω` for
`omega_limit`, as well as `ω⁺` and `ω⁻` for `omega_limit at_top` and
`omega_limit at_bot` respectively for when the acting monoid is
endowed with an order.
-/
open set function filter
open_locale topological_space
/-!
### Definition and notation
-/
section omega_limit
variables {τ : Type*} {α : Type*} {β : Type*} {ι : Type*}
/-- The ω-limit of a set `s` under `ϕ` with respect to a filter `f` is
⋂ u ∈ f, cl (ϕ u s). -/
def omega_limit [topological_space β] (f : filter τ) (ϕ : τ → α → β) (s : set α) : set β :=
⋂ u ∈ f, closure (image2 ϕ u s)
localized "notation `ω` := omega_limit" in omega_limit
localized "notation `ω⁺` := omega_limit filter.at_top" in omega_limit
localized "notation `ω⁻` := omega_limit filter.at_bot" in omega_limit
variables [topological_space β]
variables (f : filter τ) (ϕ : τ → α → β) (s s₁ s₂: set α)
/-!
### Elementary properties
-/
lemma omega_limit_def : ω f ϕ s = ⋂ u ∈ f, closure (image2 ϕ u s) := rfl
lemma omega_limit_subset_of_tendsto {m : τ → τ} {f₁ f₂ : filter τ} (hf : tendsto m f₁ f₂) :
ω f₁ (λ t x, ϕ (m t) x) s ⊆ ω f₂ ϕ s :=
begin
refine Inter₂_mono' (λ u hu, ⟨m ⁻¹' u, tendsto_def.mp hf _ hu, _⟩),
rw ←image2_image_left,
exact closure_mono (image2_subset (image_preimage_subset _ _) subset.rfl),
end
lemma omega_limit_mono_left {f₁ f₂ : filter τ} (hf : f₁ ≤ f₂) : ω f₁ ϕ s ⊆ ω f₂ ϕ s :=
omega_limit_subset_of_tendsto ϕ s (tendsto_id' hf)
lemma omega_limit_mono_right {s₁ s₂ : set α} (hs : s₁ ⊆ s₂) : ω f ϕ s₁ ⊆ ω f ϕ s₂ :=
Inter₂_mono $ λ u hu, closure_mono (image2_subset subset.rfl hs)
lemma is_closed_omega_limit : is_closed (ω f ϕ s) :=
is_closed_Inter $ λ u, is_closed_Inter $ λ hu, is_closed_closure
lemma maps_to_omega_limit' {α' β' : Type*} [topological_space β'] {f : filter τ} {ϕ : τ → α → β}
{ϕ' : τ → α' → β'} {ga : α → α'} {s' : set α'} (hs : maps_to ga s s')
{gb : β → β'} (hg : ∀ᶠ t in f, eq_on (gb ∘ (ϕ t)) (ϕ' t ∘ ga) s)
(hgc : continuous gb) :
maps_to gb (ω f ϕ s) (ω f ϕ' s') :=
begin
simp only [omega_limit_def, mem_Inter, maps_to],
intros y hy u hu,
refine map_mem_closure hgc (hy _ (inter_mem hu hg)) (forall_image2_iff.2 $ λ t ht x hx, _),
calc gb (ϕ t x) = ϕ' t (ga x) : ht.2 hx
... ∈ image2 ϕ' u s' : mem_image2_of_mem ht.1 (hs hx)
end
lemma maps_to_omega_limit {α' β' : Type*} [topological_space β'] {f : filter τ} {ϕ : τ → α → β}
{ϕ' : τ → α' → β'} {ga : α → α'} {s' : set α'} (hs : maps_to ga s s')
{gb : β → β'} (hg : ∀ t x, gb (ϕ t x) = ϕ' t (ga x))
(hgc : continuous gb) :
maps_to gb (ω f ϕ s) (ω f ϕ' s') :=
maps_to_omega_limit' _ hs (eventually_of_forall $ λ t x hx, hg t x) hgc
lemma omega_limit_image_eq {α' : Type*} (ϕ : τ → α' → β) (f : filter τ) (g : α → α') :
ω f ϕ (g '' s) = ω f (λ t x, ϕ t (g x)) s :=
by simp only [omega_limit, image2_image_right]
lemma omega_limit_preimage_subset {α' : Type*} (ϕ : τ → α' → β) (s : set α') (f : filter τ)
(g : α → α') :
ω f (λ t x, ϕ t (g x)) (g ⁻¹' s) ⊆ ω f ϕ s :=
maps_to_omega_limit _ (maps_to_preimage _ _) (λ t x, rfl) continuous_id
/-!
### Equivalent definitions of the omega limit
The next few lemmas are various versions of the property
characterising ω-limits:
-/
/-- An element `y` is in the ω-limit set of `s` w.r.t. `f` if the
preimages of an arbitrary neighbourhood of `y` frequently
(w.r.t. `f`) intersects of `s`. -/
lemma mem_omega_limit_iff_frequently (y : β) : y ∈ ω f ϕ s ↔
∀ n ∈ 𝓝 y, ∃ᶠ t in f, (s ∩ ϕ t ⁻¹' n).nonempty :=
begin
simp_rw [frequently_iff, omega_limit_def, mem_Inter, mem_closure_iff_nhds],
split,
{ intros h _ hn _ hu,
rcases h _ hu _ hn with ⟨_, _, _, _, ht, hx, hϕtx⟩,
exact ⟨_, ht, _, hx, by rwa [mem_preimage, hϕtx]⟩, },
{ intros h _ hu _ hn,
rcases h _ hn hu with ⟨_, ht, _, hx, hϕtx⟩,
exact ⟨_, hϕtx, _, _, ht, hx, rfl⟩ }
end
/-- An element `y` is in the ω-limit set of `s` w.r.t. `f` if the
forward images of `s` frequently (w.r.t. `f`) intersect arbitrary
neighbourhoods of `y`. -/
lemma mem_omega_limit_iff_frequently₂ (y : β) : y ∈ ω f ϕ s ↔
∀ n ∈ 𝓝 y, ∃ᶠ t in f, (ϕ t '' s ∩ n).nonempty :=
by simp_rw [mem_omega_limit_iff_frequently, image_inter_nonempty_iff]
/-- An element `y` is in the ω-limit of `x` w.r.t. `f` if the forward
images of `x` frequently (w.r.t. `f`) falls within an arbitrary
neighbourhood of `y`. -/
lemma mem_omega_limit_singleton_iff_map_cluster_point (x : α) (y : β) :
y ∈ ω f ϕ {x} ↔ map_cluster_pt y f (λ t, ϕ t x) :=
by simp_rw [mem_omega_limit_iff_frequently, map_cluster_pt_iff, singleton_inter_nonempty,
mem_preimage]
/-!
### Set operations and omega limits
-/
lemma omega_limit_inter : ω f ϕ (s₁ ∩ s₂) ⊆ ω f ϕ s₁ ∩ ω f ϕ s₂ :=
subset_inter (omega_limit_mono_right _ _ (inter_subset_left _ _))
(omega_limit_mono_right _ _(inter_subset_right _ _))
lemma omega_limit_Inter (p : ι → set α) : ω f ϕ (⋂ i, p i) ⊆ ⋂ i, ω f ϕ (p i) :=
subset_Inter $ λ i, omega_limit_mono_right _ _ (Inter_subset _ _)
lemma omega_limit_union : ω f ϕ (s₁ ∪ s₂) = ω f ϕ s₁ ∪ ω f ϕ s₂ :=
begin
ext y, split,
{ simp only [mem_union, mem_omega_limit_iff_frequently, union_inter_distrib_right,
union_nonempty, frequently_or_distrib],
contrapose!,
simp only [not_frequently, not_nonempty_iff_eq_empty, ← subset_empty_iff],
rintro ⟨⟨n₁, hn₁, h₁⟩, ⟨n₂, hn₂, h₂⟩⟩,
refine ⟨n₁ ∩ n₂, inter_mem hn₁ hn₂, h₁.mono $ λ t, _, h₂.mono $ λ t, _⟩,
exacts [subset.trans $ inter_subset_inter_right _ $ preimage_mono $ inter_subset_left _ _,
subset.trans $ inter_subset_inter_right _ $ preimage_mono $ inter_subset_right _ _] },
{ rintros (hy|hy),
exacts [omega_limit_mono_right _ _ (subset_union_left _ _) hy,
omega_limit_mono_right _ _ (subset_union_right _ _) hy] },
end
lemma omega_limit_Union (p : ι → set α) : (⋃ i, ω f ϕ (p i)) ⊆ ω f ϕ ⋃ i, p i :=
by { rw Union_subset_iff,
exact λ i, omega_limit_mono_right _ _ (subset_Union _ _)}
/-!
Different expressions for omega limits, useful for rewrites. In
particular, one may restrict the intersection to sets in `f` which are
subsets of some set `v` also in `f`.
-/
lemma omega_limit_eq_Inter : ω f ϕ s = ⋂ u : ↥f.sets, closure (image2 ϕ u s) :=
bInter_eq_Inter _ _
lemma omega_limit_eq_bInter_inter {v : set τ} (hv : v ∈ f) :
ω f ϕ s = ⋂ u ∈ f, closure (image2 ϕ (u ∩ v) s) :=
subset.antisymm
(Inter₂_mono' $ λ u hu, ⟨u ∩ v, inter_mem hu hv, subset.rfl⟩)
(Inter₂_mono $ λ u hu, closure_mono $ image2_subset (inter_subset_left _ _) subset.rfl)
lemma omega_limit_eq_Inter_inter {v : set τ} (hv : v ∈ f) :
ω f ϕ s = ⋂ (u : ↥f.sets), closure (image2 ϕ (u ∩ v) s) :=
by { rw omega_limit_eq_bInter_inter _ _ _ hv, apply bInter_eq_Inter }
lemma omega_limit_subset_closure_fw_image {u : set τ} (hu : u ∈ f) :
ω f ϕ s ⊆ closure (image2 ϕ u s) :=
begin
rw omega_limit_eq_Inter,
intros _ hx,
rw mem_Inter at hx,
exact hx ⟨u, hu⟩,
end
/-!
### `ω-limits and compactness
-/
/-- A set is eventually carried into any open neighbourhood of its ω-limit:
if `c` is a compact set such that `closure {ϕ t x | t ∈ v, x ∈ s} ⊆ c` for some `v ∈ f`
and `n` is an open neighbourhood of `ω f ϕ s`, then for some `u ∈ f` we have
`closure {ϕ t x | t ∈ u, x ∈ s} ⊆ n`. -/
lemma eventually_closure_subset_of_is_compact_absorbing_of_is_open_of_omega_limit_subset'
{c : set β} (hc₁ : is_compact c) (hc₂ : ∃ v ∈ f, closure (image2 ϕ v s) ⊆ c)
{n : set β} (hn₁ : is_open n) (hn₂ : ω f ϕ s ⊆ n) :
∃ u ∈ f, closure (image2 ϕ u s) ⊆ n :=
begin
rcases hc₂ with ⟨v, hv₁, hv₂⟩,
let k := closure (image2 ϕ v s),
have hk : is_compact (k \ n) :=
is_compact.diff (compact_of_is_closed_subset hc₁ is_closed_closure hv₂) hn₁,
let j := λ u, (closure (image2 ϕ (u ∩ v) s))ᶜ,
have hj₁ : ∀ u ∈ f, is_open (j u), from
λ _ _, (is_open_compl_iff.mpr is_closed_closure),
have hj₂ : k \ n ⊆ ⋃ u ∈ f, j u, begin
have : (⋃ u ∈ f, j u) = ⋃ (u : ↥f.sets), j u, from bUnion_eq_Union _ _,
rw [this, diff_subset_comm, diff_Union],
rw omega_limit_eq_Inter_inter _ _ _ hv₁ at hn₂,
simp_rw diff_compl,
rw ←inter_Inter,
exact subset.trans (inter_subset_right _ _) hn₂,
end,
rcases hk.elim_finite_subcover_image hj₁ hj₂ with ⟨g, hg₁ : ∀ u ∈ g, u ∈ f, hg₂, hg₃⟩,
let w := (⋂ u ∈ g, u) ∩ v,
have hw₂ : w ∈ f, by simpa *,
have hw₃ : k \ n ⊆ (closure (image2 ϕ w s))ᶜ, from
calc k \ n ⊆ ⋃ u ∈ g, j u : hg₃
... ⊆ (closure (image2 ϕ w s))ᶜ :
begin
simp only [Union_subset_iff, compl_subset_compl],
intros u hu,
mono* using [w],
exact Inter_subset_of_subset u (Inter_subset_of_subset hu subset.rfl),
end,
have hw₄ : kᶜ ⊆ (closure (image2 ϕ w s))ᶜ, begin
rw compl_subset_compl,
calc closure (image2 ϕ w s)
⊆ _ : closure_mono (image2_subset (inter_subset_right _ _) subset.rfl)
end,
have hnc : nᶜ ⊆ (k \ n) ∪ kᶜ, by rw [union_comm, ←inter_subset, diff_eq, inter_comm],
have hw : closure (image2 ϕ w s) ⊆ n, from
compl_subset_compl.mp (subset.trans hnc (union_subset hw₃ hw₄)),
exact ⟨_, hw₂, hw⟩
end
/-- A set is eventually carried into any open neighbourhood of its ω-limit:
if `c` is a compact set such that `closure {ϕ t x | t ∈ v, x ∈ s} ⊆ c` for some `v ∈ f`
and `n` is an open neighbourhood of `ω f ϕ s`, then for some `u ∈ f` we have
`closure {ϕ t x | t ∈ u, x ∈ s} ⊆ n`. -/
lemma eventually_closure_subset_of_is_compact_absorbing_of_is_open_of_omega_limit_subset
[t2_space β] {c : set β} (hc₁ : is_compact c) (hc₂ : ∀ᶠ t in f, maps_to (ϕ t) s c)
{n : set β} (hn₁ : is_open n) (hn₂ : ω f ϕ s ⊆ n) :
∃ u ∈ f, closure (image2 ϕ u s) ⊆ n :=
eventually_closure_subset_of_is_compact_absorbing_of_is_open_of_omega_limit_subset'
f ϕ _ hc₁ ⟨_, hc₂, closure_minimal (image2_subset_iff.2 (λ t, id)) hc₁.is_closed⟩ hn₁ hn₂
lemma eventually_maps_to_of_is_compact_absorbing_of_is_open_of_omega_limit_subset
[t2_space β] {c : set β} (hc₁ : is_compact c) (hc₂ : ∀ᶠ t in f, maps_to (ϕ t) s c)
{n : set β} (hn₁ : is_open n) (hn₂ : ω f ϕ s ⊆ n) :
∀ᶠ t in f, maps_to (ϕ t) s n :=
begin
rcases eventually_closure_subset_of_is_compact_absorbing_of_is_open_of_omega_limit_subset
f ϕ s hc₁ hc₂ hn₁ hn₂ with ⟨u, hu_mem, hu⟩,
refine mem_of_superset hu_mem (λ t ht x hx, _),
exact hu (subset_closure $ mem_image2_of_mem ht hx)
end
lemma eventually_closure_subset_of_is_open_of_omega_limit_subset [compact_space β]
{v : set β} (hv₁ : is_open v) (hv₂ : ω f ϕ s ⊆ v) :
∃ u ∈ f, closure (image2 ϕ u s) ⊆ v :=
eventually_closure_subset_of_is_compact_absorbing_of_is_open_of_omega_limit_subset'
_ _ _ compact_univ ⟨univ, univ_mem, subset_univ _⟩ hv₁ hv₂
lemma eventually_maps_to_of_is_open_of_omega_limit_subset [compact_space β]
{v : set β} (hv₁ : is_open v) (hv₂ : ω f ϕ s ⊆ v) :
∀ᶠ t in f, maps_to (ϕ t) s v :=
begin
rcases eventually_closure_subset_of_is_open_of_omega_limit_subset f ϕ s hv₁ hv₂
with ⟨u, hu_mem, hu⟩,
refine mem_of_superset hu_mem (λ t ht x hx, _),
exact hu (subset_closure $ mem_image2_of_mem ht hx)
end
/-- The ω-limit of a nonempty set w.r.t. a nontrivial filter is nonempty. -/
lemma nonempty_omega_limit_of_is_compact_absorbing [ne_bot f] {c : set β} (hc₁ : is_compact c)
(hc₂ : ∃ v ∈ f, closure (image2 ϕ v s) ⊆ c) (hs : s.nonempty) :
(ω f ϕ s).nonempty :=
begin
rcases hc₂ with ⟨v, hv₁, hv₂⟩,
rw omega_limit_eq_Inter_inter _ _ _ hv₁,
apply is_compact.nonempty_Inter_of_directed_nonempty_compact_closed,
{ rintro ⟨u₁, hu₁⟩ ⟨u₂, hu₂⟩,
use ⟨u₁ ∩ u₂, inter_mem hu₁ hu₂⟩, split,
all_goals { exact closure_mono (image2_subset
(inter_subset_inter_left _ (by simp)) subset.rfl) }},
{ intro u,
have hn : (image2 ϕ (u ∩ v) s).nonempty, from
nonempty.image2 (nonempty_of_mem (inter_mem u.prop hv₁)) hs,
exact hn.mono subset_closure },
{ intro _,
apply compact_of_is_closed_subset hc₁ is_closed_closure,
calc _ ⊆ closure (image2 ϕ v s) : closure_mono (image2_subset
(inter_subset_right _ _) subset.rfl)
... ⊆ c : hv₂ },
{ exact λ _, is_closed_closure },
end
lemma nonempty_omega_limit [compact_space β] [ne_bot f] (hs : s.nonempty) :
(ω f ϕ s).nonempty :=
nonempty_omega_limit_of_is_compact_absorbing _ _ _
compact_univ ⟨univ, univ_mem, subset_univ _⟩ hs
end omega_limit
/-!
### ω-limits of Flows by a Monoid
-/
namespace flow
variables
{τ : Type*} [topological_space τ] [add_monoid τ] [has_continuous_add τ]
{α : Type*} [topological_space α]
(f : filter τ) (ϕ : flow τ α) (s : set α)
open_locale omega_limit
lemma is_invariant_omega_limit (hf : ∀ t, tendsto ((+) t) f f) :
is_invariant ϕ (ω f ϕ s) :=
begin
refine λ t, maps_to.mono_right _ (omega_limit_subset_of_tendsto ϕ s (hf t)),
exact maps_to_omega_limit _ (maps_to_id _) (λ t' x, (ϕ.map_add _ _ _).symm)
(continuous_const.flow ϕ continuous_id)
end
lemma omega_limit_image_subset (t : τ) (ht : tendsto (+ t) f f) :
ω f ϕ (ϕ t '' s) ⊆ ω f ϕ s :=
begin
simp only [omega_limit_image_eq, ← map_add],
exact omega_limit_subset_of_tendsto ϕ s ht
end
end flow
/-!
### ω-limits of Flows by a Group
-/
namespace flow
variables
{τ : Type*} [topological_space τ] [add_comm_group τ] [topological_add_group τ]
{α : Type*} [topological_space α]
(f : filter τ) (ϕ : flow τ α) (s : set α)
open_locale omega_limit
/-- the ω-limit of a forward image of `s` is the same as the ω-limit of `s`. -/
@[simp] lemma omega_limit_image_eq (hf : ∀ t, tendsto (+ t) f f) (t : τ) :
ω f ϕ (ϕ t '' s) = ω f ϕ s :=
subset.antisymm (omega_limit_image_subset _ _ _ _ (hf t)) $
calc ω f ϕ s = ω f ϕ (ϕ (-t) '' (ϕ t '' s)) : by simp [image_image, ← map_add]
... ⊆ ω f ϕ (ϕ t '' s) : omega_limit_image_subset _ _ _ _ (hf _)
lemma omega_limit_omega_limit (hf : ∀ t, tendsto ((+) t) f f) :
ω f ϕ (ω f ϕ s) ⊆ ω f ϕ s :=
begin
simp only [subset_def, mem_omega_limit_iff_frequently₂, frequently_iff],
intros _ h,
rintro n hn u hu,
rcases mem_nhds_iff.mp hn with ⟨o, ho₁, ho₂, ho₃⟩,
rcases h o (is_open.mem_nhds ho₂ ho₃) hu with ⟨t, ht₁, ht₂⟩,
have l₁ : (ω f ϕ s ∩ o).nonempty, from
ht₂.mono (inter_subset_inter_left _
((is_invariant_iff_image _ _).mp (is_invariant_omega_limit _ _ _ hf) _)),
have l₂ : ((closure (image2 ϕ u s)) ∩ o).nonempty :=
l₁.mono (λ b hb, ⟨omega_limit_subset_closure_fw_image _ _ _ hu hb.1, hb.2⟩),
have l₃ : (o ∩ image2 ϕ u s).nonempty,
begin
rcases l₂ with ⟨b, hb₁, hb₂⟩,
exact mem_closure_iff_nhds.mp hb₁ o (is_open.mem_nhds ho₂ hb₂)
end,
rcases l₃ with ⟨ϕra, ho, ⟨_, _, hr, ha, hϕra⟩⟩,
exact ⟨_, hr, ϕra, ⟨_, ha, hϕra⟩, ho₁ ho⟩,
end
end flow
|
0d0a6e7a75291a6ee3cd7beb41bd8b010068a3ad | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /hott/hit/two_quotient.hlean | 25111b9b6ab08a1fde70062c94526c25fad6861d | [
"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 | 22,956 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import homotopy.circle eq2 algebra.e_closure cubical.squareover cubical.cube cubical.square2
open quotient eq circle sum sigma equiv function relation e_closure
/-
This files defines a general class of nonrecursive HITs using just quotients.
We can define any HIT X which has
- a single 0-constructor
f : A → X (for some type A)
- a single 1-constructor
e : Π{a a' : A}, R a a' → a = a' (for some (type-valued) relation R on A)
and furthermore has 2-constructors which are all of the form
p = p'
where p, p' are of the form
- refl (f a), for some a : A;
- e r, for some r : R a a';
- ap f q, where q : a = a' :> A;
- inverses of such paths;
- concatenations of such paths.
so an example 2-constructor could be (as long as it typechecks):
ap f q' ⬝ ((e r)⁻¹ ⬝ ap f q)⁻¹ ⬝ e r' = idp
-/
namespace simple_two_quotient
section
parameters {A : Type}
(R : A → A → Type)
local abbreviation T := e_closure R -- the (type-valued) equivalence closure of R
parameter (Q : Π⦃a⦄, T a a → Type)
variables ⦃a a' : A⦄ {s : R a a'} {r : T a a}
local abbreviation B := A ⊎ Σ(a : A) (r : T a a), Q r
inductive pre_two_quotient_rel : B → B → Type :=
| pre_Rmk {} : Π⦃a a'⦄ (r : R a a'), pre_two_quotient_rel (inl a) (inl a')
--BUG: if {} not provided, the alias for pre_Rmk is wrong
definition pre_two_quotient := quotient pre_two_quotient_rel
open pre_two_quotient_rel
local abbreviation C := quotient pre_two_quotient_rel
protected definition j [constructor] (a : A) : C := class_of pre_two_quotient_rel (inl a)
protected definition pre_aux [constructor] (q : Q r) : C :=
class_of pre_two_quotient_rel (inr ⟨a, r, q⟩)
protected definition e (s : R a a') : j a = j a' := eq_of_rel _ (pre_Rmk s)
protected definition et (t : T a a') : j a = j a' := e_closure.elim e t
protected definition f [unfold 7] (q : Q r) : S¹ → C :=
circle.elim (j a) (et r)
protected definition pre_rec [unfold 8] {P : C → Type}
(Pj : Πa, P (j a)) (Pa : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), P (pre_aux q))
(Pe : Π⦃a a' : A⦄ (s : R a a'), Pj a =[e s] Pj a') (x : C) : P x :=
begin
induction x with p,
{ induction p,
{ apply Pj},
{ induction a with a1 a2, induction a2, apply Pa}},
{ induction H, esimp, apply Pe},
end
protected definition pre_elim [unfold 8] {P : Type} (Pj : A → P)
(Pa : Π⦃a : A⦄ ⦃r : T a a⦄, Q r → P) (Pe : Π⦃a a' : A⦄ (s : R a a'), Pj a = Pj a') (x : C)
: P :=
pre_rec Pj Pa (λa a' s, pathover_of_eq (Pe s)) x
protected theorem rec_e {P : C → Type}
(Pj : Πa, P (j a)) (Pa : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), P (pre_aux q))
(Pe : Π⦃a a' : A⦄ (s : R a a'), Pj a =[e s] Pj a') ⦃a a' : A⦄ (s : R a a')
: apdo (pre_rec Pj Pa Pe) (e s) = Pe s :=
!rec_eq_of_rel
protected theorem elim_e {P : Type} (Pj : A → P) (Pa : Π⦃a : A⦄ ⦃r : T a a⦄, Q r → P)
(Pe : Π⦃a a' : A⦄ (s : R a a'), Pj a = Pj a') ⦃a a' : A⦄ (s : R a a')
: ap (pre_elim Pj Pa Pe) (e s) = Pe s :=
begin
apply eq_of_fn_eq_fn_inv !(pathover_constant (e s)),
rewrite [▸*,-apdo_eq_pathover_of_eq_ap,↑pre_elim,rec_e],
end
protected definition elim_et {P : Type} (Pj : A → P) (Pa : Π⦃a : A⦄ ⦃r : T a a⦄, Q r → P)
(Pe : Π⦃a a' : A⦄ (s : R a a'), Pj a = Pj a') ⦃a a' : A⦄ (t : T a a')
: ap (pre_elim Pj Pa Pe) (et t) = e_closure.elim Pe t :=
ap_e_closure_elim_h e (elim_e Pj Pa Pe) t
protected definition rec_et {P : C → Type}
(Pj : Πa, P (j a)) (Pa : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), P (pre_aux q))
(Pe : Π⦃a a' : A⦄ (s : R a a'), Pj a =[e s] Pj a') ⦃a a' : A⦄ (t : T a a')
: apdo (pre_rec Pj Pa Pe) (et t) = e_closure.elimo e Pe t :=
ap_e_closure_elimo_h e Pe (rec_e Pj Pa Pe) t
inductive simple_two_quotient_rel : C → C → Type :=
| Rmk {} : Π{a : A} {r : T a a} (q : Q r) (x : circle),
simple_two_quotient_rel (f q x) (pre_aux q)
open simple_two_quotient_rel
definition simple_two_quotient := quotient simple_two_quotient_rel
local abbreviation D := simple_two_quotient
local abbreviation i := class_of simple_two_quotient_rel
definition incl0 (a : A) : D := i (j a)
protected definition aux (q : Q r) : D := i (pre_aux q)
definition incl1 (s : R a a') : incl0 a = incl0 a' := ap i (e s)
definition inclt (t : T a a') : incl0 a = incl0 a' := e_closure.elim incl1 t
-- "wrong" version inclt, which is ap i (p ⬝ q) instead of ap i p ⬝ ap i q
-- it is used in the proof, because incltw is easier to work with
protected definition incltw (t : T a a') : incl0 a = incl0 a' := ap i (et t)
protected definition inclt_eq_incltw (t : T a a') : inclt t = incltw t :=
(ap_e_closure_elim i e t)⁻¹
definition incl2' (q : Q r) (x : S¹) : i (f q x) = aux q :=
eq_of_rel simple_two_quotient_rel (Rmk q x)
protected definition incl2w (q : Q r) : incltw r = idp :=
(ap02 i (elim_loop (j a) (et r))⁻¹) ⬝
(ap_compose i (f q) loop)⁻¹ ⬝
ap_is_constant (incl2' q) loop ⬝
!con.right_inv
definition incl2 (q : Q r) : inclt r = idp :=
inclt_eq_incltw r ⬝ incl2w q
local attribute simple_two_quotient f i D incl0 aux incl1 incl2' inclt [reducible]
local attribute i aux incl0 [constructor]
parameters {R Q}
protected definition rec {P : D → Type} (P0 : Π(a : A), P (incl0 a))
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a')
(P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r),
change_path (incl2 q) (e_closure.elimo incl1 P1 r) = idpo) (x : D) : P x :=
begin
induction x,
{ refine (pre_rec _ _ _ a),
{ exact P0},
{ intro a r q, exact incl2' q base ▸ P0 a},
{ intro a a' s, exact pathover_of_pathover_ap P i (P1 s)}},
{ exact abstract [irreducible] begin induction H, induction x,
{ esimp, exact pathover_tr (incl2' q base) (P0 a)},
{ apply pathover_pathover,
esimp, fold [i, incl2' q],
refine eq_hconcato _ _, apply _,
{ transitivity _,
{ apply ap (pathover_ap _ _),
transitivity _, apply apdo_compose2 (pre_rec P0 _ _) (f q) loop,
apply ap (pathover_of_pathover_ap _ _),
transitivity _, apply apdo_change_path, exact !elim_loop⁻¹,
transitivity _,
apply ap (change_path _),
transitivity _, apply rec_et,
transitivity (pathover_of_pathover_ap P i (change_path (inclt_eq_incltw r)
(e_closure.elimo incl1 (λ (a a' : A) (s : R a a'), P1 s) r))),
apply e_closure_elimo_ap,
exact idp,
apply change_path_pathover_of_pathover_ap},
esimp, transitivity _, apply pathover_ap_pathover_of_pathover_ap P i (f q),
transitivity _, apply ap (change_path _), apply to_right_inv !pathover_compose,
do 2 (transitivity _; exact !change_path_con⁻¹),
transitivity _, apply ap (change_path _),
exact (to_left_inv (change_path_equiv _ _ (incl2 q)) _)⁻¹, esimp,
rewrite P2, transitivity _; exact !change_path_con⁻¹, apply ap (λx, change_path x _),
rewrite [↑incl2, con_inv], transitivity _, exact !con.assoc⁻¹,
rewrite [inv_con_cancel_right, ↑incl2w, ↑ap02, +con_inv, +ap_inv, +inv_inv, -+con.assoc,
+con_inv_cancel_right], reflexivity},
rewrite [change_path_con, apdo_constant],
apply squareover_change_path_left, apply squareover_change_path_right',
apply squareover_change_path_left,
refine change_square _ vrflo,
symmetry, apply inv_ph_eq_of_eq_ph, rewrite [ap_is_constant_natural_square],
apply whisker_bl_whisker_tl_eq} end end},
end
protected definition rec_on [reducible] {P : D → Type} (x : D) (P0 : Π(a : A), P (incl0 a))
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a')
(P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r),
change_path (incl2 q) (e_closure.elimo incl1 P1 r) = idpo) : P x :=
rec P0 P1 P2 x
theorem rec_incl1 {P : D → Type} (P0 : Π(a : A), P (incl0 a))
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a')
(P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r),
change_path (incl2 q) (e_closure.elimo incl1 P1 r) = idpo) ⦃a a' : A⦄ (s : R a a')
: apdo (rec P0 P1 P2) (incl1 s) = P1 s :=
begin
unfold [rec, incl1], refine !apdo_ap ⬝ _, esimp, rewrite rec_e,
apply to_right_inv !pathover_compose
end
theorem rec_inclt {P : D → Type} (P0 : Π(a : A), P (incl0 a))
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a')
(P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r),
change_path (incl2 q) (e_closure.elimo incl1 P1 r) = idpo) ⦃a a' : A⦄ (t : T a a')
: apdo (rec P0 P1 P2) (inclt t) = e_closure.elimo incl1 P1 t :=
ap_e_closure_elimo_h incl1 P1 (rec_incl1 P0 P1 P2) t
protected definition elim {P : Type} (P0 : A → P)
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a')
(P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp)
(x : D) : P :=
begin
induction x,
{ refine (pre_elim _ _ _ a),
{ exact P0},
{ intro a r q, exact P0 a},
{ exact P1}},
{ exact abstract begin induction H, induction x,
{ exact idpath (P0 a)},
{ unfold f, apply eq_pathover, apply hdeg_square,
exact abstract ap_compose (pre_elim P0 _ P1) (f q) loop ⬝
ap _ !elim_loop ⬝
!elim_et ⬝
P2 q ⬝
!ap_constant⁻¹ end} end end},
end
local attribute elim [unfold 8]
protected definition elim_on {P : Type} (x : D) (P0 : A → P)
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a')
(P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp)
: P :=
elim P0 P1 P2 x
definition elim_incl1 {P : Type} {P0 : A → P}
{P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'}
(P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp)
⦃a a' : A⦄ (s : R a a') : ap (elim P0 P1 P2) (incl1 s) = P1 s :=
(ap_compose (elim P0 P1 P2) i (e s))⁻¹ ⬝ !elim_e
definition elim_inclt {P : Type} {P0 : A → P}
{P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'}
(P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp)
⦃a a' : A⦄ (t : T a a') : ap (elim P0 P1 P2) (inclt t) = e_closure.elim P1 t :=
ap_e_closure_elim_h incl1 (elim_incl1 P2) t
protected definition elim_incltw {P : Type} {P0 : A → P}
{P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'}
(P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp)
⦃a a' : A⦄ (t : T a a') : ap (elim P0 P1 P2) (incltw t) = e_closure.elim P1 t :=
(ap_compose (elim P0 P1 P2) i (et t))⁻¹ ⬝ !elim_et
protected theorem elim_inclt_eq_elim_incltw {P : Type} {P0 : A → P}
{P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'}
(P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp)
⦃a a' : A⦄ (t : T a a')
: elim_inclt P2 t = ap (ap (elim P0 P1 P2)) (inclt_eq_incltw t) ⬝ elim_incltw P2 t :=
begin
unfold [elim_inclt,elim_incltw,inclt_eq_incltw,et],
refine !ap_e_closure_elim_h_eq ⬝ _,
rewrite [ap_inv,-con.assoc],
xrewrite [eq_of_square (ap_ap_e_closure_elim i (elim P0 P1 P2) e t)⁻¹ʰ],
rewrite [↓incl1,con.assoc], apply whisker_left,
rewrite [↑[elim_et,elim_incl1],+ap_e_closure_elim_h_eq,con_inv,↑[i,function.compose]],
rewrite [-con.assoc (_ ⬝ _),con.assoc _⁻¹,con.left_inv,▸*,-ap_inv,-ap_con],
apply ap (ap _),
krewrite [-eq_of_homotopy3_inv,-eq_of_homotopy3_con]
end
definition elim_incl2' {P : Type} {P0 : A → P}
{P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'}
(P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp)
⦃a : A⦄ ⦃r : T a a⦄ (q : Q r) : ap (elim P0 P1 P2) (incl2' q base) = idpath (P0 a) :=
!elim_eq_of_rel
protected theorem elim_incl2w {P : Type} (P0 : A → P)
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a')
(P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp)
⦃a : A⦄ ⦃r : T a a⦄ (q : Q r)
: square (ap02 (elim P0 P1 P2) (incl2w q)) (P2 q) (elim_incltw P2 r) idp :=
begin
esimp [incl2w,ap02],
rewrite [+ap_con (ap _),▸*],
xrewrite [-ap_compose (ap _) (ap i)],
rewrite [+ap_inv],
xrewrite [eq_top_of_square
((ap_compose_natural (elim P0 P1 P2) i (elim_loop (j a) (et r)))⁻¹ʰ⁻¹ᵛ ⬝h
(ap_ap_compose (elim P0 P1 P2) i (f q) loop)⁻¹ʰ⁻¹ᵛ ⬝h
ap_ap_is_constant (elim P0 P1 P2) (incl2' q) loop ⬝h
ap_con_right_inv_sq (elim P0 P1 P2) (incl2' q base)),
↑[elim_incltw]],
apply whisker_tl,
rewrite [ap_is_constant_eq],
xrewrite [naturality_apdo_eq (λx, !elim_eq_of_rel) loop],
rewrite [↑elim_2,rec_loop,square_of_pathover_concato_eq,square_of_pathover_eq_concato,
eq_of_square_vconcat_eq,eq_of_square_eq_vconcat],
apply eq_vconcat,
{ apply ap (λx, _ ⬝ eq_con_inv_of_con_eq ((_ ⬝ x ⬝ _)⁻¹ ⬝ _) ⬝ _),
transitivity _, apply ap eq_of_square,
apply to_right_inv !eq_pathover_equiv_square (hdeg_square (elim_1 P A R Q P0 P1 a r q P2)),
transitivity _, apply eq_of_square_hdeg_square,
unfold elim_1, reflexivity},
rewrite [+con_inv,whisker_left_inv,+inv_inv,-whisker_right_inv,
con.assoc (whisker_left _ _),con.assoc _ (whisker_right _ _),▸*,
whisker_right_con_whisker_left _ !ap_constant],
xrewrite [-con.assoc _ _ (whisker_right _ _)],
rewrite [con.assoc _ _ (whisker_left _ _),idp_con_whisker_left,▸*,
con.assoc _ !ap_constant⁻¹,con.left_inv],
xrewrite [eq_con_inv_of_con_eq_whisker_left,▸*],
rewrite [+con.assoc _ _ !con.right_inv,
right_inv_eq_idp (
(λ(x : ap (elim P0 P1 P2) (incl2' q base) = idpath
(elim P0 P1 P2 (class_of simple_two_quotient_rel (f q base)))), x)
(elim_incl2' P2 q)),
↑[whisker_left]],
xrewrite [con2_con_con2],
rewrite [idp_con,↑elim_incl2',con.left_inv,whisker_right_inv,↑whisker_right],
xrewrite [con.assoc _ _ (_ ◾ _)],
rewrite [con.left_inv,▸*,-+con.assoc,con.assoc _⁻¹,↑[elim,function.compose],con.left_inv,
▸*,↑j,con.left_inv,idp_con],
apply square_of_eq, reflexivity
end
theorem elim_incl2 {P : Type} (P0 : A → P)
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a')
(P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp)
⦃a : A⦄ ⦃r : T a a⦄ (q : Q r)
: square (ap02 (elim P0 P1 P2) (incl2 q)) (P2 q) (elim_inclt P2 r) idp :=
begin
rewrite [↑incl2,↑ap02,ap_con,elim_inclt_eq_elim_incltw],
apply whisker_tl,
apply elim_incl2w
end
end
end simple_two_quotient
attribute simple_two_quotient.j [constructor]
attribute simple_two_quotient.rec simple_two_quotient.elim [unfold 8] [recursor 8]
--attribute simple_two_quotient.elim_type [unfold 9] -- TODO
attribute simple_two_quotient.rec_on simple_two_quotient.elim_on [unfold 5]
--attribute simple_two_quotient.elim_type_on [unfold 6] -- TODO
namespace two_quotient
open simple_two_quotient
section
parameters {A : Type}
(R : A → A → Type)
local abbreviation T := e_closure R -- the (type-valued) equivalence closure of R
parameter (Q : Π⦃a a'⦄, T a a' → T a a' → Type)
variables ⦃a a' a'' : A⦄ {s : R a a'} {t t' : T a a'}
inductive two_quotient_Q : Π⦃a : A⦄, e_closure R a a → Type :=
| Qmk : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄, Q t t' → two_quotient_Q (t ⬝r t'⁻¹ʳ)
open two_quotient_Q
local abbreviation Q2 := two_quotient_Q
definition two_quotient := simple_two_quotient R Q2
definition incl0 (a : A) : two_quotient := incl0 _ _ a
definition incl1 (s : R a a') : incl0 a = incl0 a' := incl1 _ _ s
definition inclt (t : T a a') : incl0 a = incl0 a' := e_closure.elim incl1 t
definition incl2 (q : Q t t') : inclt t = inclt t' :=
eq_of_con_inv_eq_idp (incl2 _ _ (Qmk R q))
parameters {R Q}
protected definition rec {P : two_quotient → Type} (P0 : Π(a : A), P (incl0 a))
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a')
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'),
change_path (incl2 q) (e_closure.elimo incl1 P1 t) = e_closure.elimo incl1 P1 t')
(x : two_quotient) : P x :=
begin
induction x,
{ exact P0 a},
{ exact P1 s},
{ exact abstract [irreducible] begin induction q with a a' t t' q,
rewrite [elimo_con (simple_two_quotient.incl1 R Q2) P1,
elimo_inv (simple_two_quotient.incl1 R Q2) P1,
-whisker_right_eq_of_con_inv_eq_idp (simple_two_quotient.incl2 R Q2 (Qmk R q)),
change_path_con],
xrewrite [change_path_cono],
refine ap (λx, change_path _ (_ ⬝o x)) !change_path_invo ⬝ _, esimp,
apply cono_invo_eq_idpo, apply P2 end end}
end
protected definition rec_on [reducible] {P : two_quotient → Type} (x : two_quotient)
(P0 : Π(a : A), P (incl0 a))
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a')
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'),
change_path (incl2 q) (e_closure.elimo incl1 P1 t) = e_closure.elimo incl1 P1 t') : P x :=
rec P0 P1 P2 x
theorem rec_incl1 {P : two_quotient → Type} (P0 : Π(a : A), P (incl0 a))
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a')
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'),
change_path (incl2 q) (e_closure.elimo incl1 P1 t) = e_closure.elimo incl1 P1 t')
⦃a a' : A⦄ (s : R a a') : apdo (rec P0 P1 P2) (incl1 s) = P1 s :=
rec_incl1 _ _ _ s
theorem rec_inclt {P : two_quotient → Type} (P0 : Π(a : A), P (incl0 a))
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a')
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'),
change_path (incl2 q) (e_closure.elimo incl1 P1 t) = e_closure.elimo incl1 P1 t')
⦃a a' : A⦄ (t : T a a') : apdo (rec P0 P1 P2) (inclt t) = e_closure.elimo incl1 P1 t :=
rec_inclt _ _ _ t
protected definition elim {P : Type} (P0 : A → P)
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a')
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t')
(x : two_quotient) : P :=
begin
induction x,
{ exact P0 a},
{ exact P1 s},
{ exact abstract [unfold 10] begin induction q with a a' t t' q,
esimp [e_closure.elim],
apply con_inv_eq_idp, exact P2 q end end},
end
local attribute elim [unfold 8]
protected definition elim_on {P : Type} (x : two_quotient) (P0 : A → P)
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a')
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t')
: P :=
elim P0 P1 P2 x
definition elim_incl1 {P : Type} {P0 : A → P}
{P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'}
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t')
⦃a a' : A⦄ (s : R a a') : ap (elim P0 P1 P2) (incl1 s) = P1 s :=
!elim_incl1
definition elim_inclt {P : Type} {P0 : A → P}
{P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'}
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t')
⦃a a' : A⦄ (t : T a a') : ap (elim P0 P1 P2) (inclt t) = e_closure.elim P1 t :=
!elim_inclt
theorem elim_incl2 {P : Type} (P0 : A → P)
(P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a')
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t')
⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t')
: square (ap02 (elim P0 P1 P2) (incl2 q)) (P2 q) (elim_inclt P2 t) (elim_inclt P2 t') :=
begin
rewrite [↑[incl2,elim],ap_eq_of_con_inv_eq_idp],
xrewrite [eq_top_of_square (elim_incl2 P0 P1 (elim_1 A R Q P P0 P1 P2) (Qmk R q))],
xrewrite [{simple_two_quotient.elim_inclt (elim_1 A R Q P P0 P1 P2)
(t ⬝r t'⁻¹ʳ)}
idpath (ap_con (simple_two_quotient.elim P0 P1 (elim_1 A R Q P P0 P1 P2))
(inclt t) (inclt t')⁻¹ ⬝
(simple_two_quotient.elim_inclt (elim_1 A R Q P P0 P1 P2) t ◾
(ap_inv (simple_two_quotient.elim P0 P1 (elim_1 A R Q P P0 P1 P2))
(inclt t') ⬝
inverse2 (simple_two_quotient.elim_inclt (elim_1 A R Q P P0 P1 P2) t')))),▸*],
rewrite [-con.assoc _ _ (con_inv_eq_idp _),-con.assoc _ _ (_ ◾ _),con.assoc _ _ (ap_con _ _ _),
con.left_inv,↑whisker_left,con2_con_con2,-con.assoc (ap_inv _ _)⁻¹,
con.left_inv,+idp_con,eq_of_con_inv_eq_idp_con2],
xrewrite [to_left_inv !eq_equiv_con_inv_eq_idp (P2 q)],
apply top_deg_square
end
definition elim_inclt_rel [unfold_full] {P : Type} {P0 : A → P}
{P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'}
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t')
⦃a a' : A⦄ (r : R a a') : elim_inclt P2 [r] = elim_incl1 P2 r :=
idp
definition elim_inclt_inv [unfold_full] {P : Type} {P0 : A → P}
{P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'}
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t')
⦃a a' : A⦄ (t : T a a')
: elim_inclt P2 t⁻¹ʳ = ap_inv (elim P0 P1 P2) (inclt t) ⬝ (elim_inclt P2 t)⁻² :=
idp
definition elim_inclt_con [unfold_full] {P : Type} {P0 : A → P}
{P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'}
(P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t')
⦃a a' a'' : A⦄ (t : T a a') (t': T a' a'')
: elim_inclt P2 (t ⬝r t') =
ap_con (elim P0 P1 P2) (inclt t) (inclt t') ⬝ (elim_inclt P2 t ◾ elim_inclt P2 t') :=
idp
definition inclt_rel [unfold_full] (r : R a a') : inclt [r] = incl1 r := idp
definition inclt_inv [unfold_full] (t : T a a') : inclt t⁻¹ʳ = (inclt t)⁻¹ := idp
definition inclt_con [unfold_full] (t : T a a') (t' : T a' a'')
: inclt (t ⬝r t') = inclt t ⬝ inclt t' := idp
end
end two_quotient
attribute two_quotient.incl0 [constructor]
attribute two_quotient.rec two_quotient.elim [unfold 8] [recursor 8]
--attribute two_quotient.elim_type [unfold 9]
attribute two_quotient.rec_on two_quotient.elim_on [unfold 5]
--attribute two_quotient.elim_type_on [unfold 6]
|
02d034d1384c5538bdb3b5d69c184db7089dea42 | 82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7 | /tests/lean/run/fun.lean | b4af8c6be4d05193b449234a4998175a7fbecd1c | [
"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 | 295 | lean | open Function Bool
constant f : Nat → Bool := arbitrary _
constant g : Nat → Nat := arbitrary _
#check f ∘ g ∘ g
#check (id : Nat → Nat)
constant h : Nat → Bool → Nat := arbitrary _
constant f1 : Nat → Nat → Bool := arbitrary _
constant f2 : Bool → Nat := arbitrary _
|
4763a9d202199128433ba50f202f7945de5ec82f | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/nat/units.lean | 5b2818a4c7816734acfa9de92456eceec170c685 | [
"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,109 | lean | /-
Copyright (c) 2014 Floris van Doorn (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad, Mario Carneiro
-/
import data.nat.basic
import algebra.group.units
/-! # The units of the natural numbers as a `monoid` and `add_monoid`
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.-/
namespace nat
theorem units_eq_one (u : ℕˣ) : u = 1 :=
units.ext $ nat.eq_one_of_dvd_one ⟨u.inv, u.val_inv.symm⟩
theorem add_units_eq_zero (u : add_units ℕ) : u = 0 :=
add_units.ext $ (nat.eq_zero_of_add_eq_zero u.val_neg).1
@[simp] protected theorem is_unit_iff {n : ℕ} : is_unit n ↔ n = 1 :=
iff.intro
(λ ⟨u, hu⟩, match n, u, hu, nat.units_eq_one u with _, _, rfl, rfl := rfl end)
(λ h, h.symm ▸ ⟨1, rfl⟩)
instance unique_units : unique ℕˣ :=
{ default := 1, uniq := nat.units_eq_one }
instance unique_add_units : unique (add_units ℕ) :=
{ default := 0, uniq := nat.add_units_eq_zero }
end nat
|
062f250fa720e6e4d709a1ee89aa99e5518fde13 | 1446f520c1db37e157b631385707cc28a17a595e | /stage0/src/Init/Data/String/Basic.lean | c5309c9aa14697d67f13e0366db14643150906f3 | [
"Apache-2.0"
] | permissive | bdbabiak/lean4 | cab06b8a2606d99a168dd279efdd404edb4e825a | 3f4d0d78b2ce3ef541cb643bbe21496bd6b057ac | refs/heads/master | 1,615,045,275,530 | 1,583,793,696,000 | 1,583,793,696,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 15,507 | 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.List.Basic
import Init.Data.Char.Basic
import Init.Data.Option.Basic
universes u
structure String :=
(data : List Char)
abbrev String.Pos := Nat
structure Substring :=
(str : String) (startPos : String.Pos) (stopPos : String.Pos)
attribute [extern "lean_string_mk"] String.mk
attribute [extern "lean_string_data"] String.data
@[extern "lean_string_dec_eq"]
def String.decEq (s₁ s₂ : @& String) : Decidable (s₁ = s₂) :=
match s₁, s₂ with
| ⟨s₁⟩, ⟨s₂⟩ =>
if h : s₁ = s₂ then isTrue (congrArg _ h)
else isFalse (fun h' => String.noConfusion h' (fun h' => absurd h' h))
instance : DecidableEq String :=
String.decEq
def List.asString (s : List Char) : String :=
⟨s⟩
namespace String
instance : HasLess String :=
⟨fun s₁ s₂ => s₁.data < s₂.data⟩
@[extern "lean_string_dec_lt"]
instance decLt (s₁ s₂ : @& String) : Decidable (s₁ < s₂) :=
List.hasDecidableLt s₁.data s₂.data
@[extern "lean_string_length"]
def length : (@& String) → Nat
| ⟨s⟩ => s.length
/- The internal implementation uses dynamic arrays and will perform destructive updates
if the String is not shared. -/
@[extern "lean_string_push"]
def push : String → Char → String
| ⟨s⟩, c => ⟨s ++ [c]⟩
/- The internal implementation uses dynamic arrays and will perform destructive updates
if the String is not shared. -/
@[extern "lean_string_append"]
def append : String → (@& String) → String
| ⟨a⟩, ⟨b⟩ => ⟨a ++ b⟩
/- O(n) in the runtime, where n is the length of the String -/
def toList (s : String) : List Char :=
s.data
private def csize (c : Char) : Nat :=
c.utf8Size.toNat
private def utf8ByteSizeAux : List Char → Nat → Nat
| [], r => r
| c::cs, r => utf8ByteSizeAux cs (r + csize c)
@[extern "lean_string_utf8_byte_size"]
def utf8ByteSize : (@& String) → Nat
| ⟨s⟩ => utf8ByteSizeAux s 0
@[inline] def bsize (s : String) : Nat :=
utf8ByteSize s
@[inline] def toSubstring (s : String) : Substring :=
{str := s, startPos := 0, stopPos := s.bsize}
private def utf8GetAux : List Char → Pos → Pos → Char
| [], i, p => arbitrary Char
| c::cs, i, p => if i = p then c else utf8GetAux cs (i + csize c) p
@[extern "lean_string_utf8_get"]
def get : (@& String) → (@& Pos) → Char
| ⟨s⟩, p => utf8GetAux s 0 p
private def utf8SetAux (c' : Char) : List Char → Pos → Pos → List Char
| [], i, p => []
| c::cs, i, p =>
if i = p then (c'::cs) else c::(utf8SetAux cs (i + csize c) p)
@[extern "lean_string_utf8_set"]
def set : String → (@& Pos) → Char → String
| ⟨s⟩, i, c => ⟨utf8SetAux c s 0 i⟩
def modify (s : String) (i : Pos) (f : Char → Char) : String :=
s.set i $ f $ s.get i
@[extern "lean_string_utf8_next"]
def next (s : @& String) (p : @& Pos) : Pos :=
let c := get s p;
p + csize c
private def utf8PrevAux : List Char → Pos → Pos → Pos
| [], i, p => 0
| c::cs, i, p =>
let cz := csize c;
let i' := i + cz;
if i' = p then i else utf8PrevAux cs i' p
@[extern "lean_string_utf8_prev"]
def prev : (@& String) → (@& Pos) → Pos
| ⟨s⟩, p => if p = 0 then 0 else utf8PrevAux s 0 p
def front (s : String) : Char :=
get s 0
def back (s : String) : Char :=
get s (prev s (bsize s))
@[extern "lean_string_utf8_at_end"]
def atEnd : (@& String) → (@& Pos) → Bool
| s, p => p ≥ utf8ByteSize s
/- TODO: remove `partial` keywords after we restore the tactic
framework and wellfounded recursion support -/
partial def posOfAux (s : String) (c : Char) (stopPos : Pos) : Pos → Pos
| pos =>
if pos == stopPos then pos
else if s.get pos == c then pos
else posOfAux (s.next pos)
@[inline] def posOf (s : String) (c : Char) : Pos :=
posOfAux s c s.bsize 0
partial def revPosOfAux (s : String) (c : Char) : Pos → Option Pos
| pos =>
if s.get pos == c then some pos
else if pos == 0 then none
else revPosOfAux (s.prev pos)
def revPosOf (s : String) (c : Char) : Option Pos :=
if s.bsize == 0 then none
else revPosOfAux s c (s.prev s.bsize)
private def utf8ExtractAux₂ : List Char → Pos → Pos → List Char
| [], _, _ => []
| c::cs, i, e => if i = e then [] else c :: utf8ExtractAux₂ cs (i + csize c) e
private def utf8ExtractAux₁ : List Char → Pos → Pos → Pos → List Char
| [], _, _, _ => []
| s@(c::cs), i, b, e => if i = b then utf8ExtractAux₂ s i e else utf8ExtractAux₁ cs (i + csize c) b e
@[extern "lean_string_utf8_extract"]
def extract : (@& String) → (@& Pos) → (@& Pos) → String
| ⟨s⟩, b, e => if b ≥ e then ⟨[]⟩ else ⟨utf8ExtractAux₁ s 0 b e⟩
@[specialize] partial def splitAux (s : String) (p : Char → Bool) : Pos → Pos → List String → List String
| b, i, r =>
if s.atEnd i then
let r := if p (s.get i) then ""::(s.extract b (i-1))::r else (s.extract b i)::r;
r.reverse
else if p (s.get i) then
let i := s.next i;
splitAux i i (s.extract b (i-1)::r)
else splitAux b (s.next i) r
@[specialize] def split (s : String) (p : Char → Bool) : List String :=
splitAux s p 0 0 []
partial def splitOnAux (s sep : String) : Pos → Pos → Pos → List String → List String
| b, i, j, r =>
if s.atEnd i then
let r := if sep.atEnd j then ""::(s.extract b (i-j))::r else (s.extract b i)::r;
r.reverse
else if s.get i == sep.get j then
let i := s.next i;
let j := sep.next j;
if sep.atEnd j then splitOnAux i i 0 (s.extract b (i-j)::r)
else splitOnAux b i j r
else splitOnAux b (s.next i) 0 r
def splitOn (s : String) (sep : String := " ") : List String :=
if sep == "" then [s] else splitOnAux s sep 0 0 0 []
instance : Inhabited String :=
⟨""⟩
instance : HasSizeof String :=
⟨String.length⟩
instance : HasAppend String :=
⟨String.append⟩
def str : String → Char → String := push
def pushn (s : String) (c : Char) (n : Nat) : String :=
n.repeat (fun s => s.push c) s
def isEmpty (s : String) : Bool :=
s.bsize == 0
def join (l : List String) : String :=
l.foldl (fun r s => r ++ s) ""
def singleton (c : Char) : String :=
"".push c
def intercalate (s : String) (ss : List String) : String :=
(List.intercalate s.toList (ss.map toList)).asString
structure Iterator :=
(s : String) (i : Pos)
def mkIterator (s : String) : Iterator :=
⟨s, 0⟩
namespace Iterator
def toString : Iterator → String
| ⟨s, _⟩ => s
def remainingBytes : Iterator → Nat
| ⟨s, i⟩ => s.bsize - i
def pos : Iterator → Pos
| ⟨s, i⟩ => i
def curr : Iterator → Char
| ⟨s, i⟩ => get s i
def next : Iterator → Iterator
| ⟨s, i⟩ => ⟨s, s.next i⟩
def prev : Iterator → Iterator
| ⟨s, i⟩ => ⟨s, s.prev i⟩
def hasNext : Iterator → Bool
| ⟨s, i⟩ => i < utf8ByteSize s
def hasPrev : Iterator → Bool
| ⟨s, i⟩ => i > 0
def setCurr : Iterator → Char → Iterator
| ⟨s, i⟩, c => ⟨s.set i c, i⟩
def toEnd : Iterator → Iterator
| ⟨s, _⟩ => ⟨s, s.bsize⟩
def extract : Iterator → Iterator → String
| ⟨s₁, b⟩, ⟨s₂, e⟩ =>
if s₁ ≠ s₂ || b > e then ""
else s₁.extract b e
def forward : Iterator → Nat → Iterator
| it, 0 => it
| it, n+1 => forward it.next n
def remainingToString : Iterator → String
| ⟨s, i⟩ => s.extract i s.bsize
/- (isPrefixOfRemaining it₁ it₂) is `true` Iff `it₁.remainingToString` is a prefix
of `it₂.remainingToString`. -/
def isPrefixOfRemaining : Iterator → Iterator → Bool
| ⟨s₁, i₁⟩, ⟨s₂, i₂⟩ => s₁.extract i₁ s₁.bsize = s₂.extract i₂ (i₂ + (s₁.bsize - i₁))
def nextn : Iterator → Nat → Iterator
| it, 0 => it
| it, i+1 => nextn it.next i
def prevn : Iterator → Nat → Iterator
| it, 0 => it
| it, i+1 => prevn it.prev i
end Iterator
partial def offsetOfPosAux (s : String) (pos : Pos) : Pos → Nat → Nat
| i, offset =>
if i == pos || s.atEnd i then offset
else offsetOfPosAux (s.next i) (offset+1)
def offsetOfPos (s : String) (pos : Pos) : Nat :=
offsetOfPosAux s pos 0 0
@[specialize] partial def foldlAux {α : Type u} (f : α → Char → α) (s : String) (stopPos : Pos) : Pos → α → α
| i, a =>
if i == stopPos then a
else foldlAux (s.next i) (f a (s.get i))
@[inline] def foldl {α : Type u} (f : α → Char → α) (a : α) (s : String) : α :=
foldlAux f s s.bsize 0 a
@[specialize] partial def foldrAux {α : Type u} (f : Char → α → α) (a : α) (s : String) (stopPos : Pos) : Pos → α
| i =>
if i == stopPos then a
else f (s.get i) (foldrAux (s.next i))
@[inline] def foldr {α : Type u} (f : Char → α → α) (a : α) (s : String) : α :=
foldrAux f a s s.bsize 0
@[specialize] partial def anyAux (s : String) (stopPos : Pos) (p : Char → Bool) : Pos → Bool
| i =>
if i == stopPos then false
else if p (s.get i) then true
else anyAux (s.next i)
@[inline] def any (s : String) (p : Char → Bool) : Bool :=
anyAux s s.bsize p 0
@[inline] def all (s : String) (p : Char → Bool) : Bool :=
!s.any (fun c => !p c)
def contains (s : String) (c : Char) : Bool :=
s.any (fun a => a == c)
@[specialize] partial def mapAux (f : Char → Char) : Pos → String → String
| i, s =>
if s.atEnd i then s
else
let c := f (s.get i);
let s := s.set i c;
mapAux (s.next i) s
@[inline] def map (f : Char → Char) (s : String) : String :=
mapAux f 0 s
def toNat (s : String) : Nat :=
s.foldl (fun n c => n*10 + (c.toNat - '0'.toNat)) 0
def isNat (s : String) : Bool :=
s.all $ fun c => c.isDigit
partial def isPrefixOfAux (p s : String) : Pos → Bool
| i =>
if p.atEnd i then true
else
let c₁ := p.get i;
let c₂ := s.get i;
c₁ == c₂ && isPrefixOfAux (s.next i)
/- Return true iff `p` is a prefix of `s` -/
def isPrefixOf (p : String) (s : String) : Bool :=
p.length ≤ s.length && isPrefixOfAux p s 0
end String
namespace Substring
@[inline] def toString : Substring → String
| ⟨s, b, e⟩ => s.extract b e
@[inline] def toIterator : Substring → String.Iterator
| ⟨s, b, _⟩ => ⟨s, b⟩
@[inline] def get : Substring → String.Pos → Char
| ⟨s, b, _⟩, p => s.get (b+p)
@[inline] def next : Substring → String.Pos → String.Pos
| ⟨s, b, e⟩, p =>
let p := s.next (b+p);
if p > e then e - b else p - b
@[inline] def prev : Substring → String.Pos → String.Pos
| ⟨s, b, _⟩, p =>
if p = b then p else s.prev (b+p) - b
@[inline] def front (s : Substring) : Char :=
s.get 0
@[inline] def posOf (s : Substring) (c : Char) : String.Pos :=
match s with
| ⟨s, b, e⟩ => (String.posOfAux s c e b) - b
@[inline] def drop : Substring → Nat → Substring
| ⟨s, b, e⟩, n =>
if b + n ≥ e then "".toSubstring
else ⟨s, b+n, e⟩
@[inline] def dropRight : Substring → Nat → Substring
| ⟨s, b, e⟩, n =>
if e - n ≤ e then "".toSubstring
else ⟨s, b, e - n⟩
@[inline] def take : Substring → Nat → Substring
| ⟨s, b, e⟩, n =>
let e := if b + n ≥ e then e else b + n;
⟨s, b, e⟩
@[inline] def takeRight : Substring → Nat → Substring
| ⟨s, b, e⟩, n =>
let b := if e - n ≤ b then b else e - n;
⟨s, b, e⟩
@[inline] def atEnd : Substring → String.Pos → Bool
| ⟨s, b, e⟩, p => b + p == e
@[inline] def extract : Substring → String.Pos → String.Pos → Substring
| ⟨s, b, _⟩, b', e' => if b' ≥ e' then ⟨"", 0, 1⟩ else ⟨s, b+b', b+e'⟩
partial def splitOnAux (s sep : String) (stopPos : String.Pos) : String.Pos → String.Pos → String.Pos → List Substring → List Substring
| b, i, j, r =>
if i == stopPos then
let r := if sep.atEnd j then "".toSubstring::{str := s, startPos := b, stopPos := i-j}::r else {str := s, startPos := b, stopPos := i}::r;
r.reverse
else if s.get i == sep.get j then
let i := s.next i;
let j := sep.next j;
if sep.atEnd j then splitOnAux i i 0 ({str := s, startPos := b, stopPos := i-j}::r)
else splitOnAux b i j r
else splitOnAux b (s.next i) 0 r
def splitOn (s : Substring) (sep : String := " ") : List Substring :=
if sep == "" then [s] else splitOnAux s.str sep s.stopPos s.startPos s.startPos 0 []
@[inline] def foldl {α : Type u} (f : α → Char → α) (a : α) (s : Substring) : α :=
match s with
| ⟨s, b, e⟩ => String.foldlAux f s e b a
@[inline] def foldr {α : Type u} (f : Char → α → α) (a : α) (s : Substring) : α :=
match s with
| ⟨s, b, e⟩ => String.foldrAux f a s e b
@[inline] def any (s : Substring) (p : Char → Bool) : Bool :=
match s with
| ⟨s, b, e⟩ => String.anyAux s e p b
@[inline] def all (s : Substring) (p : Char → Bool) : Bool :=
!s.any (fun c => !p c)
def contains (s : Substring) (c : Char) : Bool :=
s.any (fun a => a == c)
@[specialize] partial def takeWhileAux (s : String) (stopPos : String.Pos) (p : Char → Bool) : String.Pos → String.Pos
| i =>
if i == stopPos then i
else if p (s.get i) then takeWhileAux (s.next i)
else i
@[inline] def takeWhile : Substring → (Char → Bool) → Substring
| ⟨s, b, e⟩, p =>
let e := takeWhileAux s e p b;
⟨s, b, e⟩
@[inline] def dropWhile : Substring → (Char → Bool) → Substring
| ⟨s, b, e⟩, p =>
let b := takeWhileAux s e p b;
⟨s, b, e⟩
@[specialize] partial def takeRightWhileAux (s : String) (begPos : String.Pos) (p : Char → Bool) : String.Pos → String.Pos
| i =>
if i == begPos then i
else
let i' := s.prev i;
let c := s.get i';
if !p c then i
else takeRightWhileAux i'
@[inline] def takeRightWhile : Substring → (Char → Bool) → Substring
| ⟨s, b, e⟩, p =>
let b := takeRightWhileAux s b p e;
⟨s, b, e⟩
@[inline] def dropRightWhile : Substring → (Char → Bool) → Substring
| ⟨s, b, e⟩, p =>
let e := takeRightWhileAux s b p e;
⟨s, b, e⟩
@[inline] def trimLeft (s : Substring) : Substring :=
s.dropWhile Char.isWhitespace
@[inline] def trimRight (s : Substring) : Substring :=
s.dropRightWhile Char.isWhitespace
@[inline] def trim : Substring → Substring
| ⟨s, b, e⟩ =>
let b := takeWhileAux s e Char.isWhitespace b;
let e := takeRightWhileAux s b Char.isWhitespace e;
⟨s, b, e⟩
def toNat (s : Substring) : Nat :=
s.foldl (fun n c => n*10 + (c.toNat - '0'.toNat)) 0
def isNat (s : Substring) : Bool :=
s.all $ fun c => c.isDigit
end Substring
namespace String
def drop (s : String) (n : Nat) : String :=
(s.toSubstring.drop n).toString
def dropRight (s : String) (n : Nat) : String :=
(s.toSubstring.dropRight n).toString
def take (s : String) (n : Nat) : String :=
(s.toSubstring.take n).toString
def takeRight (s : String) (n : Nat) : String :=
(s.toSubstring.takeRight n).toString
def takeWhile (s : String) (p : Char → Bool) : String :=
(s.toSubstring.takeWhile p).toString
def dropWhile (s : String) (p : Char → Bool) : String :=
(s.toSubstring.dropWhile p).toString
def trimRight (s : String) : String :=
s.toSubstring.trimRight.toString
def trimLeft (s : String) : String :=
s.toSubstring.trimLeft.toString
def trim (s : String) : String :=
s.toSubstring.trim.toString
@[inline] def nextWhile (s : String) (p : Char → Bool) (i : String.Pos) : String.Pos :=
Substring.takeWhileAux s s.bsize p i
@[inline] def nextUntil (s : String) (p : Char → Bool) (i : String.Pos) : String.Pos :=
nextWhile s (fun c => !p c) i
end String
protected def Char.toString (c : Char) : String :=
String.singleton c
|
1512354448a4b5daf25309929fce92a50ba52858 | e00ea76a720126cf9f6d732ad6216b5b824d20a7 | /src/category_theory/functor_category.lean | faa4f6b1515660ddf8ebf355ebf1a627cdb0d2e3 | [
"Apache-2.0"
] | permissive | vaibhavkarve/mathlib | a574aaf68c0a431a47fa82ce0637f0f769826bfe | 17f8340912468f49bdc30acdb9a9fa02eeb0473a | refs/heads/master | 1,621,263,802,637 | 1,585,399,588,000 | 1,585,399,588,000 | 250,833,447 | 0 | 0 | Apache-2.0 | 1,585,410,341,000 | 1,585,410,341,000 | null | UTF-8 | Lean | false | false | 4,228 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn
-/
import category_theory.natural_transformation
namespace category_theory
universes v₁ v₂ v₃ u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation
open nat_trans category category_theory.functor
variables (C : Type u₁) [𝒞 : category.{v₁} C] (D : Type u₂) [𝒟 : category.{v₂} D]
include 𝒞 𝒟
local attribute [simp] vcomp_app
/--
`functor.category C D` gives the category structure on functors and natural transformations
between categories `C` and `D`.
Notice that if `C` and `D` are both small categories at the same universe level,
this is another small category at that level.
However if `C` and `D` are both large categories at the same universe level,
this is a small category at the next higher level.
-/
instance functor.category : category.{(max u₁ v₂)} (C ⥤ D) :=
{ hom := λ F G, nat_trans F G,
id := λ F, nat_trans.id F,
comp := λ _ _ _ α β, vcomp α β }
variables {C D} {E : Type u₃} [ℰ : category.{v₃} E]
variables {F G H I : C ⥤ D}
namespace nat_trans
@[simp] lemma vcomp_eq_comp (α : F ⟶ G) (β : G ⟶ H) : vcomp α β = α ≫ β := rfl
lemma vcomp_app' (α : F ⟶ G) (β : G ⟶ H) (X : C) :
(α ≫ β).app X = (α.app X) ≫ (β.app X) := rfl
lemma congr_app {α β : F ⟶ G} (h : α = β) (X : C) : α.app X = β.app X := by rw h
@[simp] lemma id_app (F : C ⥤ D) (X : C) : (𝟙 F : F ⟶ F).app X = 𝟙 (F.obj X) := rfl
@[simp] lemma comp_app {F G H : C ⥤ D} (α : F ⟶ G) (β : G ⟶ H) (X : C) :
(α ≫ β).app X = α.app X ≫ β.app X := rfl
include ℰ
lemma app_naturality {F G : C ⥤ (D ⥤ E)} (T : F ⟶ G) (X : C) {Y Z : D} (f : Y ⟶ Z) :
((F.obj X).map f) ≫ ((T.app X).app Z) = ((T.app X).app Y) ≫ ((G.obj X).map f) :=
(T.app X).naturality f
lemma naturality_app {F G : C ⥤ (D ⥤ E)} (T : F ⟶ G) (Z : D) {X Y : C} (f : X ⟶ Y) :
((F.map f).app Z) ≫ ((T.app Y).app Z) = ((T.app X).app Z) ≫ ((G.map f).app Z) :=
congr_fun (congr_arg app (T.naturality f)) Z
/-- `hcomp α β` is the horizontal composition of natural transformations. -/
def hcomp {H I : D ⥤ E} (α : F ⟶ G) (β : H ⟶ I) : (F ⋙ H) ⟶ (G ⋙ I) :=
{ app := λ X : C, (β.app (F.obj X)) ≫ (I.map (α.app X)),
naturality' := λ X Y f,
begin
rw [functor.comp_map, functor.comp_map, ←assoc, naturality, assoc,
←map_comp I, naturality, map_comp, assoc]
end }
infix ` ◫ `:80 := hcomp
@[simp] lemma hcomp_app {H I : D ⥤ E} (α : F ⟶ G) (β : H ⟶ I) (X : C) :
(α ◫ β).app X = (β.app (F.obj X)) ≫ (I.map (α.app X)) := rfl
-- Note that we don't yet prove a `hcomp_assoc` lemma here: even stating it is painful, because we
-- need to use associativity of functor composition. (It's true without the explicit associator,
-- because functor composition is definitionally associative, but relying on the definitional equality
-- causes bad problems with elaboration later.)
lemma exchange {I J K : D ⥤ E} (α : F ⟶ G) (β : G ⟶ H)
(γ : I ⟶ J) (δ : J ⟶ K) : (α ≫ β) ◫ (γ ≫ δ) = (α ◫ γ) ≫ (β ◫ δ) :=
by { ext, dsimp, rw [assoc, assoc, map_comp, ←assoc _ (δ.app _), ← naturality, assoc] }
end nat_trans
open nat_trans
namespace functor
include ℰ
protected def flip (F : C ⥤ (D ⥤ E)) : D ⥤ (C ⥤ E) :=
{ obj := λ k,
{ obj := λ j, (F.obj j).obj k,
map := λ j j' f, (F.map f).app k,
map_id' := λ X, begin rw category_theory.functor.map_id, refl end,
map_comp' := λ X Y Z f g, by rw [map_comp, ←comp_app] },
map := λ c c' f,
{ app := λ j, (F.obj j).map f } }.
@[simp] lemma flip_obj_obj (F : C ⥤ (D ⥤ E)) (c) (d) : (F.flip.obj d).obj c = (F.obj c).obj d := rfl
@[simp] lemma flip_obj_map (F : C ⥤ (D ⥤ E)) {c c' : C} (f : c ⟶ c') (d : D) :
(F.flip.obj d).map f = (F.map f).app d := rfl
@[simp] lemma flip_map_app (F : C ⥤ (D ⥤ E)) {d d' : D} (f : d ⟶ d') (c : C) :
(F.flip.map f).app c = (F.obj c).map f := rfl
end functor
end category_theory
|
055628b1e8d654817bbca3ed9db64d8dbf9f78b5 | d642a6b1261b2cbe691e53561ac777b924751b63 | /src/algebra/pi_instances.lean | 6fd375338c3b23fab8a2c805f965bd1ed79f7a19 | [
"Apache-2.0"
] | permissive | cipher1024/mathlib | fee56b9954e969721715e45fea8bcb95f9dc03fe | d077887141000fefa5a264e30fa57520e9f03522 | refs/heads/master | 1,651,806,490,504 | 1,573,508,694,000 | 1,573,508,694,000 | 107,216,176 | 0 | 0 | Apache-2.0 | 1,647,363,136,000 | 1,508,213,014,000 | Lean | UTF-8 | Lean | false | false | 18,362 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Patrick Massot
Pi instances for algebraic structures.
-/
import order.basic
import algebra.module algebra.group
import data.finset
import ring_theory.subring
import tactic.pi_instances
namespace pi
universes u v w
variable {I : Type u} -- The indexing type
variable {f : I → Type v} -- The family of types already equiped with instances
variables (x y : Π i, f i) (i : I)
instance has_zero [∀ i, has_zero $ f i] : has_zero (Π i : I, f i) := ⟨λ i, 0⟩
@[simp] lemma zero_apply [∀ i, has_zero $ f i] : (0 : Π i, f i) i = 0 := rfl
instance has_one [∀ i, has_one $ f i] : has_one (Π i : I, f i) := ⟨λ i, 1⟩
@[simp] lemma one_apply [∀ i, has_one $ f i] : (1 : Π i, f i) i = 1 := rfl
attribute [to_additive] pi.has_one
attribute [to_additive] pi.one_apply
instance has_add [∀ i, has_add $ f i] : has_add (Π i : I, f i) := ⟨λ x y, λ i, x i + y i⟩
@[simp] lemma add_apply [∀ i, has_add $ f i] : (x + y) i = x i + y i := rfl
instance has_mul [∀ i, has_mul $ f i] : has_mul (Π i : I, f i) := ⟨λ x y, λ i, x i * y i⟩
@[simp] lemma mul_apply [∀ i, has_mul $ f i] : (x * y) i = x i * y i := rfl
attribute [to_additive] pi.has_mul
attribute [to_additive] pi.mul_apply
instance has_inv [∀ i, has_inv $ f i] : has_inv (Π i : I, f i) := ⟨λ x, λ i, (x i)⁻¹⟩
@[simp] lemma inv_apply [∀ i, has_inv $ f i] : x⁻¹ i = (x i)⁻¹ := rfl
instance has_neg [∀ i, has_neg $ f i] : has_neg (Π i : I, f i) := ⟨λ x, λ i, -(x i)⟩
@[simp] lemma neg_apply [∀ i, has_neg $ f i] : (-x) i = -x i := rfl
attribute [to_additive] pi.has_inv
attribute [to_additive] pi.inv_apply
instance has_scalar {α : Type*} [∀ i, has_scalar α $ f i] : has_scalar α (Π i : I, f i) := ⟨λ s x, λ i, s • (x i)⟩
@[simp] lemma smul_apply {α : Type*} [∀ i, has_scalar α $ f i] (s : α) : (s • x) i = s • x i := rfl
instance semigroup [∀ i, semigroup $ f i] : semigroup (Π i : I, f i) := by pi_instance
instance comm_semigroup [∀ i, comm_semigroup $ f i] : comm_semigroup (Π i : I, f i) := by pi_instance
instance monoid [∀ i, monoid $ f i] : monoid (Π i : I, f i) := by pi_instance
instance comm_monoid [∀ i, comm_monoid $ f i] : comm_monoid (Π i : I, f i) := by pi_instance
instance group [∀ i, group $ f i] : group (Π i : I, f i) := by pi_instance
instance comm_group [∀ i, comm_group $ f i] : comm_group (Π i : I, f i) := by pi_instance
instance add_semigroup [∀ i, add_semigroup $ f i] : add_semigroup (Π i : I, f i) := by pi_instance
instance add_comm_semigroup [∀ i, add_comm_semigroup $ f i] : add_comm_semigroup (Π i : I, f i) := by pi_instance
instance add_monoid [∀ i, add_monoid $ f i] : add_monoid (Π i : I, f i) := by pi_instance
instance add_comm_monoid [∀ i, add_comm_monoid $ f i] : add_comm_monoid (Π i : I, f i) := by pi_instance
instance add_group [∀ i, add_group $ f i] : add_group (Π i : I, f i) := by pi_instance
instance add_comm_group [∀ i, add_comm_group $ f i] : add_comm_group (Π i : I, f i) := by pi_instance
instance ring [∀ i, ring $ f i] : ring (Π i : I, f i) := by pi_instance
instance comm_ring [∀ i, comm_ring $ f i] : comm_ring (Π i : I, f i) := by pi_instance
instance mul_action (α) {m : monoid α} [∀ i, mul_action α $ f i] : mul_action α (Π i : I, f i) :=
{ smul := λ c f i, c • f i,
mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _,
one_smul := λ f, funext $ λ i, one_smul α _ }
instance distrib_mul_action (α) {m : monoid α} [∀ i, add_monoid $ f i] [∀ i, distrib_mul_action α $ f i] : distrib_mul_action α (Π i : I, f i) :=
{ smul_zero := λ c, funext $ λ i, smul_zero _,
smul_add := λ c f g, funext $ λ i, smul_add _ _ _,
..pi.mul_action _ }
variables (I f)
instance semimodule (α) {r : semiring α} [∀ i, add_comm_monoid $ f i] [∀ i, semimodule α $ f i] : semimodule α (Π i : I, f i) :=
{ add_smul := λ c f g, funext $ λ i, add_smul _ _ _,
zero_smul := λ f, funext $ λ i, zero_smul α _,
..pi.distrib_mul_action _ }
variables {I f}
instance module (α) {r : ring α} [∀ i, add_comm_group $ f i] [∀ i, module α $ f i] : module α (Π i : I, f i) := {..pi.semimodule I f α}
instance vector_space (α) {r : discrete_field α} [∀ i, add_comm_group $ f i] [∀ i, vector_space α $ f i] : vector_space α (Π i : I, f i) := {..pi.module α}
instance left_cancel_semigroup [∀ i, left_cancel_semigroup $ f i] : left_cancel_semigroup (Π i : I, f i) :=
by pi_instance
instance add_left_cancel_semigroup [∀ i, add_left_cancel_semigroup $ f i] : add_left_cancel_semigroup (Π i : I, f i) :=
by pi_instance
instance right_cancel_semigroup [∀ i, right_cancel_semigroup $ f i] : right_cancel_semigroup (Π i : I, f i) :=
by pi_instance
instance add_right_cancel_semigroup [∀ i, add_right_cancel_semigroup $ f i] : add_right_cancel_semigroup (Π i : I, f i) :=
by pi_instance
instance ordered_cancel_comm_monoid [∀ i, ordered_cancel_comm_monoid $ f i] : ordered_cancel_comm_monoid (Π i : I, f i) :=
by pi_instance
instance ordered_comm_group [∀ i, ordered_comm_group $ f i] : ordered_comm_group (Π i : I, f i) :=
{ add_lt_add_left := λ a b hab c, ⟨λ i, add_le_add_left (hab.1 i) (c i),
λ h, hab.2 $ λ i, le_of_add_le_add_left (h i)⟩,
add_le_add_left := λ x y hxy c i, add_le_add_left (hxy i) _,
..pi.add_comm_group,
..pi.partial_order }
attribute [to_additive add_semigroup] pi.semigroup
attribute [to_additive add_comm_semigroup] pi.comm_semigroup
attribute [to_additive add_monoid] pi.monoid
attribute [to_additive add_comm_monoid] pi.comm_monoid
attribute [to_additive add_group] pi.group
attribute [to_additive add_comm_group] pi.comm_group
attribute [to_additive add_left_cancel_semigroup] pi.left_cancel_semigroup
attribute [to_additive add_right_cancel_semigroup] pi.right_cancel_semigroup
@[to_additive]
lemma list_prod_apply {α : Type*} {β : α → Type*} [∀a, monoid (β a)] (a : α) :
∀ (l : list (Πa, β a)), l.prod a = (l.map (λf:Πa, β a, f a)).prod
| [] := rfl
| (f :: l) := by simp [mul_apply f l.prod a, list_prod_apply l]
@[to_additive]
lemma multiset_prod_apply {α : Type*} {β : α → Type*} [∀a, comm_monoid (β a)] (a : α)
(s : multiset (Πa, β a)) : s.prod a = (s.map (λf:Πa, β a, f a)).prod :=
quotient.induction_on s $ assume l, begin simp [list_prod_apply a l] end
@[to_additive]
lemma finset_prod_apply {α : Type*} {β : α → Type*} {γ} [∀a, comm_monoid (β a)] (a : α)
(s : finset γ) (g : γ → Πa, β a) : s.prod g a = s.prod (λc, g c a) :=
show (s.val.map g).prod a = (s.val.map (λc, g c a)).prod,
by rw [multiset_prod_apply, multiset.map_map]
instance is_ring_hom_pi
{α : Type u} {β : α → Type v} [R : Π a : α, ring (β a)]
{γ : Type w} [ring γ]
(f : Π a : α, γ → β a) [Rh : Π a : α, is_ring_hom (f a)] :
is_ring_hom (λ x b, f b x) :=
begin
split,
-- It's a pity that these can't be done using `simp` lemmas.
{ ext, rw [is_ring_hom.map_one (f x)], refl, },
{ intros x y, ext1 z, rw [is_ring_hom.map_mul (f z)], refl, },
{ intros x y, ext1 z, rw [is_ring_hom.map_add (f z)], refl, }
end
end pi
namespace prod
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {p q : α × β}
instance [has_add α] [has_add β] : has_add (α × β) :=
⟨λp q, (p.1 + q.1, p.2 + q.2)⟩
@[to_additive]
instance [has_mul α] [has_mul β] : has_mul (α × β) :=
⟨λp q, (p.1 * q.1, p.2 * q.2)⟩
@[simp, to_additive]
lemma fst_mul [has_mul α] [has_mul β] : (p * q).1 = p.1 * q.1 := rfl
@[simp, to_additive]
lemma snd_mul [has_mul α] [has_mul β] : (p * q).2 = p.2 * q.2 := rfl
@[simp, to_additive]
lemma mk_mul_mk [has_mul α] [has_mul β] (a₁ a₂ : α) (b₁ b₂ : β) :
(a₁, b₁) * (a₂, b₂) = (a₁ * a₂, b₁ * b₂) := rfl
instance [has_zero α] [has_zero β] : has_zero (α × β) := ⟨(0, 0)⟩
@[to_additive]
instance [has_one α] [has_one β] : has_one (α × β) := ⟨(1, 1)⟩
@[simp, to_additive]
lemma fst_one [has_one α] [has_one β] : (1 : α × β).1 = 1 := rfl
@[simp, to_additive]
lemma snd_one [has_one α] [has_one β] : (1 : α × β).2 = 1 := rfl
@[to_additive]
lemma one_eq_mk [has_one α] [has_one β] : (1 : α × β) = (1, 1) := rfl
instance [has_neg α] [has_neg β] : has_neg (α × β) := ⟨λp, (- p.1, - p.2)⟩
@[to_additive]
instance [has_inv α] [has_inv β] : has_inv (α × β) := ⟨λp, (p.1⁻¹, p.2⁻¹)⟩
@[simp, to_additive]
lemma fst_inv [has_inv α] [has_inv β] : (p⁻¹).1 = (p.1)⁻¹ := rfl
@[simp, to_additive]
lemma snd_inv [has_inv α] [has_inv β] : (p⁻¹).2 = (p.2)⁻¹ := rfl
@[to_additive]
lemma inv_mk [has_inv α] [has_inv β] (a : α) (b : β) : (a, b)⁻¹ = (a⁻¹, b⁻¹) := rfl
instance [add_semigroup α] [add_semigroup β] : add_semigroup (α × β) :=
{ add_assoc := assume a b c, mk.inj_iff.mpr ⟨add_assoc _ _ _, add_assoc _ _ _⟩,
.. prod.has_add }
@[to_additive add_semigroup]
instance [semigroup α] [semigroup β] : semigroup (α × β) :=
{ mul_assoc := assume a b c, mk.inj_iff.mpr ⟨mul_assoc _ _ _, mul_assoc _ _ _⟩,
.. prod.has_mul }
instance [add_monoid α] [add_monoid β] : add_monoid (α × β) :=
{ zero_add := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨zero_add _, zero_add _⟩,
add_zero := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨add_zero _, add_zero _⟩,
.. prod.add_semigroup, .. prod.has_zero }
@[to_additive add_monoid]
instance [monoid α] [monoid β] : monoid (α × β) :=
{ one_mul := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨one_mul _, one_mul _⟩,
mul_one := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨mul_one _, mul_one _⟩,
.. prod.semigroup, .. prod.has_one }
instance [add_group α] [add_group β] : add_group (α × β) :=
{ add_left_neg := assume a, mk.inj_iff.mpr ⟨add_left_neg _, add_left_neg _⟩,
.. prod.add_monoid, .. prod.has_neg }
@[to_additive add_group]
instance [group α] [group β] : group (α × β) :=
{ mul_left_inv := assume a, mk.inj_iff.mpr ⟨mul_left_inv _, mul_left_inv _⟩,
.. prod.monoid, .. prod.has_inv }
instance [add_comm_semigroup α] [add_comm_semigroup β] : add_comm_semigroup (α × β) :=
{ add_comm := assume a b, mk.inj_iff.mpr ⟨add_comm _ _, add_comm _ _⟩,
.. prod.add_semigroup }
@[to_additive add_comm_semigroup]
instance [comm_semigroup α] [comm_semigroup β] : comm_semigroup (α × β) :=
{ mul_comm := assume a b, mk.inj_iff.mpr ⟨mul_comm _ _, mul_comm _ _⟩,
.. prod.semigroup }
instance [add_comm_monoid α] [add_comm_monoid β] : add_comm_monoid (α × β) :=
{ .. prod.add_comm_semigroup, .. prod.add_monoid }
@[to_additive add_comm_monoid]
instance [comm_monoid α] [comm_monoid β] : comm_monoid (α × β) :=
{ .. prod.comm_semigroup, .. prod.monoid }
instance [add_comm_group α] [add_comm_group β] : add_comm_group (α × β) :=
{ .. prod.add_comm_semigroup, .. prod.add_group }
@[to_additive add_comm_group]
instance [comm_group α] [comm_group β] : comm_group (α × β) :=
{ .. prod.comm_semigroup, .. prod.group }
@[to_additive is_add_monoid_hom]
lemma fst.is_monoid_hom [monoid α] [monoid β] : is_monoid_hom (prod.fst : α × β → α) :=
{ map_mul := λ _ _, rfl, map_one := rfl }
@[to_additive is_add_monoid_hom]
lemma snd.is_monoid_hom [monoid α] [monoid β] : is_monoid_hom (prod.snd : α × β → β) :=
{ map_mul := λ _ _, rfl, map_one := rfl }
@[to_additive is_add_group_hom]
lemma fst.is_group_hom [group α] [group β] : is_group_hom (prod.fst : α × β → α) :=
{ map_mul := λ _ _, rfl }
@[to_additive is_add_group_hom]
lemma snd.is_group_hom [group α] [group β] : is_group_hom (prod.snd : α × β → β) :=
{ map_mul := λ _ _, rfl }
attribute [instance] fst.is_monoid_hom fst.is_add_monoid_hom snd.is_monoid_hom snd.is_add_monoid_hom
fst.is_group_hom fst.is_add_group_hom snd.is_group_hom snd.is_add_group_hom
@[to_additive]
lemma fst_prod [comm_monoid α] [comm_monoid β] {t : finset γ} {f : γ → α × β} :
(t.prod f).1 = t.prod (λc, (f c).1) :=
(finset.prod_hom prod.fst).symm
@[to_additive]
lemma snd_prod [comm_monoid α] [comm_monoid β] {t : finset γ} {f : γ → α × β} :
(t.prod f).2 = t.prod (λc, (f c).2) :=
(finset.prod_hom prod.snd).symm
instance [semiring α] [semiring β] : semiring (α × β) :=
{ zero_mul := λ a, mk.inj_iff.mpr ⟨zero_mul _, zero_mul _⟩,
mul_zero := λ a, mk.inj_iff.mpr ⟨mul_zero _, mul_zero _⟩,
left_distrib := λ a b c, mk.inj_iff.mpr ⟨left_distrib _ _ _, left_distrib _ _ _⟩,
right_distrib := λ a b c, mk.inj_iff.mpr ⟨right_distrib _ _ _, right_distrib _ _ _⟩,
..prod.add_comm_monoid, ..prod.monoid }
instance [ring α] [ring β] : ring (α × β) :=
{ ..prod.add_comm_group, ..prod.semiring }
instance [comm_ring α] [comm_ring β] : comm_ring (α × β) :=
{ ..prod.ring, ..prod.comm_monoid }
instance [nonzero_comm_ring α] [comm_ring β] : nonzero_comm_ring (α × β) :=
{ zero_ne_one := mt (congr_arg prod.fst) zero_ne_one,
..prod.comm_ring }
instance fst.is_semiring_hom [semiring α] [semiring β] : is_semiring_hom (prod.fst : α × β → α) :=
by refine_struct {..}; simp
instance snd.is_semiring_hom [semiring α] [semiring β] : is_semiring_hom (prod.snd : α × β → β) :=
by refine_struct {..}; simp
instance fst.is_ring_hom [ring α] [ring β] : is_ring_hom (prod.fst : α × β → α) :=
by refine_struct {..}; simp
instance snd.is_ring_hom [ring α] [ring β] : is_ring_hom (prod.snd : α × β → β) :=
by refine_struct {..}; simp
/-- Left injection function for the inner product
From a vector space (and also group and module) perspective the product is the same as the sum of
two vector spaces. `inl` and `inr` provide the corresponding injection functions.
-/
def inl [has_zero β] (a : α) : α × β := (a, 0)
/-- Right injection function for the inner product -/
def inr [has_zero α] (b : β) : α × β := (0, b)
lemma injective_inl [has_zero β] : function.injective (inl : α → α × β) :=
assume x y h, (prod.mk.inj_iff.mp h).1
lemma injective_inr [has_zero α] : function.injective (inr : β → α × β) :=
assume x y h, (prod.mk.inj_iff.mp h).2
@[simp] lemma inl_eq_inl [has_zero β] {a₁ a₂ : α} : (inl a₁ : α × β) = inl a₂ ↔ a₁ = a₂ :=
iff.intro (assume h, injective_inl h) (assume h, h ▸ rfl)
@[simp] lemma inr_eq_inr [has_zero α] {b₁ b₂ : β} : (inr b₁ : α × β) = inr b₂ ↔ b₁ = b₂ :=
iff.intro (assume h, injective_inr h) (assume h, h ▸ rfl)
@[simp] lemma inl_eq_inr [has_zero α] [has_zero β] {a : α} {b : β} :
inl a = inr b ↔ a = 0 ∧ b = 0 :=
by constructor; simp [inl, inr] {contextual := tt}
@[simp] lemma inr_eq_inl [has_zero α] [has_zero β] {a : α} {b : β} :
inr b = inl a ↔ a = 0 ∧ b = 0 :=
by constructor; simp [inl, inr] {contextual := tt}
@[simp] lemma fst_inl [has_zero β] (a : α) : (inl a : α × β).1 = a := rfl
@[simp] lemma snd_inl [has_zero β] (a : α) : (inl a : α × β).2 = 0 := rfl
@[simp] lemma fst_inr [has_zero α] (b : β) : (inr b : α × β).1 = 0 := rfl
@[simp] lemma snd_inr [has_zero α] (b : β) : (inr b : α × β).2 = b := rfl
instance [has_scalar α β] [has_scalar α γ] : has_scalar α (β × γ) := ⟨λa p, (a • p.1, a • p.2)⟩
@[simp] theorem smul_fst [has_scalar α β] [has_scalar α γ]
(a : α) (x : β × γ) : (a • x).1 = a • x.1 := rfl
@[simp] theorem smul_snd [has_scalar α β] [has_scalar α γ]
(a : α) (x : β × γ) : (a • x).2 = a • x.2 := rfl
@[simp] theorem smul_mk [has_scalar α β] [has_scalar α γ]
(a : α) (b : β) (c : γ) : a • (b, c) = (a • b, a • c) := rfl
instance {r : semiring α} [add_comm_monoid β] [add_comm_monoid γ]
[semimodule α β] [semimodule α γ] : semimodule α (β × γ) :=
{ smul_add := assume a p₁ p₂, mk.inj_iff.mpr ⟨smul_add _ _ _, smul_add _ _ _⟩,
add_smul := assume a p₁ p₂, mk.inj_iff.mpr ⟨add_smul _ _ _, add_smul _ _ _⟩,
mul_smul := assume a₁ a₂ p, mk.inj_iff.mpr ⟨mul_smul _ _ _, mul_smul _ _ _⟩,
one_smul := assume ⟨b, c⟩, mk.inj_iff.mpr ⟨one_smul _ _, one_smul _ _⟩,
zero_smul := assume ⟨b, c⟩, mk.inj_iff.mpr ⟨zero_smul _ _, zero_smul _ _⟩,
smul_zero := assume a, mk.inj_iff.mpr ⟨smul_zero _, smul_zero _⟩,
.. prod.has_scalar }
instance {r : ring α} [add_comm_group β] [add_comm_group γ]
[module α β] [module α γ] : module α (β × γ) := {}
instance {r : discrete_field α} [add_comm_group β] [add_comm_group γ]
[vector_space α β] [vector_space α γ] : vector_space α (β × γ) := {}
section substructures
variables (s : set α) (t : set β)
@[to_additive is_add_submonoid]
instance [monoid α] [monoid β] [is_submonoid s] [is_submonoid t] :
is_submonoid (s.prod t) :=
{ one_mem := by rw set.mem_prod; split; apply is_submonoid.one_mem,
mul_mem := by intros; rw set.mem_prod at *; split; apply is_submonoid.mul_mem; tauto }
@[to_additive prod.is_add_subgroup.prod]
instance is_subgroup.prod [group α] [group β] [is_subgroup s] [is_subgroup t] :
is_subgroup (s.prod t) :=
{ inv_mem := by intros; rw set.mem_prod at *; split; apply is_subgroup.inv_mem; tauto,
.. prod.is_submonoid s t }
instance is_subring.prod [ring α] [ring β] [is_subring s] [is_subring t] :
is_subring (s.prod t) :=
{ .. prod.is_submonoid s t, .. prod.is_add_subgroup.prod s t }
end substructures
end prod
namespace finset
@[to_additive prod_mk_sum]
lemma prod_mk_prod {α β γ : Type*} [comm_monoid α] [comm_monoid β] (s : finset γ)
(f : γ → α) (g : γ → β) : (s.prod f, s.prod g) = s.prod (λ x, (f x, g x)) :=
by haveI := classical.dec_eq γ; exact
finset.induction_on s rfl (by simp [prod.ext_iff] {contextual := tt})
end finset
|
cd840493d3c917e32db555e712dbef6bdee53188 | d7189ea2ef694124821b033e533f18905b5e87ef | /galois/network/action.lean | f7d0b44f10c4b207832c383b8a5f43b1de8812f0 | [
"Apache-2.0"
] | permissive | digama0/lean-protocol-support | eaa7e6f8b8e0d5bbfff1f7f52bfb79a3b11b0f59 | cabfa3abedbdd6fdca6e2da6fbbf91a13ed48dda | refs/heads/master | 1,625,421,450,627 | 1,506,035,462,000 | 1,506,035,462,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,317 | lean | import galois.map.fmap_func
galois.network.labels
universes u v
namespace network
inductive act (A : Type u) : Type u
-- return a poll result and the amount of time elapsed
| poll : Π (ports : list port) (sockets : list socket) (bound : time),
(poll_result ports sockets bound → (list (socket × message_t) × A)) → act
namespace act
def just_send_messages {A : Type u} (ms : list (socket × message_t))
(x : A) := act.poll [] [] 0 (λ _, (ms, x))
def return {A : Type u} (x : A) : act A := just_send_messages [] x
end act
/-- Indicates that an agent is polling -/
inductive polls_on_socket {A : Type u} (s : socket) : act A → Prop
| mk : ∀ ports sockets bound cont, 0 < bound → s ∈ sockets
→ polls_on_socket (act.poll ports sockets bound cont)
instance polls_decidable {A : Type} (s : socket) : decidable_pred (@polls_on_socket A s)
:= begin
intros x, induction x,
apply (if H : 0 < bound ∧ s ∈ sockets then _ else _),
{ apply decidable.is_true, induction H with H1 H2,
constructor; assumption },
{ apply decidable.is_false, intros contra, cases contra,
apply H, split; assumption }
end
-- An agent is defined as a type for the internal state, an process that produces
-- the state, and a looping process that will execute when the process is complete.
--
-- Semantically, think of the behavior as `next >>= forever loop` where
-- `forever loop = loop >=> forever loop`.
structure agent : Type 1 :=
(state_type : Type)
(loop : state_type → act state_type)
inductive dlabel {A : Type u} : act A → Type u
| poll : ∀ (ports : list port) (sockets : list socket) (bound : time) cont
(r : poll_result ports sockets bound),
dlabel (act.poll ports sockets bound cont)
namespace dlabel
def cont_result {A : Type u} : ∀ {next : act A} (la : dlabel next),
list (socket × message_t) × A
| (act.poll ports sockets bound cont) (dlabel.poll ._ ._ ._ ._ r) := cont r
def messages {A : Type u} {next : act A} (la : dlabel next) : list (socket × message_t)
:= la.cont_result.fst
lemma invert {A : Type u}
{ports sockets bound cont} (l : @dlabel A (act.poll ports sockets bound cont))
: ∃ r : poll_result ports sockets bound,
l = dlabel.poll ports sockets bound cont r
:= begin
cases l, constructor, reflexivity
end
end dlabel
end network |
f971148d1df41a9f3de13ea0f6a7d1bb5ccb16a5 | b00eb947a9c4141624aa8919e94ce6dcd249ed70 | /stage0/src/Init/Data/List/Basic.lean | f3a78bb2214d2ab400c20e890d9c483e966cf73c | [
"Apache-2.0"
] | permissive | gebner/lean4-old | a4129a041af2d4d12afb3a8d4deedabde727719b | ee51cdfaf63ee313c914d83264f91f414a0e3b6e | refs/heads/master | 1,683,628,606,745 | 1,622,651,300,000 | 1,622,654,405,000 | 142,608,821 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 11,382 | 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.SimpLemmas
import Init.Data.Nat.Basic
open Decidable List
universes u v w
variable {α : Type u} {β : Type v} {γ : Type w}
namespace List
@[simp] theorem length_nil : length ([] : List α) = 0 :=
rfl
def reverseAux : List α → List α → List α
| [], r => r
| a::l, r => reverseAux l (a::r)
def reverse (as : List α) :List α :=
reverseAux as []
protected def append (as bs : List α) : List α :=
reverseAux as.reverse bs
instance : Append (List α) := ⟨List.append⟩
theorem reverseAux_reverseAux_nil (as bs : List α) : reverseAux (reverseAux as bs) [] = reverseAux bs as := by
induction as generalizing bs with
| nil => rfl
| cons a as ih => simp [reverseAux, ih]
@[simp] theorem nil_append (as : List α) : [] ++ as = as := rfl
@[simp] theorem append_nil (as : List α) : as ++ [] = as := by
show reverseAux (reverseAux as []) [] = as
simp [reverseAux_reverseAux_nil, reverseAux]
theorem reverseAux_reverseAux (as bs cs : List α) : reverseAux (reverseAux as bs) cs = reverseAux bs (reverseAux (reverseAux as []) cs) := by
induction as generalizing bs cs with
| nil => rfl
| cons a as ih => simp [reverseAux, ih (a::bs), ih [a]]
@[simp] theorem cons_append (a : α) (as bs : List α) : (a::as) ++ bs = a::(as ++ bs) :=
reverseAux_reverseAux as [a] bs
theorem append_assoc (as bs cs : List α) : (as ++ bs) ++ cs = as ++ (bs ++ cs) := by
induction as with
| nil => rfl
| cons a as ih => simp [ih]
instance : EmptyCollection (List α) := ⟨List.nil⟩
protected def erase {α} [BEq α] : List α → α → List α
| [], b => []
| a::as, b => match a == b with
| true => as
| false => a :: List.erase as b
def eraseIdx : List α → Nat → List α
| [], _ => []
| a::as, 0 => as
| a::as, n+1 => a :: eraseIdx as n
def isEmpty : List α → Bool
| [] => true
| _ :: _ => false
@[specialize] def map (f : α → β) : List α → List β
| [] => []
| a::as => f a :: map f as
@[specialize] def map₂ (f : α → β → γ) : List α → List β → List γ
| [], _ => []
| _, [] => []
| a::as, b::bs => f a b :: map₂ f as bs
def join : List (List α) → List α
| [] => []
| a :: as => a ++ join as
@[specialize] def filterMap (f : α → Option β) : List α → List β
| [] => []
| a::as =>
match f a with
| none => filterMap f as
| some b => b :: filterMap f as
@[specialize] def filterAux (p : α → Bool) : List α → List α → List α
| [], rs => rs.reverse
| a::as, rs => match p a with
| true => filterAux p as (a::rs)
| false => filterAux p as rs
@[inline] def filter (p : α → Bool) (as : List α) : List α :=
filterAux p as []
@[specialize] def partitionAux (p : α → Bool) : List α → List α × List α → List α × List α
| [], (bs, cs) => (bs.reverse, cs.reverse)
| a::as, (bs, cs) =>
match p a with
| true => partitionAux p as (a::bs, cs)
| false => partitionAux p as (bs, a::cs)
@[inline] def partition (p : α → Bool) (as : List α) : List α × List α :=
partitionAux p as ([], [])
def dropWhile (p : α → Bool) : List α → List α
| [] => []
| a::l => match p a with
| true => dropWhile p l
| false => a::l
def find? (p : α → Bool) : List α → Option α
| [] => none
| a::as => match p a with
| true => some a
| false => find? p as
def findSome? (f : α → Option β) : List α → Option β
| [] => none
| a::as => match f a with
| some b => some b
| none => findSome? f as
def replace [BEq α] : List α → α → α → List α
| [], _, _ => []
| a::as, b, c => match a == b with
| true => c::as
| false => a :: (replace as b c)
def elem [BEq α] (a : α) : List α → Bool
| [] => false
| b::bs => match a == b with
| true => true
| false => elem a bs
def notElem [BEq α] (a : α) (as : List α) : Bool :=
!(as.elem a)
abbrev contains [BEq α] (as : List α) (a : α) : Bool :=
elem a as
def eraseDupsAux {α} [BEq α] : List α → List α → List α
| [], bs => bs.reverse
| a::as, bs => match bs.elem a with
| true => eraseDupsAux as bs
| false => eraseDupsAux as (a::bs)
def eraseDups {α} [BEq α] (as : List α) : List α :=
eraseDupsAux as []
def eraseRepsAux {α} [BEq α] : α → List α → List α → List α
| a, [], rs => (a::rs).reverse
| a, a'::as, rs => match a == a' with
| true => eraseRepsAux a as rs
| false => eraseRepsAux a' as (a::rs)
/-- Erase repeated adjacent elements. -/
def eraseReps {α} [BEq α] : List α → List α
| [] => []
| a::as => eraseRepsAux a as []
@[specialize] def spanAux (p : α → Bool) : List α → List α → List α × List α
| [], rs => (rs.reverse, [])
| a::as, rs => match p a with
| true => spanAux p as (a::rs)
| false => (rs.reverse, a::as)
@[inline] def span (p : α → Bool) (as : List α) : List α × List α :=
spanAux p as []
@[specialize] def groupByAux (eq : α → α → Bool) : List α → List (List α) → List (List α)
| a::as, (ag::g)::gs => match eq a ag with
| true => groupByAux eq as ((a::ag::g)::gs)
| false => groupByAux eq as ([a]::(ag::g).reverse::gs)
| _, gs => gs.reverse
@[specialize] def groupBy (p : α → α → Bool) : List α → List (List α)
| [] => []
| a::as => groupByAux p as [[a]]
def lookup [BEq α] : α → List (α × β) → Option β
| _, [] => none
| a, (k,b)::es => match a == k with
| true => some b
| false => lookup a es
def removeAll [BEq α] (xs ys : List α) : List α :=
xs.filter (fun x => ys.notElem x)
def drop : Nat → List α → List α
| 0, a => a
| n+1, [] => []
| n+1, a::as => drop n as
def take : Nat → List α → List α
| 0, a => []
| n+1, [] => []
| n+1, a::as => a :: take n as
@[specialize] def foldr (f : α → β → β) (init : β) : List α → β
| [] => init
| a :: l => f a (foldr f init l)
@[inline] def any (l : List α) (p : α → Bool) : Bool :=
foldr (fun a r => p a || r) false l
@[inline] def all (l : List α) (p : α → Bool) : Bool :=
foldr (fun a r => p a && r) true l
def or (bs : List Bool) : Bool := bs.any id
def and (bs : List Bool) : Bool := bs.all id
def zipWith (f : α → β → γ) : List α → List β → List γ
| x::xs, y::ys => f x y :: zipWith f xs ys
| _, _ => []
def zip : List α → List β → List (Prod α β) :=
zipWith Prod.mk
def unzip : List (α × β) → List α × List β
| [] => ([], [])
| (a, b) :: t => match unzip t with | (al, bl) => (a::al, b::bl)
def rangeAux : Nat → List Nat → List Nat
| 0, ns => ns
| n+1, ns => rangeAux n (n::ns)
def range (n : Nat) : List Nat :=
rangeAux n []
def iota : Nat → List Nat
| 0 => []
| m@(n+1) => m :: iota n
def enumFrom : Nat → List α → List (Nat × α)
| n, [] => nil
| n, x :: xs => (n, x) :: enumFrom (n + 1) xs
def enum : List α → List (Nat × α) := enumFrom 0
def init : List α → List α
| [] => []
| [a] => []
| a::l => a::init l
def intersperse (sep : α) : List α → List α
| [] => []
| [x] => [x]
| x::xs => x :: sep :: intersperse sep xs
def intercalate (sep : List α) (xs : List (List α)) : List α :=
join (intersperse sep xs)
@[inline] protected def bind {α : Type u} {β : Type v} (a : List α) (b : α → List β) : List β := join (map b a)
@[inline] protected def pure {α : Type u} (a : α) : List α := [a]
inductive lt [LT α] : List α → List α → Prop where
| nil (b : α) (bs : List α) : lt [] (b::bs)
| head {a : α} (as : List α) {b : α} (bs : List α) : a < b → lt (a::as) (b::bs)
| tail {a : α} {as : List α} {b : α} {bs : List α} : ¬ a < b → ¬ b < a → lt as bs → lt (a::as) (b::bs)
instance [LT α] : LT (List α) := ⟨List.lt⟩
instance hasDecidableLt [LT α] [h : DecidableRel (α:=α) (·<·)] : (l₁ l₂ : List α) → Decidable (l₁ < l₂)
| [], [] => isFalse (fun h => nomatch h)
| [], b::bs => isTrue (List.lt.nil _ _)
| a::as, [] => isFalse (fun h => nomatch h)
| a::as, b::bs =>
match h a b with
| isTrue h₁ => isTrue (List.lt.head _ _ h₁)
| isFalse h₁ =>
match h b a with
| isTrue h₂ => isFalse (fun h => match h with
| List.lt.head _ _ h₁' => absurd h₁' h₁
| List.lt.tail _ h₂' _ => absurd h₂ h₂')
| isFalse h₂ =>
match hasDecidableLt as bs with
| isTrue h₃ => isTrue (List.lt.tail h₁ h₂ h₃)
| isFalse h₃ => isFalse (fun h => match h with
| List.lt.head _ _ h₁' => absurd h₁' h₁
| List.lt.tail _ _ h₃' => absurd h₃' h₃)
@[reducible] protected def le [LT α] (a b : List α) : Prop := ¬ b < a
instance [LT α] : LE (List α) := ⟨List.le⟩
instance [LT α] [h : DecidableRel ((· < ·) : α → α → Prop)] : (l₁ l₂ : List α) → Decidable (l₁ ≤ l₂) :=
fun a b => inferInstanceAs (Decidable (Not _))
/-- `isPrefixOf l₁ l₂` returns `true` Iff `l₁` is a prefix of `l₂`. -/
def isPrefixOf [BEq α] : List α → List α → Bool
| [], _ => true
| _, [] => false
| a::as, b::bs => a == b && isPrefixOf as bs
/-- `isSuffixOf l₁ l₂` returns `true` Iff `l₁` is a suffix of `l₂`. -/
def isSuffixOf [BEq α] (l₁ l₂ : List α) : Bool :=
isPrefixOf l₁.reverse l₂.reverse
@[specialize] def isEqv : List α → List α → (α → α → Bool) → Bool
| [], [], _ => true
| a::as, b::bs, eqv => eqv a b && isEqv as bs eqv
| _, _, eqv => false
protected def beq [BEq α] : List α → List α → Bool
| [], [] => true
| a::as, b::bs => a == b && List.beq as bs
| _, _ => false
instance [BEq α] : BEq (List α) := ⟨List.beq⟩
def replicate {α : Type u} (n : Nat) (a : α) : List α :=
let rec loop : Nat → List α → List α
| 0, as => as
| n+1, as => loop n (a::as)
loop n []
def dropLast {α} : List α → List α
| [] => []
| [a] => []
| a::as => a :: dropLast as
@[simp] theorem length_replicate (n : Nat) (a : α) : (replicate n a).length = n :=
let rec aux (n : Nat) (as : List α) : (replicate.loop a n as).length = n + as.length := by
induction n generalizing as with
| zero => simp [replicate.loop]
| succ n ih => simp [replicate.loop, ih, Nat.succ_add, Nat.add_succ]
aux n []
@[simp] theorem length_concat (as : List α) (a : α) : (concat as a).length = as.length + 1 := by
induction as with
| nil => rfl
| cons x xs ih => simp [concat, ih]
@[simp] theorem length_set (as : List α) (i : Nat) (a : α) : (as.set i a).length = as.length := by
induction as generalizing i with
| nil => rfl
| cons x xs ih =>
cases i with
| zero => rfl
| succ i => simp [set, ih]
@[simp] theorem length_dropLast (as : List α) : as.dropLast.length = as.length - 1 := by
match as with
| [] => rfl
| [a] => rfl
| a::b::as =>
have ih := length_dropLast (b::as)
simp[dropLast, ih]
rfl
end List
|
908d5b235e04327b2890f3542c3c5f21d621db2e | de91c42b87530c3bdcc2b138ef1a3c3d9bee0d41 | /old/expressions/language_expressions.lean | 435587f0a602d9db906f80cbd5d0c0d4ffd2b295 | [] | 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 | 20 | lean | import .expression
|
7c0f3d9603b5c1306a782dd3f2b7e138698067b3 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/equiv/basic.lean | 67f841b00ddaa60d0f97bcafbfde75b06082db4f | [] | 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 | 97,090 | 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, Mario Carneiro
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.set.function
import Mathlib.PostPort
universes u_1 u_2 l u v w u_3 u' v' u_4 u_5 u_6 ua1 ua2 ub1 ub2 ug1 ug2 z
namespace Mathlib
/-!
# Equivalence between types
In this file we define two types:
* `equiv α β` a.k.a. `α ≃ β`: a bijective map `α → β` bundled with its inverse map; we use this (and
not equality!) to express that various `Type`s or `Sort`s are equivalent.
* `equiv.perm α`: the group of permutations `α ≃ α`. More lemmas about `equiv.perm` can be found in
`group_theory/perm`.
Then we define
* canonical isomorphisms between various types: e.g.,
- `equiv.refl α` is the identity map interpreted as `α ≃ α`;
- `equiv.sum_equiv_sigma_bool` is the canonical equivalence between the sum of two types `α ⊕ β`
and the sigma-type `Σ b : bool, cond b α β`;
- `equiv.prod_sum_distrib : α × (β ⊕ γ) ≃ (α × β) ⊕ (α × γ)` shows that type product and type sum
satisfy the distributive law up to a canonical equivalence;
* operations on equivalences: e.g.,
- `equiv.symm e : β ≃ α` is the inverse of `e : α ≃ β`;
- `equiv.trans e₁ e₂ : α ≃ γ` is the composition of `e₁ : α ≃ β` and `e₂ : β ≃ γ` (note the order
of the arguments!);
- `equiv.prod_congr ea eb : α₁ × β₁ ≃ α₂ × β₂`: combine two equivalences `ea : α₁ ≃ α₂` and
`eb : β₁ ≃ β₂` using `prod.map`.
* definitions that transfer some instances along an equivalence. By convention, we transfer
instances from right to left.
- `equiv.inhabited` takes `e : α ≃ β` and `[inhabited β]` and returns `inhabited α`;
- `equiv.unique` takes `e : α ≃ β` and `[unique β]` and returns `unique α`;
- `equiv.decidable_eq` takes `e : α ≃ β` and `[decidable_eq β]` and returns `decidable_eq α`.
More definitions of this kind can be found in other files. E.g., `data/equiv/transfer_instance`
does it for many algebraic type classes like `group`, `module`, etc.
## Tags
equivalence, congruence, bijective map
-/
/-- `α ≃ β` is the type of functions from `α → β` with a two-sided inverse. -/
structure equiv (α : Sort u_1) (β : Sort u_2)
where
to_fun : α → β
inv_fun : β → α
left_inv : function.left_inverse inv_fun to_fun
right_inv : function.right_inverse inv_fun to_fun
infixl:25 " ≃ " => Mathlib.equiv
/-- Convert an involutive function `f` to an equivalence with `to_fun = inv_fun = f`. -/
def function.involutive.to_equiv {α : Sort u} (f : α → α) (h : function.involutive f) : α ≃ α :=
equiv.mk f f (function.involutive.left_inverse h) (function.involutive.right_inverse h)
namespace equiv
/-- `perm α` is the type of bijections from `α` to itself. -/
def perm (α : Sort u_1) :=
α ≃ α
protected instance has_coe_to_fun {α : Sort u} {β : Sort v} : has_coe_to_fun (α ≃ β) :=
has_coe_to_fun.mk (fun (x : α ≃ β) => α → β) to_fun
@[simp] theorem coe_fn_mk {α : Sort u} {β : Sort v} (f : α → β) (g : β → α) (l : function.left_inverse g f) (r : function.right_inverse g f) : ⇑(mk f g l r) = f :=
rfl
/-- The map `coe_fn : (r ≃ s) → (r → s)` is injective. -/
theorem injective_coe_fn {α : Sort u} {β : Sort v} : function.injective fun (e : α ≃ β) (x : α) => coe_fn e x := sorry
@[simp] protected theorem coe_inj {α : Sort u} {β : Sort v} {e₁ : α ≃ β} {e₂ : α ≃ β} : ⇑e₁ = ⇑e₂ ↔ e₁ = e₂ :=
function.injective.eq_iff injective_coe_fn
theorem ext {α : Sort u} {β : Sort v} {f : α ≃ β} {g : α ≃ β} (H : ∀ (x : α), coe_fn f x = coe_fn g x) : f = g :=
injective_coe_fn (funext H)
protected theorem congr_arg {α : Sort u} {β : Sort v} {f : α ≃ β} {x : α} {x' : α} : x = x' → coe_fn f x = coe_fn f x' := sorry
protected theorem congr_fun {α : Sort u} {β : Sort v} {f : α ≃ β} {g : α ≃ β} (h : f = g) (x : α) : coe_fn f x = coe_fn g x :=
h ▸ rfl
theorem ext_iff {α : Sort u} {β : Sort v} {f : α ≃ β} {g : α ≃ β} : f = g ↔ ∀ (x : α), coe_fn f x = coe_fn g x :=
{ mp := fun (h : f = g) (x : α) => h ▸ rfl, mpr := ext }
theorem perm.ext {α : Sort u} {σ : perm α} {τ : perm α} (H : ∀ (x : α), coe_fn σ x = coe_fn τ x) : σ = τ :=
ext H
protected theorem perm.congr_arg {α : Sort u} {f : perm α} {x : α} {x' : α} : x = x' → coe_fn f x = coe_fn f x' :=
equiv.congr_arg
protected theorem perm.congr_fun {α : Sort u} {f : perm α} {g : perm α} (h : f = g) (x : α) : coe_fn f x = coe_fn g x :=
equiv.congr_fun h x
theorem perm.ext_iff {α : Sort u} {σ : perm α} {τ : perm α} : σ = τ ↔ ∀ (x : α), coe_fn σ x = coe_fn τ x :=
ext_iff
/-- Any type is equivalent to itself. -/
protected def refl (α : Sort u_1) : α ≃ α :=
mk id id sorry sorry
protected instance inhabited' {α : Sort u} : Inhabited (α ≃ α) :=
{ default := equiv.refl α }
/-- Inverse of an equivalence `e : α ≃ β`. -/
protected def symm {α : Sort u} {β : Sort v} (e : α ≃ β) : β ≃ α :=
mk (inv_fun e) (to_fun e) (right_inv e) (left_inv e)
/-- See Note [custom simps projection] -/
def simps.inv_fun {α : Sort u} {β : Sort v} (e : α ≃ β) : β → α :=
⇑(equiv.symm e)
/-- Composition of equivalences `e₁ : α ≃ β` and `e₂ : β ≃ γ`. -/
protected def trans {α : Sort u} {β : Sort v} {γ : Sort w} (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ :=
mk (⇑e₂ ∘ ⇑e₁) (⇑(equiv.symm e₁) ∘ ⇑(equiv.symm e₂)) sorry sorry
@[simp] theorem to_fun_as_coe {α : Sort u} {β : Sort v} (e : α ≃ β) : to_fun e = ⇑e :=
rfl
@[simp] theorem inv_fun_as_coe {α : Sort u} {β : Sort v} (e : α ≃ β) : inv_fun e = ⇑(equiv.symm e) :=
rfl
protected theorem injective {α : Sort u} {β : Sort v} (e : α ≃ β) : function.injective ⇑e :=
function.left_inverse.injective (left_inv e)
protected theorem surjective {α : Sort u} {β : Sort v} (e : α ≃ β) : function.surjective ⇑e :=
function.right_inverse.surjective (right_inv e)
protected theorem bijective {α : Sort u} {β : Sort v} (f : α ≃ β) : function.bijective ⇑f :=
{ left := equiv.injective f, right := equiv.surjective f }
@[simp] theorem range_eq_univ {α : Type u_1} {β : Type u_2} (e : α ≃ β) : set.range ⇑e = set.univ :=
set.eq_univ_of_forall (equiv.surjective e)
protected theorem subsingleton {α : Sort u} {β : Sort v} (e : α ≃ β) [subsingleton β] : subsingleton α :=
function.injective.subsingleton (equiv.injective e)
protected theorem subsingleton.symm {α : Sort u} {β : Sort v} (e : α ≃ β) [subsingleton α] : subsingleton β :=
function.injective.subsingleton (equiv.injective (equiv.symm e))
protected instance equiv_subsingleton_cod {α : Sort u} {β : Sort v} [subsingleton β] : subsingleton (α ≃ β) :=
subsingleton.intro fun (f g : α ≃ β) => ext fun (x : α) => subsingleton.elim (coe_fn f x) (coe_fn g x)
protected instance equiv_subsingleton_dom {α : Sort u} {β : Sort v} [subsingleton α] : subsingleton (α ≃ β) :=
subsingleton.intro fun (f g : α ≃ β) => ext fun (x : α) => subsingleton.elim (coe_fn f x) (coe_fn g x)
protected instance perm_subsingleton {α : Sort u} [subsingleton α] : subsingleton (perm α) :=
equiv.equiv_subsingleton_cod
theorem perm.subsingleton_eq_refl {α : Sort u} [subsingleton α] (e : perm α) : e = equiv.refl α :=
subsingleton.elim e (equiv.refl α)
/-- Transfer `decidable_eq` across an equivalence. -/
protected def decidable_eq {α : Sort u} {β : Sort v} (e : α ≃ β) [DecidableEq β] : DecidableEq α :=
function.injective.decidable_eq (equiv.injective e)
theorem nonempty_iff_nonempty {α : Sort u} {β : Sort v} (e : α ≃ β) : Nonempty α ↔ Nonempty β :=
nonempty.congr ⇑e ⇑(equiv.symm e)
/-- If `α ≃ β` and `β` is inhabited, then so is `α`. -/
protected def inhabited {α : Sort u} {β : Sort v} [Inhabited β] (e : α ≃ β) : Inhabited α :=
{ default := coe_fn (equiv.symm e) Inhabited.default }
/-- If `α ≃ β` and `β` is a singleton type, then so is `α`. -/
protected def unique {α : Sort u} {β : Sort v} [unique β] (e : α ≃ β) : unique α :=
function.surjective.unique sorry
/-- Equivalence between equal types. -/
protected def cast {α : Sort u_1} {β : Sort u_1} (h : α = β) : α ≃ β :=
mk (cast h) (cast sorry) sorry sorry
@[simp] theorem coe_fn_symm_mk {α : Sort u} {β : Sort v} (f : α → β) (g : β → α) (l : function.left_inverse g f) (r : function.right_inverse g f) : ⇑(equiv.symm (mk f g l r)) = g :=
rfl
@[simp] theorem coe_refl {α : Sort u} : ⇑(equiv.refl α) = id :=
rfl
@[simp] theorem perm.coe_subsingleton {α : Type u_1} [subsingleton α] (e : perm α) : ⇑e = id :=
eq.mpr (id (Eq._oldrec (Eq.refl (⇑e = id)) (perm.subsingleton_eq_refl e)))
(eq.mpr (id (Eq._oldrec (Eq.refl (⇑(equiv.refl α) = id)) coe_refl)) (Eq.refl id))
theorem refl_apply {α : Sort u} (x : α) : coe_fn (equiv.refl α) x = x :=
rfl
@[simp] theorem coe_trans {α : Sort u} {β : Sort v} {γ : Sort w} (f : α ≃ β) (g : β ≃ γ) : ⇑(equiv.trans f g) = ⇑g ∘ ⇑f :=
rfl
theorem trans_apply {α : Sort u} {β : Sort v} {γ : Sort w} (f : α ≃ β) (g : β ≃ γ) (a : α) : coe_fn (equiv.trans f g) a = coe_fn g (coe_fn f a) :=
rfl
@[simp] theorem apply_symm_apply {α : Sort u} {β : Sort v} (e : α ≃ β) (x : β) : coe_fn e (coe_fn (equiv.symm e) x) = x :=
right_inv e x
@[simp] theorem symm_apply_apply {α : Sort u} {β : Sort v} (e : α ≃ β) (x : α) : coe_fn (equiv.symm e) (coe_fn e x) = x :=
left_inv e x
@[simp] theorem symm_comp_self {α : Sort u} {β : Sort v} (e : α ≃ β) : ⇑(equiv.symm e) ∘ ⇑e = id :=
funext (symm_apply_apply e)
@[simp] theorem self_comp_symm {α : Sort u} {β : Sort v} (e : α ≃ β) : ⇑e ∘ ⇑(equiv.symm e) = id :=
funext (apply_symm_apply e)
@[simp] theorem symm_trans_apply {α : Sort u} {β : Sort v} {γ : Sort w} (f : α ≃ β) (g : β ≃ γ) (a : γ) : coe_fn (equiv.symm (equiv.trans f g)) a = coe_fn (equiv.symm f) (coe_fn (equiv.symm g) a) :=
rfl
-- The `simp` attribute is needed to make this a `dsimp` lemma.
-- `simp` will always rewrite with `equiv.symm_symm` before this has a chance to fire.
@[simp] theorem symm_symm_apply {α : Sort u} {β : Sort v} (f : α ≃ β) (b : α) : coe_fn (equiv.symm (equiv.symm f)) b = coe_fn f b :=
rfl
@[simp] theorem apply_eq_iff_eq {α : Sort u} {β : Sort v} (f : α ≃ β) {x : α} {y : α} : coe_fn f x = coe_fn f y ↔ x = y :=
function.injective.eq_iff (equiv.injective f)
theorem apply_eq_iff_eq_symm_apply {α : Sort u_1} {β : Sort u_2} (f : α ≃ β) {x : α} {y : β} : coe_fn f x = y ↔ x = coe_fn (equiv.symm f) y := sorry
@[simp] theorem cast_apply {α : Sort u_1} {β : Sort u_1} (h : α = β) (x : α) : coe_fn (equiv.cast h) x = cast h x :=
rfl
theorem symm_apply_eq {α : Sort u_1} {β : Sort u_2} (e : α ≃ β) {x : β} {y : α} : coe_fn (equiv.symm e) x = y ↔ x = coe_fn e y := sorry
theorem eq_symm_apply {α : Sort u_1} {β : Sort u_2} (e : α ≃ β) {x : β} {y : α} : y = coe_fn (equiv.symm e) x ↔ coe_fn e y = x :=
iff.trans (iff.trans eq_comm (symm_apply_eq e)) eq_comm
@[simp] theorem symm_symm {α : Sort u} {β : Sort v} (e : α ≃ β) : equiv.symm (equiv.symm e) = e := sorry
@[simp] theorem trans_refl {α : Sort u} {β : Sort v} (e : α ≃ β) : equiv.trans e (equiv.refl β) = e := sorry
@[simp] theorem refl_symm {α : Sort u} : equiv.symm (equiv.refl α) = equiv.refl α :=
rfl
@[simp] theorem refl_trans {α : Sort u} {β : Sort v} (e : α ≃ β) : equiv.trans (equiv.refl α) e = e := sorry
@[simp] theorem symm_trans {α : Sort u} {β : Sort v} (e : α ≃ β) : equiv.trans (equiv.symm e) e = equiv.refl β := sorry
@[simp] theorem trans_symm {α : Sort u} {β : Sort v} (e : α ≃ β) : equiv.trans e (equiv.symm e) = equiv.refl α := sorry
theorem trans_assoc {α : Sort u} {β : Sort v} {γ : Sort w} {δ : Sort u_1} (ab : α ≃ β) (bc : β ≃ γ) (cd : γ ≃ δ) : equiv.trans (equiv.trans ab bc) cd = equiv.trans ab (equiv.trans bc cd) :=
ext fun (a : α) => rfl
theorem left_inverse_symm {α : Sort u} {β : Sort v} (f : α ≃ β) : function.left_inverse ⇑(equiv.symm f) ⇑f :=
left_inv f
theorem right_inverse_symm {α : Sort u} {β : Sort v} (f : α ≃ β) : function.right_inverse ⇑(equiv.symm f) ⇑f :=
right_inv f
/-- If `α` is equivalent to `β` and `γ` is equivalent to `δ`, then the type of equivalences `α ≃ γ`
is equivalent to the type of equivalences `β ≃ δ`. -/
def equiv_congr {α : Sort u} {β : Sort v} {γ : Sort w} {δ : Sort u_1} (ab : α ≃ β) (cd : γ ≃ δ) : α ≃ γ ≃ (β ≃ δ) :=
mk (fun (ac : α ≃ γ) => equiv.trans (equiv.trans (equiv.symm ab) ac) cd)
(fun (bd : β ≃ δ) => equiv.trans ab (equiv.trans bd (equiv.symm cd))) sorry sorry
@[simp] theorem equiv_congr_refl {α : Sort u_1} {β : Sort u_2} : equiv_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α ≃ β) :=
ext fun (x : α ≃ β) => ext fun (x_1 : α) => Eq.refl (coe_fn (coe_fn (equiv_congr (equiv.refl α) (equiv.refl β)) x) x_1)
@[simp] theorem equiv_congr_symm {α : Sort u} {β : Sort v} {γ : Sort w} {δ : Sort u_1} (ab : α ≃ β) (cd : γ ≃ δ) : equiv.symm (equiv_congr ab cd) = equiv_congr (equiv.symm ab) (equiv.symm cd) :=
ext fun (x : β ≃ δ) => ext fun (x_1 : α) => Eq.refl (coe_fn (coe_fn (equiv.symm (equiv_congr ab cd)) x) x_1)
@[simp] theorem equiv_congr_trans {α : Sort u} {β : Sort v} {γ : Sort w} {δ : Sort u_1} {ε : Sort u_2} {ζ : Sort u_3} (ab : α ≃ β) (de : δ ≃ ε) (bc : β ≃ γ) (ef : ε ≃ ζ) : equiv.trans (equiv_congr ab de) (equiv_congr bc ef) = equiv_congr (equiv.trans ab bc) (equiv.trans de ef) :=
ext
fun (x : α ≃ δ) =>
ext fun (x_1 : γ) => Eq.refl (coe_fn (coe_fn (equiv.trans (equiv_congr ab de) (equiv_congr bc ef)) x) x_1)
@[simp] theorem equiv_congr_refl_left {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} (bg : β ≃ γ) (e : α ≃ β) : coe_fn (equiv_congr (equiv.refl α) bg) e = equiv.trans e bg :=
rfl
@[simp] theorem equiv_congr_refl_right {α : Sort u_1} {β : Sort u_2} (ab : α ≃ β) (e : α ≃ β) : coe_fn (equiv_congr ab (equiv.refl β)) e = equiv.trans (equiv.symm ab) e :=
rfl
@[simp] theorem equiv_congr_apply_apply {α : Sort u} {β : Sort v} {γ : Sort w} {δ : Sort u_1} (ab : α ≃ β) (cd : γ ≃ δ) (e : α ≃ γ) (x : β) : coe_fn (coe_fn (equiv_congr ab cd) e) x = coe_fn cd (coe_fn e (coe_fn (equiv.symm ab) x)) :=
rfl
/-- If `α` is equivalent to `β`, then `perm α` is equivalent to `perm β`. -/
def perm_congr {α : Type u_1} {β : Type u_2} (e : α ≃ β) : perm α ≃ perm β :=
equiv_congr e e
theorem perm_congr_def {α : Type u_1} {β : Type u_2} (e : α ≃ β) (p : perm α) : coe_fn (perm_congr e) p = equiv.trans (equiv.trans (equiv.symm e) p) e :=
rfl
@[simp] theorem perm_congr_symm {α : Type u_1} {β : Type u_2} (e : α ≃ β) : equiv.symm (perm_congr e) = perm_congr (equiv.symm e) :=
rfl
@[simp] theorem perm_congr_apply {α : Type u_1} {β : Type u_2} (e : α ≃ β) (p : perm α) (x : β) : coe_fn (coe_fn (perm_congr e) p) x = coe_fn e (coe_fn p (coe_fn (equiv.symm e) x)) :=
rfl
theorem perm_congr_symm_apply {α : Type u_1} {β : Type u_2} (e : α ≃ β) (p : perm β) (x : α) : coe_fn (coe_fn (equiv.symm (perm_congr e)) p) x = coe_fn (equiv.symm e) (coe_fn p (coe_fn e x)) :=
rfl
protected theorem image_eq_preimage {α : Type u_1} {β : Type u_2} (e : α ≃ β) (s : set α) : ⇑e '' s = ⇑(equiv.symm e) ⁻¹' s :=
set.ext fun (x : β) => set.mem_image_iff_of_inverse (left_inv e) (right_inv e)
protected theorem subset_image {α : Type u_1} {β : Type u_2} (e : α ≃ β) (s : set α) (t : set β) : t ⊆ ⇑e '' s ↔ ⇑(equiv.symm e) '' t ⊆ s :=
eq.mpr (id (Eq._oldrec (Eq.refl (t ⊆ ⇑e '' s ↔ ⇑(equiv.symm e) '' t ⊆ s)) (propext set.image_subset_iff)))
(eq.mpr (id (Eq._oldrec (Eq.refl (t ⊆ ⇑e '' s ↔ t ⊆ ⇑(equiv.symm e) ⁻¹' s)) (equiv.image_eq_preimage e s)))
(iff.refl (t ⊆ ⇑(equiv.symm e) ⁻¹' s)))
@[simp] theorem symm_image_image {α : Type u_1} {β : Type u_2} (f : α ≃ β) (s : set α) : ⇑(equiv.symm f) '' (⇑f '' s) = s := sorry
@[simp] theorem image_preimage {α : Type u_1} {β : Type u_2} (e : α ≃ β) (s : set β) : ⇑e '' (⇑e ⁻¹' s) = s :=
function.surjective.image_preimage (equiv.surjective e) s
@[simp] theorem preimage_image {α : Type u_1} {β : Type u_2} (e : α ≃ β) (s : set α) : ⇑e ⁻¹' (⇑e '' s) = s :=
set.preimage_image_eq s (equiv.injective e)
protected theorem image_compl {α : Type u_1} {β : Type u_2} (f : α ≃ β) (s : set α) : ⇑f '' (sᶜ) = (⇑f '' sᶜ) :=
set.image_compl_eq (equiv.bijective f)
/-- If `α` is an empty type, then it is equivalent to the `empty` type. -/
def equiv_empty {α : Sort u} (h : α → False) : α ≃ empty :=
mk (fun (x : α) => false.elim (h x)) (fun (e : empty) => empty.rec (fun (e : empty) => α) e) sorry sorry
/-- `false` is equivalent to `empty`. -/
def false_equiv_empty : False ≃ empty :=
equiv_empty id
/-- If `α` is an empty type, then it is equivalent to the `pempty` type in any universe. -/
def equiv_pempty {α : Sort v'} (h : α → False) : α ≃ pempty :=
mk (fun (x : α) => false.elim (h x)) (fun (e : pempty) => pempty.rec (fun (e : pempty) => α) e) sorry sorry
/-- `false` is equivalent to `pempty`. -/
def false_equiv_pempty : False ≃ pempty :=
equiv_pempty id
/-- `empty` is equivalent to `pempty`. -/
def empty_equiv_pempty : empty ≃ pempty :=
equiv_pempty sorry
/-- `pempty` types from any two universes are equivalent. -/
def pempty_equiv_pempty : pempty ≃ pempty :=
equiv_pempty pempty.elim
/-- If `α` is not `nonempty`, then it is equivalent to `empty`. -/
def empty_of_not_nonempty {α : Sort u_1} (h : ¬Nonempty α) : α ≃ empty :=
equiv_empty sorry
/-- If `α` is not `nonempty`, then it is equivalent to `pempty`. -/
def pempty_of_not_nonempty {α : Sort u_1} (h : ¬Nonempty α) : α ≃ pempty :=
equiv_pempty sorry
/-- The `Sort` of proofs of a true proposition is equivalent to `punit`. -/
def prop_equiv_punit {p : Prop} (h : p) : p ≃ PUnit :=
mk (fun (x : p) => Unit.unit) sorry sorry sorry
/-- `true` is equivalent to `punit`. -/
def true_equiv_punit : True ≃ PUnit :=
prop_equiv_punit trivial
/-- `ulift α` is equivalent to `α`. -/
@[simp] theorem ulift_symm_apply {α : Type v} : ⇑(equiv.symm equiv.ulift) = ulift.up :=
Eq.refl ⇑(equiv.symm equiv.ulift)
/-- `plift α` is equivalent to `α`. -/
protected def plift {α : Sort u} : plift α ≃ α :=
mk plift.down plift.up plift.up_down plift.down_up
/-- equivalence of propositions is the same as iff -/
def of_iff {P : Prop} {Q : Prop} (h : P ↔ Q) : P ≃ Q :=
mk (iff.mp h) (iff.mpr h) sorry sorry
/-- If `α₁` is equivalent to `α₂` and `β₁` is equivalent to `β₂`, then the type of maps `α₁ → β₁`
is equivalent to the type of maps `α₂ → β₂`. -/
def arrow_congr {α₁ : Sort u_1} {β₁ : Sort u_2} {α₂ : Sort u_3} {β₂ : Sort u_4} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (α₁ → β₁) ≃ (α₂ → β₂) :=
mk (fun (f : α₁ → β₁) => ⇑e₂ ∘ f ∘ ⇑(equiv.symm e₁)) (fun (f : α₂ → β₂) => ⇑(equiv.symm e₂) ∘ f ∘ ⇑e₁) sorry sorry
theorem arrow_congr_comp {α₁ : Sort u_1} {β₁ : Sort u_2} {γ₁ : Sort u_3} {α₂ : Sort u_4} {β₂ : Sort u_5} {γ₂ : Sort u_6} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) (ec : γ₁ ≃ γ₂) (f : α₁ → β₁) (g : β₁ → γ₁) : coe_fn (arrow_congr ea ec) (g ∘ f) = coe_fn (arrow_congr eb ec) g ∘ coe_fn (arrow_congr ea eb) f := sorry
@[simp] theorem arrow_congr_refl {α : Sort u_1} {β : Sort u_2} : arrow_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α → β) :=
rfl
@[simp] theorem arrow_congr_trans {α₁ : Sort u_1} {β₁ : Sort u_2} {α₂ : Sort u_3} {β₂ : Sort u_4} {α₃ : Sort u_5} {β₃ : Sort u_6} (e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) : arrow_congr (equiv.trans e₁ e₂) (equiv.trans e₁' e₂') = equiv.trans (arrow_congr e₁ e₁') (arrow_congr e₂ e₂') :=
rfl
@[simp] theorem arrow_congr_symm {α₁ : Sort u_1} {β₁ : Sort u_2} {α₂ : Sort u_3} {β₂ : Sort u_4} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : equiv.symm (arrow_congr e₁ e₂) = arrow_congr (equiv.symm e₁) (equiv.symm e₂) :=
rfl
/--
A version of `equiv.arrow_congr` in `Type`, rather than `Sort`.
The `equiv_rw` tactic is not able to use the default `Sort` level `equiv.arrow_congr`,
because Lean's universe rules will not unify `?l_1` with `imax (1 ?m_1)`.
-/
def arrow_congr' {α₁ : Type u_1} {β₁ : Type u_2} {α₂ : Type u_3} {β₂ : Type u_4} (hα : α₁ ≃ α₂) (hβ : β₁ ≃ β₂) : (α₁ → β₁) ≃ (α₂ → β₂) :=
arrow_congr hα hβ
@[simp] theorem arrow_congr'_refl {α : Type u_1} {β : Type u_2} : arrow_congr' (equiv.refl α) (equiv.refl β) = equiv.refl (α → β) :=
rfl
@[simp] theorem arrow_congr'_trans {α₁ : Type u_1} {β₁ : Type u_2} {α₂ : Type u_3} {β₂ : Type u_4} {α₃ : Type u_5} {β₃ : Type u_6} (e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) : arrow_congr' (equiv.trans e₁ e₂) (equiv.trans e₁' e₂') = equiv.trans (arrow_congr' e₁ e₁') (arrow_congr' e₂ e₂') :=
rfl
@[simp] theorem arrow_congr'_symm {α₁ : Type u_1} {β₁ : Type u_2} {α₂ : Type u_3} {β₂ : Type u_4} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : equiv.symm (arrow_congr' e₁ e₂) = arrow_congr' (equiv.symm e₁) (equiv.symm e₂) :=
rfl
/-- Conjugate a map `f : α → α` by an equivalence `α ≃ β`. -/
def conj {α : Sort u} {β : Sort v} (e : α ≃ β) : (α → α) ≃ (β → β) :=
arrow_congr e e
@[simp] theorem conj_refl {α : Sort u} : conj (equiv.refl α) = equiv.refl (α → α) :=
rfl
@[simp] theorem conj_symm {α : Sort u} {β : Sort v} (e : α ≃ β) : equiv.symm (conj e) = conj (equiv.symm e) :=
rfl
@[simp] theorem conj_trans {α : Sort u} {β : Sort v} {γ : Sort w} (e₁ : α ≃ β) (e₂ : β ≃ γ) : conj (equiv.trans e₁ e₂) = equiv.trans (conj e₁) (conj e₂) :=
rfl
-- This should not be a simp lemma as long as `(∘)` is reducible:
-- when `(∘)` is reducible, Lean can unify `f₁ ∘ f₂` with any `g` using
-- `f₁ := g` and `f₂ := λ x, x`. This causes nontermination.
theorem conj_comp {α : Sort u} {β : Sort v} (e : α ≃ β) (f₁ : α → α) (f₂ : α → α) : coe_fn (conj e) (f₁ ∘ f₂) = coe_fn (conj e) f₁ ∘ coe_fn (conj e) f₂ :=
arrow_congr_comp e e e f₂ f₁
theorem semiconj_conj {α₁ : Type u_1} {β₁ : Type u_2} (e : α₁ ≃ β₁) (f : α₁ → α₁) : function.semiconj (⇑e) f (coe_fn (conj e) f) := sorry
theorem semiconj₂_conj {α₁ : Type u_1} {β₁ : Type u_2} (e : α₁ ≃ β₁) (f : α₁ → α₁ → α₁) : function.semiconj₂ (⇑e) f (coe_fn (arrow_congr e (conj e)) f) := sorry
protected instance arrow_congr.is_associative {α₁ : Type u_1} {β₁ : Type u_2} (e : α₁ ≃ β₁) (f : α₁ → α₁ → α₁) [is_associative α₁ f] : is_associative β₁ (coe_fn (arrow_congr e (arrow_congr e e)) f) :=
function.semiconj₂.is_associative_right (semiconj₂_conj e f) (equiv.surjective e)
protected instance arrow_congr.is_idempotent {α₁ : Type u_1} {β₁ : Type u_2} (e : α₁ ≃ β₁) (f : α₁ → α₁ → α₁) [is_idempotent α₁ f] : is_idempotent β₁ (coe_fn (arrow_congr e (arrow_congr e e)) f) :=
function.semiconj₂.is_idempotent_right (semiconj₂_conj e f) (equiv.surjective e)
protected instance arrow_congr.is_left_cancel {α₁ : Type u_1} {β₁ : Type u_2} (e : α₁ ≃ β₁) (f : α₁ → α₁ → α₁) [is_left_cancel α₁ f] : is_left_cancel β₁ (coe_fn (arrow_congr e (arrow_congr e e)) f) := sorry
protected instance arrow_congr.is_right_cancel {α₁ : Type u_1} {β₁ : Type u_2} (e : α₁ ≃ β₁) (f : α₁ → α₁ → α₁) [is_right_cancel α₁ f] : is_right_cancel β₁ (coe_fn (arrow_congr e (arrow_congr e e)) f) := sorry
/-- `punit` sorts in any two universes are equivalent. -/
def punit_equiv_punit : PUnit ≃ PUnit :=
mk (fun (_x : PUnit) => PUnit.unit) (fun (_x : PUnit) => PUnit.unit) sorry sorry
/-- The sort of maps to `punit.{v}` is equivalent to `punit.{w}`. -/
def arrow_punit_equiv_punit (α : Sort u_1) : (α → PUnit) ≃ PUnit :=
mk (fun (f : α → PUnit) => PUnit.unit) (fun (u : PUnit) (f : α) => PUnit.unit) sorry sorry
/-- The sort of maps from `punit` is equivalent to the codomain. -/
def punit_arrow_equiv (α : Sort u_1) : (PUnit → α) ≃ α :=
mk (fun (f : PUnit → α) => f PUnit.unit) (fun (a : α) (u : PUnit) => a) sorry sorry
/-- The sort of maps from `true` is equivalent to the codomain. -/
def true_arrow_equiv (α : Sort u_1) : (True → α) ≃ α :=
mk (fun (f : True → α) => f trivial) (fun (a : α) (u : True) => a) sorry sorry
/-- The sort of maps from `empty` is equivalent to `punit`. -/
def empty_arrow_equiv_punit (α : Sort u_1) : (empty → α) ≃ PUnit :=
mk (fun (f : empty → α) => PUnit.unit) (fun (u : PUnit) (e : empty) => empty.rec (fun (e : empty) => α) e) sorry sorry
/-- The sort of maps from `pempty` is equivalent to `punit`. -/
def pempty_arrow_equiv_punit (α : Sort u_1) : (pempty → α) ≃ PUnit :=
mk (fun (f : pempty → α) => PUnit.unit) (fun (u : PUnit) (e : pempty) => pempty.rec (fun (e : pempty) => α) e) sorry
sorry
/-- The sort of maps from `false` is equivalent to `punit`. -/
def false_arrow_equiv_punit (α : Sort u_1) : (False → α) ≃ PUnit :=
equiv.trans (arrow_congr false_equiv_empty (equiv.refl α)) (empty_arrow_equiv_punit α)
/-- Product of two equivalences. If `α₁ ≃ α₂` and `β₁ ≃ β₂`, then `α₁ × β₁ ≃ α₂ × β₂`. -/
@[simp] theorem prod_congr_apply {α₁ : Type u_1} {β₁ : Type u_2} {α₂ : Type u_3} {β₂ : Type u_4} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (x : α₁ × β₁) : coe_fn (prod_congr e₁ e₂) x = prod.map (⇑e₁) (⇑e₂) x :=
Eq.refl (coe_fn (prod_congr e₁ e₂) x)
@[simp] theorem prod_congr_symm {α₁ : Type u_1} {β₁ : Type u_2} {α₂ : Type u_3} {β₂ : Type u_4} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : equiv.symm (prod_congr e₁ e₂) = prod_congr (equiv.symm e₁) (equiv.symm e₂) :=
rfl
/-- Type product is commutative up to an equivalence: `α × β ≃ β × α`. -/
@[simp] theorem prod_comm_apply (α : Type u_1) (β : Type u_2) : ∀ (ᾰ : α × β), coe_fn (prod_comm α β) ᾰ = prod.swap ᾰ :=
fun (ᾰ : α × β) => Eq.refl (coe_fn (prod_comm α β) ᾰ)
@[simp] theorem prod_comm_symm (α : Type u_1) (β : Type u_2) : equiv.symm (prod_comm α β) = prod_comm β α :=
rfl
/-- Type product is associative up to an equivalence. -/
@[simp] theorem prod_assoc_apply (α : Type u_1) (β : Type u_2) (γ : Type u_3) (p : (α × β) × γ) : coe_fn (prod_assoc α β γ) p = (prod.fst (prod.fst p), prod.snd (prod.fst p), prod.snd p) :=
Eq.refl (coe_fn (prod_assoc α β γ) p)
theorem prod_assoc_preimage {α : Type u_1} {β : Type u_2} {γ : Type u_3} {s : set α} {t : set β} {u : set γ} : ⇑(prod_assoc α β γ) ⁻¹' set.prod s (set.prod t u) = set.prod (set.prod s t) u := sorry
/-- `punit` is a right identity for type product up to an equivalence. -/
@[simp] theorem prod_punit_apply (α : Type u_1) (p : α × PUnit) : coe_fn (prod_punit α) p = prod.fst p :=
Eq.refl (coe_fn (prod_punit α) p)
/-- `punit` is a left identity for type product up to an equivalence. -/
@[simp] theorem punit_prod_apply (α : Type u_1) : ∀ (ᾰ : PUnit × α), coe_fn (punit_prod α) ᾰ = prod.snd ᾰ :=
fun (ᾰ : PUnit × α) => Eq.refl (prod.snd ᾰ)
/-- `empty` type is a right absorbing element for type product up to an equivalence. -/
def prod_empty (α : Type u_1) : α × empty ≃ empty :=
equiv_empty sorry
/-- `empty` type is a left absorbing element for type product up to an equivalence. -/
def empty_prod (α : Type u_1) : empty × α ≃ empty :=
equiv_empty sorry
/-- `pempty` type is a right absorbing element for type product up to an equivalence. -/
def prod_pempty (α : Type u_1) : α × pempty ≃ pempty :=
equiv_pempty sorry
/-- `pempty` type is a left absorbing element for type product up to an equivalence. -/
def pempty_prod (α : Type u_1) : pempty × α ≃ pempty :=
equiv_pempty sorry
/-- `psum` is equivalent to `sum`. -/
def psum_equiv_sum (α : Type u_1) (β : Type u_2) : psum α β ≃ α ⊕ β :=
mk (fun (s : psum α β) => psum.cases_on s sum.inl sum.inr) (fun (s : α ⊕ β) => sum.cases_on s psum.inl psum.inr) sorry
sorry
/-- If `α ≃ α'` and `β ≃ β'`, then `α ⊕ β ≃ α' ⊕ β'`. -/
def sum_congr {α₁ : Type u_1} {β₁ : Type u_2} {α₂ : Type u_3} {β₂ : Type u_4} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) : α₁ ⊕ β₁ ≃ α₂ ⊕ β₂ :=
mk (sum.map ⇑ea ⇑eb) (sum.map ⇑(equiv.symm ea) ⇑(equiv.symm eb)) sorry sorry
@[simp] theorem sum_congr_trans {α₁ : Type u_1} {α₂ : Type u_2} {β₁ : Type u_3} {β₂ : Type u_4} {γ₁ : Type u_5} {γ₂ : Type u_6} (e : α₁ ≃ β₁) (f : α₂ ≃ β₂) (g : β₁ ≃ γ₁) (h : β₂ ≃ γ₂) : equiv.trans (sum_congr e f) (sum_congr g h) = sum_congr (equiv.trans e g) (equiv.trans f h) := sorry
@[simp] theorem sum_congr_symm {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (e : α ≃ β) (f : γ ≃ δ) : equiv.symm (sum_congr e f) = sum_congr (equiv.symm e) (equiv.symm f) :=
rfl
@[simp] theorem sum_congr_refl {α : Type u_1} {β : Type u_2} : sum_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α ⊕ β) := sorry
namespace perm
/-- Combine a permutation of `α` and of `β` into a permutation of `α ⊕ β`. -/
def sum_congr {α : Type u_1} {β : Type u_2} (ea : perm α) (eb : perm β) : perm (α ⊕ β) :=
sum_congr ea eb
@[simp] theorem sum_congr_apply {α : Type u_1} {β : Type u_2} (ea : perm α) (eb : perm β) (x : α ⊕ β) : coe_fn (sum_congr ea eb) x = sum.map (⇑ea) (⇑eb) x :=
sum_congr_apply ea eb x
@[simp] theorem sum_congr_trans {α : Type u_1} {β : Type u_2} (e : perm α) (f : perm β) (g : perm α) (h : perm β) : equiv.trans (sum_congr e f) (sum_congr g h) = sum_congr (equiv.trans e g) (equiv.trans f h) :=
sum_congr_trans e f g h
@[simp] theorem sum_congr_symm {α : Type u_1} {β : Type u_2} (e : perm α) (f : perm β) : equiv.symm (sum_congr e f) = sum_congr (equiv.symm e) (equiv.symm f) :=
sum_congr_symm e f
@[simp] theorem sum_congr_refl {α : Type u_1} {β : Type u_2} : sum_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α ⊕ β) :=
sum_congr_refl
end perm
/-- `bool` is equivalent the sum of two `punit`s. -/
def bool_equiv_punit_sum_punit : Bool ≃ PUnit ⊕ PUnit :=
mk (fun (b : Bool) => cond b (sum.inr PUnit.unit) (sum.inl PUnit.unit))
(fun (s : PUnit ⊕ PUnit) => sum.rec_on s (fun (_x : PUnit) => false) fun (_x : PUnit) => tt) sorry sorry
/-- `Prop` is noncomputably equivalent to `bool`. -/
def Prop_equiv_bool : Prop ≃ Bool :=
mk (fun (p : Prop) => to_bool p) (fun (b : Bool) => ↥b) sorry sorry
/-- Sum of types is commutative up to an equivalence. -/
@[simp] theorem sum_comm_apply (α : Type u_1) (β : Type u_2) : ∀ (ᾰ : α ⊕ β), coe_fn (sum_comm α β) ᾰ = sum.swap ᾰ :=
fun (ᾰ : α ⊕ β) => Eq.refl (coe_fn (sum_comm α β) ᾰ)
@[simp] theorem sum_comm_symm (α : Type u_1) (β : Type u_2) : equiv.symm (sum_comm α β) = sum_comm β α :=
rfl
/-- Sum of types is associative up to an equivalence. -/
def sum_assoc (α : Type u_1) (β : Type u_2) (γ : Type u_3) : (α ⊕ β) ⊕ γ ≃ α ⊕ β ⊕ γ :=
mk (sum.elim (sum.elim sum.inl (sum.inr ∘ sum.inl)) (sum.inr ∘ sum.inr))
(sum.elim (sum.inl ∘ sum.inl) (sum.elim (sum.inl ∘ sum.inr) sum.inr)) sorry sorry
@[simp] theorem sum_assoc_apply_in1 {α : Type u_1} {β : Type u_2} {γ : Type u_3} (a : α) : coe_fn (sum_assoc α β γ) (sum.inl (sum.inl a)) = sum.inl a :=
rfl
@[simp] theorem sum_assoc_apply_in2 {α : Type u_1} {β : Type u_2} {γ : Type u_3} (b : β) : coe_fn (sum_assoc α β γ) (sum.inl (sum.inr b)) = sum.inr (sum.inl b) :=
rfl
@[simp] theorem sum_assoc_apply_in3 {α : Type u_1} {β : Type u_2} {γ : Type u_3} (c : γ) : coe_fn (sum_assoc α β γ) (sum.inr c) = sum.inr (sum.inr c) :=
rfl
/-- Sum with `empty` is equivalent to the original type. -/
def sum_empty (α : Type u_1) : α ⊕ empty ≃ α :=
mk (sum.elim id (empty.rec fun (n : empty) => α)) sum.inl sorry sorry
@[simp] theorem sum_empty_apply_inl {α : Type u_1} (a : α) : coe_fn (sum_empty α) (sum.inl a) = a :=
rfl
/-- The sum of `empty` with any `Sort*` is equivalent to the right summand. -/
def empty_sum (α : Type u_1) : empty ⊕ α ≃ α :=
equiv.trans (sum_comm empty α) (sum_empty α)
@[simp] theorem empty_sum_apply_inr {α : Type u_1} (a : α) : coe_fn (empty_sum α) (sum.inr a) = a :=
rfl
/-- Sum with `pempty` is equivalent to the original type. -/
def sum_pempty (α : Type u_1) : α ⊕ pempty ≃ α :=
mk (sum.elim id (pempty.rec fun (n : pempty) => α)) sum.inl sorry sorry
@[simp] theorem sum_pempty_apply_inl {α : Type u_1} (a : α) : coe_fn (sum_pempty α) (sum.inl a) = a :=
rfl
/-- The sum of `pempty` with any `Sort*` is equivalent to the right summand. -/
def pempty_sum (α : Type u_1) : pempty ⊕ α ≃ α :=
equiv.trans (sum_comm pempty α) (sum_pempty α)
@[simp] theorem pempty_sum_apply_inr {α : Type u_1} (a : α) : coe_fn (pempty_sum α) (sum.inr a) = a :=
rfl
/-- `option α` is equivalent to `α ⊕ punit` -/
def option_equiv_sum_punit (α : Type u_1) : Option α ≃ α ⊕ PUnit :=
mk (fun (o : Option α) => sorry) (fun (s : α ⊕ PUnit) => sorry) sorry sorry
@[simp] theorem option_equiv_sum_punit_none {α : Type u_1} : coe_fn (option_equiv_sum_punit α) none = sum.inr PUnit.unit :=
rfl
@[simp] theorem option_equiv_sum_punit_some {α : Type u_1} (a : α) : coe_fn (option_equiv_sum_punit α) (some a) = sum.inl a :=
rfl
@[simp] theorem option_equiv_sum_punit_coe {α : Type u_1} (a : α) : coe_fn (option_equiv_sum_punit α) ↑a = sum.inl a :=
rfl
@[simp] theorem option_equiv_sum_punit_symm_inl {α : Type u_1} (a : α) : coe_fn (equiv.symm (option_equiv_sum_punit α)) (sum.inl a) = ↑a :=
rfl
@[simp] theorem option_equiv_sum_punit_symm_inr {α : Type u_1} (a : PUnit) : coe_fn (equiv.symm (option_equiv_sum_punit α)) (sum.inr a) = none :=
rfl
/-- The set of `x : option α` such that `is_some x` is equivalent to `α`. -/
def option_is_some_equiv (α : Type u_1) : (Subtype fun (x : Option α) => ↥(option.is_some x)) ≃ α :=
mk (fun (o : Subtype fun (x : Option α) => ↥(option.is_some x)) => option.get sorry)
(fun (x : α) => { val := some x, property := sorry }) sorry sorry
/-- `α ⊕ β` is equivalent to a `sigma`-type over `bool`. Note that this definition assumes `α` and
`β` to be types from the same universe, so it cannot by used directly to transfer theorems about
sigma types to theorems about sum types. In many cases one can use `ulift` to work around this
difficulty. -/
def sum_equiv_sigma_bool (α : Type u) (β : Type u) : α ⊕ β ≃ sigma fun (b : Bool) => cond b α β :=
mk (fun (s : α ⊕ β) => sum.elim (fun (x : α) => sigma.mk tt x) (fun (x : β) => sigma.mk false x) s)
(fun (s : sigma fun (b : Bool) => cond b α β) => sorry) sorry sorry
/-- `sigma_preimage_equiv f` for `f : α → β` is the natural equivalence between
the type of all fibres of `f` and the total space `α`. -/
@[simp] theorem sigma_preimage_equiv_symm_apply_fst {α : Type u_1} {β : Type u_2} (f : α → β) (x : α) : sigma.fst (coe_fn (equiv.symm (sigma_preimage_equiv f)) x) = f x :=
Eq.refl (sigma.fst (coe_fn (equiv.symm (sigma_preimage_equiv f)) x))
/-- A set `s` in `α × β` is equivalent to the sigma-type `Σ x, {y | (x, y) ∈ s}`. -/
def set_prod_equiv_sigma {α : Type u_1} {β : Type u_2} (s : set (α × β)) : ↥s ≃ sigma fun (x : α) => ↥(set_of fun (y : β) => (x, y) ∈ s) :=
mk (fun (x : ↥s) => sigma.mk (prod.fst (subtype.val x)) { val := prod.snd (subtype.val x), property := sorry })
(fun (x : sigma fun (x : α) => ↥(set_of fun (y : β) => (x, y) ∈ s)) =>
{ val := (sigma.fst x, subtype.val (sigma.snd x)), property := sorry })
sorry sorry
/-- For any predicate `p` on `α`,
the sum of the two subtypes `{a // p a}` and its complement `{a // ¬ p a}`
is naturally equivalent to `α`. -/
def sum_compl {α : Type u_1} (p : α → Prop) [decidable_pred p] : ((Subtype fun (a : α) => p a) ⊕ Subtype fun (a : α) => ¬p a) ≃ α :=
mk (sum.elim coe coe)
(fun (a : α) =>
dite (p a) (fun (h : p a) => sum.inl { val := a, property := h })
fun (h : ¬p a) => sum.inr { val := a, property := h })
sorry sorry
@[simp] theorem sum_compl_apply_inl {α : Type u_1} (p : α → Prop) [decidable_pred p] (x : Subtype fun (a : α) => p a) : coe_fn (sum_compl p) (sum.inl x) = ↑x :=
rfl
@[simp] theorem sum_compl_apply_inr {α : Type u_1} (p : α → Prop) [decidable_pred p] (x : Subtype fun (a : α) => ¬p a) : coe_fn (sum_compl p) (sum.inr x) = ↑x :=
rfl
@[simp] theorem sum_compl_apply_symm_of_pos {α : Type u_1} (p : α → Prop) [decidable_pred p] (a : α) (h : p a) : coe_fn (equiv.symm (sum_compl p)) a = sum.inl { val := a, property := h } :=
dif_pos h
@[simp] theorem sum_compl_apply_symm_of_neg {α : Type u_1} (p : α → Prop) [decidable_pred p] (a : α) (h : ¬p a) : coe_fn (equiv.symm (sum_compl p)) a = sum.inr { val := a, property := h } :=
dif_neg h
/-- For a fixed function `x₀ : {a // p a} → β` defined on a subtype of `α`,
the subtype of functions `x : α → β` that agree with `x₀` on the subtype `{a // p a}`
is naturally equivalent to the type of functions `{a // ¬ p a} → β`. -/
@[simp] theorem subtype_preimage_apply {α : Sort u} {β : Sort v} (p : α → Prop) [decidable_pred p] (x₀ : (Subtype fun (a : α) => p a) → β) (x : Subtype fun (x : α → β) => x ∘ coe = x₀) (a : Subtype fun (a : α) => ¬p a) : coe_fn (subtype_preimage p x₀) x a = coe x ↑a :=
Eq.refl (coe_fn (subtype_preimage p x₀) x a)
theorem subtype_preimage_symm_apply_coe_pos {α : Sort u} {β : Sort v} (p : α → Prop) [decidable_pred p] (x₀ : (Subtype fun (a : α) => p a) → β) (x : (Subtype fun (a : α) => ¬p a) → β) (a : α) (h : p a) : coe (coe_fn (equiv.symm (subtype_preimage p x₀)) x) a = x₀ { val := a, property := h } :=
dif_pos h
theorem subtype_preimage_symm_apply_coe_neg {α : Sort u} {β : Sort v} (p : α → Prop) [decidable_pred p] (x₀ : (Subtype fun (a : α) => p a) → β) (x : (Subtype fun (a : α) => ¬p a) → β) (a : α) (h : ¬p a) : coe (coe_fn (equiv.symm (subtype_preimage p x₀)) x) a = x { val := a, property := h } :=
dif_neg h
/-- If `α` has a unique term, then the type of function `α → β` is equivalent to `β`. -/
@[simp] theorem fun_unique_apply (α : Sort u) (β : Sort v) [unique α] (f : α → β) : coe_fn (fun_unique α β) f = f Inhabited.default :=
Eq.refl (coe_fn (fun_unique α β) f)
/-- A family of equivalences `Π a, β₁ a ≃ β₂ a` generates an equivalence between `Π a, β₁ a` and
`Π a, β₂ a`. -/
def Pi_congr_right {α : Sort u_1} {β₁ : α → Sort u_2} {β₂ : α → Sort u_3} (F : (a : α) → β₁ a ≃ β₂ a) : ((a : α) → β₁ a) ≃ ((a : α) → β₂ a) :=
mk (fun (H : (a : α) → β₁ a) (a : α) => coe_fn (F a) (H a))
(fun (H : (a : α) → β₂ a) (a : α) => coe_fn (equiv.symm (F a)) (H a)) sorry sorry
/-- Dependent `curry` equivalence: the type of dependent functions on `Σ i, β i` is equivalent
to the type of dependent functions of two arguments (i.e., functions to the space of functions). -/
def Pi_curry {α : Type u_1} {β : α → Type u_2} (γ : (a : α) → β a → Sort u_3) : ((x : sigma fun (i : α) => β i) → γ (sigma.fst x) (sigma.snd x)) ≃ ((a : α) → (b : β a) → γ a b) :=
mk (fun (f : (x : sigma fun (i : α) => β i) → γ (sigma.fst x) (sigma.snd x)) (x : α) (y : β x) => f (sigma.mk x y))
(fun (f : (a : α) → (b : β a) → γ a b) (x : sigma fun (i : α) => β i) => f (sigma.fst x) (sigma.snd x)) sorry sorry
/-- A `psigma`-type is equivalent to the corresponding `sigma`-type. -/
def psigma_equiv_sigma {α : Type u_1} (β : α → Type u_2) : (psigma fun (i : α) => β i) ≃ sigma fun (i : α) => β i :=
mk (fun (a : psigma fun (i : α) => β i) => sigma.mk (psigma.fst a) (psigma.snd a))
(fun (a : sigma fun (i : α) => β i) => psigma.mk (sigma.fst a) (sigma.snd a)) sorry sorry
/-- A family of equivalences `Π a, β₁ a ≃ β₂ a` generates an equivalence between `Σ a, β₁ a` and
`Σ a, β₂ a`. -/
@[simp] theorem sigma_congr_right_apply {α : Type u_1} {β₁ : α → Type u_2} {β₂ : α → Type u_3} (F : (a : α) → β₁ a ≃ β₂ a) (a : sigma fun (a : α) => β₁ a) : coe_fn (sigma_congr_right F) a = sigma.mk (sigma.fst a) (coe_fn (F (sigma.fst a)) (sigma.snd a)) :=
Eq.refl (coe_fn (sigma_congr_right F) a)
@[simp] theorem sigma_congr_right_trans {α : Type u_1} {β₁ : α → Type u_2} {β₂ : α → Type u_3} {β₃ : α → Type u_4} (F : (a : α) → β₁ a ≃ β₂ a) (G : (a : α) → β₂ a ≃ β₃ a) : equiv.trans (sigma_congr_right F) (sigma_congr_right G) = sigma_congr_right fun (a : α) => equiv.trans (F a) (G a) := sorry
@[simp] theorem sigma_congr_right_symm {α : Type u_1} {β₁ : α → Type u_2} {β₂ : α → Type u_3} (F : (a : α) → β₁ a ≃ β₂ a) : equiv.symm (sigma_congr_right F) = sigma_congr_right fun (a : α) => equiv.symm (F a) := sorry
@[simp] theorem sigma_congr_right_refl {α : Type u_1} {β : α → Type u_2} : (sigma_congr_right fun (a : α) => equiv.refl (β a)) = equiv.refl (sigma fun (a : α) => β a) := sorry
namespace perm
/-- A family of permutations `Π a, perm (β a)` generates a permuation `perm (Σ a, β₁ a)`. -/
def sigma_congr_right {α : Type u_1} {β : α → Type u_2} (F : (a : α) → perm (β a)) : perm (sigma fun (a : α) => β a) :=
sigma_congr_right F
@[simp] theorem sigma_congr_right_trans {α : Type u_1} {β : α → Type u_2} (F : (a : α) → perm (β a)) (G : (a : α) → perm (β a)) : equiv.trans (sigma_congr_right F) (sigma_congr_right G) = sigma_congr_right fun (a : α) => equiv.trans (F a) (G a) :=
sigma_congr_right_trans F G
@[simp] theorem sigma_congr_right_symm {α : Type u_1} {β : α → Type u_2} (F : (a : α) → perm (β a)) : equiv.symm (sigma_congr_right F) = sigma_congr_right fun (a : α) => equiv.symm (F a) :=
sigma_congr_right_symm F
@[simp] theorem sigma_congr_right_refl {α : Type u_1} {β : α → Type u_2} : (sigma_congr_right fun (a : α) => equiv.refl (β a)) = equiv.refl (sigma fun (a : α) => β a) :=
sigma_congr_right_refl
end perm
/-- An equivalence `f : α₁ ≃ α₂` generates an equivalence between `Σ a, β (f a)` and `Σ a, β a`. -/
def sigma_congr_left {α₁ : Type u_1} {α₂ : Type u_2} {β : α₂ → Type u_3} (e : α₁ ≃ α₂) : (sigma fun (a : α₁) => β (coe_fn e a)) ≃ sigma fun (a : α₂) => β a :=
mk (fun (a : sigma fun (a : α₁) => β (coe_fn e a)) => sigma.mk (coe_fn e (sigma.fst a)) (sigma.snd a))
(fun (a : sigma fun (a : α₂) => β a) =>
sigma.mk (coe_fn (equiv.symm e) (sigma.fst a)) (Eq._oldrec (sigma.snd a) sorry))
sorry sorry
/-- Transporting a sigma type through an equivalence of the base -/
def sigma_congr_left' {α₁ : Type u_1} {α₂ : Type u_2} {β : α₁ → Type u_3} (f : α₁ ≃ α₂) : (sigma fun (a : α₁) => β a) ≃ sigma fun (a : α₂) => β (coe_fn (equiv.symm f) a) :=
equiv.symm (sigma_congr_left (equiv.symm f))
/-- Transporting a sigma type through an equivalence of the base and a family of equivalences
of matching fibers -/
def sigma_congr {α₁ : Type u_1} {α₂ : Type u_2} {β₁ : α₁ → Type u_3} {β₂ : α₂ → Type u_4} (f : α₁ ≃ α₂) (F : (a : α₁) → β₁ a ≃ β₂ (coe_fn f a)) : sigma β₁ ≃ sigma β₂ :=
equiv.trans (sigma_congr_right F) (sigma_congr_left f)
/-- `sigma` type with a constant fiber is equivalent to the product. -/
@[simp] theorem sigma_equiv_prod_symm_apply (α : Type u_1) (β : Type u_2) (a : α × β) : coe_fn (equiv.symm (sigma_equiv_prod α β)) a = sigma.mk (prod.fst a) (prod.snd a) :=
Eq.refl (coe_fn (equiv.symm (sigma_equiv_prod α β)) a)
/-- If each fiber of a `sigma` type is equivalent to a fixed type, then the sigma type
is equivalent to the product. -/
def sigma_equiv_prod_of_equiv {α : Type u_1} {β : Type u_2} {β₁ : α → Type u_3} (F : (a : α) → β₁ a ≃ β) : sigma β₁ ≃ α × β :=
equiv.trans (sigma_congr_right F) (sigma_equiv_prod α β)
/-- A family of equivalences `Π (a : α₁), β₁ ≃ β₂` generates an equivalence
between `β₁ × α₁` and `β₂ × α₁`. -/
def prod_congr_left {α₁ : Type u_1} {β₁ : Type u_2} {β₂ : Type u_3} (e : α₁ → β₁ ≃ β₂) : β₁ × α₁ ≃ β₂ × α₁ :=
mk (fun (ab : β₁ × α₁) => (coe_fn (e (prod.snd ab)) (prod.fst ab), prod.snd ab))
(fun (ab : β₂ × α₁) => (coe_fn (equiv.symm (e (prod.snd ab))) (prod.fst ab), prod.snd ab)) sorry sorry
@[simp] theorem prod_congr_left_apply {α₁ : Type u_1} {β₁ : Type u_2} {β₂ : Type u_3} (e : α₁ → β₁ ≃ β₂) (b : β₁) (a : α₁) : coe_fn (prod_congr_left e) (b, a) = (coe_fn (e a) b, a) :=
rfl
theorem prod_congr_refl_right {α₁ : Type u_1} {β₁ : Type u_2} {β₂ : Type u_3} (e : β₁ ≃ β₂) : prod_congr e (equiv.refl α₁) = prod_congr_left fun (_x : α₁) => e := sorry
/-- A family of equivalences `Π (a : α₁), β₁ ≃ β₂` generates an equivalence
between `α₁ × β₁` and `α₁ × β₂`. -/
def prod_congr_right {α₁ : Type u_1} {β₁ : Type u_2} {β₂ : Type u_3} (e : α₁ → β₁ ≃ β₂) : α₁ × β₁ ≃ α₁ × β₂ :=
mk (fun (ab : α₁ × β₁) => (prod.fst ab, coe_fn (e (prod.fst ab)) (prod.snd ab)))
(fun (ab : α₁ × β₂) => (prod.fst ab, coe_fn (equiv.symm (e (prod.fst ab))) (prod.snd ab))) sorry sorry
@[simp] theorem prod_congr_right_apply {α₁ : Type u_1} {β₁ : Type u_2} {β₂ : Type u_3} (e : α₁ → β₁ ≃ β₂) (a : α₁) (b : β₁) : coe_fn (prod_congr_right e) (a, b) = (a, coe_fn (e a) b) :=
rfl
theorem prod_congr_refl_left {α₁ : Type u_1} {β₁ : Type u_2} {β₂ : Type u_3} (e : β₁ ≃ β₂) : prod_congr (equiv.refl α₁) e = prod_congr_right fun (_x : α₁) => e := sorry
@[simp] theorem prod_congr_left_trans_prod_comm {α₁ : Type u_1} {β₁ : Type u_2} {β₂ : Type u_3} (e : α₁ → β₁ ≃ β₂) : equiv.trans (prod_congr_left e) (prod_comm β₂ α₁) = equiv.trans (prod_comm β₁ α₁) (prod_congr_right e) := sorry
@[simp] theorem prod_congr_right_trans_prod_comm {α₁ : Type u_1} {β₁ : Type u_2} {β₂ : Type u_3} (e : α₁ → β₁ ≃ β₂) : equiv.trans (prod_congr_right e) (prod_comm α₁ β₂) = equiv.trans (prod_comm α₁ β₁) (prod_congr_left e) := sorry
theorem sigma_congr_right_sigma_equiv_prod {α₁ : Type u_1} {β₁ : Type u_2} {β₂ : Type u_3} (e : α₁ → β₁ ≃ β₂) : equiv.trans (sigma_congr_right e) (sigma_equiv_prod α₁ β₂) = equiv.trans (sigma_equiv_prod α₁ β₁) (prod_congr_right e) := sorry
theorem sigma_equiv_prod_sigma_congr_right {α₁ : Type u_1} {β₁ : Type u_2} {β₂ : Type u_3} (e : α₁ → β₁ ≃ β₂) : equiv.trans (equiv.symm (sigma_equiv_prod α₁ β₁)) (sigma_congr_right e) =
equiv.trans (prod_congr_right e) (equiv.symm (sigma_equiv_prod α₁ β₂)) := sorry
/-- A variation on `equiv.prod_congr` where the equivalence in the second component can depend
on the first component. A typical example is a shear mapping, explaining the name of this
declaration. -/
@[simp] theorem prod_shear_symm_apply {α₁ : Type u_1} {β₁ : Type u_2} {α₂ : Type u_3} {β₂ : Type u_4} (e₁ : α₁ ≃ α₂) (e₂ : α₁ → β₁ ≃ β₂) : ⇑(equiv.symm (prod_shear e₁ e₂)) =
fun (y : α₂ × β₂) =>
(coe_fn (equiv.symm e₁) (prod.fst y), coe_fn (equiv.symm (e₂ (coe_fn (equiv.symm e₁) (prod.fst y)))) (prod.snd y)) :=
Eq.refl ⇑(equiv.symm (prod_shear e₁ e₂))
namespace perm
/-- `prod_extend_right a e` extends `e : perm β` to `perm (α × β)` by sending `(a, b)` to
`(a, e b)` and keeping the other `(a', b)` fixed. -/
def prod_extend_right {α₁ : Type u_1} {β₁ : Type u_2} [DecidableEq α₁] (a : α₁) (e : perm β₁) : perm (α₁ × β₁) :=
mk (fun (ab : α₁ × β₁) => ite (prod.fst ab = a) (a, coe_fn e (prod.snd ab)) ab)
(fun (ab : α₁ × β₁) => ite (prod.fst ab = a) (a, coe_fn (equiv.symm e) (prod.snd ab)) ab) sorry sorry
@[simp] theorem prod_extend_right_apply_eq {α₁ : Type u_1} {β₁ : Type u_2} [DecidableEq α₁] (a : α₁) (e : perm β₁) (b : β₁) : coe_fn (prod_extend_right a e) (a, b) = (a, coe_fn e b) :=
if_pos rfl
theorem prod_extend_right_apply_ne {α₁ : Type u_1} {β₁ : Type u_2} [DecidableEq α₁] (e : perm β₁) {a : α₁} {a' : α₁} (h : a' ≠ a) (b : β₁) : coe_fn (prod_extend_right a e) (a', b) = (a', b) :=
if_neg h
theorem eq_of_prod_extend_right_ne {α₁ : Type u_1} {β₁ : Type u_2} [DecidableEq α₁] {e : perm β₁} {a : α₁} {a' : α₁} {b : β₁} (h : coe_fn (prod_extend_right a e) (a', b) ≠ (a', b)) : a' = a := sorry
@[simp] theorem fst_prod_extend_right {α₁ : Type u_1} {β₁ : Type u_2} [DecidableEq α₁] (a : α₁) (e : perm β₁) (ab : α₁ × β₁) : prod.fst (coe_fn (prod_extend_right a e) ab) = prod.fst ab := sorry
end perm
/-- The type of functions to a product `α × β` is equivalent to the type of pairs of functions
`γ → α` and `γ → β`. -/
def arrow_prod_equiv_prod_arrow (α : Type u_1) (β : Type u_2) (γ : Type u_3) : (γ → α × β) ≃ (γ → α) × (γ → β) :=
mk (fun (f : γ → α × β) => (fun (c : γ) => prod.fst (f c), fun (c : γ) => prod.snd (f c)))
(fun (p : (γ → α) × (γ → β)) (c : γ) => (prod.fst p c, prod.snd p c)) sorry sorry
/-- Functions `α → β → γ` are equivalent to functions on `α × β`. -/
def arrow_arrow_equiv_prod_arrow (α : Type u_1) (β : Type u_2) (γ : Type u_3) : (α → β → γ) ≃ (α × β → γ) :=
mk function.uncurry function.curry function.curry_uncurry function.uncurry_curry
/-- The type of functions on a sum type `α ⊕ β` is equivalent to the type of pairs of functions
on `α` and on `β`. -/
def sum_arrow_equiv_prod_arrow (α : Type u_1) (β : Type u_2) (γ : Type u_3) : (α ⊕ β → γ) ≃ (α → γ) × (β → γ) :=
mk (fun (f : α ⊕ β → γ) => (f ∘ sum.inl, f ∘ sum.inr))
(fun (p : (α → γ) × (β → γ)) => sum.elim (prod.fst p) (prod.snd p)) sorry sorry
/-- Type product is right distributive with respect to type sum up to an equivalence. -/
def sum_prod_distrib (α : Type u_1) (β : Type u_2) (γ : Type u_3) : (α ⊕ β) × γ ≃ α × γ ⊕ β × γ :=
mk (fun (p : (α ⊕ β) × γ) => sorry) (fun (s : α × γ ⊕ β × γ) => sorry) sorry sorry
@[simp] theorem sum_prod_distrib_apply_left {α : Type u_1} {β : Type u_2} {γ : Type u_3} (a : α) (c : γ) : coe_fn (sum_prod_distrib α β γ) (sum.inl a, c) = sum.inl (a, c) :=
rfl
@[simp] theorem sum_prod_distrib_apply_right {α : Type u_1} {β : Type u_2} {γ : Type u_3} (b : β) (c : γ) : coe_fn (sum_prod_distrib α β γ) (sum.inr b, c) = sum.inr (b, c) :=
rfl
/-- Type product is left distributive with respect to type sum up to an equivalence. -/
def prod_sum_distrib (α : Type u_1) (β : Type u_2) (γ : Type u_3) : α × (β ⊕ γ) ≃ α × β ⊕ α × γ :=
equiv.trans (equiv.trans (prod_comm α (β ⊕ γ)) (sum_prod_distrib β γ α)) (sum_congr (prod_comm β α) (prod_comm γ α))
@[simp] theorem prod_sum_distrib_apply_left {α : Type u_1} {β : Type u_2} {γ : Type u_3} (a : α) (b : β) : coe_fn (prod_sum_distrib α β γ) (a, sum.inl b) = sum.inl (a, b) :=
rfl
@[simp] theorem prod_sum_distrib_apply_right {α : Type u_1} {β : Type u_2} {γ : Type u_3} (a : α) (c : γ) : coe_fn (prod_sum_distrib α β γ) (a, sum.inr c) = sum.inr (a, c) :=
rfl
/-- The product of an indexed sum of types (formally, a `sigma`-type `Σ i, α i`) by a type `β` is
equivalent to the sum of products `Σ i, (α i × β)`. -/
def sigma_prod_distrib {ι : Type u_1} (α : ι → Type u_2) (β : Type u_3) : (sigma fun (i : ι) => α i) × β ≃ sigma fun (i : ι) => α i × β :=
mk (fun (p : (sigma fun (i : ι) => α i) × β) => sigma.mk (sigma.fst (prod.fst p)) (sigma.snd (prod.fst p), prod.snd p))
(fun (p : sigma fun (i : ι) => α i × β) => (sigma.mk (sigma.fst p) (prod.fst (sigma.snd p)), prod.snd (sigma.snd p)))
sorry sorry
/-- The product `bool × α` is equivalent to `α ⊕ α`. -/
def bool_prod_equiv_sum (α : Type u) : Bool × α ≃ α ⊕ α :=
equiv.trans (equiv.trans (prod_congr bool_equiv_punit_sum_punit (equiv.refl α)) (sum_prod_distrib Unit Unit α))
(sum_congr (punit_prod α) (punit_prod α))
/-- The function type `bool → α` is equivalent to `α × α`. -/
def bool_to_equiv_prod (α : Type u) : (Bool → α) ≃ α × α :=
equiv.trans
(equiv.trans (arrow_congr bool_equiv_punit_sum_punit (equiv.refl α)) (sum_arrow_equiv_prod_arrow Unit Unit α))
(prod_congr (punit_arrow_equiv α) (punit_arrow_equiv α))
@[simp] theorem bool_to_equiv_prod_apply {α : Type u} (f : Bool → α) : coe_fn (bool_to_equiv_prod α) f = (f false, f tt) :=
rfl
@[simp] theorem bool_to_equiv_prod_symm_apply_ff {α : Type u} (p : α × α) : coe_fn (equiv.symm (bool_to_equiv_prod α)) p false = prod.fst p :=
rfl
@[simp] theorem bool_to_equiv_prod_symm_apply_tt {α : Type u} (p : α × α) : coe_fn (equiv.symm (bool_to_equiv_prod α)) p tt = prod.snd p :=
rfl
/-- The set of natural numbers is equivalent to `ℕ ⊕ punit`. -/
def nat_equiv_nat_sum_punit : ℕ ≃ ℕ ⊕ PUnit :=
mk (fun (n : ℕ) => sorry) (fun (s : ℕ ⊕ PUnit) => sorry) sorry sorry
/-- `ℕ ⊕ punit` is equivalent to `ℕ`. -/
def nat_sum_punit_equiv_nat : ℕ ⊕ PUnit ≃ ℕ :=
equiv.symm nat_equiv_nat_sum_punit
/-- The type of integer numbers is equivalent to `ℕ ⊕ ℕ`. -/
def int_equiv_nat_sum_nat : ℤ ≃ ℕ ⊕ ℕ :=
mk (fun (z : ℤ) => int.cases_on z (fun (z : ℕ) => sum.inl z) fun (z : ℕ) => sum.inr z)
(fun (z : ℕ ⊕ ℕ) => sum.cases_on z (fun (z : ℕ) => Int.ofNat z) fun (z : ℕ) => Int.negSucc z) sorry sorry
/-- An equivalence between `α` and `β` generates an equivalence between `list α` and `list β`. -/
def list_equiv_of_equiv {α : Type u_1} {β : Type u_2} (e : α ≃ β) : List α ≃ List β :=
mk (list.map ⇑e) (list.map ⇑(equiv.symm e)) sorry sorry
/-- `fin n` is equivalent to `{m // m < n}`. -/
def fin_equiv_subtype (n : ℕ) : fin n ≃ Subtype fun (m : ℕ) => m < n :=
mk (fun (x : fin n) => { val := subtype.val x, property := sorry })
(fun (x : Subtype fun (m : ℕ) => m < n) => { val := subtype.val x, property := sorry }) sorry sorry
/-- If `α` is equivalent to `β`, then `unique α` is equivalent to `β`. -/
def unique_congr {α : Sort u} {β : Sort v} (e : α ≃ β) : unique α ≃ unique β :=
mk (fun (h : unique α) => equiv.unique (equiv.symm e)) (fun (h : unique β) => equiv.unique e) sorry sorry
/-- If `α` is equivalent to `β` and the predicates `p : α → Prop` and `q : β → Prop` are equivalent
at corresponding points, then `{a // p a}` is equivalent to `{b // q b}`. -/
def subtype_congr {α : Sort u} {β : Sort v} {p : α → Prop} {q : β → Prop} (e : α ≃ β) (h : ∀ (a : α), p a ↔ q (coe_fn e a)) : (Subtype fun (a : α) => p a) ≃ Subtype fun (b : β) => q b :=
mk (fun (x : Subtype fun (a : α) => p a) => { val := coe_fn e ↑x, property := sorry })
(fun (y : Subtype fun (b : β) => q b) => { val := coe_fn (equiv.symm e) ↑y, property := sorry }) sorry sorry
@[simp] theorem subtype_congr_apply {α : Sort u} {β : Sort v} {p : α → Prop} {q : β → Prop} (e : α ≃ β) (h : ∀ (a : α), p a ↔ q (coe_fn e a)) (x : Subtype fun (x : α) => p x) : coe_fn (subtype_congr e h) x = { val := coe_fn e ↑x, property := iff.mp (h ↑x) (subtype.property x) } :=
rfl
@[simp] theorem subtype_congr_symm_apply {α : Sort u} {β : Sort v} {p : α → Prop} {q : β → Prop} (e : α ≃ β) (h : ∀ (a : α), p a ↔ q (coe_fn e a)) (y : Subtype fun (y : β) => q y) : coe_fn (equiv.symm (subtype_congr e h)) y =
{ val := coe_fn (equiv.symm e) ↑y,
property := iff.mpr (h (coe_fn (equiv.symm e) ↑y)) (Eq.symm (apply_symm_apply e ↑y) ▸ subtype.property y) } :=
rfl
/-- If two predicates `p` and `q` are pointwise equivalent, then `{x // p x}` is equivalent to
`{x // q x}`. -/
def subtype_congr_right {α : Sort u} {p : α → Prop} {q : α → Prop} (e : ∀ (x : α), p x ↔ q x) : (Subtype fun (x : α) => p x) ≃ Subtype fun (x : α) => q x :=
subtype_congr (equiv.refl α) e
/-- If `α ≃ β`, then for any predicate `p : β → Prop` the subtype `{a // p (e a)}` is equivalent
to the subtype `{b // p b}`. -/
def subtype_equiv_of_subtype {α : Sort u} {β : Sort v} {p : β → Prop} (e : α ≃ β) : (Subtype fun (a : α) => p (coe_fn e a)) ≃ Subtype fun (b : β) => p b :=
subtype_congr e sorry
/-- If `α ≃ β`, then for any predicate `p : α → Prop` the subtype `{a // p a}` is equivalent
to the subtype `{b // p (e.symm b)}`. This version is used by `equiv_rw`. -/
def subtype_equiv_of_subtype' {α : Sort u} {β : Sort v} {p : α → Prop} (e : α ≃ β) : (Subtype fun (a : α) => p a) ≃ Subtype fun (b : β) => p (coe_fn (equiv.symm e) b) :=
equiv.symm (subtype_equiv_of_subtype (equiv.symm e))
/-- If two predicates are equal, then the corresponding subtypes are equivalent. -/
def subtype_congr_prop {α : Type u_1} {p : α → Prop} {q : α → Prop} (h : p = q) : Subtype p ≃ Subtype q :=
subtype_congr (equiv.refl α) sorry
/-- The subtypes corresponding to equal sets are equivalent. -/
def set_congr {α : Type u_1} {s : set α} {t : set α} (h : s = t) : ↥s ≃ ↥t :=
subtype_congr_prop h
/-- A subtype of a subtype is equivalent to the subtype of elements satisfying both predicates. This
version allows the “inner” predicate to depend on `h : p a`. -/
def subtype_subtype_equiv_subtype_exists {α : Type u} (p : α → Prop) (q : Subtype p → Prop) : Subtype q ≃ Subtype fun (a : α) => ∃ (h : p a), q { val := a, property := h } :=
mk (fun (_x : Subtype q) => sorry)
(fun (_x : Subtype fun (a : α) => ∃ (h : p a), q { val := a, property := h }) => sorry) sorry sorry
/-- A subtype of a subtype is equivalent to the subtype of elements satisfying both predicates. -/
def subtype_subtype_equiv_subtype_inter {α : Type u} (p : α → Prop) (q : α → Prop) : (Subtype fun (x : Subtype p) => q (subtype.val x)) ≃ Subtype fun (x : α) => p x ∧ q x :=
equiv.trans (subtype_subtype_equiv_subtype_exists p fun (x : Subtype p) => q (subtype.val x))
(subtype_congr_right sorry)
/-- If the outer subtype has more restrictive predicate than the inner one,
then we can drop the latter. -/
def subtype_subtype_equiv_subtype {α : Type u} {p : α → Prop} {q : α → Prop} (h : ∀ {x : α}, q x → p x) : (Subtype fun (x : Subtype p) => q (subtype.val x)) ≃ Subtype q :=
equiv.trans (subtype_subtype_equiv_subtype_inter p q) (subtype_congr_right sorry)
/-- If a proposition holds for all elements, then the subtype is
equivalent to the original type. -/
def subtype_univ_equiv {α : Type u} {p : α → Prop} (h : ∀ (x : α), p x) : Subtype p ≃ α :=
mk (fun (x : Subtype p) => ↑x) (fun (x : α) => { val := x, property := h x }) sorry sorry
/-- A subtype of a sigma-type is a sigma-type over a subtype. -/
def subtype_sigma_equiv {α : Type u} (p : α → Type v) (q : α → Prop) : (Subtype fun (y : sigma p) => q (sigma.fst y)) ≃ sigma fun (x : Subtype q) => p (subtype.val x) :=
mk
(fun (x : Subtype fun (y : sigma p) => q (sigma.fst y)) =>
sigma.mk { val := sigma.fst (subtype.val x), property := sorry } (sigma.snd (subtype.val x)))
(fun (x : sigma fun (x : Subtype q) => p (subtype.val x)) =>
{ val := sigma.mk (subtype.val (sigma.fst x)) (sigma.snd x), property := sorry })
sorry sorry
/-- A sigma type over a subtype is equivalent to the sigma set over the original type,
if the fiber is empty outside of the subset -/
def sigma_subtype_equiv_of_subset {α : Type u} (p : α → Type v) (q : α → Prop) (h : ∀ (x : α), p x → q x) : (sigma fun (x : Subtype q) => p ↑x) ≃ sigma fun (x : α) => p x :=
equiv.trans (equiv.symm (subtype_sigma_equiv p q)) (subtype_univ_equiv sorry)
/-- If a predicate `p : β → Prop` is true on the range of a map `f : α → β`, then
`Σ y : {y // p y}, {x // f x = y}` is equivalent to `α`. -/
def sigma_subtype_preimage_equiv {α : Type u} {β : Type v} (f : α → β) (p : β → Prop) (h : ∀ (x : α), p (f x)) : (sigma fun (y : Subtype p) => Subtype fun (x : α) => f x = ↑y) ≃ α :=
equiv.trans (sigma_subtype_equiv_of_subset (fun (y : β) => Subtype fun (x : α) => f x = y) p sorry)
(sigma_preimage_equiv f)
/-- If for each `x` we have `p x ↔ q (f x)`, then `Σ y : {y // q y}, f ⁻¹' {y}` is equivalent
to `{x // p x}`. -/
def sigma_subtype_preimage_equiv_subtype {α : Type u} {β : Type v} (f : α → β) {p : α → Prop} {q : β → Prop} (h : ∀ (x : α), p x ↔ q (f x)) : (sigma fun (y : Subtype q) => Subtype fun (x : α) => f x = ↑y) ≃ Subtype p :=
equiv.trans
(sigma_congr_right
fun (y : Subtype q) =>
equiv.symm
(equiv.trans
(subtype_subtype_equiv_subtype_exists p fun (x : Subtype p) => { val := f ↑x, property := sorry } = y)
(subtype_congr_right sorry)))
(sigma_preimage_equiv fun (x : Subtype p) => { val := f ↑x, property := sorry })
/-- The `pi`-type `Π i, π i` is equivalent to the type of sections `f : ι → Σ i, π i` of the
`sigma` type such that for all `i` we have `(f i).fst = i`. -/
def pi_equiv_subtype_sigma (ι : Type u_1) (π : ι → Type u_2) : ((i : ι) → π i) ≃ ↥(set_of fun (f : ι → sigma fun (i : ι) => π i) => ∀ (i : ι), sigma.fst (f i) = i) :=
mk (fun (f : (i : ι) → π i) => { val := fun (i : ι) => sigma.mk i (f i), property := sorry })
(fun (f : ↥(set_of fun (f : ι → sigma fun (i : ι) => π i) => ∀ (i : ι), sigma.fst (f i) = i)) (i : ι) =>
eq.mpr sorry (sigma.snd (subtype.val f i)))
sorry sorry
/-- The set of functions `f : Π a, β a` such that for all `a` we have `p a (f a)` is equivalent
to the set of functions `Π a, {b : β a // p a b}`. -/
def subtype_pi_equiv_pi {α : Sort u} {β : α → Sort v} {p : (a : α) → β a → Prop} : (Subtype fun (f : (a : α) → β a) => ∀ (a : α), p a (f a)) ≃ ((a : α) → Subtype fun (b : β a) => p a b) :=
mk
(fun (f : Subtype fun (f : (a : α) → β a) => ∀ (a : α), p a (f a)) (a : α) =>
{ val := subtype.val f a, property := sorry })
(fun (f : (a : α) → Subtype fun (b : β a) => p a b) => { val := fun (a : α) => subtype.val (f a), property := sorry })
sorry sorry
/-- A subtype of a product defined by componentwise conditions
is equivalent to a product of subtypes. -/
def subtype_prod_equiv_prod {α : Type u} {β : Type v} {p : α → Prop} {q : β → Prop} : (Subtype fun (c : α × β) => p (prod.fst c) ∧ q (prod.snd c)) ≃ (Subtype fun (a : α) => p a) × Subtype fun (b : β) => q b :=
mk
(fun (x : Subtype fun (c : α × β) => p (prod.fst c) ∧ q (prod.snd c)) =>
({ val := prod.fst (subtype.val x), property := sorry }, { val := prod.snd (subtype.val x), property := sorry }))
(fun (x : (Subtype fun (a : α) => p a) × Subtype fun (b : β) => q b) =>
{ val := (subtype.val (prod.fst x), subtype.val (prod.snd x)), property := sorry })
sorry sorry
/-- The type of all functions `X → Y` with prescribed values for all `x' ≠ x`
is equivalent to the codomain `Y`. -/
def subtype_equiv_codomain {X : Type u_1} {Y : Type u_2} [DecidableEq X] {x : X} (f : (Subtype fun (x' : X) => x' ≠ x) → Y) : (Subtype fun (g : X → Y) => g ∘ coe = f) ≃ Y :=
equiv.trans (subtype_preimage (fun (x' : X) => x' ≠ x) f) (fun_unique (Subtype fun (a : X) => ¬a ≠ x) Y)
@[simp] theorem coe_subtype_equiv_codomain {X : Type u_1} {Y : Type u_2} [DecidableEq X] {x : X} (f : (Subtype fun (x' : X) => x' ≠ x) → Y) : ⇑(subtype_equiv_codomain f) = fun (g : Subtype fun (g : X → Y) => g ∘ coe = f) => coe g x :=
rfl
@[simp] theorem subtype_equiv_codomain_apply {X : Type u_1} {Y : Type u_2} [DecidableEq X] {x : X} (f : (Subtype fun (x' : X) => x' ≠ x) → Y) (g : Subtype fun (g : X → Y) => g ∘ coe = f) : coe_fn (subtype_equiv_codomain f) g = coe g x :=
rfl
theorem coe_subtype_equiv_codomain_symm {X : Type u_1} {Y : Type u_2} [DecidableEq X] {x : X} (f : (Subtype fun (x' : X) => x' ≠ x) → Y) : ⇑(equiv.symm (subtype_equiv_codomain f)) =
fun (y : Y) =>
{ val := fun (x' : X) => dite (x' ≠ x) (fun (h : x' ≠ x) => f { val := x', property := h }) fun (h : ¬x' ≠ x) => y,
property :=
funext
fun (x' : Subtype fun (x' : X) => x' ≠ x) =>
id
(eq.mpr
(id
(Eq._oldrec
(Eq.refl
((dite (¬↑x' = x) (fun (h : ¬↑x' = x) => f { val := ↑x', property := h })
fun (h : ¬¬↑x' = x) => y) =
f x'))
(dif_pos (subtype.property x'))))
(eq.mpr
(id
(Eq._oldrec (Eq.refl (f { val := ↑x', property := subtype.property x' } = f x'))
(subtype.coe_eta x' (subtype.property x'))))
(Eq.refl (f x')))) } :=
rfl
@[simp] theorem subtype_equiv_codomain_symm_apply {X : Type u_1} {Y : Type u_2} [DecidableEq X] {x : X} (f : (Subtype fun (x' : X) => x' ≠ x) → Y) (y : Y) (x' : X) : coe (coe_fn (equiv.symm (subtype_equiv_codomain f)) y) x' =
dite (x' ≠ x) (fun (h : x' ≠ x) => f { val := x', property := h }) fun (h : ¬x' ≠ x) => y :=
rfl
@[simp] theorem subtype_equiv_codomain_symm_apply_eq {X : Type u_1} {Y : Type u_2} [DecidableEq X] {x : X} (f : (Subtype fun (x' : X) => x' ≠ x) → Y) (y : Y) : coe (coe_fn (equiv.symm (subtype_equiv_codomain f)) y) x = y :=
dif_neg (iff.mpr not_not rfl)
theorem subtype_equiv_codomain_symm_apply_ne {X : Type u_1} {Y : Type u_2} [DecidableEq X] {x : X} (f : (Subtype fun (x' : X) => x' ≠ x) → Y) (y : Y) (x' : X) (h : x' ≠ x) : coe (coe_fn (equiv.symm (subtype_equiv_codomain f)) y) x' = f { val := x', property := h } :=
dif_pos h
namespace set
/-- `univ α` is equivalent to `α`. -/
@[simp] theorem univ_symm_apply (α : Type u_1) (a : α) : coe_fn (equiv.symm (set.univ α)) a = { val := a, property := trivial } :=
Eq.refl (coe_fn (equiv.symm (set.univ α)) a)
/-- An empty set is equivalent to the `empty` type. -/
protected def empty (α : Type u_1) : ↥∅ ≃ empty :=
equiv_empty sorry
/-- An empty set is equivalent to a `pempty` type. -/
protected def pempty (α : Type u_1) : ↥∅ ≃ pempty :=
equiv_pempty sorry
/-- If sets `s` and `t` are separated by a decidable predicate, then `s ∪ t` is equivalent to
`s ⊕ t`. -/
protected def union' {α : Type u_1} {s : set α} {t : set α} (p : α → Prop) [decidable_pred p] (hs : ∀ (x : α), x ∈ s → p x) (ht : ∀ (x : α), x ∈ t → ¬p x) : ↥(s ∪ t) ≃ ↥s ⊕ ↥t :=
mk
(fun (x : ↥(s ∪ t)) =>
dite (p ↑x) (fun (hp : p ↑x) => sum.inl { val := subtype.val x, property := sorry })
fun (hp : ¬p ↑x) => sum.inr { val := subtype.val x, property := sorry })
(fun (o : ↥s ⊕ ↥t) => sorry) sorry sorry
/-- If sets `s` and `t` are disjoint, then `s ∪ t` is equivalent to `s ⊕ t`. -/
protected def union {α : Type u_1} {s : set α} {t : set α} [decidable_pred fun (x : α) => x ∈ s] (H : s ∩ t ⊆ ∅) : ↥(s ∪ t) ≃ ↥s ⊕ ↥t :=
set.union' (fun (x : α) => x ∈ s) sorry sorry
theorem union_apply_left {α : Type u_1} {s : set α} {t : set α} [decidable_pred fun (x : α) => x ∈ s] (H : s ∩ t ⊆ ∅) {a : ↥(s ∪ t)} (ha : ↑a ∈ s) : coe_fn (set.union H) a = sum.inl { val := ↑a, property := ha } :=
dif_pos ha
theorem union_apply_right {α : Type u_1} {s : set α} {t : set α} [decidable_pred fun (x : α) => x ∈ s] (H : s ∩ t ⊆ ∅) {a : ↥(s ∪ t)} (ha : ↑a ∈ t) : coe_fn (set.union H) a = sum.inr { val := ↑a, property := ha } :=
dif_neg fun (h : ↑a ∈ s) => H { left := h, right := ha }
@[simp] theorem union_symm_apply_left {α : Type u_1} {s : set α} {t : set α} [decidable_pred fun (x : α) => x ∈ s] (H : s ∩ t ⊆ ∅) (a : ↥s) : coe_fn (equiv.symm (set.union H)) (sum.inl a) =
{ val := ↑a, property := set.subset_union_left s t (subtype.property a) } :=
rfl
@[simp] theorem union_symm_apply_right {α : Type u_1} {s : set α} {t : set α} [decidable_pred fun (x : α) => x ∈ s] (H : s ∩ t ⊆ ∅) (a : ↥t) : coe_fn (equiv.symm (set.union H)) (sum.inr a) =
{ val := ↑a, property := set.subset_union_right s t (subtype.property a) } :=
rfl
-- TODO: Any reason to use the same universe?
/-- A singleton set is equivalent to a `punit` type. -/
protected def singleton {α : Type u_1} (a : α) : ↥(singleton a) ≃ PUnit :=
mk (fun (_x : ↥(singleton a)) => PUnit.unit) (fun (_x : PUnit) => { val := a, property := set.mem_singleton a }) sorry
sorry
/-- Equal sets are equivalent. -/
@[simp] theorem of_eq_symm_apply {α : Type u} {s : set α} {t : set α} (h : s = t) (x : ↥t) : coe_fn (equiv.symm (set.of_eq h)) x = { val := ↑x, property := of_eq._proof_2 h x } :=
Eq.refl (coe_fn (equiv.symm (set.of_eq h)) x)
/-- If `a ∉ s`, then `insert a s` is equivalent to `s ⊕ punit`. -/
protected def insert {α : Type u} {s : set α} [decidable_pred s] {a : α} (H : ¬a ∈ s) : ↥(insert a s) ≃ ↥s ⊕ PUnit :=
equiv.trans (equiv.trans (set.of_eq sorry) (set.union sorry)) (sum_congr (equiv.refl ↥s) (set.singleton a))
@[simp] theorem insert_symm_apply_inl {α : Type u} {s : set α} [decidable_pred s] {a : α} (H : ¬a ∈ s) (b : ↥s) : coe_fn (equiv.symm (set.insert H)) (sum.inl b) = { val := ↑b, property := Or.inr (subtype.property b) } :=
rfl
@[simp] theorem insert_symm_apply_inr {α : Type u} {s : set α} [decidable_pred s] {a : α} (H : ¬a ∈ s) (b : PUnit) : coe_fn (equiv.symm (set.insert H)) (sum.inr b) = { val := a, property := Or.inl rfl } :=
rfl
@[simp] theorem insert_apply_left {α : Type u} {s : set α} [decidable_pred s] {a : α} (H : ¬a ∈ s) : coe_fn (set.insert H) { val := a, property := Or.inl rfl } = sum.inr PUnit.unit :=
iff.mpr (apply_eq_iff_eq_symm_apply (set.insert H)) rfl
@[simp] theorem insert_apply_right {α : Type u} {s : set α} [decidable_pred s] {a : α} (H : ¬a ∈ s) (b : ↥s) : coe_fn (set.insert H) { val := ↑b, property := Or.inr (subtype.property b) } = sum.inl b :=
iff.mpr (apply_eq_iff_eq_symm_apply (set.insert H)) rfl
/-- If `s : set α` is a set with decidable membership, then `s ⊕ sᶜ` is equivalent to `α`. -/
protected def sum_compl {α : Type u_1} (s : set α) [decidable_pred s] : ↥s ⊕ ↥(sᶜ) ≃ α :=
equiv.trans (equiv.trans (equiv.symm (set.union sorry)) (set.of_eq sorry)) (set.univ α)
@[simp] theorem sum_compl_apply_inl {α : Type u} (s : set α) [decidable_pred s] (x : ↥s) : coe_fn (set.sum_compl s) (sum.inl x) = ↑x :=
rfl
@[simp] theorem sum_compl_apply_inr {α : Type u} (s : set α) [decidable_pred s] (x : ↥(sᶜ)) : coe_fn (set.sum_compl s) (sum.inr x) = ↑x :=
rfl
theorem sum_compl_symm_apply_of_mem {α : Type u} {s : set α} [decidable_pred s] {x : α} (hx : x ∈ s) : coe_fn (equiv.symm (set.sum_compl s)) x = sum.inl { val := x, property := hx } := sorry
theorem sum_compl_symm_apply_of_not_mem {α : Type u} {s : set α} [decidable_pred s] {x : α} (hx : ¬x ∈ s) : coe_fn (equiv.symm (set.sum_compl s)) x = sum.inr { val := x, property := hx } := sorry
@[simp] theorem sum_compl_symm_apply {α : Type u_1} {s : set α} [decidable_pred s] {x : ↥s} : coe_fn (equiv.symm (set.sum_compl s)) ↑x = sum.inl x :=
subtype.cases_on x fun (x : α) (hx : x ∈ s) => sum_compl_symm_apply_of_mem hx
@[simp] theorem sum_compl_symm_apply_compl {α : Type u_1} {s : set α} [decidable_pred s] {x : ↥(sᶜ)} : coe_fn (equiv.symm (set.sum_compl s)) ↑x = sum.inr x :=
subtype.cases_on x fun (x : α) (hx : x ∈ (sᶜ)) => sum_compl_symm_apply_of_not_mem hx
/-- `sum_diff_subset s t` is the natural equivalence between
`s ⊕ (t \ s)` and `t`, where `s` and `t` are two sets. -/
protected def sum_diff_subset {α : Type u_1} {s : set α} {t : set α} (h : s ⊆ t) [decidable_pred s] : ↥s ⊕ ↥(t \ s) ≃ ↥t :=
equiv.trans (equiv.symm (set.union sorry)) (set.of_eq sorry)
@[simp] theorem sum_diff_subset_apply_inl {α : Type u_1} {s : set α} {t : set α} (h : s ⊆ t) [decidable_pred s] (x : ↥s) : coe_fn (set.sum_diff_subset h) (sum.inl x) = set.inclusion h x :=
rfl
@[simp] theorem sum_diff_subset_apply_inr {α : Type u_1} {s : set α} {t : set α} (h : s ⊆ t) [decidable_pred s] (x : ↥(t \ s)) : coe_fn (set.sum_diff_subset h) (sum.inr x) = set.inclusion (set.diff_subset t s) x :=
rfl
theorem sum_diff_subset_symm_apply_of_mem {α : Type u_1} {s : set α} {t : set α} (h : s ⊆ t) [decidable_pred s] {x : ↥t} (hx : subtype.val x ∈ s) : coe_fn (equiv.symm (set.sum_diff_subset h)) x = sum.inl { val := ↑x, property := hx } := sorry
theorem sum_diff_subset_symm_apply_of_not_mem {α : Type u_1} {s : set α} {t : set α} (h : s ⊆ t) [decidable_pred s] {x : ↥t} (hx : ¬subtype.val x ∈ s) : coe_fn (equiv.symm (set.sum_diff_subset h)) x =
sum.inr { val := ↑x, property := { left := subtype.property x, right := hx } } := sorry
/-- If `s` is a set with decidable membership, then the sum of `s ∪ t` and `s ∩ t` is equivalent
to `s ⊕ t`. -/
protected def union_sum_inter {α : Type u} (s : set α) (t : set α) [decidable_pred s] : ↥(s ∪ t) ⊕ ↥(s ∩ t) ≃ ↥s ⊕ ↥t :=
equiv.trans
(equiv.trans
(equiv.trans
(equiv.trans (eq.mpr sorry (equiv.refl (↥(s ∪ t) ⊕ ↥(s ∩ t))))
(sum_congr (set.union sorry) (equiv.refl ↥(s ∩ t))))
(sum_assoc ↥s ↥(t \ s) ↥(s ∩ t)))
(sum_congr (equiv.refl ↥s) (equiv.symm (set.union' (fun (_x : α) => ¬_x ∈ s) sorry sorry))))
(eq.mpr sorry (equiv.refl (↥s ⊕ ↥t)))
/-- Given an equivalence `e₀` between sets `s : set α` and `t : set β`, the set of equivalences
`e : α ≃ β` such that `e ↑x = ↑(e₀ x)` for each `x : s` is equivalent to the set of equivalences
between `sᶜ` and `tᶜ`. -/
protected def compl {α : Type u} {β : Type v} {s : set α} {t : set β} [decidable_pred s] [decidable_pred t] (e₀ : ↥s ≃ ↥t) : (Subtype fun (e : α ≃ β) => ∀ (x : ↥s), coe_fn e ↑x = ↑(coe_fn e₀ x)) ≃ (↥(sᶜ) ≃ ↥(tᶜ)) :=
mk (fun (e : Subtype fun (e : α ≃ β) => ∀ (x : ↥s), coe_fn e ↑x = ↑(coe_fn e₀ x)) => subtype_congr ↑e sorry)
(fun (e₁ : ↥(sᶜ) ≃ ↥(tᶜ)) =>
{ val := equiv.trans (equiv.trans (equiv.symm (set.sum_compl s)) (sum_congr e₀ e₁)) (set.sum_compl t),
property := sorry })
sorry sorry
/-- The set product of two sets is equivalent to the type product of their coercions to types. -/
protected def prod {α : Type u_1} {β : Type u_2} (s : set α) (t : set β) : ↥(set.prod s t) ≃ ↥s × ↥t :=
subtype_prod_equiv_prod
/-- If a function `f` is injective on a set `s`, then `s` is equivalent to `f '' s`. -/
protected def image_of_inj_on {α : Type u_1} {β : Type u_2} (f : α → β) (s : set α) (H : set.inj_on f s) : ↥s ≃ ↥(f '' s) :=
mk (fun (p : ↥s) => { val := f ↑p, property := sorry })
(fun (p : ↥(f '' s)) => { val := classical.some sorry, property := sorry }) sorry sorry
/-- If `f` is an injective function, then `s` is equivalent to `f '' s`. -/
@[simp] theorem image_apply {α : Type u_1} {β : Type u_2} (f : α → β) (s : set α) (H : function.injective f) (p : ↥s) : coe_fn (set.image f s H) p = { val := f ↑p, property := image_of_inj_on._proof_1 f s p } :=
Eq.refl { val := f ↑p, property := image_of_inj_on._proof_1 f s p }
theorem image_symm_preimage {α : Type u_1} {β : Type u_2} {f : α → β} (hf : function.injective f) (u : set α) (s : set α) : (fun (x : ↥(f '' s)) => ↑(coe_fn (equiv.symm (set.image f s hf)) x)) ⁻¹' u = coe ⁻¹' (f '' u) := sorry
/-- If `f : α → β` is an injective function, then `α` is equivalent to the range of `f`. -/
@[simp] theorem range_apply {α : Sort u_1} {β : Type u_2} (f : α → β) (H : function.injective f) (x : α) : coe_fn (set.range f H) x = { val := f x, property := set.mem_range_self x } :=
Eq.refl (coe_fn (set.range f H) x)
theorem apply_range_symm {α : Sort u_1} {β : Type u_2} (f : α → β) (H : function.injective f) (b : ↥(set.range f)) : f (coe_fn (equiv.symm (set.range f H)) b) = ↑b := sorry
/-- If `α` is equivalent to `β`, then `set α` is equivalent to `set β`. -/
protected def congr {α : Type u_1} {β : Type u_2} (e : α ≃ β) : set α ≃ set β :=
mk (fun (s : set α) => ⇑e '' s) (fun (t : set β) => ⇑(equiv.symm e) '' t) (symm_image_image e) sorry
/-- The set `{x ∈ s | t x}` is equivalent to the set of `x : s` such that `t x`. -/
protected def sep {α : Type u} (s : set α) (t : α → Prop) : ↥(has_sep.sep (fun (x : α) => t x) s) ≃ ↥(set_of fun (x : ↥s) => t ↑x) :=
equiv.symm (subtype_subtype_equiv_subtype_inter s t)
/-- The set `𝒫 S := {x | x ⊆ S}` is equivalent to the type `set S`. -/
protected def powerset {α : Type u_1} (S : set α) : ↥(𝒫 S) ≃ set ↥S :=
mk (fun (x : ↥(𝒫 S)) => coe ⁻¹' ↑x) (fun (x : set ↥S) => { val := coe '' x, property := sorry }) sorry sorry
end set
/-- If `f` is a bijective function, then its domain is equivalent to its codomain. -/
def of_bijective {α : Sort u_1} {β : Type u_2} (f : α → β) (hf : function.bijective f) : α ≃ β :=
equiv.trans (set.range f sorry) (equiv.trans (set_congr sorry) (set.univ β))
theorem of_bijective_apply_symm_apply {α : Sort u_1} {β : Type u_2} (f : α → β) (hf : function.bijective f) (x : β) : f (coe_fn (equiv.symm (of_bijective f hf)) x) = x :=
apply_symm_apply (of_bijective f hf) x
@[simp] theorem of_bijective_symm_apply_apply {α : Sort u_1} {β : Type u_2} (f : α → β) (hf : function.bijective f) (x : α) : coe_fn (equiv.symm (of_bijective f hf)) (f x) = x :=
symm_apply_apply (of_bijective f hf) x
/-- If `f` is an injective function, then its domain is equivalent to its range. -/
@[simp] theorem of_injective_apply {α : Sort u_1} {β : Type u_2} (f : α → β) (hf : function.injective f) : ∀ (ᾰ : α), coe_fn (of_injective f hf) ᾰ = { val := f ᾰ, property := set.mem_range_self ᾰ } :=
fun (ᾰ : α) => Eq.refl { val := f ᾰ, property := set.mem_range_self ᾰ }
/-- Subtype of the quotient is equivalent to the quotient of the subtype. Let `α` be a setoid with
equivalence relation `~`. Let `p₂` be a predicate on the quotient type `α/~`, and `p₁` be the lift
of this predicate to `α`: `p₁ a ↔ p₂ ⟦a⟧`. Let `~₂` be the restriction of `~` to `{x // p₁ x}`.
Then `{x // p₂ x}` is equivalent to the quotient of `{x // p₁ x}` by `~₂`. -/
def subtype_quotient_equiv_quotient_subtype {α : Sort u} (p₁ : α → Prop) [s₁ : setoid α] [s₂ : setoid (Subtype p₁)] (p₂ : quotient s₁ → Prop) (hp₂ : ∀ (a : α), p₁ a ↔ p₂ (quotient.mk a)) (h : ∀ (x y : Subtype p₁), setoid.r x y ↔ ↑x ≈ ↑y) : (Subtype fun (x : quotient s₁) => p₂ x) ≃ quotient s₂ :=
mk
(fun (a : Subtype fun (x : quotient s₁) => p₂ x) =>
quotient.hrec_on (subtype.val a)
(fun (a : α) (h : p₂ (quotient.mk a)) => quotient.mk { val := a, property := sorry }) sorry sorry)
(fun (a : quotient s₂) =>
quotient.lift_on a (fun (a : Subtype p₁) => { val := quotient.mk (subtype.val a), property := sorry }) sorry)
sorry sorry
/-- A helper function for `equiv.swap`. -/
def swap_core {α : Sort u} [DecidableEq α] (a : α) (b : α) (r : α) : α :=
ite (r = a) b (ite (r = b) a r)
theorem swap_core_self {α : Sort u} [DecidableEq α] (r : α) (a : α) : swap_core a a r = r := sorry
theorem swap_core_swap_core {α : Sort u} [DecidableEq α] (r : α) (a : α) (b : α) : swap_core a b (swap_core a b r) = r := sorry
theorem swap_core_comm {α : Sort u} [DecidableEq α] (r : α) (a : α) (b : α) : swap_core a b r = swap_core b a r := sorry
/-- `swap a b` is the permutation that swaps `a` and `b` and
leaves other values as is. -/
def swap {α : Sort u} [DecidableEq α] (a : α) (b : α) : perm α :=
mk (swap_core a b) (swap_core a b) sorry sorry
@[simp] theorem swap_self {α : Sort u} [DecidableEq α] (a : α) : swap a a = equiv.refl α :=
ext fun (r : α) => swap_core_self r a
theorem swap_comm {α : Sort u} [DecidableEq α] (a : α) (b : α) : swap a b = swap b a :=
ext fun (r : α) => swap_core_comm r a b
theorem swap_apply_def {α : Sort u} [DecidableEq α] (a : α) (b : α) (x : α) : coe_fn (swap a b) x = ite (x = a) b (ite (x = b) a x) :=
rfl
@[simp] theorem swap_apply_left {α : Sort u} [DecidableEq α] (a : α) (b : α) : coe_fn (swap a b) a = b :=
if_pos rfl
@[simp] theorem swap_apply_right {α : Sort u} [DecidableEq α] (a : α) (b : α) : coe_fn (swap a b) b = a := sorry
theorem swap_apply_of_ne_of_ne {α : Sort u} [DecidableEq α] {a : α} {b : α} {x : α} : x ≠ a → x ≠ b → coe_fn (swap a b) x = x := sorry
@[simp] theorem swap_swap {α : Sort u} [DecidableEq α] (a : α) (b : α) : equiv.trans (swap a b) (swap a b) = equiv.refl α :=
ext fun (x : α) => swap_core_swap_core x a b
theorem swap_comp_apply {α : Sort u} [DecidableEq α] {a : α} {b : α} {x : α} (π : perm α) : coe_fn (equiv.trans π (swap a b)) x = ite (coe_fn π x = a) b (ite (coe_fn π x = b) a (coe_fn π x)) := sorry
theorem swap_eq_update {α : Sort u} [DecidableEq α] (i : α) (j : α) : ⇑(swap i j) = function.update (function.update id j i) i j := sorry
theorem comp_swap_eq_update {α : Sort u} {β : Sort v} [DecidableEq α] (i : α) (j : α) (f : α → β) : f ∘ ⇑(swap i j) = function.update (function.update f j (f i)) i (f j) := sorry
@[simp] theorem symm_trans_swap_trans {α : Sort u} {β : Sort v} [DecidableEq α] [DecidableEq β] (a : α) (b : α) (e : α ≃ β) : equiv.trans (equiv.trans (equiv.symm e) (swap a b)) e = swap (coe_fn e a) (coe_fn e b) := sorry
@[simp] theorem trans_swap_trans_symm {α : Sort u} {β : Sort v} [DecidableEq α] [DecidableEq β] (a : β) (b : β) (e : α ≃ β) : equiv.trans (equiv.trans e (swap a b)) (equiv.symm e) = swap (coe_fn (equiv.symm e) a) (coe_fn (equiv.symm e) b) :=
symm_trans_swap_trans a b (equiv.symm e)
@[simp] theorem swap_apply_self {α : Sort u} [DecidableEq α] (i : α) (j : α) (a : α) : coe_fn (swap i j) (coe_fn (swap i j) a) = a := sorry
/-- A function is invariant to a swap if it is equal at both elements -/
theorem apply_swap_eq_self {α : Sort u} {β : Sort v} [DecidableEq α] {v : α → β} {i : α} {j : α} (hv : v i = v j) (k : α) : v (coe_fn (swap i j) k) = v k := sorry
namespace perm
@[simp] theorem sum_congr_swap_refl {α : Type u_1} {β : Type u_2} [DecidableEq α] [DecidableEq β] (i : α) (j : α) : sum_congr (swap i j) (equiv.refl β) = swap (sum.inl i) (sum.inl j) := sorry
@[simp] theorem sum_congr_refl_swap {α : Type u_1} {β : Type u_2} [DecidableEq α] [DecidableEq β] (i : β) (j : β) : sum_congr (equiv.refl α) (swap i j) = swap (sum.inr i) (sum.inr j) := sorry
end perm
/-- Augment an equivalence with a prescribed mapping `f a = b` -/
def set_value {α : Sort u} {β : Sort v} [DecidableEq α] (f : α ≃ β) (a : α) (b : β) : α ≃ β :=
equiv.trans (swap a (coe_fn (equiv.symm f) b)) f
@[simp] theorem set_value_eq {α : Sort u} {β : Sort v} [DecidableEq α] (f : α ≃ β) (a : α) (b : β) : coe_fn (set_value f a b) a = b := sorry
protected theorem exists_unique_congr {α : Sort u} {β : Sort v} {p : α → Prop} {q : β → Prop} (f : α ≃ β) (h : ∀ {x : α}, p x ↔ q (coe_fn f x)) : (exists_unique fun (x : α) => p x) ↔ exists_unique fun (y : β) => q y := sorry
protected theorem exists_unique_congr_left' {α : Sort u} {β : Sort v} {p : α → Prop} (f : α ≃ β) : (exists_unique fun (x : α) => p x) ↔ exists_unique fun (y : β) => p (coe_fn (equiv.symm f) y) := sorry
protected theorem exists_unique_congr_left {α : Sort u} {β : Sort v} {p : β → Prop} (f : α ≃ β) : (exists_unique fun (x : α) => p (coe_fn f x)) ↔ exists_unique fun (y : β) => p y :=
iff.symm (equiv.exists_unique_congr_left' (equiv.symm f))
protected theorem forall_congr {α : Sort u} {β : Sort v} {p : α → Prop} {q : β → Prop} (f : α ≃ β) (h : ∀ {x : α}, p x ↔ q (coe_fn f x)) : (∀ (x : α), p x) ↔ ∀ (y : β), q y := sorry
protected theorem forall_congr' {α : Sort u} {β : Sort v} {p : α → Prop} {q : β → Prop} (f : α ≃ β) (h : ∀ {x : β}, p (coe_fn (equiv.symm f) x) ↔ q x) : (∀ (x : α), p x) ↔ ∀ (y : β), q y :=
iff.symm (equiv.forall_congr (equiv.symm f) fun (x : β) => iff.symm h)
-- We next build some higher arity versions of `equiv.forall_congr`.
-- Although they appear to just be repeated applications of `equiv.forall_congr`,
-- unification of metavariables works better with these versions.
-- In particular, they are necessary in `equiv_rw`.
-- (Stopping at ternary functions seems reasonable: at least in 1-categorical mathematics,
-- it's rare to have axioms involving more than 3 elements at once.)
protected theorem forall₂_congr {α₁ : Sort ua1} {α₂ : Sort ua2} {β₁ : Sort ub1} {β₂ : Sort ub2} {p : α₁ → β₁ → Prop} {q : α₂ → β₂ → Prop} (eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (h : ∀ {x : α₁} {y : β₁}, p x y ↔ q (coe_fn eα x) (coe_fn eβ y)) : (∀ (x : α₁) (y : β₁), p x y) ↔ ∀ (x : α₂) (y : β₂), q x y :=
equiv.forall_congr eα fun (x : α₁) => equiv.forall_congr eβ fun (x_1 : β₁) => h
protected theorem forall₂_congr' {α₁ : Sort ua1} {α₂ : Sort ua2} {β₁ : Sort ub1} {β₂ : Sort ub2} {p : α₁ → β₁ → Prop} {q : α₂ → β₂ → Prop} (eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (h : ∀ {x : α₂} {y : β₂}, p (coe_fn (equiv.symm eα) x) (coe_fn (equiv.symm eβ) y) ↔ q x y) : (∀ (x : α₁) (y : β₁), p x y) ↔ ∀ (x : α₂) (y : β₂), q x y :=
iff.symm (equiv.forall₂_congr (equiv.symm eα) (equiv.symm eβ) fun (x : α₂) (y : β₂) => iff.symm h)
protected theorem forall₃_congr {α₁ : Sort ua1} {α₂ : Sort ua2} {β₁ : Sort ub1} {β₂ : Sort ub2} {γ₁ : Sort ug1} {γ₂ : Sort ug2} {p : α₁ → β₁ → γ₁ → Prop} {q : α₂ → β₂ → γ₂ → Prop} (eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (eγ : γ₁ ≃ γ₂) (h : ∀ {x : α₁} {y : β₁} {z : γ₁}, p x y z ↔ q (coe_fn eα x) (coe_fn eβ y) (coe_fn eγ z)) : (∀ (x : α₁) (y : β₁) (z : γ₁), p x y z) ↔ ∀ (x : α₂) (y : β₂) (z : γ₂), q x y z :=
equiv.forall₂_congr eα eβ fun (x : α₁) (y : β₁) => equiv.forall_congr eγ fun (x_1 : γ₁) => h
protected theorem forall₃_congr' {α₁ : Sort ua1} {α₂ : Sort ua2} {β₁ : Sort ub1} {β₂ : Sort ub2} {γ₁ : Sort ug1} {γ₂ : Sort ug2} {p : α₁ → β₁ → γ₁ → Prop} {q : α₂ → β₂ → γ₂ → Prop} (eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (eγ : γ₁ ≃ γ₂) (h : ∀ {x : α₂} {y : β₂} {z : γ₂},
p (coe_fn (equiv.symm eα) x) (coe_fn (equiv.symm eβ) y) (coe_fn (equiv.symm eγ) z) ↔ q x y z) : (∀ (x : α₁) (y : β₁) (z : γ₁), p x y z) ↔ ∀ (x : α₂) (y : β₂) (z : γ₂), q x y z :=
iff.symm
(equiv.forall₃_congr (equiv.symm eα) (equiv.symm eβ) (equiv.symm eγ) fun (x : α₂) (y : β₂) (z : γ₂) => iff.symm h)
protected theorem forall_congr_left' {α : Sort u} {β : Sort v} {p : α → Prop} (f : α ≃ β) : (∀ (x : α), p x) ↔ ∀ (y : β), p (coe_fn (equiv.symm f) y) := sorry
protected theorem forall_congr_left {α : Sort u} {β : Sort v} {p : β → Prop} (f : α ≃ β) : (∀ (x : α), p (coe_fn f x)) ↔ ∀ (y : β), p y :=
iff.symm (equiv.forall_congr_left' (equiv.symm f))
/--
Transport dependent functions through an equivalence of the base space.
-/
@[simp] theorem Pi_congr_left'_symm_apply {α : Sort u} {β : Sort v} (P : α → Sort w) (e : α ≃ β) (f : (b : β) → P (coe_fn (equiv.symm e) b)) (x : α) : coe_fn (equiv.symm (Pi_congr_left' P e)) f x = eq.mpr (Pi_congr_left'._proof_1 P e x) (f (coe_fn e x)) :=
Eq.refl (coe_fn (equiv.symm (Pi_congr_left' P e)) f x)
/--
Transporting dependent functions through an equivalence of the base,
expressed as a "simplification".
-/
def Pi_congr_left {α : Sort u} {β : Sort v} (P : β → Sort w) (e : α ≃ β) : ((a : α) → P (coe_fn e a)) ≃ ((b : β) → P b) :=
equiv.symm (Pi_congr_left' P (equiv.symm e))
/--
Transport dependent functions through
an equivalence of the base spaces and a family
of equivalences of the matching fibers.
-/
def Pi_congr {α : Sort u} {β : Sort v} {W : α → Sort w} {Z : β → Sort z} (h₁ : α ≃ β) (h₂ : (a : α) → W a ≃ Z (coe_fn h₁ a)) : ((a : α) → W a) ≃ ((b : β) → Z b) :=
equiv.trans (Pi_congr_right h₂) (Pi_congr_left Z h₁)
/--
Transport dependent functions through
an equivalence of the base spaces and a family
of equivalences of the matching fibres.
-/
def Pi_congr' {α : Sort u} {β : Sort v} {W : α → Sort w} {Z : β → Sort z} (h₁ : α ≃ β) (h₂ : (b : β) → W (coe_fn (equiv.symm h₁) b) ≃ Z b) : ((a : α) → W a) ≃ ((b : β) → Z b) :=
equiv.symm (Pi_congr (equiv.symm h₁) fun (b : β) => equiv.symm (h₂ b))
end equiv
theorem function.injective.swap_apply {α : Sort u} {β : Sort v} [DecidableEq α] [DecidableEq β] {f : α → β} (hf : function.injective f) (x : α) (y : α) (z : α) : coe_fn (equiv.swap (f x) (f y)) (f z) = f (coe_fn (equiv.swap x y) z) := sorry
theorem function.injective.swap_comp {α : Sort u} {β : Sort v} [DecidableEq α] [DecidableEq β] {f : α → β} (hf : function.injective f) (x : α) (y : α) : ⇑(equiv.swap (f x) (f y)) ∘ f = f ∘ ⇑(equiv.swap x y) :=
funext fun (z : α) => function.injective.swap_apply hf x y z
protected instance ulift.subsingleton {α : Type u_1} [subsingleton α] : subsingleton (ulift α) :=
equiv.subsingleton equiv.ulift
protected instance plift.subsingleton {α : Sort u_1} [subsingleton α] : subsingleton (plift α) :=
equiv.subsingleton equiv.plift
protected instance ulift.decidable_eq {α : Type u_1} [DecidableEq α] : DecidableEq (ulift α) :=
equiv.decidable_eq equiv.ulift
protected instance plift.decidable_eq {α : Sort u_1} [DecidableEq α] : DecidableEq (plift α) :=
equiv.decidable_eq equiv.plift
/-- If both `α` and `β` are singletons, then `α ≃ β`. -/
def equiv_of_unique_of_unique {α : Sort u} {β : Sort v} [unique α] [unique β] : α ≃ β :=
equiv.mk (fun (_x : α) => Inhabited.default) (fun (_x : β) => Inhabited.default) sorry sorry
/-- If `α` is a singleton, then it is equivalent to any `punit`. -/
def equiv_punit_of_unique {α : Sort u} [unique α] : α ≃ PUnit :=
equiv_of_unique_of_unique
/-- If `α` is a subsingleton, then it is equivalent to `α × α`. -/
def subsingleton_prod_self_equiv {α : Type u_1} [subsingleton α] : α × α ≃ α :=
equiv.mk (fun (p : α × α) => prod.fst p) (fun (a : α) => (a, a)) sorry sorry
/-- To give an equivalence between two subsingleton types, it is sufficient to give any two
functions between them. -/
def equiv_of_subsingleton_of_subsingleton {α : Sort u} {β : Sort v} [subsingleton α] [subsingleton β] (f : α → β) (g : β → α) : α ≃ β :=
equiv.mk f g sorry sorry
/-- `unique (unique α)` is equivalent to `unique α`. -/
def unique_unique_equiv {α : Sort u} : unique (unique α) ≃ unique α :=
equiv_of_subsingleton_of_subsingleton (fun (h : unique (unique α)) => Inhabited.default)
fun (h : unique α) => unique.mk { default := h } sorry
namespace quot
/-- An equivalence `e : α ≃ β` generates an equivalence between quotient spaces,
if `ra a₁ a₂ ↔ rb (e a₁) (e a₂). -/
protected def congr {α : Sort u} {β : Sort v} {ra : α → α → Prop} {rb : β → β → Prop} (e : α ≃ β) (eq : ∀ (a₁ a₂ : α), ra a₁ a₂ ↔ rb (coe_fn e a₁) (coe_fn e a₂)) : Quot ra ≃ Quot rb :=
equiv.mk (quot.map ⇑e sorry) (quot.map ⇑(equiv.symm e) sorry) sorry sorry
/-- Quotients are congruent on equivalences under equality of their relation.
An alternative is just to use rewriting with `eq`, but then computational proofs get stuck. -/
protected def congr_right {α : Sort u} {r : α → α → Prop} {r' : α → α → Prop} (eq : ∀ (a₁ a₂ : α), r a₁ a₂ ↔ r' a₁ a₂) : Quot r ≃ Quot r' :=
quot.congr (equiv.refl α) eq
/-- An equivalence `e : α ≃ β` generates an equivalence between the quotient space of `α`
by a relation `ra` and the quotient space of `β` by the image of this relation under `e`. -/
protected def congr_left {α : Sort u} {β : Sort v} {r : α → α → Prop} (e : α ≃ β) : Quot r ≃ Quot fun (b b' : β) => r (coe_fn (equiv.symm e) b) (coe_fn (equiv.symm e) b') :=
quot.congr e sorry
end quot
namespace quotient
/-- An equivalence `e : α ≃ β` generates an equivalence between quotient spaces,
if `ra a₁ a₂ ↔ rb (e a₁) (e a₂). -/
protected def congr {α : Sort u} {β : Sort v} {ra : setoid α} {rb : setoid β} (e : α ≃ β) (eq : ∀ (a₁ a₂ : α), setoid.r a₁ a₂ ↔ setoid.r (coe_fn e a₁) (coe_fn e a₂)) : quotient ra ≃ quotient rb :=
quot.congr e eq
/-- Quotients are congruent on equivalences under equality of their relation.
An alternative is just to use rewriting with `eq`, but then computational proofs get stuck. -/
protected def congr_right {α : Sort u} {r : setoid α} {r' : setoid α} (eq : ∀ (a₁ a₂ : α), setoid.r a₁ a₂ ↔ setoid.r a₁ a₂) : quotient r ≃ quotient r' :=
quot.congr_right eq
end quotient
/-- If a function is a bijection between two sets `s` and `t`, then it induces an
equivalence between the the types `↥s` and ``↥t`. -/
def set.bij_on.equiv {α : Type u_1} {β : Type u_2} {s : set α} {t : set β} (f : α → β) (h : set.bij_on f s t) : ↥s ≃ ↥t :=
equiv.of_bijective (set.cod_restrict (set.restrict f s) t sorry) (set.bij_on.bijective h)
namespace function
theorem update_comp_equiv {α : Sort u_1} {β : Sort u_2} {α' : Sort u_3} [DecidableEq α'] [DecidableEq α] (f : α → β) (g : α' ≃ α) (a : α) (v : β) : update f a v ∘ ⇑g = update (f ∘ ⇑g) (coe_fn (equiv.symm g) a) v := sorry
theorem update_apply_equiv_apply {α : Sort u_1} {β : Sort u_2} {α' : Sort u_3} [DecidableEq α'] [DecidableEq α] (f : α → β) (g : α' ≃ α) (a : α) (v : β) (a' : α') : update f a v (coe_fn g a') = update (f ∘ ⇑g) (coe_fn (equiv.symm g) a) v a' :=
congr_fun (update_comp_equiv f g a v) a'
end function
/-- The composition of an updated function with an equiv on a subset can be expressed as an
updated function. -/
theorem dite_comp_equiv_update {α : Type u_1} {β : Sort u_2} {γ : Sort u_3} {s : set α} (e : β ≃ ↥s) (v : β → γ) (w : α → γ) (j : β) (x : γ) [DecidableEq β] [DecidableEq α] [(j : α) → Decidable (j ∈ s)] : (fun (i : α) =>
dite (i ∈ s) (fun (h : i ∈ s) => function.update v j x (coe_fn (equiv.symm e) { val := i, property := h }))
fun (h : ¬i ∈ s) => w i) =
function.update
(fun (i : α) =>
dite (i ∈ s) (fun (h : i ∈ s) => v (coe_fn (equiv.symm e) { val := i, property := h })) fun (h : ¬i ∈ s) => w i)
(↑(coe_fn e j)) x := sorry
|
2532971833d5cb7ddacff2b49416b0d9b2c641cb | 02005f45e00c7ecf2c8ca5db60251bd1e9c860b5 | /src/algebra/continued_fractions/computation/approximations.lean | f30a6481d8655ea8560c54450d227318d2f368a9 | [
"Apache-2.0"
] | permissive | anthony2698/mathlib | 03cd69fe5c280b0916f6df2d07c614c8e1efe890 | 407615e05814e98b24b2ff322b14e8e3eb5e5d67 | refs/heads/master | 1,678,792,774,873 | 1,614,371,563,000 | 1,614,371,563,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 14,571 | lean | /-
Copyright (c) 2020 Kevin Kappelmann. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Kappelmann
-/
import algebra.continued_fractions.computation.translations
import algebra.continued_fractions.continuants_recurrence
import algebra.continued_fractions.terminated_stable
import data.nat.fib
/-!
# Approximations for Continued Fraction Computations (`gcf.of`)
## Summary
Let us write `gcf` for `generalized_continued_fraction`. This file contains useful approximations
for the values involved in the continued fractions computation `gcf.of`.
## Main Theorems
- `gcf.of_part_num_eq_one`: shows that all partial numerators `aᵢ` are equal to one.
- `gcf.exists_int_eq_of_part_denom`: shows that all partial denominators `bᵢ` correspond to an
integer.
- `gcf.one_le_of_nth_part_denom`: shows that `1 ≤ bᵢ`.
- `gcf.succ_nth_fib_le_of_nth_denom`: shows that the `n`th denominator `Bₙ` is greater than or equal
to the `n + 1`th fibonacci number `nat.fib (n + 1)`.
- `gcf.le_of_succ_nth_denom`: shows that `Bₙ₊₁ ≥ bₙ * Bₙ`, where `bₙ` is the `n`th partial
denominator of the continued fraction.
## References
- [*Hardy, GH and Wright, EM and Heath-Brown, Roger and Silverman, Joseph*][hardy2008introduction]
-/
namespace generalized_continued_fraction
open generalized_continued_fraction as gcf
variables {K : Type*} {v : K} {n : ℕ} [linear_ordered_field K] [floor_ring K]
/-
We begin with some lemmas about the stream of `int_fract_pair`s, which presumably are not
of great interest for the end user.
-/
namespace int_fract_pair
/-- Shows that the fractional parts of the stream are in `[0,1)`. -/
lemma nth_stream_fr_nonneg_lt_one {ifp_n : int_fract_pair K}
(nth_stream_eq : int_fract_pair.stream v n = some ifp_n) :
0 ≤ ifp_n.fr ∧ ifp_n.fr < 1 :=
begin
cases n,
case nat.zero
{ have : int_fract_pair.of v = ifp_n, by injection nth_stream_eq,
simp [fract_lt_one, fract_nonneg, int_fract_pair.of, this.symm] },
case nat.succ
{ rcases (succ_nth_stream_eq_some_iff.elim_left nth_stream_eq) with ⟨_, _, _, if_of_eq_ifp_n⟩,
simp [fract_lt_one, fract_nonneg, int_fract_pair.of, if_of_eq_ifp_n.symm] }
end
/-- Shows that the fractional parts of the stream are nonnegative. -/
lemma nth_stream_fr_nonneg {ifp_n : int_fract_pair K}
(nth_stream_eq : int_fract_pair.stream v n = some ifp_n) :
0 ≤ ifp_n.fr :=
(nth_stream_fr_nonneg_lt_one nth_stream_eq).left
/-- Shows that the fractional parts of the stream smaller than one. -/
lemma nth_stream_fr_lt_one {ifp_n : int_fract_pair K}
(nth_stream_eq : int_fract_pair.stream v n = some ifp_n) :
ifp_n.fr < 1 :=
(nth_stream_fr_nonneg_lt_one nth_stream_eq).right
/-- Shows that the integer parts of the stream are at least one. -/
lemma one_le_succ_nth_stream_b {ifp_succ_n : int_fract_pair K}
(succ_nth_stream_eq : int_fract_pair.stream v (n + 1) = some ifp_succ_n) :
1 ≤ ifp_succ_n.b :=
begin
obtain ⟨ifp_n, nth_stream_eq, stream_nth_fr_ne_zero, ⟨_⟩⟩ :
∃ ifp_n, int_fract_pair.stream v n = some ifp_n ∧ ifp_n.fr ≠ 0
∧ int_fract_pair.of ifp_n.fr⁻¹ = ifp_succ_n, from
succ_nth_stream_eq_some_iff.elim_left succ_nth_stream_eq,
change 1 ≤ ⌊ifp_n.fr⁻¹⌋,
suffices : 1 ≤ ifp_n.fr⁻¹, { rw_mod_cast [le_floor], assumption },
suffices : ifp_n.fr ≤ 1,
{ have h : 0 < ifp_n.fr :=
lt_of_le_of_ne (nth_stream_fr_nonneg nth_stream_eq) stream_nth_fr_ne_zero.symm,
apply one_le_inv h this },
simp [(le_of_lt (nth_stream_fr_lt_one nth_stream_eq))]
end
/--
Shows that the `n + 1`th integer part `bₙ₊₁` of the stream is smaller or equal than the inverse of
the `n`th fractional part `frₙ` of the stream.
This result is straight-forward as `bₙ₊₁` is defined as the floor of `1 / frₙ`
-/
lemma succ_nth_stream_b_le_nth_stream_fr_inv {ifp_n ifp_succ_n : int_fract_pair K}
(nth_stream_eq : int_fract_pair.stream v n = some ifp_n)
(succ_nth_stream_eq : int_fract_pair.stream v (n + 1) = some ifp_succ_n) :
(ifp_succ_n.b : K) ≤ ifp_n.fr⁻¹ :=
begin
suffices : (⌊ifp_n.fr⁻¹⌋ : K) ≤ ifp_n.fr⁻¹,
{ cases ifp_n with _ ifp_n_fr,
have : ifp_n_fr ≠ 0,
{ intro h, simpa [h, int_fract_pair.stream, nth_stream_eq] using succ_nth_stream_eq },
have : int_fract_pair.of ifp_n_fr⁻¹ = ifp_succ_n,
{ simpa [this, int_fract_pair.stream, nth_stream_eq, option.coe_def] using succ_nth_stream_eq },
rwa ←this },
exact (floor_le ifp_n.fr⁻¹)
end
end int_fract_pair
/-
Next we translate above results about the stream of `int_fract_pair`s to the computed continued
fraction `gcf.of`.
-/
/-- Shows that the integer parts of the continued fraction are at least one. -/
lemma of_one_le_nth_part_denom {b : K}
(nth_part_denom_eq : (gcf.of v).partial_denominators.nth n = some b) :
1 ≤ b :=
begin
obtain ⟨gp_n, nth_s_eq, ⟨_⟩⟩ : ∃ gp_n, (gcf.of v).s.nth n = some gp_n ∧ gp_n.b = b, from
exists_s_b_of_part_denom nth_part_denom_eq,
obtain ⟨ifp_n, succ_nth_stream_eq, ifp_n_b_eq_gp_n_b⟩ :
∃ ifp, int_fract_pair.stream v (n + 1) = some ifp ∧ (ifp.b : K) = gp_n.b, from
int_fract_pair.exists_succ_nth_stream_of_gcf_of_nth_eq_some nth_s_eq,
rw [←ifp_n_b_eq_gp_n_b],
exact_mod_cast (int_fract_pair.one_le_succ_nth_stream_b succ_nth_stream_eq)
end
/--
Shows that the partial numerators `aᵢ` of the continued fraction are equal to one and the partial
denominators `bᵢ` correspond to integers.
-/
lemma of_part_num_eq_one_and_exists_int_part_denom_eq {gp : gcf.pair K}
(nth_s_eq : (gcf.of v).s.nth n = some gp) :
gp.a = 1 ∧ ∃ (z : ℤ), gp.b = (z : K) :=
begin
obtain ⟨ifp, stream_succ_nth_eq, ifp_b_eq_gp_b⟩ :
∃ ifp, int_fract_pair.stream v (n + 1) = some ifp ∧ (ifp.b : K) = gp.b,
from int_fract_pair.exists_succ_nth_stream_of_gcf_of_nth_eq_some nth_s_eq,
have : (gcf.of v).s.nth n = some ⟨1, ifp.b⟩, from
nth_of_eq_some_of_succ_nth_int_fract_pair_stream stream_succ_nth_eq,
have : some gp = some ⟨1, ifp.b⟩, by rwa nth_s_eq at this,
have : gp = ⟨1, ifp.b⟩, by injection this,
-- We know the shape of gp, so now we just have to split the goal and use this knowledge.
cases gp,
split,
{ injection this },
{ existsi ifp.b, injection this }
end
/-- Shows that the partial numerators `aᵢ` are equal to one. -/
lemma of_part_num_eq_one {a : K} (nth_part_num_eq : (gcf.of v).partial_numerators.nth n = some a) :
a = 1 :=
begin
obtain ⟨gp, nth_s_eq, gp_a_eq_a_n⟩ : ∃ gp, (gcf.of v).s.nth n = some gp ∧ gp.a = a, from
exists_s_a_of_part_num nth_part_num_eq,
have : gp.a = 1, from (of_part_num_eq_one_and_exists_int_part_denom_eq nth_s_eq).left,
rwa gp_a_eq_a_n at this
end
/-- Shows that the partial denominators `bᵢ` correspond to an integer. -/
lemma exists_int_eq_of_part_denom {b : K}
(nth_part_denom_eq : (gcf.of v).partial_denominators.nth n = some b) :
∃ (z : ℤ), b = (z : K) :=
begin
obtain ⟨gp, nth_s_eq, gp_b_eq_b_n⟩ : ∃ gp, (gcf.of v).s.nth n = some gp ∧ gp.b = b, from
exists_s_b_of_part_denom nth_part_denom_eq,
have : ∃ (z : ℤ), gp.b = (z : K), from
(of_part_num_eq_one_and_exists_int_part_denom_eq nth_s_eq).right,
rwa gp_b_eq_b_n at this
end
/-
One of our next goals is to show that `Bₙ₊₁ ≥ bₙ * Bₙ`. For this, we first show that the partial
denominators `Bₙ` are bounded from below by the fibonacci sequence `nat.fib`. This then implies that
`0 ≤ Bₙ` and hence `Bₙ₊₂ = bₙ₊₁ * Bₙ₊₁ + Bₙ ≥ bₙ₊₁ * Bₙ₊₁ + 0 = bₙ₊₁ * Bₙ₊₁`.
-/
-- open `nat` as we will make use of fibonacci numbers.
open nat
lemma fib_le_of_continuants_aux_b : (n ≤ 1 ∨ ¬(gcf.of v).terminated_at (n - 2)) →
(fib n : K) ≤ ((gcf.of v).continuants_aux n).b :=
nat.strong_induction_on n
begin
clear n,
assume n IH hyp,
rcases n with _|_|n,
{ simp [fib_succ_succ, continuants_aux] }, -- case n = 0
{ simp [fib_succ_succ, continuants_aux] }, -- case n = 1
{ let g := gcf.of v, -- case 2 ≤ n
have : ¬(n + 2 ≤ 1), by linarith,
have not_terminated_at_n : ¬g.terminated_at n, from or.resolve_left hyp this,
obtain ⟨gp, s_ppred_nth_eq⟩ : ∃ gp, g.s.nth n = some gp, from
option.ne_none_iff_exists'.mp not_terminated_at_n,
set pconts := g.continuants_aux (n + 1) with pconts_eq,
set ppconts := g.continuants_aux n with ppconts_eq,
-- use the recurrence of continuants_aux
suffices : (fib n : K) + fib (n + 1) ≤ gp.a * ppconts.b + gp.b * pconts.b, by
simpa [fib_succ_succ, add_comm,
(continuants_aux_recurrence s_ppred_nth_eq ppconts_eq pconts_eq)],
-- make use of the fact that gp.a = 1
suffices : (fib n : K) + fib (n + 1) ≤ ppconts.b + gp.b * pconts.b, by
simpa [(of_part_num_eq_one $ part_num_eq_s_a s_ppred_nth_eq)],
have not_terminated_at_pred_n : ¬g.terminated_at (n - 1), from
mt (terminated_stable $ nat.sub_le n 1) not_terminated_at_n,
have not_terminated_at_ppred_n : ¬terminated_at g (n - 2), from
mt (terminated_stable (n - 1).pred_le) not_terminated_at_pred_n,
-- use the IH to get the inequalities for `pconts` and `ppconts`
have : (fib (n + 1) : K) ≤ pconts.b, from
IH _ (nat.lt.base $ n + 1) (or.inr not_terminated_at_pred_n),
have ppred_nth_fib_le_ppconts_B : (fib n : K) ≤ ppconts.b, from
IH n (lt_trans (nat.lt.base n) $ nat.lt.base $ n + 1)
(or.inr not_terminated_at_ppred_n),
suffices : (fib (n + 1) : K) ≤ gp.b * pconts.b,
solve_by_elim [(add_le_add ppred_nth_fib_le_ppconts_B)],
-- finally use the fact that 1 ≤ gp.b to solve the goal
suffices : 1 * (fib (n + 1) : K) ≤ gp.b * pconts.b, by rwa [one_mul] at this,
have one_le_gp_b : (1 : K) ≤ gp.b, from
of_one_le_nth_part_denom (part_denom_eq_s_b s_ppred_nth_eq),
have : (0 : K) ≤ fib (n + 1), by exact_mod_cast (fib (n + 1)).zero_le,
have : (0 : K) ≤ gp.b, from le_trans zero_le_one one_le_gp_b,
mono }
end
/-- Shows that the `n`th denominator is greater than or equal to the `n + 1`th fibonacci number,
that is `nat.fib (n + 1) ≤ Bₙ`. -/
lemma succ_nth_fib_le_of_nth_denom (hyp: n = 0 ∨ ¬(gcf.of v).terminated_at (n - 1)) :
(fib (n + 1) : K) ≤ (gcf.of v).denominators n :=
begin
rw [denom_eq_conts_b, nth_cont_eq_succ_nth_cont_aux],
have : (n + 1) ≤ 1 ∨ ¬(gcf.of v).terminated_at (n - 1), by
{ cases n,
case nat.zero : { exact (or.inl $ le_refl 1) },
case nat.succ : { exact or.inr (or.resolve_left hyp n.succ_ne_zero) } },
exact (fib_le_of_continuants_aux_b this)
end
/- As a simple consequence, we can now derive that all denominators are nonnegative. -/
lemma zero_le_of_continuants_aux_b : 0 ≤ ((gcf.of v).continuants_aux n).b :=
begin
let g := gcf.of v,
induction n with n IH,
case nat.zero: { refl },
case nat.succ:
{ cases (decidable.em $ g.terminated_at (n - 1)) with terminated not_terminated,
{ cases n,
{ simp[zero_le_one] },
{ have : g.continuants_aux (n + 2) = g.continuants_aux (n + 1), from
continuants_aux_stable_step_of_terminated terminated,
simp[this, IH] } },
{ calc
(0 : K) ≤ fib (n + 1) : by exact_mod_cast (n + 1).fib.zero_le
... ≤ ((gcf.of v).continuants_aux (n + 1)).b : fib_le_of_continuants_aux_b
(or.inr not_terminated) } }
end
/-- Shows that all denominators are nonnegative. -/
lemma zero_le_of_denom : 0 ≤ (gcf.of v).denominators n :=
by { rw [denom_eq_conts_b, nth_cont_eq_succ_nth_cont_aux], exact zero_le_of_continuants_aux_b }
lemma le_of_succ_succ_nth_continuants_aux_b {b : K}
(nth_part_denom_eq : (gcf.of v).partial_denominators.nth n = some b) :
b * ((gcf.of v).continuants_aux $ n + 1).b ≤ ((gcf.of v).continuants_aux $ n + 2).b :=
begin
set g := gcf.of v with g_eq,
obtain ⟨gp_n, nth_s_eq, ⟨_⟩⟩ : ∃ gp_n, g.s.nth n = some gp_n ∧ gp_n.b = b, from
exists_s_b_of_part_denom nth_part_denom_eq,
let conts := g.continuants_aux (n + 2),
set pconts := g.continuants_aux (n + 1) with pconts_eq,
set ppconts := g.continuants_aux n with ppconts_eq,
-- use the recurrence of continuants_aux and the fact that gp_n.a = 1
suffices : gp_n.b * pconts.b ≤ ppconts.b + gp_n.b * pconts.b, by
{ have : gp_n.a = 1, from of_part_num_eq_one (part_num_eq_s_a nth_s_eq),
finish [(gcf.continuants_aux_recurrence nth_s_eq ppconts_eq pconts_eq)] },
have : 0 ≤ ppconts.b, from zero_le_of_continuants_aux_b,
solve_by_elim [le_add_of_nonneg_of_le, le_refl]
end
/-- Shows that `Bₙ₊₁ ≥ bₙ * Bₙ`, where `bₙ` is the `n`th partial denominator and `Bₙ₊₁` and `Bₙ` are
the `n + 1`th and `n`th denominator of the continued fraction. -/
theorem le_of_succ_nth_denom {b : K}
(nth_part_denom_eq : (gcf.of v).partial_denominators.nth n = some b) :
b * (gcf.of v).denominators n ≤ (gcf.of v).denominators (n + 1) :=
begin
rw [denom_eq_conts_b, nth_cont_eq_succ_nth_cont_aux],
exact (le_of_succ_succ_nth_continuants_aux_b nth_part_denom_eq)
end
/-- Shows that the sequence of denominators is monotonically increasing, that is `Bₙ ≤ Bₙ₊₁`. -/
theorem of_denom_mono : (gcf.of v).denominators n ≤ (gcf.of v).denominators (n + 1) :=
begin
let g := gcf.of v,
cases (decidable.em $ g.partial_denominators.terminated_at n) with terminated not_terminated,
{ have : g.partial_denominators.nth n = none, by rwa seq.terminated_at at terminated,
have : g.terminated_at n, from
terminated_at_iff_part_denom_none.elim_right (by rwa seq.terminated_at at terminated),
have : (gcf.of v).denominators (n + 1) = (gcf.of v).denominators n, from
denominators_stable_of_terminated n.le_succ this,
rw this },
{ obtain ⟨b, nth_part_denom_eq⟩ : ∃ b, g.partial_denominators.nth n = some b, from
option.ne_none_iff_exists'.mp not_terminated,
have : 1 ≤ b, from of_one_le_nth_part_denom nth_part_denom_eq,
calc
(gcf.of v).denominators n ≤ b * (gcf.of v).denominators n : by simpa using
mul_le_mul_of_nonneg_right
this zero_le_of_denom
... ≤ (gcf.of v).denominators (n + 1) : le_of_succ_nth_denom
nth_part_denom_eq }
end
end generalized_continued_fraction
|
e41210aba95d3cd639e1eb5b2df46cd6da07aa62 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Elab/Tactic/Conv/Basic.lean | bc4bb3ce7632261390ac8d03349e2ebf7aa44def | [
"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 | 7,405 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Reduce
import Lean.Meta.Tactic.Apply
import Lean.Meta.Tactic.Replace
import Lean.Elab.Tactic.Basic
import Lean.Elab.Tactic.BuiltinTactic
namespace Lean.Elab.Tactic.Conv
open Meta
/--
Annotate `e` with the LHS annotation. The delaborator displays
expressions of the form `lhs = rhs` as `lhs` when they have this annotation.
This is used to implement the infoview for the `conv` mode.
-/
def mkLHSGoal (e : Expr) : MetaM Expr :=
if let some _ := Expr.eq? e then
return mkLHSGoalRaw e
else
return mkLHSGoalRaw (← whnf e)
/-- Given `lhs`, returns a pair of metavariables `(?rhs, ?newGoal)`
where `?newGoal : lhs = ?rhs`. `tag` is the name of `newGoal`. -/
def mkConvGoalFor (lhs : Expr) (tag : Name := .anonymous) : MetaM (Expr × Expr) := do
let lhsType ← inferType lhs
let rhs ← mkFreshExprMVar lhsType
let targetNew := mkLHSGoalRaw (← mkEq lhs rhs)
let newGoal ← mkFreshExprSyntheticOpaqueMVar targetNew tag
return (rhs, newGoal)
def markAsConvGoal (mvarId : MVarId) : MetaM MVarId := do
let target ← mvarId.getType
if isLHSGoal? target |>.isSome then
return mvarId -- it is already tagged as LHS goal
mvarId.replaceTargetDefEq (← mkLHSGoal (← mvarId.getType))
/-- Given `lhs`, runs the `conv` tactic with the goal `⊢ lhs = ?rhs`.
`conv` should produce no remaining goals that are not solvable with refl.
Returns a pair of instantiated expressions `(?rhs, ?p)` where `?p : lhs = ?rhs`. -/
def convert (lhs : Expr) (conv : TacticM Unit) : TacticM (Expr × Expr) := do
let (rhs, newGoal) ← mkConvGoalFor lhs
let savedGoals ← getGoals
try
setGoals [newGoal.mvarId!]
conv
for mvarId in (← getGoals) do
liftM <| mvarId.refl <|> mvarId.inferInstance <|> pure ()
pruneSolvedGoals
unless (← getGoals).isEmpty do
throwError "convert tactic failed, there are unsolved goals\n{goalsToMessageData (← getGoals)}"
pure ()
finally
setGoals savedGoals
return (← instantiateMVars rhs, ← instantiateMVars newGoal)
def getLhsRhsCore (mvarId : MVarId) : MetaM (Expr × Expr) :=
mvarId.withContext do
let some (_, lhs, rhs) ← matchEq? (← mvarId.getType) | throwError "invalid 'conv' goal"
return (lhs, rhs)
def getLhsRhs : TacticM (Expr × Expr) := do
getLhsRhsCore (← getMainGoal)
def getLhs : TacticM Expr :=
return (← getLhsRhs).1
def getRhs : TacticM Expr :=
return (← getLhsRhs).2
/-- `⊢ lhs = rhs` ~~> `⊢ lhs' = rhs` using `h : lhs = lhs'`. -/
def updateLhs (lhs' : Expr) (h : Expr) : TacticM Unit := do
let mvarId ← getMainGoal
let rhs ← getRhs
let newGoal ← mkFreshExprSyntheticOpaqueMVar (mkLHSGoalRaw (← mkEq lhs' rhs)) (← mvarId.getTag)
mvarId.assign (← mkEqTrans h newGoal)
replaceMainGoal [newGoal.mvarId!]
/-- Replace `lhs` with the definitionally equal `lhs'`. -/
def changeLhs (lhs' : Expr) : TacticM Unit := do
let rhs ← getRhs
liftMetaTactic1 fun mvarId => do
mvarId.replaceTargetDefEq (mkLHSGoalRaw (← mkEq lhs' rhs))
@[builtin_tactic Lean.Parser.Tactic.Conv.whnf] def evalWhnf : Tactic := fun _ =>
withMainContext do
changeLhs (← whnf (← getLhs))
@[builtin_tactic Lean.Parser.Tactic.Conv.reduce] def evalReduce : Tactic := fun _ =>
withMainContext do
changeLhs (← reduce (← getLhs))
@[builtin_tactic Lean.Parser.Tactic.Conv.zeta] def evalZeta : Tactic := fun _ =>
withMainContext do
changeLhs (← zetaReduce (← getLhs))
/-- Evaluate `sepByIndent conv "; " -/
def evalSepByIndentConv (stx : Syntax) : TacticM Unit := do
for arg in stx.getArgs, i in [:stx.getArgs.size] do
if i % 2 == 0 then
evalTactic arg
else
saveTacticInfoForToken arg
@[builtin_tactic Lean.Parser.Tactic.Conv.convSeq1Indented] def evalConvSeq1Indented : Tactic := fun stx => do
evalSepByIndentConv stx[0]
@[builtin_tactic Lean.Parser.Tactic.Conv.convSeqBracketed] def evalConvSeqBracketed : Tactic := fun stx => do
let initInfo ← mkInitialTacticInfo stx[0]
withRef stx[2] <| closeUsingOrAdmit do
-- save state before/after entering focus on `{`
withInfoContext (pure ()) initInfo
evalSepByIndentConv stx[1]
evalTactic (← `(tactic| all_goals (try rfl)))
@[builtin_tactic Lean.Parser.Tactic.Conv.nestedConv] def evalNestedConv : Tactic := fun stx => do
evalConvSeqBracketed stx[0]
@[builtin_tactic Lean.Parser.Tactic.Conv.convSeq] def evalConvSeq : Tactic := fun stx => do
evalTactic stx[0]
@[builtin_tactic Lean.Parser.Tactic.Conv.convConvSeq] def evalConvConvSeq : Tactic := fun stx =>
withMainContext do
let (lhsNew, proof) ← convert (← getLhs) (evalTactic stx[2][0])
updateLhs lhsNew proof
@[builtin_tactic Lean.Parser.Tactic.Conv.paren] def evalParen : Tactic := fun stx =>
evalTactic stx[1]
/-- Mark goals of the form `⊢ a = ?m ..` with the conv goal annotation -/
def remarkAsConvGoal : TacticM Unit := do
let newGoals ← (← getUnsolvedGoals).mapM fun mvarId => mvarId.withContext do
let target ← mvarId.getType
if let some (_, _, rhs) ← matchEq? target then
if rhs.getAppFn.isMVar then
mvarId.replaceTargetDefEq (← mkLHSGoal target)
else
return mvarId
else
return mvarId
setGoals newGoals
@[builtin_tactic Lean.Parser.Tactic.Conv.nestedTacticCore] def evalNestedTacticCore : Tactic := fun stx => do
let seq := stx[2]
evalTactic seq; remarkAsConvGoal
@[builtin_tactic Lean.Parser.Tactic.Conv.nestedTactic] def evalNestedTactic : Tactic := fun stx => do
let seq := stx[2]
let target ← getMainTarget
if let some _ := isLHSGoal? target then
liftMetaTactic1 fun mvarId =>
mvarId.replaceTargetDefEq target.mdataExpr!
focus do evalTactic seq; remarkAsConvGoal
@[builtin_tactic Lean.Parser.Tactic.Conv.convTactic] def evalConvTactic : Tactic := fun stx =>
evalTactic stx[2]
private def convTarget (conv : Syntax) : TacticM Unit := withMainContext do
let target ← getMainTarget
let (targetNew, proof) ← convert target (withTacticInfoContext (← getRef) (evalTactic conv))
liftMetaTactic1 fun mvarId => mvarId.replaceTargetEq targetNew proof
evalTactic (← `(tactic| try rfl))
private def convLocalDecl (conv : Syntax) (hUserName : Name) : TacticM Unit := withMainContext do
let localDecl ← getLocalDeclFromUserName hUserName
let (typeNew, proof) ← convert localDecl.type (withTacticInfoContext (← getRef) (evalTactic conv))
liftMetaTactic1 fun mvarId =>
return some (← mvarId.replaceLocalDecl localDecl.fvarId typeNew proof).mvarId
@[builtin_tactic Lean.Parser.Tactic.Conv.conv] def evalConv : Tactic := fun stx => do
match stx with
| `(tactic| conv%$tk $[at $loc?]? in $(occs)? $p =>%$arr $code) =>
evalTactic (← `(tactic| conv%$tk $[at $loc?]? =>%$arr pattern $(occs)? $p; ($code:convSeq)))
| `(tactic| conv%$tk $[at $loc?]? =>%$arr $code) =>
-- show initial conv goal state between `conv` and `=>`
withRef (mkNullNode #[tk, arr]) do
if let some loc := loc? then
convLocalDecl code loc.getId
else
convTarget code
| _ => throwUnsupportedSyntax
@[builtin_tactic Lean.Parser.Tactic.Conv.first] partial def evalFirst : Tactic :=
Tactic.evalFirst
end Lean.Elab.Tactic.Conv
|
9660c184c249f9cf118fe1a6ee42e7650e4ef4ef | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/topology/uniform_space/uniform_embedding.lean | c2871bd762278a35367f882e381f71d6eec99df4 | [
"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 | 26,239 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Sébastien Gouëzel, Patrick Massot
-/
import topology.uniform_space.cauchy
import topology.uniform_space.separation
import topology.dense_embedding
/-!
# Uniform embeddings of uniform spaces.
Extension of uniform continuous functions.
-/
open filter topological_space set classical
open_locale classical uniformity topological_space filter
section
variables {α : Type*} {β : Type*} {γ : Type*}
[uniform_space α] [uniform_space β] [uniform_space γ]
universes u v
/-- A map `f : α → β` between uniform spaces is called *uniform inducing* if the uniformity filter
on `α` is the pullback of the uniformity filter on `β` under `prod.map f f`. If `α` is a separated
space, then this implies that `f` is injective, hence it is a `uniform_embedding`. -/
structure uniform_inducing (f : α → β) : Prop :=
(comap_uniformity : comap (λx:α×α, (f x.1, f x.2)) (𝓤 β) = 𝓤 α)
lemma uniform_inducing.mk' {f : α → β} (h : ∀ s, s ∈ 𝓤 α ↔
∃ t ∈ 𝓤 β, ∀ x y : α, (f x, f y) ∈ t → (x, y) ∈ s) : uniform_inducing f :=
⟨by simp [eq_comm, filter.ext_iff, subset_def, h]⟩
lemma uniform_inducing_id : uniform_inducing (@id α) :=
⟨by rw [← prod.map_def, prod.map_id, comap_id]⟩
lemma uniform_inducing.comp {g : β → γ} (hg : uniform_inducing g)
{f : α → β} (hf : uniform_inducing f) : uniform_inducing (g ∘ f) :=
⟨ by rw [show (λ (x : α × α), ((g ∘ f) x.1, (g ∘ f) x.2)) =
(λ y : β × β, (g y.1, g y.2)) ∘ (λ x : α × α, (f x.1, f x.2)), by ext ; simp,
← filter.comap_comap, hg.1, hf.1]⟩
lemma uniform_inducing.basis_uniformity {f : α → β} (hf : uniform_inducing f)
{ι : Sort*} {p : ι → Prop} {s : ι → set (β × β)} (H : (𝓤 β).has_basis p s) :
(𝓤 α).has_basis p (λ i, prod.map f f ⁻¹' s i) :=
hf.1 ▸ H.comap _
lemma uniform_inducing.cauchy_map_iff {f : α → β} (hf : uniform_inducing f) {F : filter α} :
cauchy (map f F) ↔ cauchy F :=
by simp only [cauchy, map_ne_bot_iff, prod_map_map_eq, map_le_iff_le_comap, ← hf.comap_uniformity]
lemma uniform_inducing_of_compose {f : α → β} {g : β → γ} (hf : uniform_continuous f)
(hg : uniform_continuous g) (hgf : uniform_inducing (g ∘ f)) : uniform_inducing f :=
begin
refine ⟨le_antisymm _ hf.le_comap⟩,
rw [← hgf.1, ← prod.map_def, ← prod.map_def, ← prod.map_comp_map f f g g,
← @comap_comap _ _ _ _ (prod.map f f)],
exact comap_mono hg.le_comap
end
/-- A map `f : α → β` between uniform spaces is a *uniform embedding* if it is uniform inducing and
injective. If `α` is a separated space, then the latter assumption follows from the former. -/
structure uniform_embedding (f : α → β) extends uniform_inducing f : Prop :=
(inj : function.injective f)
lemma uniform_embedding_subtype_val {p : α → Prop} :
uniform_embedding (subtype.val : subtype p → α) :=
{ comap_uniformity := rfl,
inj := subtype.val_injective }
lemma uniform_embedding_subtype_coe {p : α → Prop} :
uniform_embedding (coe : subtype p → α) :=
uniform_embedding_subtype_val
lemma uniform_embedding_set_inclusion {s t : set α} (hst : s ⊆ t) :
uniform_embedding (inclusion hst) :=
{ comap_uniformity :=
by { erw [uniformity_subtype, uniformity_subtype, comap_comap], congr },
inj := inclusion_injective hst }
lemma uniform_embedding.comp {g : β → γ} (hg : uniform_embedding g)
{f : α → β} (hf : uniform_embedding f) : uniform_embedding (g ∘ f) :=
{ inj := hg.inj.comp hf.inj,
..hg.to_uniform_inducing.comp hf.to_uniform_inducing }
theorem uniform_embedding_def {f : α → β} :
uniform_embedding f ↔ function.injective f ∧ ∀ s, s ∈ 𝓤 α ↔
∃ t ∈ 𝓤 β, ∀ x y : α, (f x, f y) ∈ t → (x, y) ∈ s :=
begin
split,
{ rintro ⟨⟨h⟩, h'⟩,
rw [eq_comm, filter.ext_iff] at h,
simp [*, subset_def] },
{ rintro ⟨h, h'⟩,
refine uniform_embedding.mk ⟨_⟩ h,
rw [eq_comm, filter.ext_iff],
simp [*, subset_def] }
end
theorem uniform_embedding_def' {f : α → β} :
uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧
∀ s, s ∈ 𝓤 α →
∃ t ∈ 𝓤 β, ∀ x y : α, (f x, f y) ∈ t → (x, y) ∈ s :=
by simp only [uniform_embedding_def, uniform_continuous_def]; exact
⟨λ ⟨I, H⟩, ⟨I, λ s su, (H _).2 ⟨s, su, λ x y, id⟩, λ s, (H s).1⟩,
λ ⟨I, H₁, H₂⟩, ⟨I, λ s, ⟨H₂ s,
λ ⟨t, tu, h⟩, mem_of_superset (H₁ t tu) (λ ⟨a, b⟩, h a b)⟩⟩⟩
lemma equiv.uniform_embedding {α β : Type*} [uniform_space α] [uniform_space β] (f : α ≃ β)
(h₁ : uniform_continuous f) (h₂ : uniform_continuous f.symm) : uniform_embedding f :=
{ comap_uniformity :=
begin
refine le_antisymm _ _,
{ change comap (f.prod_congr f) _ ≤ _,
rw ← map_equiv_symm (f.prod_congr f),
exact h₂ },
{ rw ← map_le_iff_le_comap,
exact h₁ }
end,
inj := f.injective }
theorem uniform_embedding_inl : uniform_embedding (sum.inl : α → α ⊕ β) :=
begin
apply uniform_embedding_def.2 ⟨sum.inl_injective, λ s, ⟨_, _⟩⟩,
{ assume hs,
refine ⟨(λ p : α × α, (sum.inl p.1, sum.inl p.2)) '' s ∪
(λ p : β × β, (sum.inr p.1, sum.inr p.2)) '' univ, _, _⟩,
{ exact union_mem_uniformity_sum hs univ_mem },
{ simp } },
{ rintros ⟨t, ht, h't⟩,
simp only [sum.uniformity, mem_sup, mem_map] at ht,
apply filter.mem_of_superset ht.1,
rintros ⟨x, y⟩ hx,
exact h't _ _ hx }
end
theorem uniform_embedding_inr : uniform_embedding (sum.inr : β → α ⊕ β) :=
begin
apply uniform_embedding_def.2 ⟨sum.inr_injective, λ s, ⟨_, _⟩⟩,
{ assume hs,
refine ⟨(λ p : α × α, (sum.inl p.1, sum.inl p.2)) '' univ ∪
(λ p : β × β, (sum.inr p.1, sum.inr p.2)) '' s, _, _⟩,
{ exact union_mem_uniformity_sum univ_mem hs },
{ simp } },
{ rintros ⟨t, ht, h't⟩,
simp only [sum.uniformity, mem_sup, mem_map] at ht,
apply filter.mem_of_superset ht.2,
rintros ⟨x, y⟩ hx,
exact h't _ _ hx }
end
/-- If the domain of a `uniform_inducing` map `f` is a `separated_space`, then `f` is injective,
hence it is a `uniform_embedding`. -/
protected theorem uniform_inducing.uniform_embedding [separated_space α] {f : α → β}
(hf : uniform_inducing f) :
uniform_embedding f :=
⟨hf, λ x y h, eq_of_uniformity_basis (hf.basis_uniformity (𝓤 β).basis_sets) $
λ s hs, mem_preimage.2 $ mem_uniformity_of_eq hs h⟩
/-- If a map `f : α → β` sends any two distinct points to point that are **not** related by a fixed
`s ∈ 𝓤 β`, then `f` is uniform inducing with respect to the discrete uniformity on `α`:
the preimage of `𝓤 β` under `prod.map f f` is the principal filter generated by the diagonal in
`α × α`. -/
lemma comap_uniformity_of_spaced_out {α} {f : α → β} {s : set (β × β)} (hs : s ∈ 𝓤 β)
(hf : pairwise (λ x y, (f x, f y) ∉ s)) :
comap (prod.map f f) (𝓤 β) = 𝓟 id_rel :=
begin
refine le_antisymm _ (@refl_le_uniformity α (uniform_space.comap f ‹_›)),
calc comap (prod.map f f) (𝓤 β) ≤ comap (prod.map f f) (𝓟 s) : comap_mono (le_principal_iff.2 hs)
... = 𝓟 (prod.map f f ⁻¹' s) : comap_principal
... ≤ 𝓟 id_rel : principal_mono.2 _,
rintro ⟨x, y⟩, simpa [not_imp_not] using @hf x y
end
/-- If a map `f : α → β` sends any two distinct points to point that are **not** related by a fixed
`s ∈ 𝓤 β`, then `f` is a uniform embedding with respect to the discrete uniformity on `α`. -/
lemma uniform_embedding_of_spaced_out {α} {f : α → β} {s : set (β × β)} (hs : s ∈ 𝓤 β)
(hf : pairwise (λ x y, (f x, f y) ∉ s)) :
@uniform_embedding α β ⊥ ‹_› f :=
begin
letI : uniform_space α := ⊥, haveI : separated_space α := separated_iff_t2.2 infer_instance,
exact uniform_inducing.uniform_embedding ⟨comap_uniformity_of_spaced_out hs hf⟩
end
lemma uniform_inducing.uniform_continuous {f : α → β}
(hf : uniform_inducing f) : uniform_continuous f :=
by simp [uniform_continuous, hf.comap_uniformity.symm, tendsto_comap]
lemma uniform_inducing.uniform_continuous_iff {f : α → β} {g : β → γ} (hg : uniform_inducing g) :
uniform_continuous f ↔ uniform_continuous (g ∘ f) :=
by { dsimp only [uniform_continuous, tendsto],
rw [← hg.comap_uniformity, ← map_le_iff_le_comap, filter.map_map] }
lemma uniform_inducing.inducing {f : α → β} (h : uniform_inducing f) : inducing f :=
begin
refine ⟨eq_of_nhds_eq_nhds $ assume a, _ ⟩,
rw [nhds_induced, nhds_eq_uniformity, nhds_eq_uniformity, ← h.comap_uniformity,
comap_lift'_eq, comap_lift'_eq2],
exacts [rfl, monotone_preimage]
end
lemma uniform_inducing.prod {α' : Type*} {β' : Type*} [uniform_space α'] [uniform_space β']
{e₁ : α → α'} {e₂ : β → β'} (h₁ : uniform_inducing e₁) (h₂ : uniform_inducing e₂) :
uniform_inducing (λp:α×β, (e₁ p.1, e₂ p.2)) :=
⟨by simp [(∘), uniformity_prod, h₁.comap_uniformity.symm, h₂.comap_uniformity.symm,
comap_inf, comap_comap]⟩
lemma uniform_inducing.dense_inducing {f : α → β} (h : uniform_inducing f) (hd : dense_range f) :
dense_inducing f :=
{ dense := hd,
induced := h.inducing.induced }
lemma uniform_embedding.embedding {f : α → β} (h : uniform_embedding f) : embedding f :=
{ induced := h.to_uniform_inducing.inducing.induced,
inj := h.inj }
lemma uniform_embedding.dense_embedding {f : α → β} (h : uniform_embedding f) (hd : dense_range f) :
dense_embedding f :=
{ dense := hd,
inj := h.inj,
induced := h.embedding.induced }
lemma closed_embedding_of_spaced_out {α} [topological_space α] [discrete_topology α]
[separated_space β] {f : α → β} {s : set (β × β)} (hs : s ∈ 𝓤 β)
(hf : pairwise (λ x y, (f x, f y) ∉ s)) :
closed_embedding f :=
begin
unfreezingI { rcases (discrete_topology.eq_bot α) with rfl }, letI : uniform_space α := ⊥,
exact { closed_range := is_closed_range_of_spaced_out hs hf,
.. (uniform_embedding_of_spaced_out hs hf).embedding }
end
lemma closure_image_mem_nhds_of_uniform_inducing
{s : set (α×α)} {e : α → β} (b : β)
(he₁ : uniform_inducing e) (he₂ : dense_inducing e) (hs : s ∈ 𝓤 α) :
∃a, closure (e '' {a' | (a, a') ∈ s}) ∈ 𝓝 b :=
have s ∈ comap (λp:α×α, (e p.1, e p.2)) (𝓤 β),
from he₁.comap_uniformity.symm ▸ hs,
let ⟨t₁, ht₁u, ht₁⟩ := this in
have ht₁ : ∀p:α×α, (e p.1, e p.2) ∈ t₁ → p ∈ s, from ht₁,
let ⟨t₂, ht₂u, ht₂s, ht₂c⟩ := comp_symm_of_uniformity ht₁u in
let ⟨t, htu, hts, htc⟩ := comp_symm_of_uniformity ht₂u in
have preimage e {b' | (b, b') ∈ t₂} ∈ comap e (𝓝 b),
from preimage_mem_comap $ mem_nhds_left b ht₂u,
let ⟨a, (ha : (b, e a) ∈ t₂)⟩ := (he₂.comap_nhds_ne_bot _).nonempty_of_mem this in
have ∀b' (s' : set (β × β)), (b, b') ∈ t → s' ∈ 𝓤 β →
({y : β | (b', y) ∈ s'} ∩ e '' {a' : α | (a, a') ∈ s}).nonempty,
from assume b' s' hb' hs',
have preimage e {b'' | (b', b'') ∈ s' ∩ t} ∈ comap e (𝓝 b'),
from preimage_mem_comap $ mem_nhds_left b' $ inter_mem hs' htu,
let ⟨a₂, ha₂s', ha₂t⟩ := (he₂.comap_nhds_ne_bot _).nonempty_of_mem this in
have (e a, e a₂) ∈ t₁,
from ht₂c $ prod_mk_mem_comp_rel (ht₂s ha) $ htc $ prod_mk_mem_comp_rel hb' ha₂t,
have e a₂ ∈ {b'':β | (b', b'') ∈ s'} ∩ e '' {a' | (a, a') ∈ s},
from ⟨ha₂s', mem_image_of_mem _ $ ht₁ (a, a₂) this⟩,
⟨_, this⟩,
have ∀b', (b, b') ∈ t → ne_bot (𝓝 b' ⊓ 𝓟 (e '' {a' | (a, a') ∈ s})),
begin
intros b' hb',
rw [nhds_eq_uniformity, lift'_inf_principal_eq, lift'_ne_bot_iff],
exact assume s, this b' s hb',
exact monotone_preimage.inter monotone_const
end,
have ∀b', (b, b') ∈ t → b' ∈ closure (e '' {a' | (a, a') ∈ s}),
from assume b' hb', by rw [closure_eq_cluster_pts]; exact this b' hb',
⟨a, (𝓝 b).sets_of_superset (mem_nhds_left b htu) this⟩
lemma uniform_embedding_subtype_emb (p : α → Prop) {e : α → β} (ue : uniform_embedding e)
(de : dense_embedding e) : uniform_embedding (dense_embedding.subtype_emb p e) :=
{ comap_uniformity := by simp [comap_comap, (∘), dense_embedding.subtype_emb,
uniformity_subtype, ue.comap_uniformity.symm],
inj := (de.subtype p).inj }
lemma uniform_embedding.prod {α' : Type*} {β' : Type*} [uniform_space α'] [uniform_space β']
{e₁ : α → α'} {e₂ : β → β'} (h₁ : uniform_embedding e₁) (h₂ : uniform_embedding e₂) :
uniform_embedding (λp:α×β, (e₁ p.1, e₂ p.2)) :=
{ inj := h₁.inj.prod_map h₂.inj,
..h₁.to_uniform_inducing.prod h₂.to_uniform_inducing }
lemma is_complete_of_complete_image {m : α → β} {s : set α} (hm : uniform_inducing m)
(hs : is_complete (m '' s)) : is_complete s :=
begin
intros f hf hfs,
rw le_principal_iff at hfs,
obtain ⟨_, ⟨x, hx, rfl⟩, hyf⟩ : ∃ y ∈ m '' s, map m f ≤ 𝓝 y,
from hs (f.map m) (hf.map hm.uniform_continuous)
(le_principal_iff.2 (image_mem_map hfs)),
rw [map_le_iff_le_comap, ← nhds_induced, ← hm.inducing.induced] at hyf,
exact ⟨x, hx, hyf⟩
end
lemma is_complete.complete_space_coe {s : set α} (hs : is_complete s) :
complete_space s :=
complete_space_iff_is_complete_univ.2 $
is_complete_of_complete_image uniform_embedding_subtype_coe.to_uniform_inducing $ by simp [hs]
/-- A set is complete iff its image under a uniform inducing map is complete. -/
lemma is_complete_image_iff {m : α → β} {s : set α} (hm : uniform_inducing m) :
is_complete (m '' s) ↔ is_complete s :=
begin
refine ⟨is_complete_of_complete_image hm, λ c, _⟩,
haveI : complete_space s := c.complete_space_coe,
set m' : s → β := m ∘ coe,
suffices : is_complete (range m'), by rwa [range_comp, subtype.range_coe] at this,
have hm' : uniform_inducing m' := hm.comp uniform_embedding_subtype_coe.to_uniform_inducing,
intros f hf hfm,
rw filter.le_principal_iff at hfm,
have cf' : cauchy (comap m' f) :=
hf.comap' hm'.comap_uniformity.le (ne_bot.comap_of_range_mem hf.1 hfm),
rcases complete_space.complete cf' with ⟨x, hx⟩,
rw [hm'.inducing.nhds_eq_comap, comap_le_comap_iff hfm] at hx,
use [m' x, mem_range_self _, hx]
end
lemma complete_space_iff_is_complete_range {f : α → β} (hf : uniform_inducing f) :
complete_space α ↔ is_complete (range f) :=
by rw [complete_space_iff_is_complete_univ, ← is_complete_image_iff hf, image_univ]
lemma uniform_inducing.is_complete_range [complete_space α] {f : α → β}
(hf : uniform_inducing f) :
is_complete (range f) :=
(complete_space_iff_is_complete_range hf).1 ‹_›
lemma complete_space_congr {e : α ≃ β} (he : uniform_embedding e) :
complete_space α ↔ complete_space β :=
by rw [complete_space_iff_is_complete_range he.to_uniform_inducing, e.range_eq_univ,
complete_space_iff_is_complete_univ]
lemma complete_space_coe_iff_is_complete {s : set α} :
complete_space s ↔ is_complete s :=
(complete_space_iff_is_complete_range uniform_embedding_subtype_coe.to_uniform_inducing).trans $
by rw [subtype.range_coe]
lemma is_closed.complete_space_coe [complete_space α] {s : set α} (hs : is_closed s) :
complete_space s :=
hs.is_complete.complete_space_coe
/-- The lift of a complete space to another universe is still complete. -/
instance ulift.complete_space [h : complete_space α] : complete_space (ulift α) :=
begin
have : uniform_embedding (@equiv.ulift α), from ⟨⟨rfl⟩, ulift.down_injective⟩,
exact (complete_space_congr this).2 h,
end
lemma complete_space_extension {m : β → α} (hm : uniform_inducing m) (dense : dense_range m)
(h : ∀f:filter β, cauchy f → ∃x:α, map m f ≤ 𝓝 x) : complete_space α :=
⟨assume (f : filter α), assume hf : cauchy f,
let
p : set (α × α) → set α → set α := λs t, {y : α| ∃x:α, x ∈ t ∧ (x, y) ∈ s},
g := (𝓤 α).lift (λs, f.lift' (p s))
in
have mp₀ : monotone p,
from assume a b h t s ⟨x, xs, xa⟩, ⟨x, xs, h xa⟩,
have mp₁ : ∀{s}, monotone (p s),
from assume s a b h x ⟨y, ya, yxs⟩, ⟨y, h ya, yxs⟩,
have f ≤ g, from
le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht,
le_principal_iff.mpr $
mem_of_superset ht $ assume x hx, ⟨x, hx, refl_mem_uniformity hs⟩,
have ne_bot g, from hf.left.mono this,
have ne_bot (comap m g), from comap_ne_bot $ assume t ht,
let ⟨t', ht', ht_mem⟩ := (mem_lift_sets $ monotone_lift' monotone_const mp₀).mp ht in
let ⟨t'', ht'', ht'_sub⟩ := (mem_lift'_sets mp₁).mp ht_mem in
let ⟨x, (hx : x ∈ t'')⟩ := hf.left.nonempty_of_mem ht'' in
have h₀ : ne_bot (𝓝[range m] x),
from dense.nhds_within_ne_bot x,
have h₁ : {y | (x, y) ∈ t'} ∈ 𝓝[range m] x,
from @mem_inf_of_left α (𝓝 x) (𝓟 (range m)) _ $ mem_nhds_left x ht',
have h₂ : range m ∈ 𝓝[range m] x,
from @mem_inf_of_right α (𝓝 x) (𝓟 (range m)) _ $ subset.refl _,
have {y | (x, y) ∈ t'} ∩ range m ∈ 𝓝[range m] x,
from @inter_mem α (𝓝[range m] x) _ _ h₁ h₂,
let ⟨y, xyt', b, b_eq⟩ := h₀.nonempty_of_mem this in
⟨b, b_eq.symm ▸ ht'_sub ⟨x, hx, xyt'⟩⟩,
have cauchy g, from
⟨‹ne_bot g›, assume s hs,
let
⟨s₁, hs₁, (comp_s₁ : comp_rel s₁ s₁ ⊆ s)⟩ := comp_mem_uniformity_sets hs,
⟨s₂, hs₂, (comp_s₂ : comp_rel s₂ s₂ ⊆ s₁)⟩ := comp_mem_uniformity_sets hs₁,
⟨t, ht, (prod_t : t ×ˢ t ⊆ s₂)⟩ := mem_prod_same_iff.mp (hf.right hs₂)
in
have hg₁ : p (preimage prod.swap s₁) t ∈ g,
from mem_lift (symm_le_uniformity hs₁) $ @mem_lift' α α f _ t ht,
have hg₂ : p s₂ t ∈ g,
from mem_lift hs₂ $ @mem_lift' α α f _ t ht,
have hg : p (prod.swap ⁻¹' s₁) t ×ˢ p s₂ t ∈ g ×ᶠ g,
from @prod_mem_prod α α _ _ g g hg₁ hg₂,
(g ×ᶠ g).sets_of_superset hg
(assume ⟨a, b⟩ ⟨⟨c₁, c₁t, hc₁⟩, ⟨c₂, c₂t, hc₂⟩⟩,
have (c₁, c₂) ∈ t ×ˢ t, from ⟨c₁t, c₂t⟩,
comp_s₁ $ prod_mk_mem_comp_rel hc₁ $
comp_s₂ $ prod_mk_mem_comp_rel (prod_t this) hc₂)⟩,
have cauchy (filter.comap m g),
from ‹cauchy g›.comap' (le_of_eq hm.comap_uniformity) ‹_›,
let ⟨x, (hx : map m (filter.comap m g) ≤ 𝓝 x)⟩ := h _ this in
have cluster_pt x (map m (filter.comap m g)),
from (le_nhds_iff_adhp_of_cauchy (this.map hm.uniform_continuous)).mp hx,
have cluster_pt x g,
from this.mono map_comap_le,
⟨x, calc f ≤ g : by assumption
... ≤ 𝓝 x : le_nhds_of_cauchy_adhp ‹cauchy g› this⟩⟩
lemma totally_bounded_preimage {f : α → β} {s : set β} (hf : uniform_embedding f)
(hs : totally_bounded s) : totally_bounded (f ⁻¹' s) :=
λ t ht, begin
rw ← hf.comap_uniformity at ht,
rcases mem_comap.2 ht with ⟨t', ht', ts⟩,
rcases totally_bounded_iff_subset.1
(totally_bounded_subset (image_preimage_subset f s) hs) _ ht' with ⟨c, cs, hfc, hct⟩,
refine ⟨f ⁻¹' c, hfc.preimage (hf.inj.inj_on _), λ x h, _⟩,
have := hct (mem_image_of_mem f h), simp at this ⊢,
rcases this with ⟨z, zc, zt⟩,
rcases cs zc with ⟨y, yc, rfl⟩,
exact ⟨y, zc, ts (by exact zt)⟩
end
instance complete_space.sum [complete_space α] [complete_space β] :
complete_space (α ⊕ β) :=
begin
rw [complete_space_iff_is_complete_univ, ← range_inl_union_range_inr],
exact uniform_embedding_inl.to_uniform_inducing.is_complete_range.union
uniform_embedding_inr.to_uniform_inducing.is_complete_range
end
end
lemma uniform_embedding_comap {α : Type*} {β : Type*} {f : α → β} [u : uniform_space β]
(hf : function.injective f) : @uniform_embedding α β (uniform_space.comap f u) u f :=
@uniform_embedding.mk _ _ (uniform_space.comap f u) _ _
(@uniform_inducing.mk _ _ (uniform_space.comap f u) _ _ rfl) hf
/-- Pull back a uniform space structure by an embedding, adjusting the new uniform structure to
make sure that its topology is defeq to the original one. -/
def embedding.comap_uniform_space {α β} [topological_space α] [u : uniform_space β] (f : α → β)
(h : embedding f) : uniform_space α :=
(u.comap f).replace_topology h.induced
lemma embedding.to_uniform_embedding {α β} [topological_space α] [u : uniform_space β] (f : α → β)
(h : embedding f) :
@uniform_embedding α β (h.comap_uniform_space f) u f :=
{ comap_uniformity := rfl,
inj := h.inj }
section uniform_extension
variables {α : Type*} {β : Type*} {γ : Type*}
[uniform_space α] [uniform_space β] [uniform_space γ]
{e : β → α}
(h_e : uniform_inducing e)
(h_dense : dense_range e)
{f : β → γ}
(h_f : uniform_continuous f)
local notation `ψ` := (h_e.dense_inducing h_dense).extend f
lemma uniformly_extend_exists [complete_space γ] (a : α) :
∃c, tendsto f (comap e (𝓝 a)) (𝓝 c) :=
let de := (h_e.dense_inducing h_dense) in
have cauchy (𝓝 a), from cauchy_nhds,
have cauchy (comap e (𝓝 a)), from
this.comap' (le_of_eq h_e.comap_uniformity) (de.comap_nhds_ne_bot _),
have cauchy (map f (comap e (𝓝 a))), from this.map h_f,
complete_space.complete this
lemma uniform_extend_subtype [complete_space γ]
{p : α → Prop} {e : α → β} {f : α → γ} {b : β} {s : set α}
(hf : uniform_continuous (λx:subtype p, f x.val))
(he : uniform_embedding e) (hd : ∀x:β, x ∈ closure (range e))
(hb : closure (e '' s) ∈ 𝓝 b) (hs : is_closed s) (hp : ∀x∈s, p x) :
∃c, tendsto f (comap e (𝓝 b)) (𝓝 c) :=
have de : dense_embedding e,
from he.dense_embedding hd,
have de' : dense_embedding (dense_embedding.subtype_emb p e),
by exact de.subtype p,
have ue' : uniform_embedding (dense_embedding.subtype_emb p e),
from uniform_embedding_subtype_emb _ he de,
have b ∈ closure (e '' {x | p x}),
from (closure_mono $ monotone_image $ hp) (mem_of_mem_nhds hb),
let ⟨c, (hc : tendsto (f ∘ subtype.val)
(comap (dense_embedding.subtype_emb p e) (𝓝 ⟨b, this⟩)) (𝓝 c))⟩ :=
uniformly_extend_exists ue'.to_uniform_inducing de'.dense hf _ in
begin
rw [nhds_subtype_eq_comap] at hc,
simp [comap_comap] at hc,
change (tendsto (f ∘ @subtype.val α p) (comap (e ∘ @subtype.val α p) (𝓝 b)) (𝓝 c)) at hc,
rw [←comap_comap, tendsto_comap'_iff] at hc,
exact ⟨c, hc⟩,
exact ⟨_, hb, assume x,
begin
change e x ∈ (closure (e '' s)) → x ∈ range subtype.val,
rw [← closure_induced, mem_closure_iff_cluster_pt, cluster_pt, ne_bot_iff,
nhds_induced, ← de.to_dense_inducing.nhds_eq_comap,
← mem_closure_iff_nhds_ne_bot, hs.closure_eq],
exact assume hxs, ⟨⟨x, hp x hxs⟩, rfl⟩,
end⟩
end
include h_f
lemma uniformly_extend_spec [complete_space γ] (a : α) :
tendsto f (comap e (𝓝 a)) (𝓝 (ψ a)) :=
by simpa only [dense_inducing.extend] using tendsto_nhds_lim (uniformly_extend_exists h_e ‹_› h_f _)
lemma uniform_continuous_uniformly_extend [cγ : complete_space γ] : uniform_continuous ψ :=
assume d hd,
let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $
monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp
(comp_le_uniformity3 hd) in
have h_pnt : ∀{a m}, m ∈ 𝓝 a → ∃c, c ∈ f '' preimage e m ∧ (c, ψ a) ∈ s ∧ (ψ a, c) ∈ s,
from assume a m hm,
have nb : ne_bot (map f (comap e (𝓝 a))),
from ((h_e.dense_inducing h_dense).comap_nhds_ne_bot _).map _,
have (f '' preimage e m) ∩ ({c | (c, ψ a) ∈ s } ∩ {c | (ψ a, c) ∈ s }) ∈ map f (comap e (𝓝 a)),
from inter_mem (image_mem_map $ preimage_mem_comap $ hm)
(uniformly_extend_spec h_e h_dense h_f _
(inter_mem (mem_nhds_right _ hs) (mem_nhds_left _ hs))),
nb.nonempty_of_mem this,
have preimage (λp:β×β, (f p.1, f p.2)) s ∈ 𝓤 β,
from h_f hs,
have preimage (λp:β×β, (f p.1, f p.2)) s ∈ comap (λx:β×β, (e x.1, e x.2)) (𝓤 α),
by rwa [h_e.comap_uniformity.symm] at this,
let ⟨t, ht, ts⟩ := this in
show preimage (λp:(α×α), (ψ p.1, ψ p.2)) d ∈ 𝓤 α,
from (𝓤 α).sets_of_superset (interior_mem_uniformity ht) $
assume ⟨x₁, x₂⟩ hx_t,
have 𝓝 (x₁, x₂) ≤ 𝓟 (interior t),
from is_open_iff_nhds.mp is_open_interior (x₁, x₂) hx_t,
have interior t ∈ 𝓝 x₁ ×ᶠ 𝓝 x₂,
by rwa [nhds_prod_eq, le_principal_iff] at this,
let ⟨m₁, hm₁, m₂, hm₂, (hm : m₁ ×ˢ m₂ ⊆ interior t)⟩ := mem_prod_iff.mp this in
let ⟨a, ha₁, _, ha₂⟩ := h_pnt hm₁ in
let ⟨b, hb₁, hb₂, _⟩ := h_pnt hm₂ in
have (e ⁻¹' m₁) ×ˢ (e ⁻¹' m₂) ⊆ (λ p : β × β, (f p.1, f p.2)) ⁻¹' s,
from calc _ ⊆ preimage (λp:(β×β), (e p.1, e p.2)) (interior t) : preimage_mono hm
... ⊆ preimage (λp:(β×β), (e p.1, e p.2)) t : preimage_mono interior_subset
... ⊆ preimage (λp:(β×β), (f p.1, f p.2)) s : ts,
have (f '' (e ⁻¹' m₁)) ×ˢ (f '' (e ⁻¹' m₂)) ⊆ s,
from calc (f '' (e ⁻¹' m₁)) ×ˢ (f '' (e ⁻¹' m₂)) =
(λp:(β×β), (f p.1, f p.2)) '' ((e ⁻¹' m₁) ×ˢ (e ⁻¹' m₂)) : prod_image_image_eq
... ⊆ (λp:(β×β), (f p.1, f p.2)) '' ((λp:(β×β), (f p.1, f p.2)) ⁻¹' s) : monotone_image this
... ⊆ s : image_preimage_subset _ _,
have (a, b) ∈ s, from @this (a, b) ⟨ha₁, hb₁⟩,
hs_comp $ show (ψ x₁, ψ x₂) ∈ comp_rel s (comp_rel s s),
from ⟨a, ha₂, ⟨b, this, hb₂⟩⟩
omit h_f
variables [separated_space γ]
lemma uniformly_extend_of_ind (b : β) : ψ (e b) = f b :=
dense_inducing.extend_eq_at _ h_f.continuous.continuous_at
lemma uniformly_extend_unique {g : α → γ} (hg : ∀ b, g (e b) = f b)
(hc : continuous g) :
ψ = g :=
dense_inducing.extend_unique _ hg hc
end uniform_extension
|
93300036abc73c465ac97ac965b1f5a4000cebdf | c31182a012eec69da0a1f6c05f42b0f0717d212d | /src/hacks_and_tricks/by_exactI_hack.lean | 106285ac889c097cc93e97fff5a07bf7c54d290f | [] | no_license | Ja1941/lean-liquid | fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc | 8e80ed0cbdf5145d6814e833a674eaf05a1495c1 | refs/heads/master | 1,689,437,983,362 | 1,628,362,719,000 | 1,628,362,719,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 556 | lean | -- brilliant hack by Gabriel Ebner
-- thanks!!
-- files that import this file can use the zero-width space char
-- to reset the TC instance cache, and avoid `by exactI` kludges
open tactic expr
open lean
open lean.parser
open interactive
open tactic
reserve prefix ` `:100 -- zero-width space Unicode char
@[user_notation]
meta def exact_notation (_ : parse $ tk "") (e : parse (lean.parser.pexpr 0)) : parser pexpr := do
expr.macro d [_] ← pure ``(by skip),
pure $ expr.macro d [const `tactic.interactive.exactI [] (cast undefined e.reflect)]
|
ddf38d166b2aed45bcc1dd7165746d6b461d3b95 | 87fd6b43d22688237c02b87c30d2a524f53bab24 | /src/game/sets/sets_level06.lean | 814810c313bf26ebab376da4df8eb5364986a02c | [
"Apache-2.0"
] | permissive | grthomson/real-number-game | 66142fedf0987db90f66daed52f9c8b42b70f909 | 8ddc15fdddc241c246653f7bb341df36e4e880a8 | refs/heads/master | 1,668,059,330,605 | 1,592,873,454,000 | 1,592,873,454,000 | 262,025,764 | 0 | 0 | null | 1,588,849,107,000 | 1,588,849,106,000 | null | UTF-8 | Lean | false | false | 1,106 | lean | import game.sets.sets_level05 -- hide
import tactic -- hide
namespace xena -- hide
variable X : Type
open_locale classical -- hide
/-
# Chapter 1 : Sets
## Level 6 : `sdiff` and `neg`
-/
/-
The set-theoretic difference `A \ B` satisfies the following property:
```
lemma mem_sdiff_iff : x ∈ A \ B ↔ x ∈ A ∧ x ∉ B
```
The complement `-A` of a set `A` (often denoted $A^c$ in textbooks)
is all the elements of `X` which are not in `A`:
```
lemma mem_neg_iff : x ∈ -A ↔ x ∉ A
```
In this lemma, you might get a shock. The `rw` tactic is aggressive
in the Real Number Game -- if after a rewrite the goal can be
solved by `rfl`, then Lean will close the goal automatically.
-/
/- Axiom : mem_sdiff_iff :
x ∈ A \ B ↔ x ∈ A ∧ x ∉ B
-/
/- Axiom : mem_neg_iff :
x ∈ -A ↔ x ∉ A
-/
/- Lemma
If $A$ and $B$ are sets with elements of type $X$, then
$$(A \setminus B) = A \cap B^{c}.$$
-/
theorem setdiff_eq_intersect_comp (A B : set X) : A \ B = A ∩ -B :=
begin
rw eq_iff,
intro x,
rw mem_sdiff_iff,
rw mem_inter_iff,
rw mem_neg_iff,
end
end xena -- hide
|
bae72e7c7a3077b303754633048d87288b9b9964 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/topology/continuous_function/cocompact_map.lean | 53042c5114a234e9adc89018073825d314dbf328 | [
"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,164 | lean | /-
Copyright (c) 2022 Jireh Loreaux. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jireh Loreaux
-/
import topology.continuous_function.basic
/-!
# Cocompact continuous maps
The type of *cocompact continuous maps* are those which tend to the cocompact filter on the
codomain along the cocompact filter on the domain. When the domain and codomain are Hausdorff, this
is equivalent to many other conditions, including that preimages of compact sets are compact. -/
universes u v w
open filter set
/-! ### Cocompact continuous maps -/
/-- A *cocompact continuous map* is a continuous function between topological spaces which
tends to the cocompact filter along the cocompact filter. Functions for which preimages of compact
sets are compact always satisfy this property, and the converse holds for cocompact continuous maps
when the codomain is Hausdorff (see `cocompact_map.tendsto_of_forall_preimage` and
`cocompact_map.is_compact_preimage`).
Cocompact maps thus generalise proper maps, with which they correspond when the codomain is
Hausdorff. -/
structure cocompact_map (α : Type u) (β : Type v) [topological_space α] [topological_space β]
extends continuous_map α β : Type (max u v) :=
(cocompact_tendsto' : tendsto to_fun (cocompact α) (cocompact β))
section
set_option old_structure_cmd true
/-- `cocompact_map_class F α β` states that `F` is a type of cocompact continuous maps.
You should also extend this typeclass when you extend `cocompact_map`. -/
class cocompact_map_class (F : Type*) (α β : out_param $ Type*) [topological_space α]
[topological_space β] extends continuous_map_class F α β :=
(cocompact_tendsto (f : F) : tendsto f (cocompact α) (cocompact β))
end
namespace cocompact_map_class
variables {F α β : Type*} [topological_space α] [topological_space β]
[cocompact_map_class F α β]
instance : has_coe_t F (cocompact_map α β) := ⟨λ f, ⟨f, cocompact_tendsto f⟩⟩
end cocompact_map_class
export cocompact_map_class (cocompact_tendsto)
namespace cocompact_map
section basics
variables {α β γ δ : Type*} [topological_space α] [topological_space β] [topological_space γ]
[topological_space δ]
instance : cocompact_map_class (cocompact_map α β) α β :=
{ coe := λ f, f.to_fun,
coe_injective' := λ f g h, by { obtain ⟨⟨_, _⟩, _⟩ := f, obtain ⟨⟨_, _⟩, _⟩ := g, congr' },
map_continuous := λ f, f.continuous_to_fun,
cocompact_tendsto := λ f, f.cocompact_tendsto' }
/-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun`
directly. -/
instance : has_coe_to_fun (cocompact_map α β) (λ _, α → β) := fun_like.has_coe_to_fun
@[simp] lemma coe_to_continuous_fun {f : cocompact_map α β} :
(f.to_continuous_map : α → β) = f := rfl
@[ext] lemma ext {f g : cocompact_map α β} (h : ∀ x, f x = g x) : f = g := fun_like.ext _ _ h
/-- Copy of a `cocompact_map` with a new `to_fun` equal to the old one. Useful
to fix definitional equalities. -/
protected def copy (f : cocompact_map α β) (f' : α → β) (h : f' = f) : cocompact_map α β :=
{ to_fun := f',
continuous_to_fun := by {rw h, exact f.continuous_to_fun},
cocompact_tendsto' := by { simp_rw h, exact f.cocompact_tendsto' } }
@[simp]
lemma coe_copy (f : cocompact_map α β) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl
lemma copy_eq (f : cocompact_map α β) (f' : α → β) (h : f' = f) : f.copy f' h = f := fun_like.ext' h
@[simp] lemma coe_mk (f : C(α, β)) (h : tendsto f (cocompact α) (cocompact β)) :
⇑(⟨f, h⟩ : cocompact_map α β) = f := rfl
section
variable (α)
/-- The identity as a cocompact continuous map. -/
protected def id : cocompact_map α α := ⟨continuous_map.id _, tendsto_id⟩
@[simp] lemma coe_id : ⇑(cocompact_map.id α) = id := rfl
end
instance : inhabited (cocompact_map α α) := ⟨cocompact_map.id α⟩
/-- The composition of cocompact continuous maps, as a cocompact continuous map. -/
def comp (f : cocompact_map β γ) (g : cocompact_map α β) : cocompact_map α γ :=
⟨f.to_continuous_map.comp g, (cocompact_tendsto f).comp (cocompact_tendsto g)⟩
@[simp] lemma coe_comp (f : cocompact_map β γ) (g : cocompact_map α β) :
⇑(comp f g) = f ∘ g := rfl
@[simp] lemma comp_apply (f : cocompact_map β γ) (g : cocompact_map α β) (a : α) :
comp f g a = f (g a) := rfl
@[simp] lemma comp_assoc (f : cocompact_map γ δ) (g : cocompact_map β γ)
(h : cocompact_map α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl
@[simp] lemma id_comp (f : cocompact_map α β) : (cocompact_map.id _).comp f = f :=
ext $ λ _, rfl
@[simp] lemma comp_id (f : cocompact_map α β) : f.comp (cocompact_map.id _) = f :=
ext $ λ _, rfl
lemma tendsto_of_forall_preimage {f : α → β} (h : ∀ s, is_compact s → is_compact (f ⁻¹' s)) :
tendsto f (cocompact α) (cocompact β) :=
λ s hs, match mem_cocompact.mp hs with ⟨t, ht, hts⟩ :=
mem_map.mpr (mem_cocompact.mpr ⟨f ⁻¹' t, h t ht, by simpa using preimage_mono hts⟩) end
/-- If the codomain is Hausdorff, preimages of compact sets are compact under a cocompact
continuous map. -/
lemma is_compact_preimage [t2_space β] (f : cocompact_map α β) ⦃s : set β⦄ (hs : is_compact s) :
is_compact (f ⁻¹' s) :=
begin
obtain ⟨t, ht, hts⟩ := mem_cocompact'.mp (by simpa only [preimage_image_preimage, preimage_compl]
using mem_map.mp (cocompact_tendsto f $ mem_cocompact.mpr ⟨s, hs, compl_subset_compl.mpr
(image_preimage_subset f _)⟩)),
exact is_compact_of_is_closed_subset ht (hs.is_closed.preimage $ map_continuous f)
(by simpa using hts),
end
end basics
end cocompact_map
/-- A homemomorphism is a cocompact map. -/
@[simps] def homeomorph.to_cocompact_map
{α β : Type*} [topological_space α] [topological_space β] (f : α ≃ₜ β) : cocompact_map α β :=
{ to_fun := f,
continuous_to_fun := f.continuous,
cocompact_tendsto' :=
begin
refine cocompact_map.tendsto_of_forall_preimage (λ K hK, _),
erw K.preimage_equiv_eq_image_symm,
exact hK.image f.symm.continuous,
end }
|
94067fce517a111f0c094bd9d4a714fc8db5a4a4 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/run/e4.lean | b378203fe6306b029a9fc5a2066c924d5ab8c5e4 | [
"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 | 665 | lean | prelude
definition Prop := Type.{0}
definition false : Prop := ∀x : Prop, x
check false
theorem false.elim (C : Prop) (H : false) : C
:= H C
definition eq {A : Type} (a b : A)
:= ∀ P : A → Prop, P a → P b
check eq
infix `=`:50 := eq
theorem refl {A : Type} (a : A) : a = a
:= λ P H, H
definition true : Prop
:= false = false
theorem trivial : true
:= refl false
attribute [elab_as_eliminator]
theorem subst {A : Type} {P : A -> Prop} {a b : A} (H1 : a = b) (H2 : P a) : P b
:= H1 _ H2
theorem symm {A : Type} {a b : A} (H : a = b) : b = a
:= subst H (refl a)
theorem trans {A : Type} {a b c : A} (H1 : a = b) (H2 : b = c) : a = c
:= subst H2 H1
|
f39b3918cbf5403ba55616b03128eece33d24ddf | 09b3e1beaeff2641ac75019c9f735d79d508071d | /Mathlib/Data/Array/Basic.lean | f9ffddc1716ddd937cae8d967a96457683846fc6 | [
"Apache-2.0"
] | permissive | abentkamp/mathlib4 | b819079cc46426b3c5c77413504b07541afacc19 | f8294a67548f8f3d1f5913677b070a2ef5bcf120 | refs/heads/master | 1,685,309,252,764 | 1,623,232,534,000 | 1,623,232,534,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,044 | lean | import Mathlib.Data.List.Basic
@[simp] theorem List.toArrayAux_data : ∀ (l : List α) a, (l.toArrayAux a).data = a.data ++ l
| [], r => (append_nil _).symm
| a::as, r => (toArrayAux_data as (r.push a)).trans $
by simp [Array.push, append_assoc, List.concat_eq_append]
@[simp] theorem List.toArray_data (l : List α) : l.toArray.data = l := toArrayAux_data _ _
namespace Array
theorem ext' : {a b : Array α} → a.data = b.data → a = b
| ⟨a⟩, ⟨_⟩, rfl => rfl
@[simp] theorem data_toArray : (a : Array α) → a.data.toArray = a
| ⟨l⟩ => ext' l.toArray_data
theorem toArrayLit_eq (a : Array α) (n : Nat) (hsz : a.size = n) : a = toArrayLit a n hsz := by
have := aux n
rw [List.drop_eq_nil_of_le (Nat.le_of_eq hsz)] at this
exact (data_toArray a).symm.trans $ congrArg List.toArray (this _).symm
where
aux : ∀ i hi, toListLitAux a n hsz i hi (a.data.drop i) = a.data
| 0, _ => rfl
| i+1, hi => by
simp [toListLitAux]
suffices _::_ = _ by rw [this]; apply aux
apply List.get_cons_drop
end Array
|
5fed0e49deaf52466e4b9679a2e5bbb489da078e | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /tests/lean/zipper.lean | c150919bafd262944064ef12a1479abee2a9b1f3 | [
"Apache-2.0"
] | permissive | mhuisi/lean4 | 28d35a4febc2e251c7f05492e13f3b05d6f9b7af | dda44bc47f3e5d024508060dac2bcb59fd12e4c0 | refs/heads/master | 1,621,225,489,283 | 1,585,142,689,000 | 1,585,142,689,000 | 250,590,438 | 0 | 2 | Apache-2.0 | 1,602,443,220,000 | 1,585,327,814,000 | C | UTF-8 | Lean | false | false | 1,384 | lean | structure ListZipper (α : Type) :=
(xs : List α) (bs : List α)
-- set_option trace.compiler.ir.rc true
variables {α : Type}
namespace ListZipper
def goForward : ListZipper α → ListZipper α
| ⟨[], bs⟩ => ⟨[], bs⟩
| ⟨x::xs, bs⟩ => ⟨xs, x::bs⟩
def goBackward : ListZipper α → ListZipper α
| ⟨xs, []⟩ => ⟨xs, []⟩
| ⟨xs, b::bs⟩ => ⟨b::xs, bs⟩
def insert : ListZipper α → α → ListZipper α
| ⟨xs, bs⟩, x => ⟨xs, x::bs⟩
def erase : ListZipper α → ListZipper α
| ⟨[], bs⟩ => ⟨[], bs⟩
| ⟨x::xs, bs⟩ => ⟨xs, bs⟩
def curr [Inhabited α] : ListZipper α → α
| ⟨[], bs⟩ => arbitrary _
| ⟨x::xs, bs⟩ => x
def currOpt : ListZipper α → Option α
| ⟨[], bs⟩ => none
| ⟨x::xs, bs⟩ => some x
def toList : ListZipper α → List α
| ⟨xs, bs⟩ => bs.reverse ++ xs
def atEnd (z : ListZipper α) : Bool :=
z.xs.isEmpty
end ListZipper
def List.toListZipper (xs : List α) : ListZipper α :=
⟨xs, []⟩
partial def testAux : ListZipper Nat → ListZipper Nat
| z =>
if z.atEnd then
z
else if z.curr % 2 == 0 then
testAux (z.goForward.insert 0)
else if z.curr > 20 then
testAux z.erase
else
testAux z.goForward
def test (xs : List Nat) : List Nat :=
(testAux xs.toListZipper).toList
#eval (IO.println (test [10, 11, 13, 20, 22, 40, 41, 11]) : IO Unit)
|
4350d9e25d3675a87cb5cddad425e2c8b0faa6a6 | d6124c8dbe5661dcc5b8c9da0a56fbf1f0480ad6 | /test/out/script/program.lean | ffe4fa09880cf72524766060b4bd99d08a6da533 | [
"Apache-2.0"
] | permissive | xubaiw/lean4-papyrus | c3fbbf8ba162eb5f210155ae4e20feb2d32c8182 | 02e82973a5badda26fc0f9fd15b3d37e2eb309e0 | refs/heads/master | 1,691,425,756,824 | 1,632,122,825,000 | 1,632,123,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,841 | lean | import Papyrus
open Papyrus Script
llvm module lean_hello do
declare %lean_object* @lean_mk_string(i8*)
declare %lean_object* @l_IO_println___at_Lean_instEval___spec__1(%lean_object*, %lean_object*)
define i32 @main() do
%hello = call @lean_mk_string("Hello World!"*)
call @l_IO_println___at_Lean_instEval___spec__1(%hello, inttoptr (i32 1 to %lean_object*))
ret i32 0
#dump lean_hello
#verify lean_hello
#jit lean_hello
llvm module lean_echo do
declare %lean_object* @lean_mk_string(i8*)
declare %lean_object* @l_IO_println___at_Lean_instEval___spec__1(%lean_object*, %lean_object*)
define i32 @main(i32 %argc, i8** %argv) do
%arg1p = getelementptr i8*, %argv, i32 1
%arg1 = load i8*, %arg1p
%arg1s = call @lean_mk_string(%arg1)
call @l_IO_println___at_Lean_instEval___spec__1(%arg1s, inttoptr (i32 1 to %lean_object*))
ret i32 0
#dump lean_echo
#verify lean_echo
#jit lean_echo #["a", "b", "c"]
llvm module lean_select do
declare %lean_object* @lean_mk_string(i8*)
declare %lean_object* @l_IO_println___at_Lean_instEval___spec__1(%lean_object*, %lean_object*)
define i32 @main(i32 %argc, i8** %argv) do
let realW ← llvm inttoptr (i32 1 to %lean_object*)
br1:
%arg1p = getelementptr i8*, %argv, i32 1
%arg1 = load i8*, %arg1p
%arg1s = call @lean_mk_string(%arg1)
call @l_IO_println___at_Lean_instEval___spec__1(%arg1s, realW)
ret i32 0
br2:
%arg2p = getelementptr i8*, %argv, i32 2
%arg2 = load i8*, %arg2p
%arg2s = call @lean_mk_string(%arg2)
call @l_IO_println___at_Lean_instEval___spec__1(%arg2s, realW)
ret i32 0;
%arg0 = load i8*, %argv
%arg0c = load i1, %arg0
br %arg0c, %br1, %br2
#dump lean_select
#verify lean_select
#jit lean_select #["some", "b", "c"]
#jit lean_select #["\x00", "b", "c"]
|
605a81708e48210b1f997ad2be6b7e67fa52b7cc | 54d7e71c3616d331b2ec3845d31deb08f3ff1dea | /tests/lean/run/dep_coe_to_fn3.lean | 0b2b320eab0c7a5da0a1e8aca3761012b4e536c0 | [
"Apache-2.0"
] | permissive | pachugupta/lean | 6f3305c4292288311cc4ab4550060b17d49ffb1d | 0d02136a09ac4cf27b5c88361750e38e1f485a1a | refs/heads/master | 1,611,110,653,606 | 1,493,130,117,000 | 1,493,167,649,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 654 | lean | universe variables u v
structure Func :=
(A : Type u) (B : A → Type v) (fn : Π a, B a → B a)
instance F_to_fn : has_coe_to_fun Func :=
{ F := λ f, Π a, f^.B a → f^.B a,
coe := λ f a b, f^.fn a (f^.fn a b) }
variables (f : Func) (a : f^.A) (b : f^.B a)
#check (f a b)
def f1 : Func :=
{ A := nat,
B := λ a, nat,
fn := add }
/- We need to mark 10 as a nat.
Reason: f1 is not reducible, then type class resolution
cannot find an instance for `has_one (Func.A f1)` -/
example : f1 (10:nat) (30:nat) = (50:nat) :=
rfl
attribute [reducible] f1
example : f1 10 30 = 50 :=
rfl
example (n m : nat) : f1 n m = n + (n + m) :=
rfl
|
4a763bf8ddf45af1fe99ebf92fdc45749d1e34d6 | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/tactic/core.lean | fc2d0a48164ae188f3530d7a2228910c4e1bf64c | [
"Apache-2.0"
] | permissive | ayush1801/mathlib | 78949b9f789f488148142221606bf15c02b960d2 | ce164e28f262acbb3de6281b3b03660a9f744e3c | refs/heads/master | 1,692,886,907,941 | 1,635,270,866,000 | 1,635,270,866,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 95,678 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek
-/
import data.dlist.basic
import logic.function.basic
import control.basic
import meta.expr
import meta.rb_map
import data.bool
import tactic.binder_matching
import tactic.lean_core_docs
import tactic.interactive_expr
import system.io
universe u
attribute [derive [has_reflect, decidable_eq]] tactic.transparency
-- Rather than import order.lexicographic here, we can get away with defining the order by hand.
instance : has_lt pos :=
{ lt := λ x y, x.line < y.line ∨ x.line = y.line ∧ x.column < y.column }
namespace tactic
/-- Reflexivity conversion: given `e` returns `(e, ⊢ e = e)` -/
meta def refl_conv (e : expr) : tactic (expr × expr) :=
do p ← mk_eq_refl e, return (e, p)
/-- Turns a conversion tactic into one that always succeeds, where failure is interpreted as a
proof by reflexivity. -/
meta def or_refl_conv (tac : expr → tactic (expr × expr))
(e : expr) : tactic (expr × expr) := tac e <|> refl_conv e
/-- Transitivity conversion: given two conversions (which take an
expression `e` and returns `(e', ⊢ e = e')`), produces another
conversion that combines them with transitivity, treating failures
as reflexivity conversions. -/
meta def trans_conv (t₁ t₂ : expr → tactic (expr × expr)) (e : expr) :
tactic (expr × expr) :=
(do (e₁, p₁) ← t₁ e,
(do (e₂, p₂) ← t₂ e₁,
p ← mk_eq_trans p₁ p₂, return (e₂, p)) <|>
return (e₁, p₁)) <|> t₂ e
end tactic
namespace expr
open tactic
/-- Given an expr `α` representing a type with numeral structure,
`of_nat α n` creates the `α`-valued numeral expression corresponding to `n`. -/
protected meta def of_nat (α : expr) : ℕ → tactic expr :=
nat.binary_rec
(tactic.mk_mapp ``has_zero.zero [some α, none])
(λ b n tac, if n = 0 then mk_mapp ``has_one.one [some α, none] else
do e ← tac, tactic.mk_app (cond b ``bit1 ``bit0) [e])
/-- Given an expr `α` representing a type with numeral structure,
`of_int α n` creates the `α`-valued numeral expression corresponding to `n`.
The output is either a numeral or the negation of a numeral. -/
protected meta def of_int (α : expr) : ℤ → tactic expr
| (n : ℕ) := expr.of_nat α n
| -[1+ n] := do
e ← expr.of_nat α (n+1),
tactic.mk_app ``has_neg.neg [e]
/-- Generates an expression of the form `∃(args), inner`. `args` is assumed to be a list of local
constants. When possible, `p ∧ q` is used instead of `∃(_ : p), q`. -/
meta def mk_exists_lst (args : list expr) (inner : expr) : tactic expr :=
args.mfoldr (λarg i:expr, do
t ← infer_type arg,
sort l ← infer_type t,
return $ if arg.occurs i ∨ l ≠ level.zero
then (const `Exists [l] : expr) t (i.lambdas [arg])
else (const `and [] : expr) t i)
inner
/-- `traverse f e` applies the monadic function `f` to the direct descendants of `e`. -/
meta def traverse {m : Type → Type u} [applicative m]
{elab elab' : bool} (f : expr elab → m (expr elab')) :
expr elab → m (expr elab')
| (var v) := pure $ var v
| (sort l) := pure $ sort l
| (const n ls) := pure $ const n ls
| (mvar n n' e) := mvar n n' <$> f e
| (local_const n n' bi e) := local_const n n' bi <$> f e
| (app e₀ e₁) := app <$> f e₀ <*> f e₁
| (lam n bi e₀ e₁) := lam n bi <$> f e₀ <*> f e₁
| (pi n bi e₀ e₁) := pi n bi <$> f e₀ <*> f e₁
| (elet n e₀ e₁ e₂) := elet n <$> f e₀ <*> f e₁ <*> f e₂
| (macro mac es) := macro mac <$> list.traverse f es
/-- `mfoldl f a e` folds the monadic function `f` over the subterms of the expression `e`,
with initial value `a`. -/
meta def mfoldl {α : Type} {m} [monad m] (f : α → expr → m α) : α → expr → m α
| x e := prod.snd <$> (state_t.run (e.traverse $ λ e',
(get >>= monad_lift ∘ flip f e' >>= put) $> e') x : m _)
/-- `kreplace e old new` replaces all occurrences of the expression `old` in `e`
with `new`. The occurrences of `old` in `e` are determined using keyed matching
with transparency `md`; see `kabstract` for details. If `unify` is true,
we may assign metavariables in `e` as we match subterms of `e` against `old`. -/
meta def kreplace (e old new : expr) (md := semireducible) (unify := tt)
: tactic expr := do
e ← kabstract e old md unify,
pure $ e.instantiate_var new
end expr
namespace interaction_monad
open result
variables {σ : Type} {α : Type u}
/-- `get_state` returns the underlying state inside an interaction monad, from within that monad. -/
-- Note that this is a generalization of `tactic.read` in core.
meta def get_state : interaction_monad σ σ :=
λ state, success state state
/-- `set_state` sets the underlying state inside an interaction monad, from within that monad. -/
-- Note that this is a generalization of `tactic.write` in core.
meta def set_state (state : σ) : interaction_monad σ unit :=
λ _, success () state
/--
`run_with_state state tac` applies `tac` to the given state `state` and returns the result,
subsequently restoring the original state.
If `tac` fails, then `run_with_state` does too.
-/
meta def run_with_state (state : σ) (tac : interaction_monad σ α) : interaction_monad σ α :=
λ s, match tac state with
| success val _ := success val s
| exception fn pos _ := exception fn pos s
end
end interaction_monad
namespace format
/-- `join' [a,b,c]` produces the format object `abc`.
It differs from `format.join` by using `format.nil` instead of `""` for the empty list. -/
meta def join' (xs : list format) : format :=
xs.foldl compose nil
/-- `intercalate x [a, b, c]` produces the format object `a.x.b.x.c`,
where `.` represents `format.join`. -/
meta def intercalate (x : format) : list format → format :=
join' ∘ list.intersperse x
/-- `soft_break` is similar to `line`. Whereas in `group (x ++ line ++ y ++ line ++ z)`
the result either fits on one line or in three, `x ++ soft_break ++ y ++ soft_break ++ z`
each line break is decided independently -/
meta def soft_break : format :=
group line
/-- Format a list as a comma separated list, without any brackets. -/
meta def comma_separated {α : Type*} [has_to_format α] : list α → format
| [] := nil
| xs := group (nest 1 $ intercalate ("," ++ soft_break) $ xs.map to_fmt)
end format
section format
open format
/-- format a `list` by separating elements with `soft_break` instead of `line` -/
meta def list.to_line_wrap_format {α : Type u} [has_to_format α] (l : list α) : format :=
bracket "[" "]" (comma_separated l)
end format
namespace tactic
open function
export interaction_monad (get_state set_state run_with_state)
/-- Private work function for `add_local_consts_as_local_hyps`: given
`mappings : list (expr × expr)` corresponding to pairs `(var, hyp)` of variables and the local
hypothesis created as a result and `(var :: rest) : list expr` of more local variables we
examine `var` to see if it contains any other variables in `rest`. If it does, we put it to the
back of the queue and recurse. If it does not, then we perform replacements inside the type of
`var` using the `mappings`, create a new associate local hypothesis, add this to the list of
mappings, and recurse. We are done once all local hypotheses have been processed.
If the list of passed local constants have types which depend on one another (which can only
happen by hand-crafting the `expr`s manually), this function will loop forever. -/
private meta def add_local_consts_as_local_hyps_aux
: list (expr × expr) → list expr → tactic (list (expr × expr))
| mappings [] := return mappings
| mappings (var :: rest) := do
/- Determine if `var` contains any local variables in the lift `rest`. -/
let is_dependent := var.local_type.fold ff $ λ e n b,
if b then b else e ∈ rest,
/- If so, then skip it---add it to the end of the variable queue. -/
if is_dependent then
add_local_consts_as_local_hyps_aux mappings (rest ++ [var])
else do
/- Otherwise, replace all of the local constants referenced by the type of `var` with the
respective new corresponding local hypotheses as recorded in the list `mappings`. -/
let new_type := var.local_type.replace_subexprs mappings,
/- Introduce a new local new local hypothesis `hyp` for `var`, with the correct type. -/
hyp ← assertv var.local_pp_name new_type (var.local_const_set_type new_type),
/- Process the next variable in the queue, with the mapping list updated to include the local
hypothesis which we just created. -/
add_local_consts_as_local_hyps_aux ((var, hyp) :: mappings) rest
/-- `add_local_consts_as_local_hyps vars` add the given list `vars` of `expr.local_const`s to the
tactic state. This is harder than it sounds, since the list of local constants which we have
been passed can have dependencies between their types.
For example, suppose we have two local constants `n : ℕ` and `h : n = 3`. Then we cannot blindly
add `h` as a local hypothesis, since we need the `n` to which it refers to be the `n` created as
a new local hypothesis, not the old local constant `n` with the same name. Of course, these
dependencies can be nested arbitrarily deep.
If the list of passed local constants have types which depend on one another (which can only
happen by hand-crafting the `expr`s manually), this function will loop forever. -/
meta def add_local_consts_as_local_hyps (vars : list expr) : tactic (list (expr × expr)) :=
/- The `list.reverse` below is a performance optimisation since the list of available variables
reported by the system is often mostly the reverse of the order in which they are dependent. -/
add_local_consts_as_local_hyps_aux [] vars.reverse.erase_dup
private meta def get_expl_pi_arity_aux : expr → tactic nat
| (expr.pi n bi d b) :=
do m ← mk_fresh_name,
let l := expr.local_const m n bi d,
new_b ← whnf (expr.instantiate_var b l),
r ← get_expl_pi_arity_aux new_b,
if bi = binder_info.default then
return (r + 1)
else
return r
| e := return 0
/-- Compute the arity of explicit arguments of `type`. -/
meta def get_expl_pi_arity (type : expr) : tactic nat :=
whnf type >>= get_expl_pi_arity_aux
/-- Compute the arity of explicit arguments of `fn`'s type. -/
meta def get_expl_arity (fn : expr) : tactic nat :=
infer_type fn >>= get_expl_pi_arity
private meta def get_app_fn_args_whnf_aux (md : transparency)
(unfold_ginductive : bool) : list expr → expr → tactic (expr × list expr) :=
λ args e, do
e ← whnf e md unfold_ginductive,
match e with
| (expr.app t u) := get_app_fn_args_whnf_aux (u :: args) t
| _ := pure (e, args)
end
/--
For `e = f x₁ ... xₙ`, `get_app_fn_args_whnf e` returns `(f, [x₁, ..., xₙ])`. `e`
is normalised as necessary; for example:
```
get_app_fn_args_whnf `(let f := g x in f y) = (`(g), [`(x), `(y)])
```
The returned expression is in whnf, but the arguments are generally not.
-/
meta def get_app_fn_args_whnf (e : expr) (md := semireducible)
(unfold_ginductive := tt) : tactic (expr × list expr) :=
get_app_fn_args_whnf_aux md unfold_ginductive [] e
/--
`get_app_fn_whnf e md unfold_ginductive` is like `expr.get_app_fn e` but `e` is
normalised as necessary (with transparency `md`). `unfold_ginductive` controls
whether constructors of generalised inductive types are unfolded. The returned
expression is in whnf.
-/
meta def get_app_fn_whnf : expr → opt_param _ semireducible → opt_param _ tt → tactic expr
| e md unfold_ginductive := do
e ← whnf e md unfold_ginductive,
match e with
| (expr.app f _) := get_app_fn_whnf f md unfold_ginductive
| _ := pure e
end
/--
`get_app_fn_const_whnf e md unfold_ginductive` expects that `e = C x₁ ... xₙ`,
where `C` is a constant, after normalisation with transparency `md`. If so, the
name of `C` is returned. Otherwise the tactic fails. `unfold_ginductive`
controls whether constructors of generalised inductive types are unfolded.
-/
meta def get_app_fn_const_whnf (e : expr) (md := semireducible)
(unfold_ginductive := tt) : tactic name := do
f ← get_app_fn_whnf e md unfold_ginductive,
match f with
| (expr.const n _) := pure n
| _ := fail format!
"expected a constant (possibly applied to some arguments), but got:\n{e}"
end
/--
`get_app_args_whnf e md unfold_ginductive` is like `expr.get_app_args e` but `e`
is normalised as necessary (with transparency `md`). `unfold_ginductive`
controls whether constructors of generalised inductive types are unfolded. The
returned expressions are not necessarily in whnf.
-/
meta def get_app_args_whnf (e : expr) (md := semireducible)
(unfold_ginductive := tt) : tactic (list expr) :=
prod.snd <$> get_app_fn_args_whnf e md unfold_ginductive
/-- `pis loc_consts f` is used to create a pi expression whose body is `f`.
`loc_consts` should be a list of local constants. The function will abstract these local
constants from `f` and bind them with pi binders.
For example, if `a, b` are local constants with types `Ta, Tb`,
``pis [a, b] `(f a b)`` will return the expression
`Π (a : Ta) (b : Tb), f a b`. -/
meta def pis : list expr → expr → tactic expr
| (e@(expr.local_const uniq pp info _) :: es) f := do
t ← infer_type e,
f' ← pis es f,
pure $ expr.pi pp info t (expr.abstract_local f' uniq)
| _ f := pure f
/-- `lambdas loc_consts f` is used to create a lambda expression whose body is `f`.
`loc_consts` should be a list of local constants. The function will abstract these local
constants from `f` and bind them with lambda binders.
For example, if `a, b` are local constants with types `Ta, Tb`,
``lambdas [a, b] `(f a b)`` will return the expression
`λ (a : Ta) (b : Tb), f a b`. -/
meta def lambdas : list expr → expr → tactic expr
| (e@(expr.local_const uniq pp info _) :: es) f := do
t ← infer_type e,
f' ← lambdas es f,
pure $ expr.lam pp info t (expr.abstract_local f' uniq)
| _ f := pure f
-- TODO: move to `declaration` namespace in `meta/expr.lean`
/-- `mk_theorem n ls t e` creates a theorem declaration with name `n`, universe parameters named
`ls`, type `t`, and body `e`. -/
meta def mk_theorem (n : name) (ls : list name) (t : expr) (e : expr) : declaration :=
declaration.thm n ls t (task.pure e)
/-- `add_theorem_by n ls type tac` uses `tac` to synthesize a term with type `type`, and adds this
to the environment as a theorem with name `n` and universe parameters `ls`. -/
meta def add_theorem_by (n : name) (ls : list name) (type : expr) (tac : tactic unit) :
tactic expr :=
do ((), body) ← solve_aux type tac,
body ← instantiate_mvars body,
add_decl $ mk_theorem n ls type body,
return $ expr.const n $ ls.map level.param
/-- `eval_expr' α e` attempts to evaluate the expression `e` in the type `α`.
This is a variant of `eval_expr` in core. Due to unexplained behavior in the VM, in rare
situations the latter will fail but the former will succeed. -/
meta def eval_expr' (α : Type*) [_inst_1 : reflected α] (e : expr) : tactic α :=
mk_app ``id [e] >>= eval_expr α
/-- `mk_fresh_name` returns identifiers starting with underscores,
which are not legal when emitted by tactic programs. `mk_user_fresh_name`
turns the useful source of random names provided by `mk_fresh_name` into
names which are usable by tactic programs.
The returned name has four components which are all strings. -/
meta def mk_user_fresh_name : tactic name :=
do nm ← mk_fresh_name,
return $ `user__ ++ nm.pop_prefix.sanitize_name ++ `user__
/-- `has_attribute' attr_name decl_name` checks
whether `decl_name` exists and has attribute `attr_name`. -/
meta def has_attribute' (attr_name decl_name : name) : tactic bool :=
succeeds (has_attribute attr_name decl_name)
/-- Checks whether the name is a simp lemma -/
meta def is_simp_lemma : name → tactic bool :=
has_attribute' `simp
/-- Checks whether the name is an instance. -/
meta def is_instance : name → tactic bool :=
has_attribute' `instance
/-- `local_decls` returns a dictionary mapping names to their corresponding declarations.
Covers all declarations from the current file. -/
meta def local_decls : tactic (name_map declaration) :=
do e ← tactic.get_env,
let xs := e.fold native.mk_rb_map
(λ d s, if environment.in_current_file e d.to_name
then s.insert d.to_name d else s),
pure xs
/-- `get_decls_from` returns a dictionary mapping names to their
corresponding declarations. Covers all declarations the files listed
in `fs`, with the current file listed as `none`.
The path of the file names is expected to be relative to
the root of the project (i.e. the location of `leanpkg.toml` when it
is present); e.g. `"src/tactic/core.lean"`
Possible issue: `get_decls_from` uses `get_cwd`, the current working
directory, which may not always point at the root of the project.
It would work better if it searched for the root directory or,
better yet, if Lean exposed its path information.
-/
meta def get_decls_from (fs : list (option string)) : tactic (name_map declaration) :=
do root ← unsafe_run_io $ io.env.get_cwd,
let fs := fs.map (option.map $ λ path, root ++ "/" ++ path),
err ← unsafe_run_io $ (fs.filter_map id).mfilter $ (<$>) bnot ∘ io.fs.file_exists,
guard (err = []) <|> fail format!"File not found: {err}",
e ← tactic.get_env,
let xs := e.fold native.mk_rb_map
(λ d s,
let source := e.decl_olean d.to_name in
if source ∈ fs ∧ (source = none → e.in_current_file d.to_name)
then s.insert d.to_name d else s),
pure xs
/-- If `{nm}_{n}` doesn't exist in the environment, returns that, otherwise tries `{nm}_{n+1}` -/
meta def get_unused_decl_name_aux (e : environment) (nm : name) : ℕ → tactic name | n :=
let nm' := nm.append_suffix ("_" ++ to_string n) in
if e.contains nm' then get_unused_decl_name_aux (n+1) else return nm'
/-- Return a name which doesn't already exist in the environment. If `nm` doesn't exist, it
returns that, otherwise it tries `nm_2`, `nm_3`, ... -/
meta def get_unused_decl_name (nm : name) : tactic name :=
get_env >>= λ e, if e.contains nm then get_unused_decl_name_aux e nm 2 else return nm
/--
Returns a pair `(e, t)`, where `e ← mk_const d.to_name`, and `t = d.type`
but with universe params updated to match the fresh universe metavariables in `e`.
This should have the same effect as just
```lean
do e ← mk_const d.to_name,
t ← infer_type e,
return (e, t)
```
but is hopefully faster.
-/
meta def decl_mk_const (d : declaration) : tactic (expr × expr) :=
do subst ← d.univ_params.mmap $ λ u, prod.mk u <$> mk_meta_univ,
let e : expr := expr.const d.to_name (prod.snd <$> subst),
return (e, d.type.instantiate_univ_params subst)
/--
Replace every universe metavariable in an expression with a universe parameter.
(This is useful when making new declarations.)
-/
meta def replace_univ_metas_with_univ_params (e : expr) : tactic expr :=
do
e.list_univ_meta_vars.enum.mmap (λ n, do
let n' := (`u).append_suffix ("_" ++ to_string (n.1+1)),
unify (expr.sort (level.mvar n.2)) (expr.sort (level.param n'))),
instantiate_mvars e
/-- `mk_local n` creates a dummy local variable with name `n`.
The type of this local constant is a constant with name `n`, so it is very unlikely to be
a meaningful expression. -/
meta def mk_local (n : name) : expr :=
expr.local_const n n binder_info.default (expr.const n [])
/-- `mk_psigma [x,y,z]`, with `[x,y,z]` list of local constants of types `x : tx`,
`y : ty x` and `z : tz x y`, creates an expression of sigma type:
`⟨x,y,z⟩ : Σ' (x : tx) (y : ty x), tz x y`.
-/
meta def mk_psigma : list expr → tactic expr
| [] := mk_const ``punit
| [x@(expr.local_const _ _ _ _)] := pure x
| (x@(expr.local_const _ _ _ _) :: xs) :=
do y ← mk_psigma xs,
α ← infer_type x,
β ← infer_type y,
t ← lambdas [x] β >>= instantiate_mvars,
r ← mk_mapp ``psigma.mk [α,t],
pure $ r x y
| _ := fail "mk_psigma expects a list of local constants"
/--
Update the type of a local constant or metavariable. For local constants and
metavariables obtained via, for example, `tactic.get_local`, the type stored in
the expression is not necessarily the same as the type returned by `infer_type`.
This tactic, given a local constant or metavariable, updates the stored type to
match the output of `infer_type`. If the input is not a local constant or
metavariable, `update_type` does nothing.
-/
meta def update_type : expr → tactic expr
| e@(expr.local_const ppname uname binfo _) :=
expr.local_const ppname uname binfo <$> infer_type e
| e@(expr.mvar ppname uname _) :=
expr.mvar ppname uname <$> infer_type e
| e := pure e
/-- `elim_gen_prod n e _ ns` with `e` an expression of type `psigma _`, applies `cases` on `e` `n`
times and uses `ns` to name the resulting variables. Returns a triple: list of new variables,
remaining term and unused variable names.
-/
meta def elim_gen_prod : nat → expr → list expr → list name → tactic (list expr × expr × list name)
| 0 e hs ns := return (hs.reverse, e, ns)
| (n + 1) e hs ns := do
t ← infer_type e,
if t.is_app_of `eq then return (hs.reverse, e, ns)
else do
[(_, [h, h'], _)] ← cases_core e (ns.take 1),
elim_gen_prod n h' (h :: hs) (ns.drop 1)
private meta def elim_gen_sum_aux : nat → expr → list expr → tactic (list expr × expr)
| 0 e hs := return (hs, e)
| (n + 1) e hs := do
[(_, [h], _), (_, [h'], _)] ← induction e [],
swap,
elim_gen_sum_aux n h' (h::hs)
/-- `elim_gen_sum n e` applies cases on `e` `n` times. `e` is assumed to be a local constant whose
type is a (nested) sum `⊕`. Returns the list of local constants representing the components of `e`.
-/
meta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do
(hs, h') ← elim_gen_sum_aux n e [],
gs ← get_goals,
set_goals $ (gs.take (n+1)).reverse ++ gs.drop (n+1),
return $ hs.reverse ++ [h']
/-- Given `elab_def`, a tactic to solve the current goal,
`extract_def n trusted elab_def` will create an auxiliary definition named `n` and use it
to close the goal. If `trusted` is false, it will be a meta definition. -/
meta def extract_def (n : name) (trusted : bool) (elab_def : tactic unit) : tactic unit :=
do cxt ← list.map expr.to_implicit_local_const <$> local_context,
t ← target,
(eqns,d) ← solve_aux t elab_def,
d ← instantiate_mvars d,
t' ← pis cxt t,
d' ← lambdas cxt d,
let univ := t'.collect_univ_params,
add_decl $ declaration.defn n univ t' d' (reducibility_hints.regular 1 tt) trusted,
applyc n
/-- Attempts to close the goal with `dec_trivial`. -/
meta def exact_dec_trivial : tactic unit := `[exact dec_trivial]
/-- Runs a tactic for a result, reverting the state after completion. -/
meta def retrieve {α} (tac : tactic α) : tactic α :=
λ s, result.cases_on (tac s)
(λ a s', result.success a s)
result.exception
/-- Runs a tactic for a result, reverting the state after completion or error. -/
meta def retrieve' {α} (tac : tactic α) : tactic α :=
λ s, result.cases_on (tac s)
(λ a s', result.success a s)
(λ msg pos s', result.exception msg pos s)
/-- Repeat a tactic at least once, calling it recursively on all subgoals,
until it fails. This tactic fails if the first invocation fails. -/
meta def repeat1 (t : tactic unit) : tactic unit := t; repeat t
/-- `iterate_range m n t`: Repeat the given tactic at least `m` times and
at most `n` times or until `t` fails. Fails if `t` does not run at least `m` times. -/
meta def iterate_range : ℕ → ℕ → tactic unit → tactic unit
| 0 0 t := skip
| 0 (n+1) t := try (t >> iterate_range 0 n t)
| (m+1) n t := t >> iterate_range m (n-1) t
/--
Given a tactic `tac` that takes an expression
and returns a new expression and a proof of equality,
use that tactic to change the type of the hypotheses listed in `hs`,
as well as the goal if `tgt = tt`.
Returns `tt` if any types were successfully changed.
-/
meta def replace_at (tac : expr → tactic (expr × expr)) (hs : list expr) (tgt : bool) :
tactic bool :=
do to_remove ← hs.mfilter $ λ h, do {
h_type ← infer_type h,
succeeds $ do
(new_h_type, pr) ← tac h_type,
assert h.local_pp_name new_h_type,
mk_eq_mp pr h >>= tactic.exact },
goal_simplified ← succeeds $ do {
guard tgt,
(new_t, pr) ← target >>= tac,
replace_target new_t pr },
to_remove.mmap' (λ h, try (clear h)),
return (¬ to_remove.empty ∨ goal_simplified)
/-- `revert_after e` reverts all local constants after local constant `e`. -/
meta def revert_after (e : expr) : tactic ℕ := do
l ← local_context,
[pos] ← return $ l.indexes_of e | pp e >>= λ s, fail format!"No such local constant {s}",
let l := l.drop pos.succ, -- all local hypotheses after `e`
revert_lst l
/-- `revert_target_deps` reverts all local constants on which the target depends (recursively).
Returns the number of local constants that have been reverted. -/
meta def revert_target_deps : tactic ℕ :=
do tgt ← target,
ctx ← local_context,
l ← ctx.mfilter (kdepends_on tgt),
n ← revert_lst l,
if l = [] then return n
else do m ← revert_target_deps, return (m + n)
/-- `generalize' e n` generalizes the target with respect to `e`. It creates a new local constant
with name `n` of the same type as `e` and replaces all occurrences of `e` by `n`.
`generalize'` is similar to `generalize` but also succeeds when `e` does not occur in the
goal, in which case it just calls `assert`.
In contrast to `generalize` it already introduces the generalized variable. -/
meta def generalize' (e : expr) (n : name) : tactic expr :=
(generalize e n >> intro n) <|> note n none e
/--
`intron_no_renames n` calls `intro` `n` times, using the pretty-printing name
provided by the binder to name the new local constant.
Unlike `intron`, it does not rename introduced constants if the names shadow existing constants.
-/
meta def intron_no_renames : ℕ → tactic unit
| 0 := pure ()
| (n+1) := do
expr.pi pp_n _ _ _ ← target,
intro pp_n,
intron_no_renames n
/-- `get_univ_level t` returns the universe level of a type `t` -/
meta def get_univ_level (t : expr) (md := semireducible) (unfold_ginductive := tt) :
tactic level :=
do expr.sort u ← infer_type t >>= λ s, whnf s md unfold_ginductive |
fail "get_univ_level: argument is not a type",
return u
/-!
### Various tactics related to local definitions (local constants of the form `x : α := t`)
We call `t` the value of `x`.
-/
/-- `local_def_value e` returns the value of the expression `e`, assuming that `e` has been defined
locally using a `let` expression. Otherwise it fails. -/
meta def local_def_value (e : expr) : tactic expr :=
pp e >>= λ s, -- running `pp` here, because we cannot access it in the `type_context` monad.
tactic.unsafe.type_context.run $ do
lctx <- tactic.unsafe.type_context.get_local_context,
some ldecl <- return $ lctx.get_local_decl e.local_uniq_name |
tactic.unsafe.type_context.fail format!"No such hypothesis {s}.",
some let_val <- return ldecl.value |
tactic.unsafe.type_context.fail format!"Variable {e} is not a local definition.",
return let_val
/-- `is_local_def e` succeeds when `e` is a local definition (a local constant of the form
`e : α := t`) and otherwise fails. -/
meta def is_local_def (e : expr) : tactic unit := do
ctx ← unsafe.type_context.get_local_context.run,
(some decl) ← pure $ ctx.get_local_decl e.local_uniq_name |
fail format!"is_local_def: {e} is not a local constant",
when decl.value.is_none $ fail
format!"is_local_def: {e} is not a local definition"
/-- Returns the local definitions from the context. A local definition is a
local constant of the form `e : α := t`. The local definitions are returned in
the order in which they appear in the context. -/
meta def local_defs : tactic (list expr) := do
ctx ← unsafe.type_context.get_local_context.run,
ctx' ← local_context,
ctx'.mfilter $ λ h, do
(some decl) ← pure $ ctx.get_local_decl h.local_uniq_name |
fail format!"local_defs: local {h} not found in the local context",
pure decl.value.is_some
/-- like `split_on_p p xs`, `partition_local_deps_aux vs xs acc` searches for matches in `xs`
(using membership to `vs` instead of a predicate) and breaks `xs` when matches are found.
whereas `split_on_p p xs` removes the matches, `partition_local_deps_aux vs xs acc` includes
them in the following partition. Also, `partition_local_deps_aux vs xs acc` discards the partition
running up to the first match. -/
private def partition_local_deps_aux {α} [decidable_eq α] (vs : list α) :
list α → list α → list (list α)
| [] acc := [acc.reverse]
| (l :: ls) acc :=
if l ∈ vs then acc.reverse :: partition_local_deps_aux ls [l]
else partition_local_deps_aux ls (l :: acc)
/-- `partition_local_deps vs`, with `vs` a list of local constants,
reorders `vs` in the order they appear in the local context together
with the variables that follow them. If local context is `[a,b,c,d,e,f]`,
and that we call `partition_local_deps [d,b]`, we get `[[d,e,f], [b,c]]`.
The head of each list is one of the variables given as a parameter. -/
meta def partition_local_deps (vs : list expr) : tactic (list (list expr)) :=
do ls ← local_context,
pure (partition_local_deps_aux vs ls []).tail.reverse
/-- `clear_value [e₀, e₁, e₂, ...]` clears the body of the local definitions `e₀`, `e₁`, `e₂`, ...
changing them into regular hypotheses. A hypothesis `e : α := t` is changed to `e : α`. The order of
locals `e₀`, `e₁`, `e₂` does not matter as a permutation will be chosen so as to preserve type
correctness. This tactic is called `clearbody` in Coq. -/
meta def clear_value (vs : list expr) : tactic unit := do
ls ← partition_local_deps vs,
ls.mmap' $ λ vs, do
{ revert_lst vs,
(expr.elet v t d b) ← target |
fail format!"Cannot clear the body of {vs.head}. It is not a local definition.",
let e := expr.pi v binder_info.default t b,
type_check e <|>
fail format!"Cannot clear the body of {vs.head}. The resulting goal is not type correct.",
g ← mk_meta_var e,
h ← note `h none g,
tactic.exact $ h d,
gs ← get_goals,
set_goals $ g :: gs },
ls.reverse.mmap' $ λ vs, intro_lst $ vs.map expr.local_pp_name
/--
`context_has_local_def` is true iff there is at least one local definition in
the context.
-/
meta def context_has_local_def : tactic bool := do
ctx ← local_context,
ctx.many (succeeds ∘ local_def_value)
/--
`context_upto_hyp_has_local_def h` is true iff any of the hypotheses in the
context up to and including `h` is a local definition.
-/
meta def context_upto_hyp_has_local_def (h : expr) : tactic bool := do
ff ← succeeds (local_def_value h) | pure tt,
ctx ← local_context,
let ctx := ctx.take_while (≠ h),
ctx.many (succeeds ∘ local_def_value)
/--
If the expression `h` is a local variable with type `x = t` or `t = x`, where `x` is a local
constant, `tactic.subst' h` substitutes `x` by `t` everywhere in the main goal and then clears `h`.
If `h` is another local variable, then we find a local constant with type `h = t` or `t = h` and
substitute `t` for `h`.
This is like `tactic.subst`, but fails with a nicer error message if the substituted variable is a
local definition. It is trickier to fix this in core, since `tactic.is_local_def` is in mathlib.
-/
meta def subst' (h : expr) : tactic unit := do
e ← do { -- we first find the variable being substituted away
t ← infer_type h,
let (f, args) := t.get_app_fn_args,
if (f.const_name = `eq ∨ f.const_name = `heq) then do {
let lhs := args.inth 1,
let rhs := args.ilast,
if rhs.is_local_constant then return rhs else
if lhs.is_local_constant then return lhs else fail
"subst tactic failed, hypothesis '{h.local_pp_name}' is not of the form (x = t) or (t = x)." }
else return h },
success_if_fail (is_local_def e) <|>
fail format!("Cannot substitute variable {e.local_pp_name}, " ++
"it is a local definition. If you really want to do this, use `clear_value` first."),
subst h
/-- A variant of `simplify_bottom_up`. Given a tactic `post` for rewriting subexpressions,
`simp_bottom_up post e` tries to rewrite `e` starting at the leaf nodes. Returns the resulting
expression and a proof of equality. -/
meta def simp_bottom_up' (post : expr → tactic (expr × expr)) (e : expr) (cfg : simp_config := {}) :
tactic (expr × expr) :=
prod.snd <$> simplify_bottom_up () (λ _, (<$>) (prod.mk ()) ∘ post) e cfg
/-- Caches unary type classes on a type `α : Type.{univ}`. -/
meta structure instance_cache :=
(α : expr)
(univ : level)
(inst : name_map expr)
/-- Creates an `instance_cache` for the type `α`. -/
meta def mk_instance_cache (α : expr) : tactic instance_cache :=
do u ← mk_meta_univ,
infer_type α >>= unify (expr.sort (level.succ u)),
u ← get_univ_assignment u,
return ⟨α, u, mk_name_map⟩
namespace instance_cache
/-- If `n` is the name of a type class with one parameter, `get c n` tries to find an instance of
`n c.α` by checking the cache `c`. If there is no entry in the cache, it tries to find the instance
via type class resolution, and updates the cache. -/
meta def get (c : instance_cache) (n : name) : tactic (instance_cache × expr) :=
match c.inst.find n with
| some i := return (c, i)
| none := do e ← mk_app n [c.α] >>= mk_instance,
return (⟨c.α, c.univ, c.inst.insert n e⟩, e)
end
open expr
/-- If `e` is a `pi` expression that binds an instance-implicit variable of type `n`,
`append_typeclasses e c l` searches `c` for an instance `p` of type `n` and returns `p :: l`. -/
meta def append_typeclasses : expr → instance_cache → list expr →
tactic (instance_cache × list expr)
| (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l :=
do (c, p) ← c.get n, return (c, p :: l)
| _ c l := return (c, l)
/-- Creates the application `n c.α p l`, where `p` is a type class instance found in the cache `c`.
-/
meta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache × expr) :=
do d ← get_decl n,
(c, l) ← append_typeclasses d.type.binding_body c l,
return (c, (expr.const n [c.univ]).mk_app (c.α :: l))
/-- `c.of_nat n` creates the `c.α`-valued numeral expression corresponding to `n`. -/
protected meta def of_nat (c : instance_cache) (n : ℕ) : tactic (instance_cache × expr) :=
if n = 0 then c.mk_app ``has_zero.zero [] else do
(c, ai) ← c.get ``has_add,
(c, oi) ← c.get ``has_one,
(c, one) ← c.mk_app ``has_one.one [],
return (c, n.binary_rec one $ λ b n e,
if n = 0 then one else
cond b
((expr.const ``bit1 [c.univ]).mk_app [c.α, oi, ai, e])
((expr.const ``bit0 [c.univ]).mk_app [c.α, ai, e]))
/-- `c.of_int n` creates the `c.α`-valued numeral expression corresponding to `n`.
The output is either a numeral or the negation of a numeral. -/
protected meta def of_int (c : instance_cache) : ℤ → tactic (instance_cache × expr)
| (n : ℕ) := c.of_nat n
| -[1+ n] := do
(c, e) ← c.of_nat (n+1),
c.mk_app ``has_neg.neg [e]
end instance_cache
/-- A variation on `assert` where a (possibly incomplete)
proof of the assertion is provided as a parameter.
``(h,gs) ← local_proof `h p tac`` creates a local `h : p` and
use `tac` to (partially) construct a proof for it. `gs` is the
list of remaining goals in the proof of `h`.
The benefits over assert are:
- unlike with ``h ← assert `h p, tac`` , `h` cannot be used by `tac`;
- when `tac` does not complete the proof of `h`, returning the list
of goals allows one to write a tactic using `h` and with the confidence
that a proof will not boil over to goals left over from the proof of `h`,
unlike what would be the case when using `tactic.swap`.
-/
meta def local_proof (h : name) (p : expr) (tac₀ : tactic unit) :
tactic (expr × list expr) :=
focus1 $
do h' ← assert h p,
[g₀,g₁] ← get_goals,
set_goals [g₀], tac₀,
gs ← get_goals,
set_goals [g₁],
return (h', gs)
/-- `var_names e` returns a list of the unique names of the initial pi bindings in `e`. -/
meta def var_names : expr → list name
| (expr.pi n _ _ b) := n :: var_names b
| _ := []
/-- When `struct_n` is the name of a structure type,
`subobject_names struct_n` returns two lists of names `(instances, fields)`.
The names in `instances` are the projections from `struct_n` to the structures that it extends
(assuming it was defined with `old_structure_cmd false`).
The names in `fields` are the standard fields of `struct_n`. -/
meta def subobject_names (struct_n : name) : tactic (list name × list name) :=
do env ← get_env,
c ← match env.constructors_of struct_n with
| [c] := pure c
| [] :=
if env.is_inductive struct_n
then fail format!"{struct_n} does not have constructors"
else fail format!"{struct_n} is not an inductive type"
| _ := fail "too many constructors"
end,
vs ← var_names <$> (mk_const c >>= infer_type),
fields ← env.structure_fields struct_n,
return $ fields.partition (λ fn, ↑("_" ++ fn.to_string) ∈ vs)
private meta def expanded_field_list' : name → tactic (dlist $ name × name) | struct_n :=
do (so,fs) ← subobject_names struct_n,
ts ← so.mmap (λ n, do
(_, e) ← mk_const (n.update_prefix struct_n) >>= infer_type >>= open_pis,
expanded_field_list' $ e.get_app_fn.const_name),
return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n)
open functor function
/-- `expanded_field_list struct_n` produces a list of the names of the fields of the structure
named `struct_n`. These are returned as pairs of names `(prefix, name)`, where the full name
of the projection is `prefix.name`.
`struct_n` cannot be a synonym for a `structure`, it must be itself a `structure` -/
meta def expanded_field_list (struct_n : name) : tactic (list $ name × name) :=
dlist.to_list <$> expanded_field_list' struct_n
/--
Return a list of all type classes which can be instantiated
for the given expression.
-/
meta def get_classes (e : expr) : tactic (list name) :=
attribute.get_instances `class >>= list.mfilter (λ n,
succeeds $ mk_app n [e] >>= mk_instance)
/--
Finds an instance of an implication `cond → tgt`.
Returns a pair of a local constant `e` of type `cond`, and an instance of `tgt` that can mention
`e`. The local constant `e` is added as an hypothesis to the tactic state, but should not be used,
since it has been "proven" by a metavariable.
-/
meta def mk_conditional_instance (cond tgt : expr) : tactic (expr × expr) := do
f ← mk_meta_var cond,
e ← assertv `c cond f, swap,
reset_instance_cache,
inst ← mk_instance tgt,
return (e, inst)
open nat
/-- Create a list of `n` fresh metavariables. -/
meta def mk_mvar_list : ℕ → tactic (list expr)
| 0 := pure []
| (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n
/-- Returns the only goal, or fails if there isn't just one goal. -/
meta def get_goal : tactic expr :=
do gs ← get_goals,
match gs with
| [a] := return a
| [] := fail "there are no goals"
| _ := fail "there are too many goals"
end
/-- `iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals,
or until it fails. Always succeeds. -/
meta def iterate_at_most_on_all_goals : nat → tactic unit → tactic unit
| 0 tac := trace "maximal iterations reached"
| (succ n) tac := tactic.all_goals' $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip
/-- `iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first
goal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on
current goal. -/
meta def iterate_at_most_on_subgoals : nat → tactic unit → tactic unit
| 0 tac := trace "maximal iterations reached"
| (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac)
/-- This makes sure that the execution of the tactic does not change the tactic state.
This can be helpful while using rewrite, apply, or expr munging.
Remember to instantiate your metavariables before you're done! -/
meta def lock_tactic_state {α} (t : tactic α) : tactic α
| s := match t s with
| result.success a s' := result.success a s
| result.exception msg pos s' := result.exception msg pos s
end
/--
`apply_list l`, for `l : list (tactic expr)`,
tries to apply the lemmas generated by the tactics in `l` on the first goal, and
fail if none succeeds.
-/
meta def apply_list_expr (opt : apply_cfg) : list (tactic expr) → tactic unit
| [] := fail "no matching rule"
| (h::t) := (do e ← h, interactive.concat_tags (apply e opt)) <|> apply_list_expr t
/--
Constructs a list of `tactic expr` given a list of p-expressions, as follows:
- if the p-expression is the name of a theorem, use `i_to_expr_for_apply` on it
- if the p-expression is a user attribute, add all the theorems with this attribute
to the list.
We need to return a list of `tactic expr`, rather than just `expr`, because these expressions
will be repeatedly applied against goals, and we need to ensure that metavariables don't get stuck.
-/
meta def build_list_expr_for_apply : list pexpr → tactic (list (tactic expr))
| [] := return []
| (h::t) := do
tail ← build_list_expr_for_apply t,
a ← i_to_expr_for_apply h,
(do l ← attribute.get_instances (expr.const_name a),
m ← l.mmap (λ n, _root_.to_pexpr <$> mk_const n),
-- We reverse the list of lemmas marked with an attribute,
-- on the assumption that lemmas proved earlier are more often applicable
-- than lemmas proved later. This is a performance optimization.
build_list_expr_for_apply (m.reverse ++ t))
<|> return ((i_to_expr_for_apply h) :: tail)
/--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the
first goal and the resulting subgoals, iteratively, at most `n` times.
Unlike `solve_by_elim`, `apply_rules` does not do any backtracking, and just greedily applies
a lemma from the list until it can't.
-/
meta def apply_rules (hs : list pexpr) (n : nat) (opt : apply_cfg) : tactic unit :=
do l ← lock_tactic_state $ build_list_expr_for_apply hs,
iterate_at_most_on_subgoals n (assumption <|> apply_list_expr opt l)
/-- `replace h p` elaborates the pexpr `p`, clears the existing hypothesis named `h` from the local
context, and adds a new hypothesis named `h`. The type of this hypothesis is the type of `p`.
Fails if there is nothing named `h` in the local context. -/
meta def replace (h : name) (p : pexpr) : tactic unit :=
do h' ← get_local h,
p ← to_expr p,
note h none p,
clear h'
/-- Auxiliary function for `iff_mp` and `iff_mpr`. Takes a name, which should be either `` `iff.mp``
or `` `iff.mpr``. If the passed expression is an iterated function type eventually producing an
`iff`, returns an expression with the `iff` converted to either the forwards or backwards
implication, as requested. -/
meta def mk_iff_mp_app (iffmp : name) : expr → (nat → expr) → option expr
| (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (λ n, f (n+1) (expr.var n))
| `(%%a ↔ %%b) f := some $ @expr.const tt iffmp [] a b (f 0)
| _ f := none
/-- `iff_mp_core e ty` assumes that `ty` is the type of `e`.
If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., A → B`. -/
meta def iff_mp_core (e ty: expr) : option expr :=
mk_iff_mp_app `iff.mp ty (λ_, e)
/-- `iff_mpr_core e ty` assumes that `ty` is the type of `e`.
If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., B → A`. -/
meta def iff_mpr_core (e ty: expr) : option expr :=
mk_iff_mp_app `iff.mpr ty (λ_, e)
/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,
create the expression which is the forward implication. -/
meta def iff_mp (e : expr) : tactic expr :=
do t ← infer_type e,
iff_mp_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`"
/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,
create the expression which is the reverse implication. -/
meta def iff_mpr (e : expr) : tactic expr :=
do t ← infer_type e,
iff_mpr_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`"
/--
Attempts to apply `e`, and if that fails, if `e` is an `iff`,
try applying both directions separately.
-/
meta def apply_iff (e : expr) : tactic (list (name × expr)) :=
let ap e := tactic.apply e {new_goals := new_goals.non_dep_only} in
ap e <|> (iff_mp e >>= ap) <|> (iff_mpr e >>= ap)
/--
Configuration options for `apply_any`:
* `use_symmetry`: if `apply_any` fails to apply any lemma, call `symmetry` and try again.
* `use_exfalso`: if `apply_any` fails to apply any lemma, call `exfalso` and try again.
* `apply`: specify an alternative to `tactic.apply`; usually `apply := tactic.eapply`.
-/
meta structure apply_any_opt extends apply_cfg :=
(use_symmetry : bool := tt)
(use_exfalso : bool := tt)
/--
This is a version of `apply_any` that takes a list of `tactic expr`s instead of `expr`s,
and evaluates these as thunks before trying to apply them.
We need to do this to avoid metavariables getting stuck during subsequent rounds of `apply`.
-/
meta def apply_any_thunk
(lemmas : list (tactic expr))
(opt : apply_any_opt := {})
(tac : tactic unit := skip)
(on_success : expr → tactic unit := (λ _, skip))
(on_failure : tactic unit := skip) : tactic unit :=
do
let modes := [skip]
++ (if opt.use_symmetry then [symmetry] else [])
++ (if opt.use_exfalso then [exfalso] else []),
modes.any_of (λ m, do m,
lemmas.any_of (λ H, H >>= (λ e, do apply e opt.to_apply_cfg, on_success e, tac))) <|>
(on_failure >> fail "apply_any tactic failed; no lemma could be applied")
/--
`apply_any lemmas` tries to apply one of the list `lemmas` to the current goal.
`apply_any lemmas opt` allows control over how lemmas are applied.
`opt` has fields:
* `use_symmetry`: if no lemma applies, call `symmetry` and try again. (Defaults to `tt`.)
* `use_exfalso`: if no lemma applies, call `exfalso` and try again. (Defaults to `tt`.)
* `apply`: use a tactic other than `tactic.apply` (e.g. `tactic.fapply` or `tactic.eapply`).
`apply_any lemmas tac` calls the tactic `tac` after a successful application.
Defaults to `skip`. This is used, for example, by `solve_by_elim` to arrange
recursive invocations of `apply_any`.
-/
meta def apply_any
(lemmas : list expr)
(opt : apply_any_opt := {})
(tac : tactic unit := skip) : tactic unit :=
apply_any_thunk (lemmas.map pure) opt tac
/-- Try to apply a hypothesis from the local context to the goal. -/
meta def apply_assumption : tactic unit :=
local_context >>= apply_any
/-- `change_core e none` is equivalent to `change e`. It tries to change the goal to `e` and fails
if this is not a definitional equality.
`change_core e (some h)` assumes `h` is a local constant, and tries to change the type of `h` to `e`
by reverting `h`, changing the goal, and reintroducing hypotheses. -/
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_with_at olde newe hyp` replaces occurences of `olde` with `newe` at hypothesis `hyp`,
assuming `olde` and `newe` are defeq when elaborated.
-/
meta def change_with_at (olde newe : pexpr) (hyp : name) : tactic unit :=
do h ← get_local hyp,
tp ← infer_type h,
olde ← to_expr olde, newe ← to_expr newe,
let repl_tp := tp.replace (λ a n, if a = olde then some newe else none),
when (repl_tp ≠ tp) $ change_core repl_tp (some h)
/-- Returns a list of all metavariables in the current partial proof. This can differ from
the list of goals, since the goals can be manually edited. -/
meta def metavariables : tactic (list expr) :=
expr.list_meta_vars <$> result
/--
`sorry_if_contains_sorry` will solve any goal already containing `sorry` in its type with `sorry`,
and fail otherwise.
-/
meta def sorry_if_contains_sorry : tactic unit :=
do
g ← target,
guard g.contains_sorry <|> fail "goal does not contain `sorrry`",
tactic.admit
/-- Fail if the target contains a metavariable. -/
meta def no_mvars_in_target : tactic unit :=
expr.has_meta_var <$> target >>= guardb ∘ bnot
/-- Succeeds only if the current goal is a proposition. -/
meta def propositional_goal : tactic unit :=
do g :: _ ← get_goals,
is_proof g >>= guardb
/-- Succeeds only if we can construct an instance showing the
current goal is a subsingleton type. -/
meta def subsingleton_goal : tactic unit :=
do g :: _ ← get_goals,
ty ← infer_type g >>= instantiate_mvars,
to_expr ``(subsingleton %%ty) >>= mk_instance >> skip
/--
Succeeds only if the current goal is "terminal",
in the sense that no other goals depend on it
(except possibly through shared metavariables; see `independent_goal`).
-/
meta def terminal_goal : tactic unit :=
propositional_goal <|> subsingleton_goal <|>
do g₀ :: _ ← get_goals,
mvars ← (λ L, list.erase L g₀) <$> metavariables,
mvars.mmap' $ λ g, do
t ← infer_type g >>= instantiate_mvars,
d ← kdepends_on t g₀,
monad.whenb d $
pp t >>= λ s, fail ("The current goal is not terminal: " ++ s.to_string ++ " depends on it.")
/--
Succeeds only if the current goal is "independent", in the sense
that no other goals depend on it, even through shared meta-variables.
-/
meta def independent_goal : tactic unit :=
no_mvars_in_target >> terminal_goal
/-- `triv'` tries to close the first goal with the proof `trivial : true`. Unlike `triv`,
it only unfolds reducible definitions, so it sometimes fails faster. -/
meta def triv' : tactic unit := do c ← mk_const `trivial, exact c reducible
variable {α : Type}
/-- Apply a tactic as many times as possible, collecting the results in a list.
Fail if the tactic does not succeed at least once. -/
meta def iterate1 (t : tactic α) : tactic (list α) :=
do r ← decorate_ex "iterate1 failed: tactic did not succeed" t,
L ← iterate t,
return (r :: L)
/-- Introduces one or more variables and returns the new local constants.
Fails if `intro` cannot be applied. -/
meta def intros1 : tactic (list expr) :=
iterate1 intro1
/-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/
meta def under_binders {α : Type} (t : tactic α) : tactic α :=
do
v ← intros,
r ← t,
revert_lst v,
return r
namespace interactive
/-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/
meta def under_binders (i : itactic) : itactic := tactic.under_binders i
end interactive
/-- `successes` invokes each tactic in turn, returning the list of successful results. -/
meta def successes (tactics : list (tactic α)) : tactic (list α) :=
list.filter_map id <$> monad.sequence (tactics.map (λ t, try_core t))
/--
Try all the tactics in a list, each time starting at the original `tactic_state`,
returning the list of successful results,
and reverting to the original `tactic_state`.
-/
-- Note this is not the same as `successes`, which keeps track of the evolving `tactic_state`.
meta def try_all {α : Type} (tactics : list (tactic α)) : tactic (list α) :=
λ s, result.success
(tactics.map $
λ t : tactic α,
match t s with
| result.success a s' := [a]
| _ := []
end).join s
/--
Try all the tactics in a list, each time starting at the original `tactic_state`,
returning the list of successful results sorted by
the value produced by a subsequent execution of the `sort_by` tactic,
and reverting to the original `tactic_state`.
-/
meta def try_all_sorted {α : Type} (tactics : list (tactic α)) (sort_by : tactic ℕ := num_goals) :
tactic (list (α × ℕ)) :=
λ s, result.success
((tactics.map $
λ t : tactic α,
match (do a ← t, n ← sort_by, return (a, n)) s with
| result.success a s' := [a]
| _ := []
end).join.qsort (λ p q : α × ℕ, p.2 < q.2)) s
/-- Return target after instantiating metavars and whnf. -/
private meta def target' : tactic expr :=
target >>= instantiate_mvars >>= whnf
/--
Just like `split`, `fsplit` applies the constructor when the type of the target is
an inductive data type with one constructor.
However it does not reorder goals or invoke `auto_param` tactics.
-/
-- FIXME check if we can remove `auto_param := ff`
meta def fsplit : tactic unit :=
do [c] ← target' >>= get_constructors_for |
fail "fsplit tactic failed, target is not an inductive datatype with only one constructor",
mk_const c >>= λ e, apply e {new_goals := new_goals.all, auto_param := ff} >> skip
run_cmd add_interactive [`fsplit]
add_tactic_doc
{ name := "fsplit",
category := doc_category.tactic,
decl_names := [`tactic.interactive.fsplit],
tags := ["logic", "goal management"] }
/-- Calls `injection` on each hypothesis, and then, for each hypothesis on which `injection`
succeeds, clears the old hypothesis. -/
meta def injections_and_clear : tactic unit :=
do l ← local_context,
results ← successes $ l.map $ λ e, injection e >> clear e,
when (results.empty) (fail "could not use `injection` then `clear` on any hypothesis")
run_cmd add_interactive [`injections_and_clear]
add_tactic_doc
{ name := "injections_and_clear",
category := doc_category.tactic,
decl_names := [`tactic.interactive.injections_and_clear],
tags := ["context management"] }
/-- Calls `cases` on every local hypothesis, succeeding if
it succeeds on at least one hypothesis. -/
meta def case_bash : tactic unit :=
do l ← local_context,
r ← successes (l.reverse.map (λ h, cases h >> skip)),
when (r.empty) failed
/--
`note_anon t v`, given a proof `v : t`,
adds `h : t` to the current context, where the name `h` is fresh.
`note_anon none v` will infer the type `t` from `v`.
-/
-- While `note` provides a default value for `t`, it doesn't seem this could ever be used.
meta def note_anon (t : option expr) (v : expr) : tactic expr :=
do h ← get_unused_name `h none,
note h t v
/-- `find_local t` returns a local constant with type t, or fails if none exists. -/
meta def find_local (t : pexpr) : tactic expr :=
do t' ← to_expr t,
(prod.snd <$> solve_aux t' assumption >>= instantiate_mvars) <|>
fail format!"No hypothesis found of the form: {t'}"
/-- `dependent_pose_core l`: introduce dependent hypotheses, where the proofs depend on the values
of the previous local constants. `l` is a list of local constants and their values. -/
meta def dependent_pose_core (l : list (expr × expr)) : tactic unit := do
let lc := l.map prod.fst,
let lm := l.map (λ⟨l, v⟩, (l.local_uniq_name, v)),
old::other_goals ← get_goals,
t ← infer_type old,
new_goal ← mk_meta_var (t.pis lc),
set_goals (old :: new_goal :: other_goals),
exact ((new_goal.mk_app lc).instantiate_locals lm),
return ()
/--
Instantiates metavariables that appear in the current goal.
-/
meta def instantiate_mvars_in_target : tactic unit :=
target >>= instantiate_mvars >>= change
/--
Instantiates metavariables in all goals.
-/
meta def instantiate_mvars_in_goals : tactic unit :=
all_goals' $ instantiate_mvars_in_target
/-- Protect the declaration `n` -/
meta def mk_protected (n : name) : tactic unit :=
do env ← get_env, set_env (env.mk_protected n)
end tactic
namespace lean.parser
open tactic interaction_monad
/-- `emit_command_here str` behaves as if the string `str` were placed as a user command at the
current line. -/
meta def emit_command_here (str : string) : lean.parser string :=
do (_, left) ← with_input command_like str,
return left
/-- Inner recursion for `emit_code_here`. -/
meta def emit_code_here_aux : string → ℕ → lean.parser unit
| str slen := do
left ← emit_command_here str,
let llen := left.length,
when (llen < slen ∧ llen ≠ 0) (emit_code_here_aux left llen)
/-- `emit_code_here str` behaves as if the string `str` were placed at the current location in
source code. -/
meta def emit_code_here (s : string) : lean.parser unit := emit_code_here_aux s s.length
/-- `run_parser p` is like `run_cmd` but for the parser monad. It executes parser `p` at the
top level, giving access to operations like `emit_code_here`. -/
@[user_command]
meta def run_parser_cmd (_ : interactive.parse $ tk "run_parser") : lean.parser unit :=
do e ← lean.parser.pexpr 0,
p ← eval_pexpr (lean.parser unit) e,
p
add_tactic_doc
{ name := "run_parser",
category := doc_category.cmd,
decl_names := [``run_parser_cmd],
tags := ["parsing"] }
/-- `get_current_namespace` returns the current namespace (it could be `name.anonymous`).
This function deserves a C++ implementation in core lean, and will fail if it is not called from
the body of a command (i.e. anywhere else that the `lean.parser` monad can be invoked). -/
meta def get_current_namespace : lean.parser name :=
do n ← tactic.mk_user_fresh_name,
emit_code_here $ sformat!"def {n} := ()",
nfull ← tactic.resolve_constant n,
return $ nfull.get_nth_prefix n.components.length
/-- `get_variables` returns a list of existing variable names, along with their types and binder
info. -/
meta def get_variables : lean.parser (list (name × binder_info × expr)) :=
list.map expr.get_local_const_kind <$> list_available_include_vars
/-- `get_included_variables` returns those variables `v` returned by `get_variables` which have been
"included" by an `include v` statement and are not (yet) `omit`ed. -/
meta def get_included_variables : lean.parser (list (name × binder_info × expr)) :=
do ns ← list_include_var_names,
list.filter (λ v, v.1 ∈ ns) <$> get_variables
/-- From the `lean.parser` monad, synthesize a `tactic_state` which includes all of the local
variables referenced in `es : list pexpr`, and those variables which have been `include`ed in the
local context---precisely those variables which would be ambiently accessible if we were in a
tactic-mode block where the goals had types `es.mmap to_expr`, for example.
Returns a new `ts : tactic_state` with these local variables added, and
`mappings : list (expr × expr)`, for which pairs `(var, hyp)` correspond to an existing variable
`var` and the local hypothesis `hyp` which was added to the tactic state `ts` as a result. -/
meta def synthesize_tactic_state_with_variables_as_hyps (es : list pexpr)
: lean.parser (tactic_state × list (expr × expr)) :=
do /- First, in order to get `to_expr e` to resolve declared `variables`, we add all of the
declared variables to a fake `tactic_state`, and perform the resolution. At the end,
`to_expr e` has done the work of determining which variables were actually referenced, which
we then obtain from `fe` via `expr.list_local_consts` (which, importantly, is not defined for
`pexpr`s). -/
vars ← list_available_include_vars,
fake_es ← lean.parser.of_tactic $ lock_tactic_state $ do {
/- Note that `add_local_consts_as_local_hyps` returns the mappings it generated, but we discard
them on this first pass. (We return the mappings generated by our second invocation of this
function below.) -/
add_local_consts_as_local_hyps vars,
es.mmap to_expr },
/- Now calculate lists of a) the explicitly `include`ed variables and b) the variables which were
referenced in `e` when it was resolved to `fake_e`.
It is important that we include variables of the kind a) because we want `simp` to have access
to declared local instances, and it is important that we only restrict to variables of kind a)
and b) together since we do not to recognise a hypothesis which is posited as a `variable`
in the environment but not referenced in the `pexpr` we were passed.
One use case for this behaviour is running `simp` on the passed `pexpr`, since we do not want
simp to use arbitrary hypotheses which were declared as `variables` in the local environment
but not referenced in the expression to simplify (as one would be expect generally in tactic
mode). -/
included_vars ← list_include_var_names,
let referenced_vars := list.join $ fake_es.map $ λ e, e.list_local_consts.map expr.local_pp_name,
/- Look up the explicit `included_vars` and the `referenced_vars` (which have appeared in the
`pexpr` list which we were passed.) -/
let directly_included_vars := vars.filter $ λ var,
(var.local_pp_name ∈ included_vars) ∨ (var.local_pp_name ∈ referenced_vars),
/- Inflate the list `directly_included_vars` to include those variables which are "implicitly
included" by virtue of reference to one or multiple others. For example, given
`variables (n : ℕ) [prime n] [ih : even n]`, a reference to `n` implies that the typeclass
instance `prime n` should be included, but `ih : even n` should not. -/
let all_implicitly_included_vars :=
expr.all_implicitly_included_variables vars directly_included_vars,
/- Capture a tactic state where both of these kinds of variables have been added as local
hypotheses, and resolve `e` against this state with `to_expr`, this time for real. -/
lean.parser.of_tactic $ do {
mappings ← add_local_consts_as_local_hyps all_implicitly_included_vars,
ts ← get_state,
return (ts, mappings) }
end lean.parser
namespace tactic
variables {α : Type}
/--
Hole command used to fill in a structure's field when specifying an instance.
In the following:
```lean
instance : monad id :=
{! !}
```
invoking the hole command "Instance Stub" ("Generate a skeleton for the structure under
construction.") produces:
```lean
instance : monad id :=
{ map := _,
map_const := _,
pure := _,
seq := _,
seq_left := _,
seq_right := _,
bind := _ }
```
-/
@[hole_command] meta def instance_stub : hole_command :=
{ name := "Instance Stub",
descr := "Generate a skeleton for the structure under construction.",
action := λ _,
do tgt ← target >>= whnf,
let cl := tgt.get_app_fn.const_name,
env ← get_env,
fs ← expanded_field_list cl,
let fs := fs.map prod.snd,
let fs := format.intercalate (",\n " : format) $ fs.map (λ fn, format!"{fn} := _"),
let out := format.to_string format!"{{ {fs} }",
return [(out,"")] }
add_tactic_doc
{ name := "instance_stub",
category := doc_category.hole_cmd,
decl_names := [`tactic.instance_stub],
tags := ["instances"] }
/-- Like `resolve_name` except when the list of goals is
empty. In that situation `resolve_name` fails whereas
`resolve_name'` simply proceeds on a dummy goal -/
meta def resolve_name' (n : name) : tactic pexpr :=
do [] ← get_goals | resolve_name n,
g ← mk_mvar,
set_goals [g],
resolve_name n <* set_goals []
private meta def strip_prefix' (n : name) : list string → name → tactic name
| s name.anonymous := pure $ s.foldl (flip name.mk_string) name.anonymous
| s (name.mk_string a p) :=
do let n' := s.foldl (flip name.mk_string) name.anonymous,
do { n'' ← tactic.resolve_constant n',
if n'' = n
then pure n'
else strip_prefix' (a :: s) p }
<|> strip_prefix' (a :: s) p
| s n@(name.mk_numeral a p) := pure $ s.foldl (flip name.mk_string) n
/-- Strips unnecessary prefixes from a name, e.g. if a namespace is open. -/
meta def strip_prefix : name → tactic name
| n@(name.mk_string a a_1) :=
if (`_private).is_prefix_of n
then let n' := n.update_prefix name.anonymous in
n' <$ resolve_name' n' <|> pure n
else strip_prefix' n [a] a_1
| n := pure n
/-- Used to format return strings for the hole commands `match_stub` and `eqn_stub`. -/
meta def mk_patterns (t : expr) : tactic (list format) :=
do let cl := t.get_app_fn.const_name,
env ← get_env,
let fs := env.constructors_of cl,
fs.mmap $ λ f,
do { (vs,_) ← mk_const f >>= infer_type >>= open_pis,
let vs := vs.filter (λ v, v.is_default_local),
vs ← vs.mmap (λ v,
do v' ← get_unused_name v.local_pp_name,
pose v' none `(()),
pure v' ),
vs.mmap' $ λ v, get_local v >>= clear,
let args := list.intersperse (" " : format) $ vs.map to_fmt,
f ← strip_prefix f,
if args.empty
then pure $ format!"| {f} := _\n"
else pure format!"| ({f} {format.join args}) := _\n" }
/--
Hole command used to generate a `match` expression.
In the following:
```lean
meta def foo (e : expr) : tactic unit :=
{! e !}
```
invoking hole command "Match Stub" ("Generate a list of equations for a `match` expression")
produces:
```lean
meta def foo (e : expr) : tactic unit :=
match e with
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
end
```
-/
@[hole_command] meta def match_stub : hole_command :=
{ name := "Match Stub",
descr := "Generate a list of equations for a `match` expression.",
action := λ es,
do [e] ← pure es | fail "expecting one expression",
e ← to_expr e,
t ← infer_type e >>= whnf,
fs ← mk_patterns t,
e ← pp e,
let out := format.to_string format!"match {e} with\n{format.join fs}end\n",
return [(out,"")] }
add_tactic_doc
{ name := "Match Stub",
category := doc_category.hole_cmd,
decl_names := [`tactic.match_stub],
tags := ["pattern matching"] }
/--
Invoking hole command "Equations Stub" ("Generate a list of equations for a recursive definition")
in the following:
```lean
meta def foo : {! expr → tactic unit !} -- `:=` is omitted
```
produces:
```lean
meta def foo : expr → tactic unit
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
```
A similar result can be obtained by invoking "Equations Stub" on the following:
```lean
meta def foo : expr → tactic unit := -- do not forget to write `:=`!!
{! !}
```
```lean
meta def foo : expr → tactic unit := -- don't forget to erase `:=`!!
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
```
-/
@[hole_command] meta def eqn_stub : hole_command :=
{ name := "Equations Stub",
descr := "Generate a list of equations for a recursive definition.",
action := λ es,
do t ← match es with
| [t] := to_expr t
| [] := target
| _ := fail "expecting one type"
end,
e ← whnf t,
(v :: _,_) ← open_pis e | fail "expecting a Pi-type",
t' ← infer_type v,
fs ← mk_patterns t',
t ← pp t,
let out :=
if es.empty then
format.to_string format!"-- do not forget to erase `:=`!!\n{format.join fs}"
else format.to_string format!"{t}\n{format.join fs}",
return [(out,"")] }
add_tactic_doc
{ name := "Equations Stub",
category := doc_category.hole_cmd,
decl_names := [`tactic.eqn_stub],
tags := ["pattern matching"] }
/--
This command lists the constructors that can be used to satisfy the expected type.
Invoking "List Constructors" ("Show the list of constructors of the expected type")
in the following hole:
```lean
def foo : ℤ ⊕ ℕ :=
{! !}
```
produces:
```lean
def foo : ℤ ⊕ ℕ :=
{! sum.inl, sum.inr !}
```
and will display:
```lean
sum.inl : ℤ → ℤ ⊕ ℕ
sum.inr : ℕ → ℤ ⊕ ℕ
```
-/
@[hole_command] meta def list_constructors_hole : hole_command :=
{ name := "List Constructors",
descr := "Show the list of constructors of the expected type.",
action := λ es,
do t ← target >>= whnf,
(_,t) ← open_pis t,
let cl := t.get_app_fn.const_name,
let args := t.get_app_args,
env ← get_env,
let cs := env.constructors_of cl,
ts ← cs.mmap $ λ c,
do { e ← mk_const c,
t ← infer_type (e.mk_app args) >>= pp,
c ← strip_prefix c,
pure format!"\n{c} : {t}\n" },
fs ← format.intercalate ", " <$> cs.mmap (strip_prefix >=> pure ∘ to_fmt),
let out := format.to_string format!"{{! {fs} !}",
trace (format.join ts).to_string,
return [(out,"")] }
add_tactic_doc
{ name := "List Constructors",
category := doc_category.hole_cmd,
decl_names := [`tactic.list_constructors_hole],
tags := ["goal information"] }
/-- Makes the declaration `classical.prop_decidable` available to type class inference.
This asserts that all propositions are decidable, but does not have computational content. -/
meta def classical : tactic unit :=
do h ← get_unused_name `_inst,
mk_const `classical.prop_decidable >>= note h none,
reset_instance_cache
open expr
/-- `mk_comp v e` checks whether `e` is a sequence of nested applications `f (g (h v))`, and if so,
returns the expression `f ∘ g ∘ h`. -/
meta def mk_comp (v : expr) : expr → tactic expr
| (app f e) :=
if e = v then pure f
else do
guard (¬ v.occurs f) <|> fail "bad guard",
e' ← mk_comp e >>= instantiate_mvars,
f ← instantiate_mvars f,
mk_mapp ``function.comp [none,none,none,f,e']
| e :=
do guard (e = v),
t ← infer_type e,
mk_mapp ``id [t]
/-- Given two expressions `e₀` and `e₁`, return the expression `` `(%%e₀ ↔ %%e₁)``. -/
meta def mk_iff (e₀ : expr) (e₁ : expr) : expr := `(%%e₀ ↔ %%e₁)
/--
From a lemma of the shape `∀ x, f (g x) = h x`
derive an auxiliary lemma of the form `f ∘ g = h`
for reasoning about higher-order functions.
-/
meta def mk_higher_order_type : expr → tactic expr
| (pi n bi d b@(pi _ _ _ _)) :=
do v ← mk_local_def n d,
let b' := (b.instantiate_var v),
(pi n bi d ∘ flip abstract_local v.local_uniq_name) <$> mk_higher_order_type b'
| (pi n bi d b) :=
do v ← mk_local_def n d,
let b' := (b.instantiate_var v),
(l,r) ← match_eq b' <|> fail format!"not an equality {b'}",
l' ← mk_comp v l,
r' ← mk_comp v r,
mk_app ``eq [l',r']
| e := failed
open lean.parser interactive.types
/-- A user attribute that applies to lemmas of the shape `∀ x, f (g x) = h x`.
It derives an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions.
-/
@[user_attribute]
meta def higher_order_attr : user_attribute unit (option name) :=
{ name := `higher_order,
parser := optional ident,
descr :=
"From a lemma of the shape `∀ x, f (g x) = h x` derive an auxiliary lemma of the
form `f ∘ g = h` for reasoning about higher-order functions.",
after_set := some $ λ lmm _ _,
do env ← get_env,
decl ← env.get lmm,
let num := decl.univ_params.length,
let lvls := (list.iota num).map (`l).append_after,
let l : expr := expr.const lmm $ lvls.map level.param,
t ← infer_type l >>= instantiate_mvars,
t' ← mk_higher_order_type t,
(_,pr) ← solve_aux t' $ do {
intros, applyc ``_root_.funext, intro1, applyc lmm; assumption },
pr ← instantiate_mvars pr,
lmm' ← higher_order_attr.get_param lmm,
lmm' ← (flip name.update_prefix lmm.get_prefix <$> lmm') <|> pure lmm.add_prime,
add_decl $ declaration.thm lmm' lvls t' (pure pr),
copy_attribute `simp lmm lmm',
copy_attribute `functor_norm lmm lmm' }
add_tactic_doc
{ name := "higher_order",
category := doc_category.attr,
decl_names := [`tactic.higher_order_attr],
tags := ["lemma derivation"] }
attribute [higher_order map_comp_pure] map_pure
/--
Copies a definition into the `tactic.interactive` namespace to make it usable
in proof scripts. It allows one to write
```lean
@[interactive]
meta def my_tactic := ...
```
instead of
```lean
meta def my_tactic := ...
run_cmd add_interactive [``my_tactic]
```
-/
@[user_attribute]
meta def interactive_attr : user_attribute :=
{ name := `interactive,
descr :=
"Put a definition in the `tactic.interactive` namespace to make it usable
in proof scripts.",
after_set := some $ λ tac _ _, add_interactive [tac] }
add_tactic_doc
{ name := "interactive",
category := doc_category.attr,
decl_names := [``tactic.interactive_attr],
tags := ["environment"] }
/--
Use `refine` to partially discharge the goal,
or call `fconstructor` and try again.
-/
private meta def use_aux (h : pexpr) : tactic unit :=
(focus1 (refine h >> done)) <|> (fconstructor >> use_aux)
/-- Similar to `existsi`, `use l` will use entries in `l` to instantiate existential obligations
at the beginning of a target. Unlike `existsi`, the pexprs in `l` are elaborated with respect to
the expected type.
```lean
example : ∃ x : ℤ, x = x :=
by tactic.use ``(42)
```
See the doc string for `tactic.interactive.use` for more information.
-/
protected meta def use (l : list pexpr) : tactic unit :=
focus1 $ seq' (l.mmap' $ λ h, use_aux h <|> fail format!"failed to instantiate goal with {h}")
instantiate_mvars_in_target
/-- `clear_aux_decl_aux l` clears all expressions in `l` that represent aux decls from the
local context. -/
meta def clear_aux_decl_aux : list expr → tactic unit
| [] := skip
| (e::l) := do cond e.is_aux_decl (tactic.clear e) skip, clear_aux_decl_aux l
/-- `clear_aux_decl` clears all expressions from the local context that represent aux decls. -/
meta def clear_aux_decl : tactic unit :=
local_context >>= clear_aux_decl_aux
/-- `apply_at_aux e et [] h ht` (with `et` the type of `e` and `ht` the type of `h`)
finds a list of expressions `vs` and returns `(e.mk_args (vs ++ [h]), vs)`. -/
meta def apply_at_aux (arg t : expr) : list expr → expr → expr → tactic (expr × list expr)
| vs e (pi n bi d b) :=
do { v ← mk_meta_var d,
apply_at_aux (v :: vs) (e v) (b.instantiate_var v) } <|>
(e arg, vs) <$ unify d t
| vs e _ := failed
/-- `apply_at e h` applies implication `e` on hypothesis `h` and replaces `h` with the result. -/
meta def apply_at (e h : expr) : tactic unit :=
do ht ← infer_type h,
et ← infer_type e,
(h', gs') ← apply_at_aux h ht [] e et,
note h.local_pp_name none h',
clear h,
gs' ← gs'.mfilter is_assigned,
(g :: gs) ← get_goals,
set_goals (g :: gs' ++ gs)
/-- `symmetry_hyp h` applies `symmetry` on hypothesis `h`. -/
meta def symmetry_hyp (h : expr) (md := semireducible) : tactic unit :=
do tgt ← infer_type h,
env ← get_env,
let r := get_app_fn tgt,
match env.symm_for (const_name r) with
| (some symm) := do s ← mk_const symm,
apply_at s h
| none := fail
"symmetry tactic failed, target is not a relation application with the expected property."
end
/-- `setup_tactic_parser` is a user command that opens the namespaces used in writing
interactive tactics, and declares the local postfix notation `?` for `optional` and `*` for `many`.
It does *not* use the `namespace` command, so it will typically be used after
`namespace tactic.interactive`.
-/
@[user_command]
meta def setup_tactic_parser_cmd (_ : interactive.parse $ tk "setup_tactic_parser") :
lean.parser unit :=
emit_code_here "
open _root_.lean
open _root_.lean.parser
open _root_.interactive _root_.interactive.types
local postfix `?`:9001 := optional
local postfix *:9001 := many .
"
/-- `finally tac finalizer` runs `tac` first, then runs `finalizer` even if
`tac` fails. `finally tac finalizer` fails if either `tac` or `finalizer` fails. -/
meta def finally {β} (tac : tactic α) (finalizer : tactic β) : tactic α :=
λ s, match tac s with
| (result.success r s') := (finalizer >> pure r) s'
| (result.exception msg p s') := (finalizer >> result.exception msg p) s'
end
/--
`on_exception handler tac` runs `tac` first, and then runs `handler` only if `tac` failed.
-/
meta def on_exception {β} (handler : tactic β) (tac : tactic α) : tactic α | s :=
match tac s with
| result.exception msg p s' := (handler *> result.exception msg p) s'
| ok := ok
end
/-- `decorate_error add_msg tac` prepends `add_msg` to an exception produced by `tac` -/
meta def decorate_error (add_msg : string) (tac : tactic α) : tactic α | s :=
match tac s with
| result.exception msg p s :=
let msg (_ : unit) : format := match msg with
| some msg := add_msg ++ format.line ++ msg ()
| none := add_msg
end in
result.exception msg p s
| ok := ok
end
/-- Applies tactic `t`. If it succeeds, revert the state, and return the value. If it fails,
returns the error message. -/
meta def retrieve_or_report_error {α : Type u} (t : tactic α) : tactic (α ⊕ string) :=
λ s, match t s with
| (interaction_monad.result.success a s') := result.success (sum.inl a) s
| (interaction_monad.result.exception msg' _ s') :=
result.success (sum.inr (msg'.iget ()).to_string) s
end
/-- Applies tactic `t`. If it succeeds, return the value. If it fails, returns the error message. -/
meta def try_or_report_error {α : Type u} (t : tactic α) : tactic (α ⊕ string) :=
λ s, match t s with
| (interaction_monad.result.success a s') := result.success (sum.inl a) s'
| (interaction_monad.result.exception msg' _ s') :=
result.success (sum.inr (msg'.iget ()).to_string) s
end
/-- This tactic succeeds if `t` succeeds or fails with message `msg` such that `p msg` is `tt`.
-/
meta def succeeds_or_fails_with_msg {α : Type} (t : tactic α) (p : string → bool) : tactic unit :=
do x ← retrieve_or_report_error t,
match x with
| (sum.inl _) := skip
| (sum.inr msg) := if p msg then skip else fail msg
end
add_tactic_doc
{ name := "setup_tactic_parser",
category := doc_category.cmd,
decl_names := [`tactic.setup_tactic_parser_cmd],
tags := ["parsing", "notation"] }
/-- `trace_error msg t` executes the tactic `t`. If `t` fails, traces `msg` and the failure message
of `t`. -/
meta def trace_error (msg : string) (t : tactic α) : tactic α
| s := match t s with
| (result.success r s') := result.success r s'
| (result.exception (some msg') p s') := (trace msg >> trace (msg' ()) >> result.exception
(some msg') p) s'
| (result.exception none p s') := result.exception none p s'
end
/--
``trace_if_enabled `n msg`` traces the message `msg`
only if tracing is enabled for the name `n`.
Create new names registered for tracing with `declare_trace n`.
Then use `set_option trace.n true/false` to enable or disable tracing for `n`.
-/
meta def trace_if_enabled
(n : name) {α : Type u} [has_to_tactic_format α] (msg : α) : tactic unit :=
when_tracing n (trace msg)
/--
``trace_state_if_enabled `n msg`` prints the tactic state,
preceded by the optional string `msg`,
only if tracing is enabled for the name `n`.
-/
meta def trace_state_if_enabled
(n : name) (msg : string := "") : tactic unit :=
when_tracing n ((if msg = "" then skip else trace msg) >> trace_state)
/--
This combinator is for testing purposes. It succeeds if `t` fails with message `msg`,
and fails otherwise.
-/
meta def success_if_fail_with_msg {α : Type u} (t : tactic α) (msg : string) : tactic unit :=
λ s, match t s with
| (interaction_monad.result.exception msg' _ s') :=
let expected_msg := (msg'.iget ()).to_string in
if msg = expected_msg then result.success () s
else mk_exception format!"failure messages didn't match. Expected:\n{expected_msg}" none s
| (interaction_monad.result.success a s) :=
mk_exception "success_if_fail_with_msg combinator failed, given tactic succeeded" none s
end
/--
Construct a `Try this: refine ...` or `Try this: exact ...` string which would construct `g`.
-/
meta def tactic_statement (g : expr) : tactic string :=
do g ← instantiate_mvars g,
g ← head_beta g,
r ← pp (replace_mvars g),
if g.has_meta_var
then return (sformat!"Try this: refine {r}")
else return (sformat!"Try this: exact {r}")
/-- `with_local_goals gs tac` runs `tac` on the goals `gs` and then restores the
initial goals and returns the goals `tac` ended on. -/
meta def with_local_goals {α} (gs : list expr) (tac : tactic α) : tactic (α × list expr) :=
do gs' ← get_goals,
set_goals gs,
finally (prod.mk <$> tac <*> get_goals) (set_goals gs')
/-- like `with_local_goals` but discards the resulting goals -/
meta def with_local_goals' {α} (gs : list expr) (tac : tactic α) : tactic α :=
prod.fst <$> with_local_goals gs tac
/-- Representation of a proof goal that lends itself to comparison. The
following goal:
```lean
l₀ : T,
l₁ : T
⊢ ∀ v : T, foo
```
is represented as
```
(2, ∀ l₀ l₁ v : T, foo)
```
The number 2 indicates that first the two bound variables of the
`∀` are actually local constant. Comparing two such goals with `=`
rather than `=ₐ` or `is_def_eq` tells us that proof script should
not see the difference between the two.
-/
meta def packaged_goal := ℕ × expr
/-- proof state made of multiple `goal` meant for comparing
the result of running different tactics -/
meta def proof_state := list packaged_goal
meta instance goal.inhabited : inhabited packaged_goal := ⟨(0,var 0)⟩
meta instance proof_state.inhabited : inhabited proof_state :=
(infer_instance : inhabited (list packaged_goal))
/-- create a `packaged_goal` corresponding to the current goal -/
meta def get_packaged_goal : tactic packaged_goal := do
ls ← local_context,
tgt ← target >>= instantiate_mvars,
tgt ← pis ls tgt,
pure (ls.length, tgt)
/-- `goal_of_mvar g`, with `g` a meta variable, creates a
`packaged_goal` corresponding to `g` interpretted as a proof goal -/
meta def goal_of_mvar (g : expr) : tactic packaged_goal :=
with_local_goals' [g] get_packaged_goal
/-- `get_proof_state` lists the user visible goal for each goal
of the current state and for each goal, abstracts all of the
meta variables of the other gaols.
This produces a list of goals in the form of `ℕ × expr` where
the `expr` encodes the following proof state:
```lean
2 goals
l₁ : t₁,
l₂ : t₂,
l₃ : t₃
⊢ tgt₁
⊢ tgt₂
```
as
```lean
[ (3, ∀ (mv : tgt₁) (mv : tgt₂) (l₁ : t₁) (l₂ : t₂) (l₃ : t₃), tgt₁),
(0, ∀ (mv : tgt₁) (mv : tgt₂), tgt₂) ]
```
with 2 goals, the first 2 bound variables encode the meta variable
of all the goals, the next 3 (in the first goal) and 0 (in the second goal)
are the local constants.
This representation allows us to compare goals and proof states while
ignoring information like the unique name of local constants and
the equality or difference of meta variables that encode the same goal.
-/
meta def get_proof_state : tactic proof_state :=
do gs ← get_goals,
gs.mmap $ λ g, do
⟨n,g⟩ ← goal_of_mvar g,
g ← gs.mfoldl (λ g v, do
g ← kabstract g v reducible ff,
pure $ pi `goal binder_info.default `(true) g ) g,
pure (n,g)
/--
Run `tac` in a disposable proof state and return the state.
See `proof_state`, `goal` and `get_proof_state`.
-/
meta def get_proof_state_after (tac : tactic unit) : tactic (option proof_state) :=
try_core $ retrieve $ tac >> get_proof_state
open lean _root_.interactive
/-- A type alias for `tactic format`, standing for "pretty print format". -/
meta def pformat := tactic format
/-- `mk` lifts `fmt : format` to the tactic monad (`pformat`). -/
meta def pformat.mk (fmt : format) : pformat := pure fmt
/-- an alias for `pp`. -/
meta def to_pfmt {α} [has_to_tactic_format α] (x : α) : pformat :=
pp x
meta instance pformat.has_to_tactic_format : has_to_tactic_format pformat :=
⟨ id ⟩
meta instance : has_append pformat :=
⟨ λ x y, (++) <$> x <*> y ⟩
meta instance tactic.has_to_tactic_format [has_to_tactic_format α] :
has_to_tactic_format (tactic α) :=
⟨ λ x, x >>= to_pfmt ⟩
private meta def parse_pformat : string → list char → parser pexpr
| acc [] := pure ``(to_pfmt %%(reflect acc))
| acc ('\n'::s) :=
do f ← parse_pformat "" s,
pure ``(to_pfmt %%(reflect acc) ++ pformat.mk format.line ++ %%f)
| acc ('{'::'{'::s) := parse_pformat (acc ++ "{") s
| acc ('{'::s) :=
do (e, s) ← with_input (lean.parser.pexpr 0) s.as_string,
'}'::s ← return s.to_list | fail "'}' expected",
f ← parse_pformat "" s,
pure ``(to_pfmt %%(reflect acc) ++ to_pfmt %%e ++ %%f)
| acc (c::s) := parse_pformat (acc.str c) s
/-- See `format!` in `init/meta/interactive_base.lean`.
The main differences are that `pp` is called instead of `to_fmt` and that we can use
arguments of type `tactic α` in the quotations.
Now, consider the following:
```lean
e ← to_expr ``(3 + 7),
trace format!"{e}" -- outputs `has_add.add.{0} nat nat.has_add
-- (bit1.{0} nat nat.has_one nat.has_add (has_one.one.{0} nat nat.has_one)) ...`
trace pformat!"{e}" -- outputs `3 + 7`
```
The difference is significant. And now, the following is expressible:
```lean
e ← to_expr ``(3 + 7),
trace pformat!"{e} : {infer_type e}" -- outputs `3 + 7 : ℕ`
```
See also: `trace!` and `fail!`
-/
@[user_notation]
meta def pformat_macro (_ : parse $ tk "pformat!") (s : string) : parser pexpr :=
do e ← parse_pformat "" s.to_list,
return ``(%%e : pformat)
/--
The combination of `pformat` and `fail`.
-/
@[user_notation]
meta def fail_macro (_ : parse $ tk "fail!") (s : string) : parser pexpr :=
do e ← pformat_macro () s,
pure ``((%%e : pformat) >>= fail)
/--
The combination of `pformat` and `trace`.
-/
@[user_notation]
meta def trace_macro (_ : parse $ tk "trace!") (s : string) : parser pexpr :=
do e ← pformat_macro () s,
pure ``((%%e : pformat) >>= trace)
/-- A hackish way to get the `src` directory of mathlib. -/
meta def get_mathlib_dir : tactic string :=
do e ← get_env,
s ← e.decl_olean `tactic.reset_instance_cache,
return $ s.popn_back 17
/-- Checks whether a declaration with the given name is declared in mathlib.
If you want to run this tactic many times, you should use `environment.is_prefix_of_file` instead,
since it is expensive to execute `get_mathlib_dir` many times. -/
meta def is_in_mathlib (n : name) : tactic bool :=
do ml ← get_mathlib_dir, e ← get_env, return $ e.is_prefix_of_file ml n
/--
Runs a tactic by name.
If it is a `tactic string`, return whatever string it returns.
If it is a `tactic unit`, return the name.
(This is mostly used in invoking "self-reporting tactics", e.g. by `tidy` and `hint`.)
-/
meta def name_to_tactic (n : name) : tactic string :=
do d ← get_decl n,
e ← mk_const n,
let t := d.type,
if (t =ₐ `(tactic unit)) then
(eval_expr (tactic unit) e) >>= (λ t, t >> (name.to_string <$> strip_prefix n))
else if (t =ₐ `(tactic string)) then
(eval_expr (tactic string) e) >>= (λ t, t)
else fail!
"name_to_tactic cannot take `{n} as input: its type must be `tactic string` or `tactic unit`"
/-- auxiliary function for `apply_under_n_pis` -/
private meta def apply_under_n_pis_aux (func arg : pexpr) : ℕ → ℕ → expr → pexpr
| n 0 _ :=
let vars := ((list.range n).reverse.map (@expr.var ff)),
bd := vars.foldl expr.app arg.mk_explicit in
func bd
| n (k+1) (expr.pi nm bi tp bd) := expr.pi nm bi (pexpr.of_expr tp)
(apply_under_n_pis_aux (n+1) k bd)
| n (k+1) t := apply_under_n_pis_aux n 0 t
/--
Assumes `pi_expr` is of the form `Π x1 ... xn xn+1..., _`.
Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`.
All arguments (implicit and explicit) to `arg` should be supplied. -/
meta def apply_under_n_pis (func arg : pexpr) (pi_expr : expr) (n : ℕ) : pexpr :=
apply_under_n_pis_aux func arg 0 n pi_expr
/--
Assumes `pi_expr` is of the form `Π x1 ... xn, _`.
Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`.
All arguments (implicit and explicit) to `arg` should be supplied. -/
meta def apply_under_pis (func arg : pexpr) (pi_expr : expr) : pexpr :=
apply_under_n_pis func arg pi_expr pi_expr.pi_arity
/--
If `func` is a `pexpr` representing a function that takes an argument `a`,
`get_pexpr_arg_arity_with_tgt func tgt` returns the arity of `a`.
When `tgt` is a `pi` expr, `func` is elaborated in a context
with the domain of `tgt`.
Examples:
* ```get_pexpr_arg_arity ``(ring) `(true)``` returns 0, since `ring` takes one non-function
argument.
* ```get_pexpr_arg_arity_with_tgt ``(monad) `(true)``` returns 1, since `monad` takes one argument
of type `α → α`.
* ```get_pexpr_arg_arity_with_tgt ``(module R) `(Π (R : Type), comm_ring R → true)``` returns 0
-/
meta def get_pexpr_arg_arity_with_tgt (func : pexpr) (tgt : expr) : tactic ℕ :=
lock_tactic_state $ do
mv ← mk_mvar,
solve_aux tgt $ intros >> to_expr ``(%%func %%mv),
expr.pi_arity <$> (infer_type mv >>= instantiate_mvars)
/-- `find_private_decl n none` finds a private declaration named `n` in any of the imported files.
`find_private_decl n (some m)` finds a private declaration named `n` in the same file where a
declaration named `m` can be found. -/
meta def find_private_decl (n : name) (fr : option name) : tactic name :=
do env ← get_env,
fn ← option_t.run (do
fr ← option_t.mk (return fr),
d ← monad_lift $ get_decl fr,
option_t.mk (return $ env.decl_olean d.to_name) ),
let p : string → bool :=
match fn with
| (some fn) := λ x, fn = x
| none := λ _, tt
end,
let xs := env.decl_filter_map (λ d,
do fn ← env.decl_olean d.to_name,
guard ((`_private).is_prefix_of d.to_name ∧ p fn ∧
d.to_name.update_prefix name.anonymous = n),
pure d.to_name),
match xs with
| [n] := pure n
| [] := fail "no such private found"
| _ := fail "many matches found"
end
open lean.parser interactive
/-- `import_private foo from bar` finds a private declaration `foo` in the same file as `bar`
and creates a local notation to refer to it.
`import_private foo` looks for `foo` in all imported files.
When possible, make `foo` non-private rather than using this feature.
-/
@[user_command]
meta def import_private_cmd (_ : parse $ tk "import_private") : lean.parser unit :=
do n ← ident,
fr ← optional (tk "from" *> ident),
n ← find_private_decl n fr,
c ← resolve_constant n,
d ← get_decl n,
let c := @expr.const tt c d.univ_levels,
new_n ← new_aux_decl_name,
add_decl $ declaration.defn new_n d.univ_params d.type c reducibility_hints.abbrev d.is_trusted,
let new_not := sformat!"local notation `{n.update_prefix name.anonymous}` := {new_n}",
emit_command_here $ new_not,
skip .
add_tactic_doc
{ name := "import_private",
category := doc_category.cmd,
decl_names := [`tactic.import_private_cmd],
tags := ["renaming"] }
/--
The command `mk_simp_attribute simp_name "description"` creates a simp set with name `simp_name`.
Lemmas tagged with `@[simp_name]` will be included when `simp with simp_name` is called.
`mk_simp_attribute simp_name none` will use a default description.
Appending the command with `with attr1 attr2 ...` will include all declarations tagged with
`attr1`, `attr2`, ... in the new simp set.
This command is preferred to using ``run_cmd mk_simp_attr `simp_name`` since it adds a doc string
to the attribute that is defined. If you need to create a simp set in a file where this command is
not available, you should use
```lean
run_cmd mk_simp_attr `simp_name
run_cmd add_doc_string `simp_attr.simp_name "Description of the simp set here"
```
-/
@[user_command]
meta def mk_simp_attribute_cmd (_ : parse $ tk "mk_simp_attribute") : lean.parser unit :=
do n ← ident,
d ← parser.pexpr,
d ← to_expr ``(%%d : option string),
descr ← eval_expr (option string) d,
with_list ← (tk "with" *> many ident) <|> return [],
mk_simp_attr n with_list,
add_doc_string (name.append `simp_attr n) $ descr.get_or_else $ "simp set for " ++ to_string n
add_tactic_doc
{ name := "mk_simp_attribute",
category := doc_category.cmd,
decl_names := [`tactic.mk_simp_attribute_cmd],
tags := ["simplification"] }
/--
Given a user attribute name `attr_name`, `get_user_attribute_name attr_name` returns
the name of the declaration that defines this attribute.
Fails if there is no user attribute with this name.
Example: ``get_user_attribute_name `norm_cast`` returns `` `norm_cast.norm_cast_attr`` -/
meta def get_user_attribute_name (attr_name : name) : tactic name := do
ns ← attribute.get_instances `user_attribute,
ns.mfirst (λ nm, do
d ← get_decl nm,
e ← mk_app `user_attribute.name [d.value],
attr_nm ← eval_expr name e,
guard $ attr_nm = attr_name,
return nm) <|> fail!"'{attr_name}' is not a user attribute."
/-- A tactic to set either a basic attribute or a user attribute.
If the user attribute has a parameter, the default value will be used.
This tactic raises an error if there is no `inhabited` instance for the parameter type. -/
meta def set_attribute (attr_name : name) (c_name : name) (persistent := tt)
(prio : option nat := none) : tactic unit := do
get_decl c_name <|> fail!"unknown declaration {c_name}",
s ← try_or_report_error (set_basic_attribute attr_name c_name persistent prio),
sum.inr msg ← return s | skip,
if msg =
(format!"set_basic_attribute tactic failed, '{attr_name}' is not a basic attribute").to_string
then do
user_attr_nm ← get_user_attribute_name attr_name,
user_attr_const ← mk_const user_attr_nm,
tac ← eval_pexpr (tactic unit)
``(user_attribute.set %%user_attr_const %%c_name (default _) %%persistent) <|>
fail! ("Cannot set attribute @[{attr_name}].\n" ++
"The corresponding user attribute {user_attr_nm} " ++
"has a parameter without a default value.\n" ++
"Solution: provide an `inhabited` instance."),
tac
else fail msg
end tactic
/--
`find_defeq red m e` looks for a key in `m` that is defeq to `e` (up to transparency `red`),
and returns the value associated with this key if it exists.
Otherwise, it fails.
-/
meta def list.find_defeq (red : tactic.transparency) {v} (m : list (expr × v)) (e : expr) :
tactic (expr × v) :=
m.mfind $ λ ⟨e', val⟩, tactic.is_def_eq e e' red
|
1fb455beb8933c91df42cc783a1f6d0036972e49 | 4e3bf8e2b29061457a887ac8889e88fa5aa0e34c | /lean/love05_inductive_predicates_homework_solution.lean | 65584a498f9441173e10c82da637167f91e6f78d | [] | no_license | mukeshtiwari/logical_verification_2019 | 9f964c067a71f65eb8884743273fbeef99e6503d | 16f62717f55ed5b7b87e03ae0134791a9bef9b9a | refs/heads/master | 1,619,158,844,208 | 1,585,139,500,000 | 1,585,139,500,000 | 249,906,380 | 0 | 0 | null | 1,585,118,728,000 | 1,585,118,727,000 | null | UTF-8 | Lean | false | false | 1,638 | lean | /- LoVe Homework 5: Inductive Predicates -/
import .lovelib
namespace LoVe
/- Question 2: Transitive Closure -/
/- In mathematics, the transitive closure `R+` of a binary relation `R` over a
set `A` can be defined as the smallest solution satisfying the following rules:
(base) for all a, b ∈ A, if a R b, then a R+ b;
(step) for all a, b, c ∈ A, if a R b and b R+ c, then a R+ c.
In Lean, we can define this concept as follows, by identifying the set `A` with
the type `α`: -/
inductive tc₁ {α : Type} (r : α → α → Prop) : α → α → Prop
| base : ∀a b, r a b → tc₁ a b
| step : ∀a b c, r a b → tc₁ b c → tc₁ a c
/- 2.4 (**optional**). Prove by rule induction on the `tc₁ r a b` premise below
that `(pets)` also holds as a lemma about `tc₁` as defined above. -/
lemma tc₁_pets {α : Type} (r : α → α → Prop) (c : α) :
∀a b, tc₁ r a b → r b c → tc₁ r a c :=
begin
intros a b tab rbc,
induction tab,
case tc₁.base : x y rxy ryc {
exact tc₁.step _ _ _ rxy (tc₁.base _ _ ryc) },
case tc₁.step : x y z rxy tyz tyc_of_rzc rzc {
exact tc₁.step _ _ _ rxy (tyc_of_rzc rzc) }
end
/- 2.5 (**optional**). Prove by rule induction that `(trans)` also holds as a
lemma about `tc₁`. -/
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 tab tbc,
induction tab,
case tc₁.base : x y rxy tyc {
exact tc₁.step _ _ _ rxy tyc },
case tc₁.step : x y z rxy tyz tyc_of_tzc tzc {
exact tc₁.step _ _ _ rxy (tyc_of_tzc tzc) }
end
end LoVe
|
c85198193e1521c74a117d66e804bc2475165c15 | d7b899533a520b46d705c8f4eaab26bb8571c153 | /basic.lean | 3c8705c78e54d888cfc3424c8e6d4acb8ee7ae6b | [
"MIT"
] | permissive | fgdorais/old_birkhoff | d043467859476eb412cc612f4daa9933dd031090 | c528743f6ebe65633cee5e9fef83a5794d2350c6 | refs/heads/master | 1,631,920,649,967 | 1,530,902,154,000 | 1,530,902,154,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,029 | lean | -- birkhoff/basic.lean --
-- Copyright Ⓒ 2015 François G. Dorais. All rights reserved.
-- Relesed under the MIT License as described in the file LICENSE.
import data
open nat
structure SIG [class] :=
(index : Type)
(arity : index → nat)
attribute SIG.index [coercion]
definition func.arity [sig : SIG] : sig → nat := SIG.arity
inductive term [sig : SIG] : nat → Type :=
| proj : ∀ {n : nat}, fin n → term n
| appl : ∀ {n : nat} (i : sig), (fin (func.arity i) → term n) → term n
definition const [sig : SIG] : Type := term 0
definition const.appl [sig : SIG] (i : sig) : (fin (func.arity i) → const) → const :=
term.appl i
namespace sig
definition const [instance] (I : Type) : SIG :=
SIG.mk I (λ i, 0)
definition add [instance] (sig₁ sig₂ : SIG) : SIG :=
SIG.mk (sum sig₁ sig₂) (sum.rec (@func.arity sig₁) (@func.arity sig₂))
definition sum [instance] {I : Type} (sig : I → SIG) : SIG :=
SIG.mk (sigma sig) (sigma.rec (λ i, @func.arity (sig i)))
end sig
|
607f6fb882822987cc96548ea27c36cbe1fc0cd0 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/linear_algebra/dfinsupp.lean | 5772a005ceae4fe30e8e3669d2a37e969f5c1e3c | [
"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 | 18,458 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Kenny Lau
-/
import data.finsupp.to_dfinsupp
import linear_algebra.basis
/-!
# Properties of the module `Π₀ i, M i`
Given an indexed collection of `R`-modules `M i`, the `R`-module structure on `Π₀ i, M i`
is defined in `data.dfinsupp`.
In this file we define `linear_map` versions of various maps:
* `dfinsupp.lsingle a : M →ₗ[R] Π₀ i, M i`: `dfinsupp.single a` as a linear map;
* `dfinsupp.lmk s : (Π i : (↑s : set ι), M i) →ₗ[R] Π₀ i, M i`: `dfinsupp.single a` as a linear map;
* `dfinsupp.lapply i : (Π₀ i, M i) →ₗ[R] M`: the map `λ f, f i` as a linear map;
* `dfinsupp.lsum`: `dfinsupp.sum` or `dfinsupp.lift_add_hom` as a `linear_map`;
## Implementation notes
This file should try to mirror `linear_algebra.finsupp` where possible. The API of `finsupp` is
much more developed, but many lemmas in that file should be eligible to copy over.
## Tags
function with finite support, module, linear algebra
-/
variables {ι : Type*} {R : Type*} {S : Type*} {M : ι → Type*} {N : Type*}
variables [dec_ι : decidable_eq ι]
namespace dfinsupp
variables [semiring R] [Π i, add_comm_monoid (M i)] [Π i, module R (M i)]
variables [add_comm_monoid N] [module R N]
include dec_ι
/-- `dfinsupp.mk` as a `linear_map`. -/
def lmk (s : finset ι) : (Π i : (↑s : set ι), M i) →ₗ[R] Π₀ i, M i :=
{ to_fun := mk s, map_add' := λ _ _, mk_add, map_smul' := λ c x, mk_smul c x}
/-- `dfinsupp.single` as a `linear_map` -/
def lsingle (i) : M i →ₗ[R] Π₀ i, M i :=
{ to_fun := single i, map_smul' := single_smul, .. dfinsupp.single_add_hom _ _ }
/-- Two `R`-linear maps from `Π₀ i, M i` which agree on each `single i x` agree everywhere. -/
lemma lhom_ext ⦃φ ψ : (Π₀ i, M i) →ₗ[R] N⦄
(h : ∀ i x, φ (single i x) = ψ (single i x)) :
φ = ψ :=
linear_map.to_add_monoid_hom_injective $ add_hom_ext h
/-- Two `R`-linear maps from `Π₀ i, M i` which agree on each `single i x` agree everywhere.
See note [partially-applied ext lemmas].
After apply this lemma, if `M = R` then it suffices to verify `φ (single a 1) = ψ (single a 1)`. -/
@[ext] lemma lhom_ext' ⦃φ ψ : (Π₀ i, M i) →ₗ[R] N⦄
(h : ∀ i, φ.comp (lsingle i) = ψ.comp (lsingle i)) :
φ = ψ :=
lhom_ext $ λ i, linear_map.congr_fun (h i)
omit dec_ι
/-- Interpret `λ (f : Π₀ i, M i), f i` as a linear map. -/
def lapply (i : ι) : (Π₀ i, M i) →ₗ[R] M i :=
{ to_fun := λ f, f i,
map_add' := λ f g, add_apply f g i,
map_smul' := λ c f, smul_apply c f i}
include dec_ι
@[simp] lemma lmk_apply (s : finset ι) (x) : (lmk s : _ →ₗ[R] Π₀ i, M i) x = mk s x := rfl
@[simp] lemma lsingle_apply (i : ι) (x : M i) : (lsingle i : _ →ₗ[R] _) x = single i x := rfl
omit dec_ι
@[simp] lemma lapply_apply (i : ι) (f : Π₀ i, M i) : (lapply i : _ →ₗ[R] _) f = f i := rfl
section lsum
/-- Typeclass inference can't find `dfinsupp.add_comm_monoid` without help for this case.
This instance allows it to be found where it is needed on the LHS of the colon in
`dfinsupp.module_of_linear_map`. -/
instance add_comm_monoid_of_linear_map : add_comm_monoid (Π₀ (i : ι), M i →ₗ[R] N) :=
@dfinsupp.add_comm_monoid _ (λ i, M i →ₗ[R] N) _
/-- Typeclass inference can't find `dfinsupp.module` without help for this case.
This is needed to define `dfinsupp.lsum` below.
The cause seems to be an inability to unify the `Π i, add_comm_monoid (M i →ₗ[R] N)` instance that
we have with the `Π i, has_zero (M i →ₗ[R] N)` instance which appears as a parameter to the
`dfinsupp` type. -/
instance module_of_linear_map [semiring S] [module S N] [smul_comm_class R S N] :
module S (Π₀ (i : ι), M i →ₗ[R] N) :=
@dfinsupp.module _ _ (λ i, M i →ₗ[R] N) _ _ _
variables (S)
include dec_ι
/-- The `dfinsupp` version of `finsupp.lsum`.
See note [bundled maps over different rings] for why separate `R` and `S` semirings are used. -/
@[simps]
def lsum [semiring S] [module S N] [smul_comm_class R S N] :
(Π i, M i →ₗ[R] N) ≃ₗ[S] ((Π₀ i, M i) →ₗ[R] N) :=
{ to_fun := λ F, {
to_fun := sum_add_hom (λ i, (F i).to_add_monoid_hom),
map_add' := (lift_add_hom (λ i, (F i).to_add_monoid_hom)).map_add,
map_smul' := λ c f, by {
dsimp,
apply dfinsupp.induction f,
{ rw [smul_zero, add_monoid_hom.map_zero, smul_zero] },
{ intros a b f ha hb hf,
rw [smul_add, add_monoid_hom.map_add, add_monoid_hom.map_add, smul_add, hf, ←single_smul,
sum_add_hom_single, sum_add_hom_single, linear_map.to_add_monoid_hom_coe,
linear_map.map_smul], } } },
inv_fun := λ F i, F.comp (lsingle i),
left_inv := λ F, by { ext x y, simp },
right_inv := λ F, by { ext x y, simp },
map_add' := λ F G, by { ext x y, simp },
map_smul' := λ c F, by { ext, simp } }
/-- While `simp` can prove this, it is often convenient to avoid unfolding `lsum` into `sum_add_hom`
with `dfinsupp.lsum_apply_apply`. -/
lemma lsum_single [semiring S] [module S N] [smul_comm_class R S N]
(F : Π i, M i →ₗ[R] N) (i) (x : M i) :
lsum S F (single i x) = F i x :=
sum_add_hom_single _ _ _
end lsum
/-! ### Bundled versions of `dfinsupp.map_range`
The names should match the equivalent bundled `finsupp.map_range` definitions.
-/
section map_range
variables {β β₁ β₂: ι → Type*}
variables [Π i, add_comm_monoid (β i)] [Π i, add_comm_monoid (β₁ i)] [Π i, add_comm_monoid (β₂ i)]
variables [Π i, module R (β i)] [Π i, module R (β₁ i)] [Π i, module R (β₂ i)]
lemma map_range_smul (f : Π i, β₁ i → β₂ i) (hf : ∀ i, f i 0 = 0)
(r : R) (hf' : ∀ i x, f i (r • x) = r • f i x) (g : Π₀ i, β₁ i):
map_range f hf (r • g) = r • map_range f hf g :=
begin
ext,
simp only [map_range_apply f, coe_smul, pi.smul_apply, hf']
end
/-- `dfinsupp.map_range` as an `linear_map`. -/
@[simps apply]
def map_range.linear_map (f : Π i, β₁ i →ₗ[R] β₂ i) : (Π₀ i, β₁ i) →ₗ[R] (Π₀ i, β₂ i) :=
{ to_fun := map_range (λ i x, f i x) (λ i, (f i).map_zero),
map_smul' := λ r, map_range_smul _ _ _ (λ i, (f i).map_smul r),
.. map_range.add_monoid_hom (λ i, (f i).to_add_monoid_hom) }
@[simp]
lemma map_range.linear_map_id :
map_range.linear_map (λ i, (linear_map.id : (β₂ i) →ₗ[R] _)) = linear_map.id :=
linear_map.ext map_range_id
lemma map_range.linear_map_comp (f : Π i, β₁ i →ₗ[R] β₂ i) (f₂ : Π i, β i →ₗ[R] β₁ i):
map_range.linear_map (λ i, (f i).comp (f₂ i)) =
(map_range.linear_map f).comp (map_range.linear_map f₂) :=
linear_map.ext $ map_range_comp (λ i x, f i x) (λ i x, f₂ i x) _ _ _
include dec_ι
lemma sum_map_range_index.linear_map
[Π (i : ι) (x : β₁ i), decidable (x ≠ 0)] [Π (i : ι) (x : β₂ i), decidable (x ≠ 0)]
{f : Π i, β₁ i →ₗ[R] β₂ i} {h : Π i, β₂ i →ₗ[R] N} {l : Π₀ i, β₁ i} :
dfinsupp.lsum ℕ h (map_range.linear_map f l) = dfinsupp.lsum ℕ (λ i, (h i).comp (f i)) l :=
by simpa [dfinsupp.sum_add_hom_apply] using
@sum_map_range_index ι N _ _ _ _ _ _ _ _ (λ i, f i) (λ i, by simp) l (λ i, h i) (λ i, by simp)
omit dec_ι
/-- `dfinsupp.map_range.linear_map` as an `linear_equiv`. -/
@[simps apply]
def map_range.linear_equiv (e : Π i, β₁ i ≃ₗ[R] β₂ i) : (Π₀ i, β₁ i) ≃ₗ[R] (Π₀ i, β₂ i) :=
{ to_fun := map_range (λ i x, e i x) (λ i, (e i).map_zero),
inv_fun := map_range (λ i x, (e i).symm x) (λ i, (e i).symm.map_zero),
.. map_range.add_equiv (λ i, (e i).to_add_equiv),
.. map_range.linear_map (λ i, (e i).to_linear_map) }
@[simp]
lemma map_range.linear_equiv_refl :
(map_range.linear_equiv $ λ i, linear_equiv.refl R (β₁ i)) = linear_equiv.refl _ _ :=
linear_equiv.ext map_range_id
lemma map_range.linear_equiv_trans (f : Π i, β i ≃ₗ[R] β₁ i) (f₂ : Π i, β₁ i ≃ₗ[R] β₂ i):
map_range.linear_equiv (λ i, (f i).trans (f₂ i)) =
(map_range.linear_equiv f).trans (map_range.linear_equiv f₂) :=
linear_equiv.ext $ map_range_comp (λ i x, f₂ i x) (λ i x, f i x) _ _ _
@[simp]
lemma map_range.linear_equiv_symm (e : Π i, β₁ i ≃ₗ[R] β₂ i) :
(map_range.linear_equiv e).symm = map_range.linear_equiv (λ i, (e i).symm) := rfl
end map_range
section basis
/-- The direct sum of free modules is free.
Note that while this is stated for `dfinsupp` not `direct_sum`, the types are defeq. -/
noncomputable def basis {η : ι → Type*} (b : Π i, basis (η i) R (M i)) :
basis (Σ i, η i) R (Π₀ i, M i) :=
basis.of_repr ((map_range.linear_equiv (λ i, (b i).repr)).trans
(sigma_finsupp_lequiv_dfinsupp R).symm)
end basis
end dfinsupp
include dec_ι
namespace submodule
variables [semiring R] [add_comm_monoid N] [module R N]
open dfinsupp
lemma dfinsupp_sum_mem {β : ι → Type*} [Π i, has_zero (β i)]
[Π i (x : β i), decidable (x ≠ 0)] (S : submodule R N)
(f : Π₀ i, β i) (g : Π i, β i → N) (h : ∀ c, f c ≠ 0 → g c (f c) ∈ S) : f.sum g ∈ S :=
S.to_add_submonoid.dfinsupp_sum_mem f g h
lemma dfinsupp_sum_add_hom_mem {β : ι → Type*} [Π i, add_zero_class (β i)]
(S : submodule R N) (f : Π₀ i, β i) (g : Π i, β i →+ N) (h : ∀ c, f c ≠ 0 → g c (f c) ∈ S) :
dfinsupp.sum_add_hom g f ∈ S :=
S.to_add_submonoid.dfinsupp_sum_add_hom_mem f g h
/-- The supremum of a family of submodules is equal to the range of `dfinsupp.lsum`; that is
every element in the `supr` can be produced from taking a finite number of non-zero elements
of `p i`, coercing them to `N`, and summing them. -/
lemma supr_eq_range_dfinsupp_lsum (p : ι → submodule R N) :
supr p = (dfinsupp.lsum ℕ (λ i, (p i).subtype)).range :=
begin
apply le_antisymm,
{ apply supr_le _,
intros i y hy,
exact ⟨dfinsupp.single i ⟨y, hy⟩, dfinsupp.sum_add_hom_single _ _ _⟩, },
{ rintros x ⟨v, rfl⟩,
exact dfinsupp_sum_add_hom_mem _ v _ (λ i _, (le_supr p i : p i ≤ _) (v i).prop) }
end
/-- The bounded supremum of a family of commutative additive submonoids is equal to the range of
`dfinsupp.sum_add_hom` composed with `dfinsupp.filter_add_monoid_hom`; that is, every element in the
bounded `supr` can be produced from taking a finite number of non-zero elements from the `S i` that
satisfy `p i`, coercing them to `γ`, and summing them. -/
lemma bsupr_eq_range_dfinsupp_lsum (p : ι → Prop)
[decidable_pred p] (S : ι → submodule R N) :
(⨆ i (h : p i), S i) =
((dfinsupp.lsum ℕ (λ i, (S i).subtype)).comp (dfinsupp.filter_linear_map R _ p)).range :=
begin
apply le_antisymm,
{ apply bsupr_le _,
intros i hi y hy,
refine ⟨dfinsupp.single i ⟨y, hy⟩, _⟩,
rw [linear_map.comp_apply, filter_linear_map_apply, filter_single_pos _ _ hi],
exact dfinsupp.sum_add_hom_single _ _ _, },
{ rintros x ⟨v, rfl⟩,
refine dfinsupp_sum_add_hom_mem _ _ _ (λ i hi, _),
refine mem_supr_of_mem i _,
by_cases hp : p i,
{ simp [hp], },
{ simp [hp] }, }
end
lemma mem_supr_iff_exists_dfinsupp (p : ι → submodule R N) (x : N) :
x ∈ supr p ↔ ∃ f : Π₀ i, p i, dfinsupp.lsum ℕ (λ i, (p i).subtype) f = x :=
set_like.ext_iff.mp (supr_eq_range_dfinsupp_lsum p) x
/-- A variant of `submodule.mem_supr_iff_exists_dfinsupp` with the RHS fully unfolded. -/
lemma mem_supr_iff_exists_dfinsupp' (p : ι → submodule R N) [Π i (x : p i), decidable (x ≠ 0)]
(x : N) :
x ∈ supr p ↔ ∃ f : Π₀ i, p i, f.sum (λ i xi, ↑xi) = x :=
begin
rw mem_supr_iff_exists_dfinsupp,
simp_rw [dfinsupp.lsum_apply_apply, dfinsupp.sum_add_hom_apply],
congr',
end
lemma mem_bsupr_iff_exists_dfinsupp (p : ι → Prop) [decidable_pred p] (S : ι → submodule R N)
(x : N) :
x ∈ (⨆ i (h : p i), S i) ↔
∃ f : Π₀ i, S i, dfinsupp.lsum ℕ (λ i, (S i).subtype) (f.filter p) = x :=
set_like.ext_iff.mp (bsupr_eq_range_dfinsupp_lsum p S) x
end submodule
namespace complete_lattice
open dfinsupp
section semiring
variables [semiring R] [add_comm_monoid N] [module R N]
/-- Independence of a family of submodules can be expressed as a quantifier over `dfinsupp`s.
This is an intermediate result used to prove
`complete_lattice.independent_of_dfinsupp_lsum_injective` and
`complete_lattice.independent.dfinsupp_lsum_injective`. -/
lemma independent_iff_forall_dfinsupp (p : ι → submodule R N) :
independent p ↔
∀ i (x : p i) (v : Π₀ (i : ι), ↥(p i)), lsum ℕ (λ i, (p i).subtype) (erase i v) = x → x = 0 :=
begin
simp_rw [complete_lattice.independent_def, submodule.disjoint_def,
submodule.mem_bsupr_iff_exists_dfinsupp, exists_imp_distrib, filter_ne_eq_erase],
apply forall_congr (λ i, _),
refine subtype.forall'.trans _,
simp_rw submodule.coe_eq_zero,
refl,
end
/- If `dfinsupp.lsum` applied with `submodule.subtype` is injective then the submodules are
independent. -/
lemma independent_of_dfinsupp_lsum_injective (p : ι → submodule R N)
(h : function.injective (lsum ℕ (λ i, (p i).subtype))) :
independent p :=
begin
rw independent_iff_forall_dfinsupp,
intros i x v hv,
replace hv : lsum ℕ (λ i, (p i).subtype) (erase i v) = lsum ℕ (λ i, (p i).subtype) (single i x),
{ simpa only [lsum_single] using hv, },
have := dfinsupp.ext_iff.mp (h hv) i,
simpa [eq_comm] using this,
end
/- If `dfinsupp.sum_add_hom` applied with `add_submonoid.subtype` is injective then the additive
submonoids are independent. -/
lemma independent_of_dfinsupp_sum_add_hom_injective (p : ι → add_submonoid N)
(h : function.injective (sum_add_hom (λ i, (p i).subtype))) :
independent p :=
begin
rw ←independent_map_order_iso_iff (add_submonoid.to_nat_submodule : add_submonoid N ≃o _),
exact independent_of_dfinsupp_lsum_injective _ h,
end
/-- Combining `dfinsupp.lsum` with `linear_map.to_span_singleton` is the same as `finsupp.total` -/
lemma lsum_comp_map_range_to_span_singleton
[Π (m : R), decidable (m ≠ 0)]
(p : ι → submodule R N) {v : ι → N} (hv : ∀ (i : ι), v i ∈ p i) :
((lsum ℕ) (λ i, (p i).subtype) : _ →ₗ[R] _).comp
((map_range.linear_map
(λ i, linear_map.to_span_singleton R ↥(p i) ⟨v i, hv i⟩) : _ →ₗ[R] _).comp
(finsupp_lequiv_dfinsupp R : (ι →₀ R) ≃ₗ[R] _).to_linear_map) =
finsupp.total ι N R v :=
by { ext, simp }
end semiring
section ring
variables [ring R] [add_comm_group N] [module R N]
/- If `dfinsupp.sum_add_hom` applied with `add_submonoid.subtype` is injective then the additive
subgroups are independent. -/
lemma independent_of_dfinsupp_sum_add_hom_injective' (p : ι → add_subgroup N)
(h : function.injective (sum_add_hom (λ i, (p i).subtype))) :
independent p :=
begin
rw ←independent_map_order_iso_iff (add_subgroup.to_int_submodule : add_subgroup N ≃o _),
exact independent_of_dfinsupp_lsum_injective _ h,
end
/-- The canonical map out of a direct sum of a family of submodules is injective when the submodules
are `complete_lattice.independent`.
Note that this is not generally true for `[semiring R]`, for instance when `A` is the
`ℕ`-submodules of the positive and negative integers.
See `counterexamples/direct_sum_is_internal.lean` for a proof of this fact. -/
lemma independent.dfinsupp_lsum_injective {p : ι → submodule R N}
(h : independent p) : function.injective (lsum ℕ (λ i, (p i).subtype)) :=
begin
-- simplify everything down to binders over equalities in `N`
rw independent_iff_forall_dfinsupp at h,
suffices : (lsum ℕ (λ i, (p i).subtype)).ker = ⊥,
{ -- Lean can't find this without our help
letI : add_comm_group (Π₀ i, p i) := @dfinsupp.add_comm_group _ (λ i, p i) _,
rw linear_map.ker_eq_bot at this, exact this },
rw linear_map.ker_eq_bot',
intros m hm,
ext i : 1,
-- split `m` into the piece at `i` and the pieces elsewhere, to match `h`
rw [dfinsupp.zero_apply, ←neg_eq_zero],
refine h i (-m i) m _,
rwa [←erase_add_single i m, linear_map.map_add, lsum_single, submodule.subtype_apply,
add_eq_zero_iff_eq_neg, ←submodule.coe_neg] at hm,
end
/-- The canonical map out of a direct sum of a family of additive subgroups is injective when the
additive subgroups are `complete_lattice.independent`. -/
lemma independent.dfinsupp_sum_add_hom_injective {p : ι → add_subgroup N}
(h : independent p) : function.injective (sum_add_hom (λ i, (p i).subtype)) :=
begin
rw ←independent_map_order_iso_iff (add_subgroup.to_int_submodule : add_subgroup N ≃o _) at h,
exact h.dfinsupp_lsum_injective,
end
/-- A family of submodules over an additive group are independent if and only iff `dfinsupp.lsum`
applied with `submodule.subtype` is injective.
Note that this is not generally true for `[semiring R]`; see
`complete_lattice.independent.dfinsupp_lsum_injective` for details. -/
lemma independent_iff_dfinsupp_lsum_injective (p : ι → submodule R N) :
independent p ↔ function.injective (lsum ℕ (λ i, (p i).subtype)) :=
⟨independent.dfinsupp_lsum_injective, independent_of_dfinsupp_lsum_injective p⟩
/-- A family of additive subgroups over an additive group are independent if and only if
`dfinsupp.sum_add_hom` applied with `add_subgroup.subtype` is injective. -/
lemma independent_iff_dfinsupp_sum_add_hom_injective (p : ι → add_subgroup N) :
independent p ↔ function.injective (sum_add_hom (λ i, (p i).subtype)) :=
⟨independent.dfinsupp_sum_add_hom_injective, independent_of_dfinsupp_sum_add_hom_injective' p⟩
omit dec_ι
/-- If a family of submodules is `independent`, then a choice of nonzero vector from each submodule
forms a linearly independent family. -/
lemma independent.linear_independent [no_zero_smul_divisors R N] (p : ι → submodule R N)
(hp : complete_lattice.independent p) {v : ι → N} (hv : ∀ i, v i ∈ p i) (hv' : ∀ i, v i ≠ 0) :
linear_independent R v :=
begin
classical,
rw linear_independent_iff,
intros l hl,
let a := dfinsupp.map_range.linear_map
(λ i, linear_map.to_span_singleton R (p i) (⟨v i, hv i⟩)) l.to_dfinsupp,
have ha : a = 0,
{ apply hp.dfinsupp_lsum_injective,
rwa ←lsum_comp_map_range_to_span_singleton _ hv at hl },
ext i,
apply smul_left_injective R (hv' i),
have : l i • v i = a i := rfl,
simp [this, ha],
end
end ring
end complete_lattice
|
6e02530ea963b382bb937b7c441be5ad2075b535 | 0408d6ea582e97d5cc55ac8a0980d26df896ce66 | /src/padics/padic_norm.lean | 4854a09546b22c30049a996fdba01c4168403f23 | [] | no_license | lean-forward/coe_tactic | bba94535c7fb6ef65fcd81bedc28062b238a1594 | d5c30df244c3402de6323a538e99b5324779a2cb | refs/heads/master | 1,588,474,971,049 | 1,557,135,293,000 | 1,557,135,293,000 | 178,387,237 | 1 | 0 | null | 1,556,542,286,000 | 1,553,856,413,000 | Lean | UTF-8 | Lean | false | false | 13,477 | lean | /-
Copyright (c) 2018 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Y. Lewis
Define the p-adic valuation on ℤ and ℚ, and the p-adic norm on ℚ
-/
import data.rat algebra.gcd_domain algebra.field_power
import ring_theory.multiplicity tactic.ring
import data.real.cau_seq
import norm_cast
universe u
open nat
attribute [class] nat.prime
local infix `/.`:70 := rat.mk
open multiplicity
def padic_val_rat (p : ℕ) (q : ℚ) : ℤ :=
if h : q ≠ 0 ∧ p ≠ 1
then (multiplicity (p : ℤ) q.num).get
(multiplicity.finite_int_iff.2 ⟨h.2, rat.num_ne_zero_of_ne_zero h.1⟩) -
(multiplicity (p : ℤ) q.denom).get
(multiplicity.finite_int_iff.2 ⟨h.2, by exact_mod_cast rat.denom_ne_zero _⟩)
else 0
lemma padic_val_rat_def (p : ℕ) [hp : p.prime] {q : ℚ} (hq : q ≠ 0) : padic_val_rat p q =
(multiplicity (p : ℤ) q.num).get (finite_int_iff.2 ⟨hp.ne_one, rat.num_ne_zero_of_ne_zero hq⟩) -
(multiplicity (p : ℤ) q.denom).get (finite_int_iff.2 ⟨hp.ne_one, by exact_mod_cast rat.denom_ne_zero _⟩) :=
dif_pos ⟨hq, hp.ne_one⟩
namespace padic_val_rat
open multiplicity
section padic_val_rat
variables {p : ℕ}
@[simp] protected lemma neg (q : ℚ) : padic_val_rat p (-q) = padic_val_rat p q :=
begin
unfold padic_val_rat,
split_ifs,
{ simp [-add_comm]; refl },
{ exfalso, simp * at * },
{ exfalso, simp * at * },
{ refl }
end
@[simp] protected lemma one : padic_val_rat p 1 = 0 :=
by unfold padic_val_rat; split_ifs; simp *
@[simp] lemma padic_val_rat_self (hp : 1 < p) : padic_val_rat p p = 1 :=
by unfold padic_val_rat; split_ifs; simp [*, nat.one_lt_iff_ne_zero_and_ne_one] at *
lemma padic_val_rat_of_int (z : ℤ) (hp : p ≠ 1) (hz : z ≠ 0) :
padic_val_rat p (z : ℚ) = (multiplicity (p : ℤ) z).get
(finite_int_iff.2 ⟨hp, hz⟩) :=
by rw [padic_val_rat, dif_pos]; simp *; refl
end padic_val_rat
section padic_val_rat
open multiplicity
variables (p : ℕ) [p_prime : nat.prime p]
include p_prime
lemma finite_int_prime_iff {p : ℕ} [p_prime : p.prime] {a : ℤ} : finite (p : ℤ) a ↔ a ≠ 0 :=
by simp [finite_int_iff, ne.symm (ne_of_lt (p_prime.gt_one))]
protected lemma defn {q : ℚ} {n d : ℤ} (hqz : q ≠ 0) (qdf : q = n /. d) :
padic_val_rat p q = (multiplicity (p : ℤ) n).get (finite_int_iff.2
⟨ne.symm $ ne_of_lt p_prime.gt_one, λ hn, by simp * at *⟩) -
(multiplicity (p : ℤ) d).get (finite_int_iff.2 ⟨ne.symm $ ne_of_lt p_prime.gt_one,
λ hd, by simp * at *⟩) :=
have hn : n ≠ 0, from rat.mk_num_ne_zero_of_ne_zero hqz qdf,
have hd : d ≠ 0, from rat.mk_denom_ne_zero_of_ne_zero hqz qdf,
let ⟨c, hc1, hc2⟩ := rat.num_denom_mk hn hd qdf in
by rw [padic_val_rat, dif_pos];
simp [hc1, hc2, multiplicity.mul' (nat.prime_iff_prime_int.1 p_prime),
(ne.symm (ne_of_lt p_prime.gt_one)), hqz]
protected lemma mul {q r : ℚ} (hq : q ≠ 0) (hr : r ≠ 0) :
padic_val_rat p (q * r) = padic_val_rat p q + padic_val_rat p r :=
have q*r = (q.num * r.num) /. (↑q.denom * ↑r.denom), by rw_mod_cast rat.mul_num_denom,
have hq' : q.num /. q.denom ≠ 0, by rw ← rat.num_denom q; exact hq,
have hr' : r.num /. r.denom ≠ 0, by rw ← rat.num_denom r; exact hr,
have hp' : _root_.prime (p : ℤ), from nat.prime_iff_prime_int.1 p_prime,
begin
rw [padic_val_rat.defn p (mul_ne_zero hq hr) this],
conv_rhs { rw [rat.num_denom q, padic_val_rat.defn p hq',
rat.num_denom r, padic_val_rat.defn p hr'] },
rw [multiplicity.mul' hp', multiplicity.mul' hp']; simp
end
protected lemma pow {q : ℚ} (hq : q ≠ 0) {k : ℕ} :
padic_val_rat p (q ^ k) = k * padic_val_rat p q :=
by induction k; simp [*, padic_val_rat.mul _ hq (pow_ne_zero _ hq),
_root_.pow_succ, add_mul]
protected lemma inv {q : ℚ} (hq : q ≠ 0) :
padic_val_rat p (q⁻¹) = -padic_val_rat p q :=
by rw [eq_neg_iff_add_eq_zero, ← padic_val_rat.mul p (inv_ne_zero hq) hq,
inv_mul_cancel hq, padic_val_rat.one]
protected lemma div {q r : ℚ} (hq : q ≠ 0) (hr : r ≠ 0) :
padic_val_rat p (q / r) = padic_val_rat p q - padic_val_rat p r :=
by rw [div_eq_mul_inv, padic_val_rat.mul p hq (inv_ne_zero hr),
padic_val_rat.inv p hr, sub_eq_add_neg]
lemma padic_val_rat_le_padic_val_rat_iff {n₁ n₂ d₁ d₂ : ℤ}
(hn₁ : n₁ ≠ 0) (hn₂ : n₂ ≠ 0) (hd₁ : d₁ ≠ 0) (hd₂ : d₂ ≠ 0) :
padic_val_rat p (n₁ /. d₁) ≤ padic_val_rat p (n₂ /. d₂) ↔
∀ (n : ℕ), ↑p ^ n ∣ n₁ * d₂ → ↑p ^ n ∣ n₂ * d₁ :=
have hf1 : finite (p : ℤ) (n₁ * d₂),
from finite_int_prime_iff.2 (mul_ne_zero hn₁ hd₂),
have hf2 : finite (p : ℤ) (n₂ * d₁),
from finite_int_prime_iff.2 (mul_ne_zero hn₂ hd₁),
by conv {
to_lhs,
rw [padic_val_rat.defn p (rat.mk_ne_zero_of_ne_zero hn₁ hd₁) rfl,
padic_val_rat.defn p (rat.mk_ne_zero_of_ne_zero hn₂ hd₂) rfl,
sub_le_iff_le_add',
← add_sub_assoc,
le_sub_iff_add_le],
norm_cast,
rw [← multiplicity.mul' (nat.prime_iff_prime_int.1 p_prime) hf1, add_comm,
← multiplicity.mul' (nat.prime_iff_prime_int.1 p_prime) hf2,
enat.get_le_get, multiplicity_le_multiplicity_iff]
}
theorem le_padic_val_rat_add_of_le {q r : ℚ}
(hq : q ≠ 0) (hr : r ≠ 0) (hqr : q + r ≠ 0)
(h : padic_val_rat p q ≤ padic_val_rat p r) :
padic_val_rat p q ≤ padic_val_rat p (q + r) :=
have hqn : q.num ≠ 0, from rat.num_ne_zero_of_ne_zero hq,
have hqd : (q.denom : ℤ) ≠ 0, by exact_mod_cast rat.denom_ne_zero _,
have hrn : r.num ≠ 0, from rat.num_ne_zero_of_ne_zero hr,
have hrd : (r.denom : ℤ) ≠ 0, by exact_mod_cast rat.denom_ne_zero _,
have hqdv : q.num /. q.denom ≠ 0, from rat.mk_ne_zero_of_ne_zero hqn hqd,
have hrdv : r.num /. r.denom ≠ 0, from rat.mk_ne_zero_of_ne_zero hrn hrd,
have hqreq : q + r = (((q.num * r.denom + q.denom * r.num : ℤ)) /. (↑q.denom * ↑r.denom : ℤ)),
from rat.add_num_denom _ _,
have hqrd : q.num * ↑(r.denom) + ↑(q.denom) * r.num ≠ 0,
from rat.mk_num_ne_zero_of_ne_zero hqr hqreq,
begin
conv_lhs { rw rat.num_denom q },
rw [hqreq, padic_val_rat_le_padic_val_rat_iff p hqn hqrd hqd (mul_ne_zero hqd hrd),
← multiplicity_le_multiplicity_iff, mul_left_comm,
multiplicity.mul (nat.prime_iff_prime_int.1 p_prime), add_mul],
rw [rat.num_denom q, rat.num_denom r, padic_val_rat_le_padic_val_rat_iff p hqn hrn hqd hrd,
← multiplicity_le_multiplicity_iff] at h,
calc _ ≤ min (multiplicity ↑p (q.num * ↑(r.denom) * ↑(q.denom)))
(multiplicity ↑p (↑(q.denom) * r.num * ↑(q.denom))) : (le_min
(by rw [@multiplicity.mul _ _ _ _ (_ * _) _ (nat.prime_iff_prime_int.1 p_prime), add_comm])
(by rw [mul_assoc, @multiplicity.mul _ _ _ _ (q.denom : ℤ)
(_ * _) (nat.prime_iff_prime_int.1 p_prime)];
exact add_le_add_left' h))
... ≤ _ : min_le_multiplicity_add
end
theorem min_le_padic_val_rat_add {q r : ℚ}
(hq : q ≠ 0) (hr : r ≠ 0) (hqr : q + r ≠ 0) :
min (padic_val_rat p q) (padic_val_rat p r) ≤ padic_val_rat p (q + r) :=
(le_total (padic_val_rat p q) (padic_val_rat p r)).elim
(λ h, by rw [min_eq_left h]; exact le_padic_val_rat_add_of_le _ hq hr hqr h)
(λ h, by rw [min_eq_right h, add_comm]; exact le_padic_val_rat_add_of_le _ hr hq
(by rwa add_comm) h)
end padic_val_rat
end padic_val_rat
def padic_norm (p : ℕ) (q : ℚ) : ℚ :=
if q = 0 then 0 else (↑p : ℚ) ^ (-(padic_val_rat p q))
namespace padic_norm
section padic_norm
open padic_val_rat
variables (p : ℕ) [hp : p.prime]
include hp
@[simp] protected lemma zero : padic_norm p 0 = 0 := by simp [padic_norm]
@[simp] protected lemma one : padic_norm p 1 = 1 := by simp [padic_norm]
@[simp] protected lemma eq_fpow_of_nonzero {q : ℚ} (hq : q ≠ 0) :
padic_norm p q = p ^ (-(padic_val_rat p q)) :=
by simp [hq, padic_norm]
protected lemma nonzero {q : ℚ} (hq : q ≠ 0) : padic_norm p q ≠ 0 :=
begin
rw padic_norm.eq_fpow_of_nonzero p hq,
apply fpow_ne_zero_of_ne_zero,
apply ne_of_gt,
exact_mod_cast hp.pos
end
@[simp] protected lemma neg (q : ℚ) : padic_norm p (-q) = padic_norm p q :=
if hq : q = 0 then by simp [hq]
else by simp [padic_norm, hq, hp.gt_one]
lemma zero_of_padic_norm_eq_zero {q : ℚ} (h : padic_norm p q = 0) : q = 0 :=
by_contradiction $
assume hq : q ≠ 0,
have padic_norm p q = p ^ (-(padic_val_rat p q)), by simp [hq],
fpow_ne_zero_of_ne_zero
(show (↑p : ℚ) ≠ 0, by simp [prime.ne_zero hp])
(-(padic_val_rat p q)) (by rw [←this, h])
protected lemma nonneg (q : ℚ) : padic_norm p q ≥ 0 :=
if hq : q = 0 then by simp [hq]
else
begin
unfold padic_norm; split_ifs,
apply fpow_nonneg_of_nonneg,
norm_cast, simp
end
@[simp] protected theorem mul (q r : ℚ) : padic_norm p (q*r) = padic_norm p q * padic_norm p r :=
if hq : q = 0 then
by simp [hq]
else if hr : r = 0 then
by simp [hr]
else
have q*r ≠ 0, from mul_ne_zero hq hr,
have (↑p : ℚ) ≠ 0, by simp [prime.ne_zero hp],
by simp [padic_norm, *, padic_val_rat.mul, fpow_add this]
@[simp] protected theorem div (q r : ℚ) : padic_norm p (q / r) = padic_norm p q / padic_norm p r :=
if hr : r = 0 then by simp [hr] else
eq_div_of_mul_eq _ _ (padic_norm.nonzero _ hr) (by rw [←padic_norm.mul, div_mul_cancel _ hr])
protected theorem of_int (z : ℤ) : padic_norm p ↑z ≤ 1 :=
if hz : z = 0 then by simp [hz] else
begin
unfold padic_norm,
rw [if_neg _],
{ refine fpow_le_one_of_nonpos _ _,
{ exact_mod_cast le_of_lt hp.gt_one, },
{ rw [padic_val_rat_of_int _ hp.ne_one hz, neg_nonpos],
norm_cast, simp }},
exact_mod_cast hz
end
--TODO: p implicit
private lemma nonarchimedean_aux {q r : ℚ} (h : padic_val_rat p q ≤ padic_val_rat p r) :
padic_norm p (q + r) ≤ max (padic_norm p q) (padic_norm p r) :=
have hnqp : padic_norm p q ≥ 0, from padic_norm.nonneg _ _,
have hnrp : padic_norm p r ≥ 0, from padic_norm.nonneg _ _,
if hq : q = 0 then
by simp [hq, max_eq_right hnrp, le_max_right]
else if hr : r = 0 then
by simp [hr, max_eq_left hnqp, le_max_left]
else if hqr : q + r = 0 then
le_trans (by simpa [hqr] using hnqp) (le_max_left _ _)
else
begin
unfold padic_norm, split_ifs,
apply le_max_iff.2,
left,
apply fpow_le_of_le,
{ exact_mod_cast le_of_lt hp.gt_one },
{ apply neg_le_neg,
have : padic_val_rat p q =
min (padic_val_rat p q) (padic_val_rat p r),
from (min_eq_left h).symm,
rw this,
apply min_le_padic_val_rat_add; assumption }
end
protected theorem nonarchimedean {q r : ℚ} :
padic_norm p (q + r) ≤ max (padic_norm p q) (padic_norm p r) :=
begin
wlog hle := le_total (padic_val_rat p q) (padic_val_rat p r) using [q r],
exact nonarchimedean_aux p hle
end
theorem triangle_ineq (q r : ℚ) : padic_norm p (q + r) ≤ padic_norm p q + padic_norm p r :=
calc padic_norm p (q + r) ≤ max (padic_norm p q) (padic_norm p r) : padic_norm.nonarchimedean p
... ≤ padic_norm p q + padic_norm p r :
max_le_add_of_nonneg (padic_norm.nonneg p _) (padic_norm.nonneg p _)
protected theorem sub {q r : ℚ} : padic_norm p (q - r) ≤ max (padic_norm p q) (padic_norm p r) :=
by rw [sub_eq_add_neg, ←padic_norm.neg p r]; apply padic_norm.nonarchimedean
lemma add_eq_max_of_ne {q r : ℚ} (hne : padic_norm p q ≠ padic_norm p r) :
padic_norm p (q + r) = max (padic_norm p q) (padic_norm p r) :=
begin
wlog hle := le_total (padic_norm p r) (padic_norm p q) using [q r],
have hlt : padic_norm p r < padic_norm p q, from lt_of_le_of_ne hle hne.symm,
have : padic_norm p q ≤ max (padic_norm p (q + r)) (padic_norm p r), from calc
padic_norm p q = padic_norm p (q + r - r) : by congr; ring
... ≤ max (padic_norm p (q + r)) (padic_norm p (-r)) : padic_norm.nonarchimedean p
... = max (padic_norm p (q + r)) (padic_norm p r) : by simp,
have hnge : padic_norm p r ≤ padic_norm p (q + r),
{ apply le_of_not_gt,
intro hgt,
rw max_eq_right_of_lt hgt at this,
apply not_lt_of_ge this,
assumption },
have : padic_norm p q ≤ padic_norm p (q + r), by rwa [max_eq_left hnge] at this,
apply _root_.le_antisymm,
{ apply padic_norm.nonarchimedean p },
{ rw max_eq_left_of_lt hlt,
assumption }
end
protected theorem image {q : ℚ} (hq : q ≠ 0) : ∃ n : ℤ, padic_norm p q = p ^ (-n) :=
⟨ (padic_val_rat p q), by simp [padic_norm, hq] ⟩
instance : is_absolute_value (padic_norm p) :=
{ abv_nonneg := padic_norm.nonneg p,
abv_eq_zero :=
begin
intros,
constructor; intro,
{ apply zero_of_padic_norm_eq_zero p, assumption },
{ simp [*] }
end,
abv_add := padic_norm.triangle_ineq p,
abv_mul := padic_norm.mul p }
lemma le_of_dvd {n : ℕ} {z : ℤ} (hd : ↑(p^n) ∣ z) : padic_norm p z ≤ ↑p ^ (-n : ℤ) :=
have hp' : (↑p : ℚ) ≥ 1, from show ↑p ≥ ↑(1 : ℕ), by exact_mod_cast le_of_lt hp.gt_one,
have hpn : (↑p : ℚ) ≥ 0, from le_trans zero_le_one hp',
begin
unfold padic_norm, split_ifs with hz hz,
{ simpa [padic_norm, hz] using fpow_nonneg_of_nonneg hpn _ },
{ apply fpow_le_of_le hp',
apply neg_le_neg,
rw padic_val_rat_of_int _ hp.ne_one _,
{ norm_cast,
rw [← enat.coe_le_coe, enat.coe_get],
apply multiplicity.le_multiplicity_of_pow_dvd,
exact_mod_cast hd },
{ exact_mod_cast hz }}
end
end padic_norm
end padic_norm
|
aa052727fd13624267fc627d7d8d6c0638edd2ca | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/1569.lean | ea18364db88f365e8acb09c9cda3884a9bc3e3f7 | [
"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 | 93 | lean | def foo (x : Nat) (_ : x = 0) : Nat := x
example : foo 0 (by simp [typo]; done) = 0 := sorry
|
258d09e8066085dbd24ffa099d2c03b6a4872d8b | 4727251e0cd73359b15b664c3170e5d754078599 | /src/analysis/normed_space/enorm.lean | 54c986e82aed4f163da1c25472a9a6fce3a6a23b | [
"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,795 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov
-/
import analysis.normed_space.basic
/-!
# Extended norm
In this file we define a structure `enorm 𝕜 V` representing an extended norm (i.e., a norm that can
take the value `∞`) on a vector space `V` over a normed field `𝕜`. We do not use `class` for
an `enorm` because the same space can have more than one extended norm. For example, the space of
measurable functions `f : α → ℝ` has a family of `L_p` extended norms.
We prove some basic inequalities, then define
* `emetric_space` structure on `V` corresponding to `e : enorm 𝕜 V`;
* the subspace of vectors with finite norm, called `e.finite_subspace`;
* a `normed_space` structure on this space.
The last definition is an instance because the type involves `e`.
## Implementation notes
We do not define extended normed groups. They can be added to the chain once someone will need them.
## Tags
normed space, extended norm
-/
noncomputable theory
local attribute [instance, priority 1001] classical.prop_decidable
open_locale ennreal
/-- Extended norm on a vector space. As in the case of normed spaces, we require only
`∥c • x∥ ≤ ∥c∥ * ∥x∥` in the definition, then prove an equality in `map_smul`. -/
structure enorm (𝕜 : Type*) (V : Type*) [normed_field 𝕜] [add_comm_group V] [module 𝕜 V] :=
(to_fun : V → ℝ≥0∞)
(eq_zero' : ∀ x, to_fun x = 0 → x = 0)
(map_add_le' : ∀ x y : V, to_fun (x + y) ≤ to_fun x + to_fun y)
(map_smul_le' : ∀ (c : 𝕜) (x : V), to_fun (c • x) ≤ ∥c∥₊ * to_fun x)
namespace enorm
variables {𝕜 : Type*} {V : Type*} [normed_field 𝕜] [add_comm_group V] [module 𝕜 V]
(e : enorm 𝕜 V)
instance : has_coe_to_fun (enorm 𝕜 V) (λ _, V → ℝ≥0∞) := ⟨enorm.to_fun⟩
lemma coe_fn_injective : function.injective (coe_fn : enorm 𝕜 V → (V → ℝ≥0∞)) :=
λ e₁ e₂ h, by cases e₁; cases e₂; congr; exact h
@[ext] lemma ext {e₁ e₂ : enorm 𝕜 V} (h : ∀ x, e₁ x = e₂ x) : e₁ = e₂ :=
coe_fn_injective $ funext h
lemma ext_iff {e₁ e₂ : enorm 𝕜 V} : e₁ = e₂ ↔ ∀ x, e₁ x = e₂ x :=
⟨λ h x, h ▸ rfl, ext⟩
@[simp, norm_cast] lemma coe_inj {e₁ e₂ : enorm 𝕜 V} : (e₁ : V → ℝ≥0∞) = e₂ ↔ e₁ = e₂ :=
coe_fn_injective.eq_iff
@[simp] lemma map_smul (c : 𝕜) (x : V) : e (c • x) = ∥c∥₊ * e x :=
le_antisymm (e.map_smul_le' c x) $
begin
by_cases hc : c = 0, { simp [hc] },
calc (∥c∥₊ : ℝ≥0∞) * e x = ∥c∥₊ * e (c⁻¹ • c • x) : by rw [inv_smul_smul₀ hc]
... ≤ ∥c∥₊ * (∥c⁻¹∥₊ * e (c • x)) : _
... = e (c • x) : _,
{ exact ennreal.mul_le_mul le_rfl (e.map_smul_le' _ _) },
{ rw [← mul_assoc, nnnorm_inv, ennreal.coe_inv,
ennreal.mul_inv_cancel _ ennreal.coe_ne_top, one_mul]; simp [hc] }
end
@[simp] lemma map_zero : e 0 = 0 :=
by { rw [← zero_smul 𝕜 (0:V), e.map_smul], norm_num }
@[simp] lemma eq_zero_iff {x : V} : e x = 0 ↔ x = 0 :=
⟨e.eq_zero' x, λ h, h.symm ▸ e.map_zero⟩
@[simp] lemma map_neg (x : V) : e (-x) = e x :=
calc e (-x) = ∥(-1 : 𝕜)∥₊ * e x : by rw [← map_smul, neg_one_smul]
... = e x : by simp
lemma map_sub_rev (x y : V) : e (x - y) = e (y - x) :=
by rw [← neg_sub, e.map_neg]
lemma map_add_le (x y : V) : e (x + y) ≤ e x + e y := e.map_add_le' x y
lemma map_sub_le (x y : V) : e (x - y) ≤ e x + e y :=
calc e (x - y) = e (x + -y) : by rw sub_eq_add_neg
... ≤ e x + e (-y) : e.map_add_le x (-y)
... = e x + e y : by rw [e.map_neg]
instance : partial_order (enorm 𝕜 V) :=
{ le := λ e₁ e₂, ∀ x, e₁ x ≤ e₂ x,
le_refl := λ e x, le_rfl,
le_trans := λ e₁ e₂ e₃ h₁₂ h₂₃ x, le_trans (h₁₂ x) (h₂₃ x),
le_antisymm := λ e₁ e₂ h₁₂ h₂₁, ext $ λ x, le_antisymm (h₁₂ x) (h₂₁ x) }
/-- The `enorm` sending each non-zero vector to infinity. -/
noncomputable instance : has_top (enorm 𝕜 V) :=
⟨{ to_fun := λ x, if x = 0 then 0 else ⊤,
eq_zero' := λ x, by { split_ifs; simp [*] },
map_add_le' := λ x y,
begin
split_ifs with hxy hx hy hy hx hy hy; try { simp [*] },
simpa [hx, hy] using hxy
end,
map_smul_le' := λ c x,
begin
split_ifs with hcx hx hx; simp only [smul_eq_zero, not_or_distrib] at hcx,
{ simp only [mul_zero, le_refl] },
{ have : c = 0, by tauto,
simp [this] },
{ tauto },
{ simp [hcx.1] }
end }⟩
noncomputable instance : inhabited (enorm 𝕜 V) := ⟨⊤⟩
lemma top_map {x : V} (hx : x ≠ 0) : (⊤ : enorm 𝕜 V) x = ⊤ := if_neg hx
noncomputable instance : order_top (enorm 𝕜 V) :=
{ top := ⊤,
le_top := λ e x, if h : x = 0 then by simp [h] else by simp [top_map h] }
noncomputable instance : semilattice_sup (enorm 𝕜 V) :=
{ le := (≤),
lt := (<),
sup := λ e₁ e₂,
{ to_fun := λ x, max (e₁ x) (e₂ x),
eq_zero' := λ x h, e₁.eq_zero_iff.1 (ennreal.max_eq_zero_iff.1 h).1,
map_add_le' := λ x y, max_le
(le_trans (e₁.map_add_le _ _) $ add_le_add (le_max_left _ _) (le_max_left _ _))
(le_trans (e₂.map_add_le _ _) $ add_le_add (le_max_right _ _) (le_max_right _ _)),
map_smul_le' := λ c x, le_of_eq $ by simp only [map_smul, ennreal.mul_max] },
le_sup_left := λ e₁ e₂ x, le_max_left _ _,
le_sup_right := λ e₁ e₂ x, le_max_right _ _,
sup_le := λ e₁ e₂ e₃ h₁ h₂ x, max_le (h₁ x) (h₂ x),
.. enorm.partial_order }
@[simp, norm_cast] lemma coe_max (e₁ e₂ : enorm 𝕜 V) : ⇑(e₁ ⊔ e₂) = λ x, max (e₁ x) (e₂ x) := rfl
@[norm_cast]
lemma max_map (e₁ e₂ : enorm 𝕜 V) (x : V) : (e₁ ⊔ e₂) x = max (e₁ x) (e₂ x) := rfl
/-- Structure of an `emetric_space` defined by an extended norm. -/
def emetric_space : emetric_space V :=
{ edist := λ x y, e (x - y),
edist_self := λ x, by simp,
eq_of_edist_eq_zero := λ x y, by simp [sub_eq_zero],
edist_comm := e.map_sub_rev,
edist_triangle := λ x y z,
calc e (x - z) = e ((x - y) + (y - z)) : by rw [sub_add_sub_cancel]
... ≤ e (x - y) + e (y - z) : e.map_add_le (x - y) (y - z) }
/-- The subspace of vectors with finite enorm. -/
def finite_subspace : subspace 𝕜 V :=
{ carrier := {x | e x < ⊤},
zero_mem' := by simp,
add_mem' := λ x y hx hy, lt_of_le_of_lt (e.map_add_le x y) (ennreal.add_lt_top.2 ⟨hx, hy⟩),
smul_mem' := λ c x (hx : _ < _),
calc e (c • x) = ∥c∥₊ * e x : e.map_smul c x
... < ⊤ : ennreal.mul_lt_top ennreal.coe_ne_top hx.ne }
/-- Metric space structure on `e.finite_subspace`. We use `emetric_space.to_metric_space_of_dist`
to ensure that this definition agrees with `e.emetric_space`. -/
instance : metric_space e.finite_subspace :=
begin
letI := e.emetric_space,
refine emetric_space.to_metric_space_of_dist _ (λ x y, _) (λ x y, rfl),
change e (x - y) ≠ ⊤,
exact ne_top_of_le_ne_top (ennreal.add_lt_top.2 ⟨x.2, y.2⟩).ne (e.map_sub_le x y)
end
lemma finite_dist_eq (x y : e.finite_subspace) : dist x y = (e (x - y)).to_real := rfl
lemma finite_edist_eq (x y : e.finite_subspace) : edist x y = e (x - y) := rfl
/-- Normed group instance on `e.finite_subspace`. -/
instance : normed_group e.finite_subspace :=
{ norm := λ x, (e x).to_real,
dist_eq := λ x y, rfl }
lemma finite_norm_eq (x : e.finite_subspace) : ∥x∥ = (e x).to_real := rfl
/-- Normed space instance on `e.finite_subspace`. -/
instance : normed_space 𝕜 e.finite_subspace :=
{ norm_smul_le := λ c x, le_of_eq $ by simp [finite_norm_eq, ennreal.to_real_mul] }
end enorm
|
408723b70a56a6e9da37aa374baac1b93c3e62e7 | ac2987d8c7832fb4a87edb6bee26141facbb6fa0 | /Mathlib/Data/List/Card.lean | 68acf299c6bf192877a5353817c5ac598b61a31d | [
"Apache-2.0"
] | permissive | AurelienSaue/mathlib4 | 52204b9bd9d207c922fe0cf3397166728bb6c2e2 | 84271fe0875bafdaa88ac41f1b5a7c18151bd0d5 | refs/heads/master | 1,689,156,096,545 | 1,629,378,840,000 | 1,629,378,840,000 | 389,648,603 | 0 | 0 | Apache-2.0 | 1,627,307,284,000 | 1,627,307,284,000 | null | UTF-8 | Lean | false | false | 7,279 | lean | /-
Author: Jeremy Avigad
This is a makeshift theory of the cardinality of a list. Any list can be taken to represent the
finite set of its elements. Cardinality counts the number of distinct elements. Cardinality
respects equivalence and is preserved by any mapping that is injective on its elements.
It might make sense to remove this when we have a proper theory of finite sets.
-/
import Mathlib.Data.List.Basic
namespace List
def disjoint (as bs : List α) := ∀ {x}, x ∈ as → x ∈ bs → False
def inj_on (f : α → β) (as : List α) := ∀ {x y}, x ∈ as → y ∈ as → f x = f y → x = y
theorem inj_on_of_subset {f : α → β} {as bs : List α} (h : inj_on f bs) (hsub : as ⊆ bs) :
inj_on f as := fun xas yas heq => h (hsub xas) (hsub yas) heq
protected def equiv (as bs : List α) := ∀ x, x ∈ as ↔ x ∈ bs
theorem equiv_iff_subset_and_subset {as bs : List α} : as.equiv bs ↔ as ⊆ bs ∧ bs ⊆ as :=
⟨fun h => ⟨fun xas => (h _).1 xas, fun xbs => (h _).2 xbs⟩, fun ⟨h1, h2⟩ x => ⟨h1, h2⟩⟩
theorem insert_equiv_cons [DecidableEq α] (a : α) (as : List α) : (insert a as).equiv (a :: as) :=
fun x => by simp
theorem union_equiv_append [DecidableEq α] (as bs : List α) : (as.union bs).equiv (as ++ bs) :=
fun x => by simp
section decidable_eq
variable [DecidableEq α] [DecidableEq β]
/- remove -/
def remove (a : α) : List α → List α
| [] => []
| (b :: bs) => if a = b then remove a bs else b :: remove a bs
theorem mem_remove_iff {a b : α} {as : List α} : b ∈ remove a as ↔ b ∈ as ∧ b ≠ a := by
induction as with
| nil => simp [remove]
| cons a' as ih =>
simp [remove]
cases Decidable.em (a = a') with
| inl h =>
simp only [if_pos h, ih]
exact ⟨fun ⟨h1, h2⟩ => ⟨Or.inr h1, h2⟩, fun ⟨h1, h2⟩ => ⟨Or.resolve_left h1 (h ▸ h2), h2⟩⟩
| inr h =>
simp [if_neg h, ih]
split
focus
intro h'
cases h' with
| inl h₁ => exact ⟨Or.inl h₁, h₁.symm ▸ (Ne.symm h)⟩
| inr h₁ => exact ⟨Or.inr h₁.1, h₁.2⟩
intro ⟨h1, h2⟩
cases h1 with
| inl h1' => exact Or.inl h1'
| inr h1' => exact Or.inr ⟨h1', h2⟩
theorem remove_eq_of_not_mem {a : α} : ∀ {as : List α}, (a ∉ as) → remove a as = as
| [], _ => by simp [remove]
| a' :: as, h => by
have h1 : a ≠ a' := fun h' => h (by rw [h']; apply mem_cons_self)
have h2 : a ∉ as := fun h' => h (mem_cons_of_mem _ h')
simp [remove, h1, remove_eq_of_not_mem h2]
theorem mem_of_mem_remove {a b : α} {as : List α} (h : b ∈ remove a as) : b ∈ as := by
rw [mem_remove_iff] at h; exact h.1
/- card -/
def card : List α → Nat
| [] => 0
| a :: as => if a ∈ as then card as else card as + 1
@[simp] theorem card_nil : card ([] : List α) = 0 := rfl
@[simp] theorem card_cons_of_mem {a : α} {as : List α} (h : a ∈ as) :
card (a :: as) = card as := by simp [card]; rw [if_pos h]
@[simp] theorem card_cons_of_not_mem {a : α} {as : List α} (h : a ∉ as) :
card (a :: as) = card as + 1 := by simp [card]; rw [if_neg h]
theorem card_le_card_cons (a : α) (as : List α) : card as ≤ card (a :: as) := by
cases Decidable.em (a ∈ as) with
| inl h => simp [h, Nat.le_refl]
| inr h => simp [h, Nat.le_succ]
@[simp] theorem card_insert_of_mem {a : α} {as : List α} (h : a ∈ as) :
card (insert a as) = card as := by simp [h]
@[simp] theorem card_insert_of_not_mem {a : α} {as : List α} (h : a ∉ as) :
card (insert a as) = card as + 1 := by simp [h]
theorem card_remove_of_mem {a : α} : ∀ {as : List α}, a ∈ as → card as = card (remove a as) + 1
| [], h => False.elim (not_mem_nil _ h)
| (a' :: as), h => by
cases Decidable.em (a = a') with
| inl h' =>
simp [remove, if_pos h']
cases Decidable.em (a ∈ as) with
| inl h'' =>
have h₃ : a' ∈ as := h' ▸ h''
simp [card_remove_of_mem h'', h₃]
| inr h'' =>
have h₃ : a' ∉ as := h' ▸ h''
simp [card_cons_of_not_mem h₃, remove_eq_of_not_mem h'']
| inr h' =>
have h₃ : a ∈ as := Or.resolve_left h h'
simp [remove, h']
cases Decidable.em (a' ∈ as) with
| inl h'' =>
have : a' ∈ remove a as := by rw [mem_remove_iff]; exact ⟨h'', Ne.symm h'⟩
simp [h'', this, card_remove_of_mem h₃]
| inr h'' =>
have : a' ∉ remove a as := fun h => h'' (mem_of_mem_remove h)
simp [h'', this, card_remove_of_mem h₃]
theorem card_subset_le : ∀ {as bs : List α}, as ⊆ bs → card as ≤ card bs
| [], bs, _ => by simp; apply Nat.zero_le
| (a :: as), bs, hsub => by
cases Decidable.em (a ∈ as) with
| inl h' =>
have hsub' : as ⊆ bs := fun xmem => hsub (mem_cons_of_mem a xmem)
simp [h', card_subset_le hsub']
| inr h' =>
have : a ∈ bs := hsub (Or.inl rfl)
simp [h', card_remove_of_mem this]
apply Nat.add_le_add_right
apply card_subset_le
intro x xmem
rw [mem_remove_iff]
exact ⟨hsub (mem_cons_of_mem _ xmem), fun h => h' (h ▸ xmem)⟩
theorem card_map_le (f : α → β) (as : List α) : card (as.map f) ≤ card as := by
induction as with
| nil => simp
| cons a as ih =>
cases Decidable.em (f a ∈ map f as) with
| inl h => simp [h]; apply Nat.le_trans ih (card_le_card_cons ..)
| inr h =>
have : a ∉ as := fun h'' => h (mem_map_of_mem _ h'')
simp [h, this]
exact Nat.add_le_add_right ih _
theorem card_map_eq_of_inj_on {f : α → β} {as : List α} :
inj_on f as → card (as.map f) = card as := by
induction as with
| nil => simp
| cons a as ih =>
cases Decidable.em (f a ∈ map f as) with
| inl h =>
intro inj_on'
cases (exists_of_mem_map h) with
| intro x hx =>
have : x = a := inj_on' (mem_cons_of_mem _ hx.1) (mem_cons_self ..) hx.2
have h1 : a ∈ as := this ▸ hx.1
have h2 : inj_on f as := inj_on_of_subset inj_on' (subset_cons _ _)
simp [h1, mem_map_of_mem f h1, ih h2]
| inr h =>
intro inj_on'
have h1 : a ∉ as := fun h'' => h (mem_map_of_mem _ h'')
have h2 : inj_on f as := inj_on_of_subset inj_on' (subset_cons _ _)
simp [h, h1, ih h2]
theorem card_eq_of_equiv {as bs : List α} (h : as.equiv bs) : card as = card bs :=
let sub_and_sub := equiv_iff_subset_and_subset.1 h
Nat.le_antisymm (card_subset_le sub_and_sub.1) (card_subset_le sub_and_sub.2)
theorem card_append_disjoint : ∀ {as bs : List α},
disjoint as bs → card (as ++ bs) = card as + card bs
| [], bs, disj => by simp
| a :: as, bs, disj => by
have disj' : disjoint as bs := fun h1 h2 => disj (mem_cons_of_mem a h1) h2
cases Decidable.em (a ∈ as) with
| inl h =>
simp [h, card_append_disjoint disj']
| inr h =>
have h1 : a ∉ bs := fun h' => disj (mem_cons_self a as) h'
simp [h, h1, card_append_disjoint disj', Nat.add_right_comm]
theorem card_union_disjoint {as bs : List α} (h : disjoint as bs) :
card (as.union bs) = card as + card bs := by
rw [card_eq_of_equiv (union_equiv_append as bs), card_append_disjoint h]
end decidable_eq
end List
|
174494b1c415d1e4c36dffea72cd34b41d0d3382 | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/topology/uniform_space/complete_separated.lean | f5a81543b009d730baf60e7b58712fc1b0f3231e | [
"Apache-2.0"
] | permissive | rmitta/mathlib | 8d90aee30b4db2b013e01f62c33f297d7e64a43d | 883d974b608845bad30ae19e27e33c285200bf84 | refs/heads/master | 1,585,776,832,544 | 1,576,874,096,000 | 1,576,874,096,000 | 153,663,165 | 0 | 2 | Apache-2.0 | 1,544,806,490,000 | 1,539,884,365,000 | Lean | UTF-8 | Lean | false | false | 1,358 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
Theory of complete separated uniform spaces.
This file is for elementary lemmas that depend on both Cauchy filters and separation.
-/
import topology.uniform_space.cauchy topology.uniform_space.separation
import topology.dense_embedding
open filter
open_locale topological_space
variables {α : Type*}
/-In a separated space, a complete set is closed -/
lemma is_closed_of_is_complete [uniform_space α] [separated α] {s : set α} (h : is_complete s) :
is_closed s :=
is_closed_iff_nhds.2 $ λ a ha, begin
let f := 𝓝 a ⊓ principal s,
have : cauchy f := cauchy_downwards (cauchy_nhds) ha (lattice.inf_le_left),
rcases h f this (lattice.inf_le_right) with ⟨y, ys, fy⟩,
rwa (tendsto_nhds_unique ha lattice.inf_le_left fy : a = y)
end
namespace dense_inducing
open filter
variables [topological_space α] {β : Type*} [topological_space β]
variables {γ : Type*} [uniform_space γ] [complete_space γ] [separated γ]
lemma continuous_extend_of_cauchy {e : α → β} {f : α → γ}
(de : dense_inducing e) (h : ∀ b : β, cauchy (map f (comap e $ 𝓝 b))) :
continuous (de.extend f) :=
de.continuous_extend $ λ b, complete_space.complete (h b)
end dense_inducing
|
38711e3534792865cc64ac9b3feff69a6cda80d8 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/linear_algebra/sesquilinear_form.lean | 6515c4dcc34e53540debd45facfa37e2b346e984 | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 12,012 | lean | /-
Copyright (c) 2018 Andreas Swerdlow. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andreas Swerdlow
-/
import ring_theory.ring_invo
import algebra.module.linear_map
/-!
# Sesquilinear form
This file defines a sesquilinear form over a module. The definition requires a ring antiautomorphism
on the scalar ring. Basic ideas such as
orthogonality are also introduced.
A sesquilinear form on an `R`-module `M`, is a function from `M × M` to `R`, that is linear in the
first argument and antilinear in the second, with respect to an antiautomorphism on `R` (an
antiisomorphism from `R` to `R`).
## Notations
Given any term `S` of type `sesq_form`, due to a coercion, can use the notation `S x y` to
refer to the function field, ie. `S x y = S.sesq x y`.
## References
* <https://en.wikipedia.org/wiki/Sesquilinear_form#Over_arbitrary_rings>
## Tags
Sesquilinear form,
-/
open_locale big_operators
universes u v w
/-- A sesquilinear form over a module -/
structure sesq_form (R : Type u) (M : Type v) [ring R] (I : R ≃+* Rᵒᵖ)
[add_comm_group M] [module R M] :=
(sesq : M → M → R)
(sesq_add_left : ∀ (x y z : M), sesq (x + y) z = sesq x z + sesq y z)
(sesq_smul_left : ∀ (a : R) (x y : M), sesq (a • x) y = a * (sesq x y))
(sesq_add_right : ∀ (x y z : M), sesq x (y + z) = sesq x y + sesq x z)
(sesq_smul_right : ∀ (a : R) (x y : M), sesq x (a • y) = (I a).unop * (sesq x y))
namespace sesq_form
section general_ring
variables {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M]
variables {I : R ≃+* Rᵒᵖ} {S : sesq_form R M I}
instance : has_coe_to_fun (sesq_form R M I) :=
⟨_, λ S, S.sesq⟩
lemma add_left (x y z : M) : S (x + y) z = S x z + S y z := sesq_add_left S x y z
lemma smul_left (a : R) (x y : M) : S (a • x) y = a * (S x y) := sesq_smul_left S a x y
lemma add_right (x y z : M) : S x (y + z) = S x y + S x z := sesq_add_right S x y z
lemma smul_right (a : R) (x y : M) : S x (a • y) = (I a).unop * (S x y) := sesq_smul_right S a x y
lemma zero_left (x : M) : S 0 x = 0 :=
by { rw [←zero_smul R (0 : M), smul_left, zero_mul] }
lemma zero_right (x : M) : S x 0 = 0 :=
by { rw [←zero_smul R (0 : M), smul_right], simp }
lemma neg_left (x y : M) : S (-x) y = -(S x y) :=
by { rw [←@neg_one_smul R _ _, smul_left, neg_one_mul] }
lemma neg_right (x y : M) : S x (-y) = -(S x y) :=
by { rw [←@neg_one_smul R _ _, smul_right], simp }
lemma sub_left (x y z : M) :
S (x - y) z = S x z - S y z :=
by simp only [sub_eq_add_neg, add_left, neg_left]
lemma sub_right (x y z : M) :
S x (y - z) = S x y - S x z :=
by simp only [sub_eq_add_neg, add_right, neg_right]
variable {D : sesq_form R M I}
@[ext] lemma ext (H : ∀ (x y : M), S x y = D x y) : S = D :=
by {cases S, cases D, congr, funext, exact H _ _}
instance : has_add (sesq_form R M I) :=
⟨λ S D, { sesq := λ x y, S x y + D x y,
sesq_add_left := λ x y z, by {rw add_left, rw add_left, abel},
sesq_smul_left := λ a x y, by {rw [smul_left, smul_left, mul_add]},
sesq_add_right := λ x y z, by {rw add_right, rw add_right, abel},
sesq_smul_right := λ a x y, by {rw [smul_right, smul_right, mul_add]} }⟩
instance : has_zero (sesq_form R M I) :=
⟨{ sesq := λ x y, 0,
sesq_add_left := λ x y z, (add_zero 0).symm,
sesq_smul_left := λ a x y, (mul_zero a).symm,
sesq_add_right := λ x y z, (zero_add 0).symm,
sesq_smul_right := λ a x y, (mul_zero (I a).unop).symm }⟩
instance : has_neg (sesq_form R M I) :=
⟨λ S, { sesq := λ x y, - (S.1 x y),
sesq_add_left := λ x y z, by rw [sesq_add_left, neg_add],
sesq_smul_left := λ a x y, by rw [sesq_smul_left, mul_neg_eq_neg_mul_symm],
sesq_add_right := λ x y z, by rw [sesq_add_right, neg_add],
sesq_smul_right := λ a x y, by rw [sesq_smul_right, mul_neg_eq_neg_mul_symm] }⟩
instance : add_comm_group (sesq_form R M I) :=
{ add := (+),
add_assoc := by { intros, ext,
unfold coe_fn has_coe_to_fun.coe sesq coe_fn has_coe_to_fun.coe sesq, rw add_assoc },
zero := 0,
zero_add := by { intros, ext, unfold coe_fn has_coe_to_fun.coe sesq, rw zero_add },
add_zero := by { intros, ext, unfold coe_fn has_coe_to_fun.coe sesq, rw add_zero },
neg := has_neg.neg,
add_left_neg := by { intros, ext, unfold coe_fn has_coe_to_fun.coe sesq, rw neg_add_self },
add_comm := by { intros, ext, unfold coe_fn has_coe_to_fun.coe sesq, rw add_comm } }
instance : inhabited (sesq_form R M I) := ⟨0⟩
/-- The proposition that two elements of a sesquilinear form space are orthogonal -/
def is_ortho (S : sesq_form R M I) (x y : M) : Prop :=
S x y = 0
lemma ortho_zero (x : M) :
is_ortho S (0 : M) x := zero_left x
lemma is_add_monoid_hom_left (S : sesq_form R M I) (x : M) : is_add_monoid_hom (λ z, S z x) :=
{ map_add := λ z y, sesq_add_left S _ _ _,
map_zero := zero_left x }
lemma is_add_monoid_hom_right (S : sesq_form R M I) (x : M) : is_add_monoid_hom (λ z, S x z) :=
{ map_add := λ z y, sesq_add_right S _ _ _,
map_zero := zero_right x }
lemma sum_left {α : Type*} (S : sesq_form R M I) (t : finset α) (g : α → M) (w : M) :
S (∑ i in t, g i) w = ∑ i in t, S (g i) w :=
by haveI s_inst := is_add_monoid_hom_left S w; exact (finset.sum_hom t (λ z, S z w)).symm
lemma sum_right {α : Type*} (S : sesq_form R M I) (t : finset α) (g : α → M) (w : M) :
S w (∑ i in t, g i) = ∑ i in t, S w (g i) :=
by haveI s_inst := is_add_monoid_hom_right S w; exact (finset.sum_hom t (λ z, S w z)).symm
variables {M₂ : Type w} [add_comm_group M₂] [module R M₂]
/-- Apply the linear maps `f` and `g` to the left and right arguments of the sesquilinear form. -/
def comp (S : sesq_form R M I) (f g : M₂ →ₗ[R] M) : sesq_form R M₂ I :=
{ sesq := λ x y, S (f x) (g y),
sesq_add_left := by simp [add_left],
sesq_smul_left := by simp [smul_left],
sesq_add_right := by simp [add_right],
sesq_smul_right := by simp [smul_right] }
/-- Apply the linear map `f` to the left argument of the sesquilinear form. -/
def comp_left (S : sesq_form R M I) (f : M →ₗ[R] M) : sesq_form R M I :=
S.comp f linear_map.id
/-- Apply the linear map `f` to the right argument of the sesquilinear form. -/
def comp_right (S : sesq_form R M I) (f : M →ₗ[R] M) : sesq_form R M I :=
S.comp linear_map.id f
lemma comp_left_comp_right (S : sesq_form R M I) (f g : M →ₗ[R] M) :
(S.comp_left f).comp_right g = S.comp f g := rfl
lemma comp_right_comp_left (S : sesq_form R M I) (f g : M →ₗ[R] M) :
(S.comp_right g).comp_left f = S.comp f g := rfl
lemma comp_comp {M₃ : Type*} [add_comm_group M₃] [module R M₃]
(S : sesq_form R M₃ I) (l r : M →ₗ[R] M₂) (l' r' : M₂ →ₗ[R] M₃) :
(S.comp l' r').comp l r = S.comp (l'.comp l) (r'.comp r) := rfl
@[simp] lemma comp_apply (S : sesq_form R M₂ I) (l r : M →ₗ[R] M₂) (v w : M) :
S.comp l r v w = S (l v) (r w) := rfl
@[simp] lemma comp_left_apply (S : sesq_form R M I) (f : M →ₗ[R] M) (v w : M) :
S.comp_left f v w = S (f v) w := rfl
@[simp] lemma comp_right_apply (S : sesq_form R M I) (f : M →ₗ[R] M) (v w : M) :
S.comp_right f v w = S v (f w) := rfl
/-- Let `l`, `r` be surjective linear maps, then two sesquilinear forms are equal if and only if
the sesquilinear forms resulting from composition with `l` and `r` are equal. -/
lemma comp_injective (S₁ S₂ : sesq_form R M₂ I) {l r : M →ₗ[R] M₂}
(hl : function.surjective l) (hr : function.surjective r) :
S₁.comp l r = S₂.comp l r ↔ S₁ = S₂ :=
begin
split; intros h,
{ ext,
rcases hl x with ⟨x', rfl⟩,
rcases hr y with ⟨y', rfl⟩,
rw [← comp_apply, ← comp_apply, h], },
{ rw h },
end
end general_ring
section comm_ring
variables {R : Type*} [comm_ring R] {M : Type v} [add_comm_group M] [module R M]
{J : R ≃+* Rᵒᵖ} (F : sesq_form R M J) (f : M → M)
instance to_module : module R (sesq_form R M J) :=
{ smul := λ c S,
{ sesq := λ x y, c * S x y,
sesq_add_left := λ x y z, by {unfold coe_fn has_coe_to_fun.coe sesq,
rw [sesq_add_left, left_distrib]},
sesq_smul_left := λ a x y, by {unfold coe_fn has_coe_to_fun.coe sesq,
rw [sesq_smul_left, ←mul_assoc, mul_comm c, mul_assoc]},
sesq_add_right := λ x y z, by {unfold coe_fn has_coe_to_fun.coe sesq,
rw [sesq_add_right, left_distrib]},
sesq_smul_right := λ a x y, by {unfold coe_fn has_coe_to_fun.coe sesq,
rw [sesq_smul_right, ←mul_assoc, mul_comm c, mul_assoc], refl} },
smul_add := λ c S D, by {ext, unfold coe_fn has_coe_to_fun.coe sesq, rw left_distrib},
add_smul := λ c S D, by {ext, unfold coe_fn has_coe_to_fun.coe sesq, rw right_distrib},
mul_smul := λ a c D, by {ext, unfold coe_fn has_coe_to_fun.coe sesq, rw mul_assoc},
one_smul := λ S, by {ext, unfold coe_fn has_coe_to_fun.coe sesq, rw one_mul},
zero_smul := λ S, by {ext, unfold coe_fn has_coe_to_fun.coe sesq, rw zero_mul},
smul_zero := λ S, by {ext, unfold coe_fn has_coe_to_fun.coe sesq, rw mul_zero} }
end comm_ring
section domain
variables {R : Type*} [domain R]
{M : Type v} [add_comm_group M] [module R M]
{K : R ≃+* Rᵒᵖ} {G : sesq_form R M K}
theorem ortho_smul_left {x y : M} {a : R} (ha : a ≠ 0) :
(is_ortho G x y) ↔ (is_ortho G (a • x) y) :=
begin
dunfold is_ortho,
split; intro H,
{ rw [smul_left, H, mul_zero] },
{ rw [smul_left, mul_eq_zero] at H,
cases H,
{ trivial },
{ exact H }}
end
theorem ortho_smul_right {x y : M} {a : R} (ha : a ≠ 0) :
(is_ortho G x y) ↔ (is_ortho G x (a • y)) :=
begin
dunfold is_ortho,
split; intro H,
{ rw [smul_right, H, mul_zero] },
{ rw [smul_right, mul_eq_zero] at H,
cases H,
{ exfalso,
-- `map_eq_zero_iff` doesn't fire here even if marked as a simp lemma, probably bcecause
-- different instance paths
simp only [opposite.unop_eq_zero_iff] at H,
exact ha (K.map_eq_zero_iff.mp H), },
{ exact H }}
end
end domain
end sesq_form
namespace refl_sesq_form
open refl_sesq_form sesq_form
variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M]
variables {I : R ≃+* Rᵒᵖ} {S : sesq_form R M I}
/-- The proposition that a sesquilinear form is reflexive -/
def is_refl (S : sesq_form R M I) : Prop := ∀ (x y : M), S x y = 0 → S y x = 0
variable (H : is_refl S)
lemma eq_zero : ∀ {x y : M}, S x y = 0 → S y x = 0 := λ x y, H x y
lemma ortho_sym {x y : M} :
is_ortho S x y ↔ is_ortho S y x := ⟨eq_zero H, eq_zero H⟩
end refl_sesq_form
namespace sym_sesq_form
open sym_sesq_form sesq_form
variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M]
variables {I : R ≃+* Rᵒᵖ} {S : sesq_form R M I}
/-- The proposition that a sesquilinear form is symmetric -/
def is_sym (S : sesq_form R M I) : Prop := ∀ (x y : M), (I (S x y)).unop = S y x
variable (H : is_sym S)
include H
lemma sym (x y : M) : (I (S x y)).unop = S y x := H x y
lemma is_refl : refl_sesq_form.is_refl S := λ x y H1, by { rw [←H], simp [H1], }
lemma ortho_sym {x y : M} :
is_ortho S x y ↔ is_ortho S y x := refl_sesq_form.ortho_sym (is_refl H)
end sym_sesq_form
namespace alt_sesq_form
open alt_sesq_form sesq_form
variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M]
variables {I : R ≃+* Rᵒᵖ} {S : sesq_form R M I}
/-- The proposition that a sesquilinear form is alternating -/
def is_alt (S : sesq_form R M I) : Prop := ∀ (x : M), S x x = 0
variable (H : is_alt S)
include H
lemma self_eq_zero (x : M) : S x x = 0 := H x
lemma neg (x y : M) :
- S x y = S y x :=
begin
have H1 : S (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_sesq_form
|
26cdc1737653f2bf292293d092074345d764d308 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/data/semiquot.lean | d0f35d73ca8288fa91d6717e342a384d4d687495 | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 7,947 | 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.set.lattice
/-! # Semiquotients
A data type for semiquotients, which are classically equivalent to
nonempty sets, but are useful for programming; the idea is that
a semiquotient set `S` represents some (particular but unknown)
element of `S`. This can be used to model nondeterministic functions,
which return something in a range of values (represented by the
predicate `S`) but are not completely determined.
-/
/-- A member of `semiquot α` is classically a nonempty `set α`,
and in the VM is represented by an element of `α`; the relation
between these is that the VM element is required to be a member
of the set `s`. The specific element of `s` that the VM computes
is hidden by a quotient construction, allowing for the representation
of nondeterministic functions. -/
structure {u} semiquot (α : Type*) := mk' ::
(s : set α)
(val : trunc ↥s)
namespace semiquot
variables {α : Type*} {β : Type*}
instance : has_mem α (semiquot α) := ⟨λ a q, a ∈ q.s⟩
/-- Construct a `semiquot α` from `h : a ∈ s` where `s : set α`. -/
def mk {a : α} {s : set α} (h : a ∈ s) : semiquot α :=
⟨s, trunc.mk ⟨a, h⟩⟩
theorem ext_s {q₁ q₂ : semiquot α} : q₁ = q₂ ↔ q₁.s = q₂.s :=
⟨congr_arg _,
λ h, by cases q₁; cases q₂; congr; exact h⟩
theorem ext {q₁ q₂ : semiquot α} : q₁ = q₂ ↔ ∀ a, a ∈ q₁ ↔ a ∈ q₂ :=
ext_s.trans set.ext_iff
theorem exists_mem (q : semiquot α) : ∃ a, a ∈ q :=
let ⟨⟨a, h⟩, h₂⟩ := q.2.exists_rep in ⟨a, h⟩
theorem eq_mk_of_mem {q : semiquot α} {a : α} (h : a ∈ q) :
q = @mk _ a q.1 h := ext_s.2 rfl
theorem nonempty (q : semiquot α) : q.s.nonempty := q.exists_mem
/-- `pure a` is `a` reinterpreted as an unspecified element of `{a}`. -/
protected def pure (a : α) : semiquot α := mk (set.mem_singleton a)
@[simp] theorem mem_pure' {a b : α} : a ∈ semiquot.pure b ↔ a = b :=
set.mem_singleton_iff
/-- Replace `s` in a `semiquot` with a superset. -/
def blur' (q : semiquot α) {s : set α} (h : q.s ⊆ s) : semiquot α :=
⟨s, trunc.lift (λ a : q.s, trunc.mk ⟨a.1, h a.2⟩)
(λ _ _, trunc.eq _ _) q.2⟩
/-- Replace `s` in a `q : semiquot α` with a union `s ∪ q.s` -/
def blur (s : set α) (q : semiquot α) : semiquot α :=
blur' q (set.subset_union_right s q.s)
theorem blur_eq_blur' (q : semiquot α) (s : set α) (h : q.s ⊆ s) :
blur s q = blur' q h :=
by unfold blur; congr; exact set.union_eq_self_of_subset_right h
@[simp] theorem mem_blur' (q : semiquot α) {s : set α} (h : q.s ⊆ s)
{a : α} : a ∈ blur' q h ↔ a ∈ s := iff.rfl
/-- Convert a `trunc α` to a `semiquot α`. -/
def of_trunc (q : trunc α) : semiquot α :=
⟨set.univ, q.map (λ a, ⟨a, trivial⟩)⟩
/-- Convert a `semiquot α` to a `trunc α`. -/
def to_trunc (q : semiquot α) : trunc α :=
q.2.map subtype.val
/-- If `f` is a constant on `q.s`, then `q.lift_on f` is the value of `f`
at any point of `q`. -/
def lift_on (q : semiquot α) (f : α → β) (h : ∀ a b ∈ q, f a = f b) : β :=
trunc.lift_on q.2 (λ x, f x.1) (λ x y, h _ _ x.2 y.2)
theorem lift_on_of_mem (q : semiquot α)
(f : α → β) (h : ∀ a b ∈ q, f a = f b)
(a : α) (aq : a ∈ q) : lift_on q f h = f a :=
by revert h; rw eq_mk_of_mem aq; intro; refl
/-- Apply a function to the unknown value stored in a `semiquot α`. -/
def map (f : α → β) (q : semiquot α) : semiquot β :=
⟨f '' q.1, q.2.map (λ x, ⟨f x.1, set.mem_image_of_mem _ x.2⟩)⟩
@[simp] theorem mem_map (f : α → β) (q : semiquot α) (b : β) :
b ∈ map f q ↔ ∃ a, a ∈ q ∧ f a = b := set.mem_image _ _ _
/-- Apply a function returning a `semiquot` to a `semiquot`. -/
def bind (q : semiquot α) (f : α → semiquot β) : semiquot β :=
⟨⋃ a ∈ q.1, (f a).1,
q.2.bind (λ a, (f a.1).2.map (λ b, ⟨b.1, set.mem_bUnion a.2 b.2⟩))⟩
@[simp] theorem mem_bind (q : semiquot α) (f : α → semiquot β) (b : β) :
b ∈ bind q f ↔ ∃ a ∈ q, b ∈ f a := set.mem_bUnion_iff
instance : monad semiquot :=
{ pure := @semiquot.pure,
map := @semiquot.map,
bind := @semiquot.bind }
@[simp] lemma map_def {β} : ((<$>) : (α → β) → semiquot α → semiquot β) = map := rfl
@[simp] lemma bind_def {β} : ((>>=) : semiquot α → (α → semiquot β) → semiquot β) = bind := rfl
@[simp] theorem mem_pure {a b : α} : a ∈ (pure b : semiquot α) ↔ a = b :=
set.mem_singleton_iff
theorem mem_pure_self (a : α) : a ∈ (pure a : semiquot α) :=
set.mem_singleton a
@[simp] theorem pure_inj {a b : α} : (pure a : semiquot α) = pure b ↔ a = b :=
ext_s.trans set.singleton_eq_singleton_iff
instance : is_lawful_monad semiquot :=
{ pure_bind := λ α β x f, ext.2 $ by simp,
bind_assoc := λ α β γ s f g, ext.2 $ by simp; exact
λ c, ⟨λ ⟨b, ⟨a, as, bf⟩, cg⟩, ⟨a, as, b, bf, cg⟩,
λ ⟨a, as, b, bf, cg⟩, ⟨b, ⟨a, as, bf⟩, cg⟩⟩,
id_map := λ α q, ext.2 $ by simp,
bind_pure_comp_eq_map := λ α β f s, ext.2 $ by simp [eq_comm] }
instance : has_le (semiquot α) := ⟨λ s t, s.s ⊆ t.s⟩
instance : partial_order (semiquot α) :=
{ le := λ s t, ∀ ⦃x⦄, x ∈ s → x ∈ t,
le_refl := λ s, set.subset.refl _,
le_trans := λ s t u, set.subset.trans,
le_antisymm := λ s t h₁ h₂, ext_s.2 (set.subset.antisymm h₁ h₂) }
instance : semilattice_sup (semiquot α) :=
{ sup := λ s, blur s.s,
le_sup_left := λ s t, set.subset_union_left _ _,
le_sup_right := λ s t, set.subset_union_right _ _,
sup_le := λ s t u, set.union_subset,
..semiquot.partial_order }
@[simp] theorem pure_le {a : α} {s : semiquot α} : pure a ≤ s ↔ a ∈ s :=
set.singleton_subset_iff
/-- Assert that a `semiquot` contains only one possible value. -/
def is_pure (q : semiquot α) : Prop := ∀ a b ∈ q, a = b
/-- Extract the value from a `is_pure` semiquotient. -/
def get (q : semiquot α) (h : q.is_pure) : α := lift_on q id h
theorem get_mem {q : semiquot α} (p) : get q p ∈ q :=
let ⟨a, h⟩ := exists_mem q in
by unfold get; rw lift_on_of_mem q _ _ a h; exact h
theorem eq_pure {q : semiquot α} (p) : q = pure (get q p) :=
ext.2 $ λ a, by simp; exact
⟨λ h, p _ _ h (get_mem _), λ e, e.symm ▸ get_mem _⟩
@[simp] theorem pure_is_pure (a : α) : is_pure (pure a)
| b c ab ac := by { simp at ab ac, cc }
theorem is_pure_iff {s : semiquot α} : is_pure s ↔ ∃ a, s = pure a :=
⟨λ h, ⟨_, eq_pure h⟩, λ ⟨a, e⟩, e.symm ▸ pure_is_pure _⟩
theorem is_pure.mono {s t : semiquot α}
(st : s ≤ t) (h : is_pure t) : is_pure s
| a b as bs := h _ _ (st as) (st bs)
theorem is_pure.min {s t : semiquot α} (h : is_pure t) : s ≤ t ↔ s = t :=
⟨λ st, le_antisymm st $ by rw [eq_pure h, eq_pure (h.mono st)]; simp;
exact h _ _ (get_mem _) (st $ get_mem _),
le_of_eq⟩
theorem is_pure_of_subsingleton [subsingleton α] (q : semiquot α) : is_pure q
| a b aq bq := subsingleton.elim _ _
/-- `univ : semiquot α` represents an unspecified element of `univ : set α`. -/
def univ [inhabited α] : semiquot α :=
mk $ set.mem_univ (default _)
instance [inhabited α] : inhabited (semiquot α) := ⟨univ⟩
@[simp] theorem mem_univ [inhabited α] : ∀ a, a ∈ @univ α _ :=
@set.mem_univ α
@[congr] theorem univ_unique (I J : inhabited α) : @univ _ I = @univ _ J :=
ext.2 $ by simp
@[simp] theorem is_pure_univ [inhabited α] : @is_pure α univ ↔ subsingleton α :=
⟨λ h, ⟨λ a b, h a b trivial trivial⟩, λ ⟨h⟩ a b _ _, h a b⟩
instance [inhabited α] : order_top (semiquot α) :=
{ top := univ,
le_top := λ s, set.subset_univ _,
..semiquot.partial_order }
instance [inhabited α] : semilattice_sup_top (semiquot α) :=
{ ..semiquot.order_top,
..semiquot.semilattice_sup }
end semiquot
|
c1a95c899cdcd295a436472a204d80ac9cbc8db8 | a1179fa077c09acc49e4fbc8d67084ba89ac4f4c | /tutorials/src/exercises/05_sequence_limits.lean | 487e9005b369ebcabc8acb2e4e321b00f1482130 | [] | no_license | Seeram/Lean-proof-assistant | 11ca0ca0e0446bacdd1773c4c481a3653b2f1074 | e672d46e0e5f39d8de2933ad4f4cac095ca6094f | refs/heads/master | 1,682,754,224,366 | 1,620,959,431,000 | 1,620,959,431,000 | 299,000,950 | 0 | 1 | null | 1,620,680,462,000 | 1,601,200,258,000 | Lean | UTF-8 | Lean | false | false | 5,889 | lean | import data.real.basic
import algebra.group.pi
import tuto_lib
notation `|`x`|` := abs x
/-
In this file we manipulate the elementary definition of limits of
sequences of real numbers.
mathlib has a much more general definition of limits, but here
we want to practice using the logical operators and relations
covered in the previous files.
A sequence u is a function from ℕ to ℝ, hence Lean says
u : ℕ → ℝ
The definition we'll be using is:
-- Definition of « u tends to l »
def seq_limit (u : ℕ → ℝ) (l : ℝ) : Prop :=
∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - l| ≤ ε
Note the use of `∀ ε > 0, ...` which is an abbreviation of
`∀ ε, ε > 0 → ... `
In particular, a statement like `h : ∀ ε > 0, ...`
can be specialized to a given ε₀ by
`specialize h ε₀ hε₀`
where hε₀ is a proof of ε₀ > 0.
Also recall that, wherever Lean expects some proof term, we can
start a tactic mode proof using the keyword `by` (followed by curly braces
if you need more than one tactic invocation).
For instance, if the local context contains:
δ : ℝ
δ_pos : δ > 0
h : ∀ ε > 0, ...
then we can specialize h to the real number δ/2 using:
`specialize h (δ/2) (by linarith)`
where `by linarith` will provide the proof of `δ/2 > 0` expected by Lean.
We'll take this opportunity to use two new tactics:
`norm_num` will perform numerical normalization on the goal and `norm_num at h`
will do the same in assumption `h`. This will get rid of trivial calculations on numbers,
like replacing |l - l| by zero in the next exercise.
`congr'` will try to prove equalities between applications of functions by recursively
proving the arguments are the same.
For instance, if the goal is `f x + g y = f z + g t` then congr will replace it by
two goals: `x = z` and `y = t`.
You can limit the recursion depth by specifying a natural number after `congr'`.
For instance, in the above example, `congr' 1` will give new goals
`f x = f z` and `g y = g t`, which only inspect arguments of the addition and not deeper.
-/
variables (u v w : ℕ → ℝ) (l l' : ℝ)
-- If u is constant with value l then u tends to l
-- 0033
example : (∀ n, u n = l) → seq_limit u l :=
begin
sorry
end
/- When dealing with absolute values, we'll use lemmas:
abs_le (x y : ℝ) : |x| ≤ y ↔ -y ≤ x ∧ x ≤ y
abs_add (x y : ℝ) : |x + y| ≤ |x| + |y|
abs_sub (x y : ℝ) : |x - y| = |y - x|
You should probably write them down on a sheet of paper that you keep at
hand since they are used in many exercises.
-/
-- Assume l > 0. Then u tends to l implies u n ≥ l/2 for large enough n
-- 0034
example (hl : l > 0) : seq_limit u l → ∃ N, ∀ n ≥ N, u n ≥ l/2 :=
begin
sorry
end
/-
When dealing with max, you can use
ge_max_iff (p q r) : r ≥ max p q ↔ r ≥ p ∧ r ≥ q
le_max_left p q : p ≤ max p q
le_max_right p q : q ≤ max p q
You should probably add them to the sheet of paper where you wrote
the `abs` lemmas since they are used in many exercises.
Let's see an example.
-/
-- If u tends to l and v tends l' then u+v tends to l+l'
example (hu : seq_limit u l) (hv : seq_limit v l') :
seq_limit (u + v) (l + l') :=
begin
intros ε ε_pos,
cases hu (ε/2) (by linarith) with N₁ hN₁,
cases hv (ε/2) (by linarith) with N₂ hN₂,
use max N₁ N₂,
intros n hn,
cases ge_max_iff.mp hn with hn₁ hn₂,
have fact₁ : |u n - l| ≤ ε/2,
from hN₁ n (by linarith), -- note the use of `from`.
-- This is an alias for `exact`,
-- but reads nicer in this context
have fact₂ : |v n - l'| ≤ ε/2,
from hN₂ n (by linarith),
calc
|(u + v) n - (l + l')| = |u n + v n - (l + l')| : rfl
... = |(u n - l) + (v n - l')| : by congr' 1 ; ring
... ≤ |u n - l| + |v n - l'| : by apply abs_add
... ≤ ε : by linarith,
end
/-
In the above proof, we used `have` to prepare facts for `linarith` consumption in the last line.
Since we have direct proof terms for them, we can feed them directly to `linarith` as in the next proof
of the same statement.
Another variation we introduce is rewriting using `ge_max_iff` and letting `linarith` handle the
conjunction, instead of creating two new assumptions.
-/
example (hu : seq_limit u l) (hv : seq_limit v l') :
seq_limit (u + v) (l + l') :=
begin
intros ε ε_pos,
cases hu (ε/2) (by linarith) with N₁ hN₁,
cases hv (ε/2) (by linarith) with N₂ hN₂,
use max N₁ N₂,
intros n hn,
rw ge_max_iff at hn,
calc
|(u + v) n - (l + l')| = |u n + v n - (l + l')| : rfl
... = |(u n - l) + (v n - l')| : by congr' 1 ; ring
... ≤ |u n - l| + |v n - l'| : by apply abs_add
... ≤ ε : by linarith [hN₁ n (by linarith), hN₂ n (by linarith)],
end
/- Let's do something similar: the squeezing theorem. -/
-- 0035
example (hu : seq_limit u l) (hw : seq_limit w l)
(h : ∀ n, u n ≤ v n)
(h' : ∀ n, v n ≤ w n) : seq_limit v l :=
begin
sorry
end
/- What about < ε? -/
-- 0036
example (u l) : seq_limit u l ↔
∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - l| < ε :=
begin
sorry
end
/- In the next exercise, we'll use
eq_of_abs_sub_le_all (x y : ℝ) : (∀ ε > 0, |x - y| ≤ ε) → x = y
-/
-- A sequence admits at most one limit
-- 0037
example : seq_limit u l → seq_limit u l' → l = l' :=
begin
sorry
end
/-
Let's now practice deciphering definitions before proving.
-/
def non_decreasing (u : ℕ → ℝ) := ∀ n m, n ≤ m → u n ≤ u m
def is_seq_sup (M : ℝ) (u : ℕ → ℝ) :=
(∀ n, u n ≤ M) ∧ ∀ ε > 0, ∃ n₀, u n₀ ≥ M - ε
-- 0038
example (M : ℝ) (h : is_seq_sup M u) (h' : non_decreasing u) :
seq_limit u M :=
begin
sorry
end
|
91d5c8dc34fb4efa5b6ecc994a3292d3d622ce0f | d1a52c3f208fa42c41df8278c3d280f075eb020c | /src/Init/WF.lean | ab339d377b80e8316c5ec8192e98b617d025b956 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | cipher1024/lean4 | 6e1f98bb58e7a92b28f5364eb38a14c8d0aae393 | 69114d3b50806264ef35b57394391c3e738a9822 | refs/heads/master | 1,642,227,983,603 | 1,642,011,696,000 | 1,642,011,696,000 | 228,607,691 | 0 | 0 | Apache-2.0 | 1,576,584,269,000 | 1,576,584,268,000 | null | UTF-8 | Lean | false | false | 10,932 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import Init.SizeOf
import Init.Data.Nat.Basic
universe u v
set_option codegen false
inductive Acc {α : Sort u} (r : α → α → Prop) : α → Prop where
| intro (x : α) (h : (y : α) → r y x → Acc r y) : Acc r x
abbrev Acc.ndrec.{u1, u2} {α : Sort u2} {r : α → α → Prop} {C : α → Sort u1}
(m : (x : α) → ((y : α) → r y x → Acc r y) → ((y : α) → (a : r y x) → C y) → C x)
{a : α} (n : Acc r a) : C a :=
Acc.rec (motive := fun α _ => C α) m n
abbrev Acc.ndrecOn.{u1, u2} {α : Sort u2} {r : α → α → Prop} {C : α → Sort u1}
{a : α} (n : Acc r a)
(m : (x : α) → ((y : α) → r y x → Acc r y) → ((y : α) → (a : r y x) → C y) → C x)
: C a :=
Acc.rec (motive := fun α _ => C α) m n
namespace Acc
variable {α : Sort u} {r : α → α → Prop}
def inv {x y : α} (h₁ : Acc r x) (h₂ : r y x) : Acc r y :=
Acc.recOn (motive := fun (x : α) _ => r y x → Acc r y)
h₁ (fun x₁ ac₁ ih h₂ => ac₁ y h₂) h₂
end Acc
inductive WellFounded {α : Sort u} (r : α → α → Prop) : Prop where
| intro (h : ∀ a, Acc r a) : WellFounded r
structure WellFoundedRelation (α : Sort u) where
rel : α → α → Prop
wf : WellFounded rel
namespace WellFounded
def apply {α : Sort u} {r : α → α → Prop} (wf : WellFounded r) (a : α) : Acc r a :=
WellFounded.recOn (motive := fun x => (y : α) → Acc r y)
wf (fun p => p) a
section
variable {α : Sort u} {r : α → α → Prop} (hwf : WellFounded r)
theorem recursion {C : α → Sort v} (a : α) (h : ∀ x, (∀ y, r y x → C y) → C x) : C a := by
induction (apply hwf a) with
| intro x₁ ac₁ ih => exact h x₁ ih
theorem induction {C : α → Prop} (a : α) (h : ∀ x, (∀ y, r y x → C y) → C x) : C a :=
recursion hwf a h
variable {C : α → Sort v}
variable (F : ∀ x, (∀ y, r y x → C y) → C x)
def fixF (x : α) (a : Acc r x) : C x := by
induction a with
| intro x₁ ac₁ ih => exact F x₁ ih
def fixFEq (x : α) (acx : Acc r x) : fixF F x acx = F x (fun (y : α) (p : r y x) => fixF F y (Acc.inv acx p)) := by
induction acx with
| intro x r ih => exact rfl
end
variable {α : Sort u} {C : α → Sort v} {r : α → α → Prop}
-- Well-founded fixpoint
def fix (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) : C x :=
fixF F x (apply hwf x)
-- Well-founded fixpoint satisfies fixpoint equation
theorem fix_eq (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) :
fix hwf F x = F x (fun y h => fix hwf F y) :=
fixFEq F x (apply hwf x)
end WellFounded
open WellFounded
-- Empty relation is well-founded
def emptyWf {α : Sort u} : WellFoundedRelation α where
rel := emptyRelation
wf := by
apply WellFounded.intro
intro a
apply Acc.intro a
intro b h
cases h
-- Subrelation of a well-founded relation is well-founded
namespace Subrelation
variable {α : Sort u} {r q : α → α → Prop}
def accessible {a : α} (h₁ : Subrelation q r) (ac : Acc r a) : Acc q a := by
induction ac with
| intro x ax ih =>
apply Acc.intro
intro y h
exact ih y (h₁ h)
def wf (h₁ : Subrelation q r) (h₂ : WellFounded r) : WellFounded q :=
⟨fun a => accessible @h₁ (apply h₂ a)⟩
end Subrelation
-- The inverse image of a well-founded relation is well-founded
namespace InvImage
variable {α : Sort u} {β : Sort v} {r : β → β → Prop}
private def accAux (f : α → β) {b : β} (ac : Acc r b) : (x : α) → f x = b → Acc (InvImage r f) x := by
induction ac with
| intro x acx ih =>
intro z e
apply Acc.intro
intro y lt
subst x
apply ih (f y) lt y rfl
def accessible {a : α} (f : α → β) (ac : Acc r (f a)) : Acc (InvImage r f) a :=
accAux f ac a rfl
def wf (f : α → β) (h : WellFounded r) : WellFounded (InvImage r f) :=
⟨fun a => accessible f (apply h (f a))⟩
end InvImage
def invImage (f : α → β) (h : WellFoundedRelation β) : WellFoundedRelation α where
rel := InvImage h.rel f
wf := InvImage.wf f h.wf
-- The transitive closure of a well-founded relation is well-founded
namespace TC
variable {α : Sort u} {r : α → α → Prop}
def accessible {z : α} (ac : Acc r z) : Acc (TC r) z := by
induction ac with
| intro x acx ih =>
apply Acc.intro x
intro y rel
induction rel with
| base a b rab => exact ih a rab
| trans a b c rab rbc ih₁ ih₂ => apply Acc.inv (ih₂ acx ih) rab
def wf (h : WellFounded r) : WellFounded (TC r) :=
⟨fun a => accessible (apply h a)⟩
end TC
-- less-than is well-founded
def Nat.lt_wfRel : WellFoundedRelation Nat where
rel := Nat.lt
wf := by
apply WellFounded.intro
intro n
induction n with
| zero =>
apply Acc.intro 0
intro _ h
apply absurd h (Nat.not_lt_zero _)
| succ n ih =>
apply Acc.intro (Nat.succ n)
intro m h
have : m = n ∨ m < n := Nat.eq_or_lt_of_le (Nat.le_of_succ_le_succ h)
match this with
| Or.inl e => subst e; assumption
| Or.inr e => exact Acc.inv ih e
def Measure {α : Sort u} : (α → Nat) → α → α → Prop :=
InvImage (fun a b => a < b)
def measure {α : Sort u} (f : α → Nat) : WellFoundedRelation α :=
invImage f Nat.lt_wfRel
def SizeOfRef (α : Sort u) [SizeOf α] : α → α → Prop :=
Measure sizeOf
def sizeOfWFRel {α : Sort u} [SizeOf α] : WellFoundedRelation α :=
measure sizeOf
namespace Prod
open WellFounded
section
variable {α : Type u} {β : Type v}
variable (ra : α → α → Prop)
variable (rb : β → β → Prop)
-- Lexicographical order based on ra and rb
inductive Lex : α × β → α × β → Prop where
| left {a₁} (b₁) {a₂} (b₂) (h : ra a₁ a₂) : Lex (a₁, b₁) (a₂, b₂)
| right (a) {b₁ b₂} (h : rb b₁ b₂) : Lex (a, b₁) (a, b₂)
-- relational product based on ra and rb
inductive RProd : α × β → α × β → Prop where
| intro {a₁ b₁ a₂ b₂} (h₁ : ra a₁ a₂) (h₂ : rb b₁ b₂) : RProd (a₁, b₁) (a₂, b₂)
end
section
variable {α : Type u} {β : Type v}
variable {ra : α → α → Prop} {rb : β → β → Prop}
def lexAccessible (aca : (a : α) → Acc ra a) (acb : (b : β) → Acc rb b) (a : α) (b : β) : Acc (Lex ra rb) (a, b) := by
induction (aca a) generalizing b with
| intro xa aca iha =>
induction (acb b) with
| intro xb acb ihb =>
apply Acc.intro (xa, xb)
intro p lt
cases lt with
| left _ _ h => apply iha _ h
| right _ h => apply ihb _ h
-- The lexicographical order of well founded relations is well-founded
def lex (ha : WellFoundedRelation α) (hb : WellFoundedRelation β) : WellFoundedRelation (α × β) where
rel := Lex ha.rel hb.rel
wf := ⟨fun (a, b) => lexAccessible (WellFounded.apply ha.wf) (WellFounded.apply hb.wf) a b⟩
-- relational product is a Subrelation of the Lex
def RProdSubLex (a : α × β) (b : α × β) (h : RProd ra rb a b) : Lex ra rb a b := by
cases h with
| intro h₁ h₂ => exact Lex.left _ _ h₁
-- The relational product of well founded relations is well-founded
def rprod (ha : WellFoundedRelation α) (hb : WellFoundedRelation β) : WellFoundedRelation (α × β) where
rel := RProd ha.rel hb.rel
wf := by
apply Subrelation.wf (r := Lex ha.rel hb.rel) (h₂ := (lex ha hb).wf)
intro a b h
exact RProdSubLex a b h
end
end Prod
namespace PSigma
section
variable {α : Sort u} {β : α → Sort v}
variable (r : α → α → Prop)
variable (s : ∀ a, β a → β a → Prop)
-- Lexicographical order based on r and s
inductive Lex : PSigma β → PSigma β → Prop where
| left : ∀ {a₁ : α} (b₁ : β a₁) {a₂ : α} (b₂ : β a₂), r a₁ a₂ → Lex ⟨a₁, b₁⟩ ⟨a₂, b₂⟩
| right : ∀ (a : α) {b₁ b₂ : β a}, s a b₁ b₂ → Lex ⟨a, b₁⟩ ⟨a, b₂⟩
end
section
variable {α : Sort u} {β : α → Sort v}
variable {r : α → α → Prop} {s : ∀ (a : α), β a → β a → Prop}
def lexAccessible {a} (aca : Acc r a) (acb : (a : α) → WellFounded (s a)) (b : β a) : Acc (Lex r s) ⟨a, b⟩ := by
induction aca with
| intro xa aca iha =>
induction (WellFounded.apply (acb xa) b) with
| intro xb acb ihb =>
apply Acc.intro
intro p lt
cases lt with
| left => apply iha; assumption
| right => apply ihb; assumption
-- The lexicographical order of well founded relations is well-founded
def lex (ha : WellFounded r) (hb : (x : α) → WellFounded (s x)) : WellFounded (Lex r s) :=
WellFounded.intro fun ⟨a, b⟩ => lexAccessible (WellFounded.apply ha a) hb b
end
section
variable {α : Sort u} {β : Sort v}
def lexNdep (r : α → α → Prop) (s : β → β → Prop) :=
Lex r (fun a => s)
def lexNdepWf {r : α → α → Prop} {s : β → β → Prop} (ha : WellFounded r) (hb : WellFounded s) : WellFounded (lexNdep r s) :=
WellFounded.intro fun ⟨a, b⟩ => lexAccessible (WellFounded.apply ha a) (fun x => hb) b
end
section
variable {α : Sort u} {β : Sort v}
-- Reverse lexicographical order based on r and s
inductive RevLex (r : α → α → Prop) (s : β → β → Prop) : @PSigma α (fun a => β) → @PSigma α (fun a => β) → Prop where
| left : {a₁ a₂ : α} → (b : β) → r a₁ a₂ → RevLex r s ⟨a₁, b⟩ ⟨a₂, b⟩
| right : (a₁ : α) → {b₁ : β} → (a₂ : α) → {b₂ : β} → s b₁ b₂ → RevLex r s ⟨a₁, b₁⟩ ⟨a₂, b₂⟩
end
section
open WellFounded
variable {α : Sort u} {β : Sort v}
variable {r : α → α → Prop} {s : β → β → Prop}
def revLexAccessible {b} (acb : Acc s b) (aca : (a : α) → Acc r a): (a : α) → Acc (RevLex r s) ⟨a, b⟩ := by
induction acb with
| intro xb acb ihb =>
intro a
induction (aca a) with
| intro xa aca iha =>
apply Acc.intro
intro p lt
cases lt with
| left => apply iha; assumption
| right => apply ihb; assumption
def revLex (ha : WellFounded r) (hb : WellFounded s) : WellFounded (RevLex r s) :=
WellFounded.intro fun ⟨a, b⟩ => revLexAccessible (apply hb b) (WellFounded.apply ha) a
end
section
def SkipLeft (α : Type u) {β : Type v} (s : β → β → Prop) : @PSigma α (fun a => β) → @PSigma α (fun a => β) → Prop :=
RevLex emptyRelation s
def skipLeft (α : Type u) {β : Type v} (hb : WellFoundedRelation β) : WellFoundedRelation (PSigma fun a : α => β) where
rel := SkipLeft α hb.rel
wf := revLex emptyWf.wf hb.wf
def mkSkipLeft {α : Type u} {β : Type v} {b₁ b₂ : β} {s : β → β → Prop} (a₁ a₂ : α) (h : s b₁ b₂) : SkipLeft α s ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ :=
RevLex.right _ _ h
end
end PSigma
|
116cf2c023b4e1031850a75ab31cec256a5eb021 | 947b78d97130d56365ae2ec264df196ce769371a | /stage0/src/Lean/Elab/Do.lean | de956aee2bad01c318f1fc7483d0a0655b241355 | [
"Apache-2.0"
] | permissive | shyamalschandra/lean4 | 27044812be8698f0c79147615b1d5090b9f4b037 | 6e7a883b21eaf62831e8111b251dc9b18f40e604 | refs/heads/master | 1,671,417,126,371 | 1,601,859,995,000 | 1,601,860,020,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 30,643 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Elab.Term
import Lean.Elab.Binders
import Lean.Elab.Quotation
import Lean.Elab.Match
namespace Lean
namespace Elab
namespace Term
open Meta
@[builtinTermElab liftMethod] def elabLiftMethod : TermElab :=
fun stx _ =>
throwErrorAt stx "invalid use of `(<- ...)`, must be nested inside a 'do' expression"
private partial def hasLiftMethod : Syntax → Bool
| Syntax.node k args =>
if k == `Lean.Parser.Term.do then false
else if k == `Lean.Parser.Term.quot then false
else if k == `Lean.Parser.Term.liftMethod then true
else args.any hasLiftMethod
| _ => false
structure ExtractMonadResult :=
(m : Expr)
(α : Expr)
(hasBindInst : Expr)
private def mkIdBindFor (type : Expr) : TermElabM ExtractMonadResult := do
u ← getLevel type;
let id := Lean.mkConst `Id [u];
let idBindVal := Lean.mkConst `Id.hasBind [u];
pure { m := id, hasBindInst := idBindVal, α := type }
private def extractBind (expectedType? : Option Expr) : TermElabM ExtractMonadResult := do
match expectedType? with
| none => throwError "invalid do notation, expected type is not available"
| some expectedType => do
type ← withReducible $ whnf expectedType;
when type.getAppFn.isMVar $ throwError "invalid do notation, expected type is not available";
match type with
| Expr.app m α _ =>
catch
(do
bindInstType ← mkAppM `HasBind #[m];
bindInstVal ← synthesizeInst bindInstType;
pure { m := m, hasBindInst := bindInstVal, α := α })
(fun ex => mkIdBindFor type)
| _ => mkIdBindFor type
namespace Do
/- A `doMatch` alternative. `vars` is the array of variables declared by `patterns`. -/
structure Alt (σ : Type) :=
(ref : Syntax) (vars : Array Name) (patterns : Array Syntax) (rhs : σ)
/-
Auxiliary datastructure for representing a `do` code block, and compiling "reassignments" (e.g., `x := x + 1`).
We convert `Code` into a `Syntax` term representing the:
- `do`-block, or
- the visitor argument for the `forIn` combinator.
We say the following constructors are terminals:
- `break`: for interrupting a `for x in s`
- `continue`: for interrupting the current iteration of a `for x in s`
- `return`: returning the result of the computation.
- `ite`: if-then-else
- `match`: pattern matching
- `jmp` a goto to a join-point
We say the terminals `break`, `continue` and `return` are "exit points"
The terminal `return` also contains the name of the variable containing the result of the computation.
We ignore this value when inside a `for x in s`.
- `decl` represents all declaration-like `doElem`s (e.g., `let`, `have`, `let rec`). The field `stx` is the actual `doElem`,
`vars` is the array of variables declared by it, and `cont` is the next instruction in the `do` code block.
`vars` is an array since we have declarations such as `let (a, b) := s`.
- `reassign` is an reassignment-like `doElem` (e.g., `x := x + 1`).
- `jointpoint` is a join point declaration: an auxiliary `let`-declaration used to represent the control-flow.
- `action` is an action-like `doElem` (e.g., `IO.println "hello"`, `dbgTrace! "foo"`).
A code block `C` is well-formed if
- For every `jmp ref j as` in `C`, there is a `jointpoint j ps b k` and `jmp ref j as` is in `k`, and
`ps.size == as.size` -/
inductive Code
| decl (xs : Array Name) (stx : Syntax) (cont : Code)
| reassign (xs : Array Name) (stx : Syntax) (cont : Code)
| jointpoint (name : Name) (params : Array Name) (body : Code) (cont : Code)
| action (stx : Syntax) (cond : Code)
| «break» (ref : Syntax)
| «continue» (ref : Syntax)
| «return» (ref : Syntax) (x? : Option Name)
/- Recall that an if-then-else may declare a variable using `optIdent` for the branches `thenBranch` and `elseBranch`. We store the variable name at `var?`. -/
| ite (ref : Syntax) (h? : Option Name) (optIdent : Syntax) (cond : Syntax) (thenBranch : Code) (elseBranch : Code)
| «match» (ref : Syntax) (discrs : Array Syntax) (type? : Option Syntax) (alts : Array (Alt Code))
| jmp (ref : Syntax) (jpName : Name) (args : Array Name)
instance Code.inhabited : Inhabited Code :=
⟨Code.«break» (arbitrary _)⟩
instance Alt.inhabited : Inhabited (Alt Code) :=
⟨{ ref := arbitrary _, vars := #[], patterns := #[], rhs := arbitrary _ }⟩
/- A code block, and the collection of variables updated by it. -/
structure CodeBlock :=
(code : Code)
(uvars : NameSet := {}) -- set of variables updated by `code`
private def varsToMessageData (vars : Array Name) : MessageData :=
MessageData.joinSep (vars.toList.map fun n => MessageData.ofName (n.simpMacroScopes)) " "
partial def toMessageDataAux (updateVars : MessageData) : Code → MessageData
| Code.decl xs _ k => "let " ++ varsToMessageData xs ++ " := ... " ++ Format.line ++ toMessageDataAux k
| Code.reassign xs _ k => varsToMessageData xs ++ " := ... " ++ Format.line ++ toMessageDataAux k
| Code.jointpoint n ps body k =>
"let " ++ n.simpMacroScopes ++ " " ++ varsToMessageData ps ++ " := " ++ indentD (toMessageDataAux body)
++ Format.line ++ toMessageDataAux k
| Code.action e k => e ++ Format.line ++ toMessageDataAux k
| Code.ite _ _ _ c t e => "if " ++ c ++ " then " ++ indentD (toMessageDataAux t) ++ Format.line ++ "else " ++ indentD (toMessageDataAux e)
| Code.jmp _ j xs => "jmp " ++ j.simpMacroScopes ++ " " ++ toString xs.toList
| Code.«break» _ => "break " ++ updateVars
| Code.«continue» _ => "continue " ++ updateVars
| Code.«return» _ none => "return " ++ updateVars
| Code.«return» _ (some x) => "return " ++ x.simpMacroScopes ++ " " ++ updateVars
| Code.«match» _ ds t alts =>
"match " ++ MessageData.joinSep (ds.toList.map MessageData.ofSyntax) ", " ++ " with " ++
alts.foldl
(fun (acc : MessageData) (alt : Alt Code) =>
acc ++ Format.line ++ "| "
++ MessageData.joinSep (alt.patterns.toList.map MessageData.ofSyntax) ", "
++ " => " ++ toMessageDataAux alt.rhs)
Format.nil
private def nameSetToArray (s : NameSet) : Array Name :=
s.fold (fun (xs : Array Name) x => xs.push x) #[]
def CodeBlock.toMessageData (c : CodeBlock) : MessageData :=
let us := (nameSetToArray c.uvars).toList.map MessageData.ofName;
toMessageDataAux (MessageData.ofList us) c.code
partial def hasExitPoint : Code → Bool
| Code.decl _ _ k => hasExitPoint k
| Code.reassign _ _ k => hasExitPoint k
| Code.jointpoint _ _ b k => hasExitPoint b || hasExitPoint k
| Code.action _ k => hasExitPoint k
| Code.ite _ _ _ _ t e => hasExitPoint t || hasExitPoint e
| Code.jmp _ _ _ => false
| Code.«break» _ => true
| Code.«continue» _ => true
| Code.«return» _ _ => true
| Code.«match» _ _ _ alts => alts.any fun alt => hasExitPoint alt.rhs
partial def convertReturnIntoJmpAux (jp : Name) (xs : Array Name) : Code → Code
| Code.decl xs stx k => Code.decl xs stx $ convertReturnIntoJmpAux k
| Code.reassign xs stx k => Code.reassign xs stx $ convertReturnIntoJmpAux k
| Code.jointpoint n ps b k => Code.jointpoint n ps (convertReturnIntoJmpAux b) (convertReturnIntoJmpAux k)
| Code.action e k => Code.action e $ convertReturnIntoJmpAux k
| Code.ite ref x? h c t e => Code.ite ref x? h c (convertReturnIntoJmpAux t) (convertReturnIntoJmpAux e)
| Code.«match» ref ds t alts => Code.«match» ref ds t $ alts.map fun alt => { alt with rhs := convertReturnIntoJmpAux alt.rhs }
| Code.«return» ref _ => Code.jmp ref jp xs
| c => c
/- Convert `return _ x` instructions in `c` into `jmp _ jp xs`. -/
def convertReturnIntoJmp (c : Code) (jp : Name) (xs : Array Name) : Code :=
convertReturnIntoJmpAux jp xs c
structure JPDecl :=
(name : Name) (params : Array Name) (body : Code)
def attachJP (jpDecl : JPDecl) (k : Code) : Code :=
Code.jointpoint jpDecl.name jpDecl.params jpDecl.body k
def attachJPs (jpDecls : Array JPDecl) (k : Code) : Code :=
jpDecls.foldr attachJP k
def mkFreshJP (ps : Array Name) (body : Code) : TermElabM JPDecl := do
name ← mkFreshUserName `jp;
pure { name := name, params := ps, body := body }
def addFreshJP (ps : Array Name) (body : Code) : StateRefT (Array JPDecl) TermElabM Name := do
jp ← liftM $ mkFreshJP ps body;
modify fun (jps : Array JPDecl) => jps.push jp;
pure jp.name
def insertVars (rs : NameSet) (xs : Array Name) : NameSet :=
xs.foldl (fun (rs : NameSet) x => rs.insert x) rs
def eraseVars (rs : NameSet) (xs : Array Name) : NameSet :=
xs.foldl (fun (rs : NameSet) x => rs.erase x) rs
def eraseOptVar (rs : NameSet) (x? : Option Name) : NameSet :=
match x? with
| none => rs
| some x => rs.insert x
/- `pullExitPointsAux rs c` auxiliary method for `pullExitPoints`, `rs` is the set of update variable in the current path. -/
partial def pullExitPointsAux : NameSet → Code → StateRefT (Array JPDecl) TermElabM Code
| rs, Code.decl xs stx k => Code.decl xs stx <$> pullExitPointsAux (eraseVars rs xs) k
| rs, Code.reassign xs stx k => Code.reassign xs stx <$> pullExitPointsAux (insertVars rs xs) k
| rs, Code.jointpoint j ps b k => Code.jointpoint j ps <$> pullExitPointsAux rs b <*> pullExitPointsAux rs k
| rs, Code.action e k => Code.action e <$> pullExitPointsAux rs k
| rs, Code.ite ref x? o c t e => Code.ite ref x? o c <$> pullExitPointsAux (eraseOptVar rs x?) t <*> pullExitPointsAux (eraseOptVar rs x?) e
| rs, Code.«match» ref ds t alts => Code.«match» ref ds t <$> alts.mapM fun alt => do
rhs ← pullExitPointsAux (eraseVars rs alt.vars) alt.rhs; pure { alt with rhs := rhs }
| rs, c@(Code.jmp _ _ _) => pure c
| rs, Code.«break» ref => do let xs := nameSetToArray rs; jp ← addFreshJP xs (Code.«break» ref); pure $ Code.jmp ref jp xs
| rs, Code.«continue» ref => do let xs := nameSetToArray rs; jp ← addFreshJP xs (Code.«continue» ref); pure $ Code.jmp ref jp xs
| rs, Code.«return» ref y? => do
let xs := nameSetToArray rs;
(ps, xs, y?) ← match y? with
| none => pure (xs, xs, none)
| some y =>
if rs.contains y then pure (xs, xs, some y)
else do {
yFresh ← mkFreshUserName y;
pure (xs.push yFresh, xs.push y, some yFresh)
};
jp ← addFreshJP ps (Code.«return» ref y?);
pure $ Code.jmp ref jp xs
/-
Auxiliary operation for adding new variables to `c.uvars` (updated variables).
When a new variable is not already in `c.uvars`, but is shadowed by some declaration in `c.code`,
we create auxiliary join points to make sure we preserve the semantics of the code block.
Example: suppose we have the code block `print x; let x := 10; return x`. And we want to extend it
with the reassignment `x := x + 1`. We first use `pullExitPoints` to create
```
let jp (x!1) := return x!1;
print x;
let x := 10;
jmp jp x
```
and then we add the reassignment
```
x := x + 1
let jp (x!1) := return x!1;
print x;
let x := 10;
jmp jp x
```
Note that we created a fresh variable `x!1` to avoid accidental name capture.
```
print x;
let x := 10
y := y + 1;
return x;
```
We transform it into
```
let jp (y x!1) := return x!1;
print x;
let x := 10
y := y + 1;
jmp jp y x
```
and then we add the reassignment as in the previous example.
We need to include `y` in the jump, because each exit point is implicitly returning the set of
update variables.
We implement the method as follows. Let `us` be `c.uvars`, then
1- for each `return _ y` in `c`, we create a join point
`let j (us y!1) := return y!1`
and replace the `return _ y` with `jmp us y`
2- for each `break`, we create a join point
`let j (us) := break`
and replace the `break` with `jmp us`.
3- Same as 2 for `continue`.
-/
def pullExitPoints (c : Code) : TermElabM Code :=
if hasExitPoint c then do
(c, jpDecls) ← (pullExitPointsAux {} c).run #[];
pure $ attachJPs jpDecls c
else
pure c
partial def extendUpdatedVarsAux (ws : NameSet) : Code → TermElabM Code
| Code.jointpoint j ps b k => Code.jointpoint j ps <$> extendUpdatedVarsAux b <*> extendUpdatedVarsAux k
| Code.action e k => Code.action e <$> extendUpdatedVarsAux k
| c@(Code.«match» ref ds t alts) =>
if alts.any fun alt => alt.vars.any fun x => ws.contains x then
-- If a pattern variable is shadowing a variable in ws, we `pullExitPoints`
pullExitPoints c
else
Code.«match» ref ds t <$> alts.mapM fun alt => do rhs ← extendUpdatedVarsAux alt.rhs; pure { alt with rhs := rhs }
| Code.ite ref none o c t e =>
Code.ite ref none o c <$> extendUpdatedVarsAux t <*> extendUpdatedVarsAux e
| c@(Code.ite ref (some h) o cond t e) =>
if ws.contains h then
-- if the `h` at `if h:c then t else e` shadows a variable in `ws`, we `pullExitPoints`
pullExitPoints c
else
Code.ite ref (some h) o cond <$> extendUpdatedVarsAux t <*> extendUpdatedVarsAux e
| Code.reassign xs stx k => Code.reassign xs stx <$> extendUpdatedVarsAux k
| c@(Code.decl xs stx k) =>
if xs.any fun x => ws.contains x then
-- One the declared variables is shadowing a variable in `ws`
pullExitPoints c
else
Code.decl xs stx <$> extendUpdatedVarsAux k
| c => pure c
/-
Extend the set of updated variables. It assumes `ws` is a super set of `c.uvars`.
We **cannot** simply update the field `c.uvars`, because `c` may have shadowed some variable in `ws`.
See discussion at `pullExitPoints`.
-/
def extendUpdatedVars (c : CodeBlock) (ws : NameSet) : TermElabM CodeBlock :=
if ws.any fun x => !c.uvars.contains x then do
-- `ws` contains a variable that is not in `c.uvars`, but in `c.dvars` (i.e., it has been shadowed)
code ← extendUpdatedVarsAux ws c.code;
pure { code := code, uvars := ws }
else
pure { c with uvars := ws }
private def union (s₁ s₂ : NameSet) : NameSet :=
s₁.fold (fun (s : NameSet) x => s.insert x) s₂
/-
Given two code blocks `c₁` and `c₂`, make sure they have the same set of updated variables.
Let `ws` the union of the updated variables in `c₁‵ and ‵c₂`.
We use `extendUpdatedVars c₁ ws` and `extendUpdatedVars c₂ ws`
-/
def homogenize (c₁ c₂ : CodeBlock) : TermElabM (CodeBlock × CodeBlock) := do
let ws := union c₁.uvars c₂.uvars;
c₁ ← extendUpdatedVars c₁ ws;
c₂ ← extendUpdatedVars c₂ ws;
pure (c₁, c₂)
/-
Extending code blocks with variable declarations: `let x : t := v` and `let x : t ← v`.
We remove `x` from the collection of updated varibles.
Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables
declared by it. It is an array because we have let-declarations that declare multiple variables.
Example: `let (x, y) := t`
-/
def mkVarDeclCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : CodeBlock :=
{ code := Code.decl xs stx c.code, uvars := eraseVars c.uvars xs }
/-
Extending code blocks with reassignments: `x : t := v` and `x : t ← v`.
Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables
declared by it. It is an array because we have let-declarations that declare multiple variables.
Example: `(x, y) ← t`
-/
def mkReassignCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : TermElabM CodeBlock := do
let us := c.uvars;
let ws := insertVars us xs;
-- If `xs` contains a new updated variable, then we must use `extendUpdatedVars`.
-- See discussion at `pullExitPoints`
code ← if xs.any fun x => !us.contains x then extendUpdatedVarsAux ws c.code else pure c.code;
pure { code := Code.reassign xs stx code, uvars := ws }
def mkAction (action : Syntax) (c : CodeBlock) : CodeBlock :=
{ c with code := Code.action action c.code }
def mkReturn (ref : Syntax) (x? : Option Name := none) : CodeBlock :=
{ code := Code.«return» ref x? }
def mkBreak (ref : Syntax) : CodeBlock :=
{ code := Code.«break» ref }
def mkContinue (ref : Syntax) : CodeBlock :=
{ code := Code.«continue» ref }
def mkIte (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : CodeBlock) (elseBranch : CodeBlock) : TermElabM CodeBlock := do
let x? := if optIdent.isNone then none else some (optIdent.getArg 0).getId;
(thenBranch, elseBranch) ← homogenize thenBranch elseBranch;
pure {
code := Code.ite ref x? optIdent cond thenBranch.code elseBranch.code,
uvars := thenBranch.uvars,
}
/- Return a code block that executes `terminal` and then `k`.
This method assumes `terminal` is a terminal -/
def concat (terminal : CodeBlock) (k : CodeBlock) : TermElabM CodeBlock := do
(terminal, k) ← homogenize terminal k;
let xs := nameSetToArray k.uvars;
jpDecl ← mkFreshJP xs k.code;
let jp := jpDecl.name;
pure {
code := attachJP jpDecl (convertReturnIntoJmp terminal.code jp xs),
uvars := terminal.uvars,
}
def mkWhen (ref : Syntax) (cond : Syntax) (c : CodeBlock) : CodeBlock :=
{ c with code := Code.ite ref none mkNullNode cond c.code (Code.«return» ref none) }
def mkUnless (ref : Syntax) (cond : Syntax) (c : CodeBlock) : CodeBlock :=
{ c with code := Code.ite ref none mkNullNode cond (Code.«return» ref none) c.code }
private def getDoSeqElems (doSeq : Syntax) : List Syntax :=
if doSeq.getKind == `Lean.Parser.Term.doSeqBracketed then
(doSeq.getArg 1).getArgs.getSepElems.toList
else
doSeq.getArgs.getSepElems.toList
private def getDoSeq (doStx : Syntax) : Syntax :=
doStx.getArg 1
def getLetIdDeclVar (letIdDecl : Syntax) : Name :=
(letIdDecl.getArg 0).getId
def getLetPatDeclVars (letPatDecl : Syntax) : TermElabM (Array Name) := do
let pattern := letPatDecl.getArg 0;
patternVars ← getPatternVars pattern;
pure $ patternVars.filterMap fun patternVar => match patternVar with
| PatternVar.localVar x => some x
| _ => none
def getLetEqnsDeclVar (letEqnsDecl : Syntax) : Name :=
(letEqnsDecl.getArg 0).getId
def getLetDeclVars (letDecl : Syntax) : TermElabM (Array Name) := do
let arg := letDecl.getArg 0;
if arg.getKind == `Lean.Parser.Term.letIdDecl then
pure #[getLetIdDeclVar arg]
else if arg.getKind == `Lean.Parser.Term.letPatDecl then
getLetPatDeclVars arg
else if arg.getKind == `Lean.Parser.Term.letEqnsDecl then
pure #[getLetEqnsDeclVar arg]
else
throwError "unexpected kind of let declaration"
def getDoLetVars (doLet : Syntax) : TermElabM (Array Name) :=
getLetDeclVars (doLet.getArg 1)
def getDoReassignVars (doReassign : Syntax) : TermElabM (Array Name) := do
let arg := doReassign.getArg 0;
if arg.getKind == `Lean.Parser.Term.letIdDecl then
pure #[getLetIdDeclVar arg]
else if arg.getKind == `Lean.Parser.Term.letPatDecl then
getLetPatDeclVars arg
else
throwError "unexpected kind of reassignment"
namespace ToCodeBlock
structure Context :=
(ref : Syntax)
(varSet : NameSet := {})
(insideFor : Bool := false)
abbrev M := ReaderT Context TermElabM
@[inline] def withNewVars {α} (newVars : Array Name) (x : M α) : M α :=
adaptReader (fun (ctx : Context) => { ctx with varSet := insertVars ctx.varSet newVars }) x
def ensureInsideFor : M Unit := do
ctx ← read;
unless ctx.insideFor $
throwError "invalid statement, can only be used inside 'for ... in ... do ...'"
def ensureEOS (doElems : List Syntax) : M Unit :=
unless doElems.isEmpty $
throwError "must be last element in a 'do' sequence"
def isDoVar? (stx : Syntax) : M (Option Name) := do
if stx.isIdent then do
ctx ← read;
let x := stx.getId;
if ctx.varSet.contains x then pure (some x) else pure none
else
pure none
def checkReassignable (xs : Array Name) : M Unit := do
ctx ← read;
xs.forM fun x =>
unless (ctx.varSet.contains x) do
throwError ("'" ++ x.simpMacroScopes ++ "' cannot be reassigned, it must be declared in the do-block")
partial def doSeqToCode : List Syntax → M CodeBlock
| [] => do ctx ← read; pure $ mkReturn ctx.ref
| doElem::doElems => withRef doElem do
let ref := doElem;
let concatWithRest (c : CodeBlock) : M CodeBlock :=
match doElems with
| [] => pure c
| _ => do {
k ← doSeqToCode doElems;
liftM $ concat c k
};
let k := doElem.getKind;
if k == `Lean.Parser.Term.doLet then do
vars ← liftM $ getDoLetVars doElem;
mkVarDeclCore vars doElem <$> withNewVars vars (doSeqToCode doElems)
else if k == `Lean.Parser.Term.doLetRec then do
throwError "WIP"
else if k == `Lean.Parser.Term.doLetArrow then
throwError "WIP"
else if k == `Lean.Parser.Term.doReassign then do
vars ← liftM $ getDoReassignVars doElem;
checkReassignable vars;
k ← withNewVars vars (doSeqToCode doElems);
liftM $ mkReassignCore vars doElem k
else if k == `Lean.Parser.Term.doReassignArrow then
throwError "WIP"
else if k == `Lean.Parser.Term.doHave then
throwError "WIP"
else if k == `Lean.Parser.Term.doIf then
throwError "WIP"
else if k == `Lean.Parser.Term.doUnless then do
let cond := doElem.getArg 1;
let doSeq := doElem.getArg 3;
body ← doSeqToCode (getDoSeqElems doSeq);
concatWithRest (mkUnless ref cond body)
else if k == `Lean.Parser.Term.doFor then
throwError "WIP"
else if k == `Lean.Parser.Term.doMatch then
throwError "WIP"
else if k == `Lean.Parser.Term.doTry then
throwError "WIP"
else if k == `Lean.Parser.Term.doBreak then do
ensureInsideFor;
ensureEOS doElems;
pure $ mkBreak ref
else if k == `Lean.Parser.Term.doContinue then do
ensureInsideFor;
ensureEOS doElems;
pure $ mkContinue ref
else if k == `Lean.Parser.Term.doReturn then do
ensureEOS doElems;
let argOpt := doElem.getArg 1;
if argOpt.isNone then
pure $ mkReturn ref
else do
let arg := argOpt.getArg 0;
x? ← isDoVar? arg;
match x? with
| some x => pure $ mkReturn ref x
| none => withFreshMacroScope do
auxDo ← `(do let x := $arg; return x);
doSeqToCode $ getDoSeqElems (getDoSeq auxDo)
else if k == `Lean.Parser.Term.doDbgTracethen then
throwError "WIP"
else if k == `Lean.Parser.Term.doAssert then
throwError "WIP"
else if k == `Lean.Parser.Term.doExpr then
let term := doElem.getArg 0;
if doElems.isEmpty then withFreshMacroScope do
auxDo ← `(do let x := $term; return x);
doSeqToCode $ getDoSeqElems (getDoSeq auxDo)
else
mkAction term <$> doSeqToCode doElems
else
throwError "unexpected do-element"
def run (doStx : Syntax) : TermElabM CodeBlock :=
(doSeqToCode $ getDoSeqElems $ getDoSeq doStx).run { ref := doStx }
end ToCodeBlock
private def mkTuple (elems : Array Syntax) : MacroM Syntax :=
if elems.size == 1 then pure (elems.get! 0)
else
(elems.extract 0 (elems.size - 1)).foldrM
(fun elem tuple => `(($elem, $tuple)))
(elems.back)
-- @[builtinTermElab «do»]
def elabDo : TermElab :=
fun stx expectedType? => do
tryPostponeIfNoneOrMVar expectedType?;
bindInfo ← extractBind expectedType?;
codeBlock ← ToCodeBlock.run stx;
throwError ("WIP" ++ Format.line ++ codeBlock.toMessageData)
end Do
----- OLD IMPLEMENTATION -----
private def getDoElems (stx : Syntax) : Array Syntax :=
let arg := stx.getArg 1;
let args := if arg.getKind == `Lean.Parser.Term.doSeqBracketed then
(arg.getArg 1).getArgs
else
arg.getArgs;
if args.back.isToken ";" || args.back.isNone || (args.back.getArg 0).isToken ";" then -- temporary hack
args.pop
else
args
private partial def expandLiftMethodAux : Syntax → StateT (Array Syntax) MacroM Syntax
| stx@(Syntax.node k args) =>
if k == `Lean.Parser.Term.do then pure stx
else if k == `Lean.Parser.Term.quot then pure stx
else if k == `Lean.Parser.Term.liftMethod then withFreshMacroScope $ do
let term := args.get! 1;
term ← expandLiftMethodAux term;
auxDo ← `(do { let a ← $term; $(Syntax.missing) });
let auxDoElems := (getDoElems auxDo).pop;
modify $ fun s => s ++ auxDoElems;
`(a)
else do
args ← args.mapM expandLiftMethodAux;
pure $ Syntax.node k args
| stx => pure stx
private def expandLiftMethod (stx : Syntax) : MacroM (Option (Array Syntax)) :=
if hasLiftMethod stx then do
(stx, doElems) ← (expandLiftMethodAux stx).run #[];
let doElems := doElems.push stx;
pure doElems
else
pure none
/- Expand `doLet`, `doPat`, nonterminal `doExpr`s, and `liftMethod` -/
private partial def expandDoElems : Bool → Array Syntax → Nat → MacroM Syntax
| modified, doElems, i =>
let mkRest : Unit → MacroM Syntax := fun _ => do {
let restElems := doElems.extract (i+2) doElems.size;
if restElems.size == 1 then
pure $ (restElems.get! 0).getArg 0
else
`(do { $restElems* })
};
let addPrefix (rest : Syntax) : MacroM Syntax := do {
if i == 0 then
pure rest
else
let newElems := doElems.extract 0 i;
let newElems := newElems.push $ Syntax.node `Lean.Parser.Term.doExpr #[rest];
`(do { $newElems* })
};
if h : i < doElems.size then do
let doElem := doElems.get ⟨i, h⟩;
doElemsNew? ← expandLiftMethod doElem;
match doElemsNew? with
| some doElemsNew => do
let post := doElems.extract (i+1) doElems.size;
let pre := doElems.extract 0 i;
let doElems := pre ++ doElemsNew ++ post;
tmp ← `(do { $doElems* });
expandDoElems true doElems i
| none =>
if doElem.getKind == `Lean.Parser.Term.doLet then do
let letDecl := doElem.getArg 1;
rest ← mkRest ();
newBody ← `(let $letDecl:letDecl; $rest);
addPrefix newBody
-- cleanup the following code
else if doElem.getKind == `Lean.Parser.Term.doLetArrow && (doElem.getArg 1).getKind == `Lean.Parser.Term.doPat then withFreshMacroScope $ do
let doElem := doElem.getArg 1;
-- (termParser >> leftArrow) >> termParser >> optional (" | " >> termParser)
let pat := doElem.getArg 0;
let discr := doElem.getArg 2;
let optElse := doElem.getArg 3;
rest ← mkRest ();
newBody ←
if optElse.isNone then do
`(do { let x ← $discr; (match x with | $pat => $rest) })
else
let elseBody := optElse.getArg 1;
`(do { let x ← $discr; (match x with | $pat => $rest | _ => $elseBody) });
addPrefix newBody
else if i < doElems.size - 1 && doElem.getKind == `Lean.Parser.Term.doExpr then do
-- def doExpr := parser! termParser
let term := doElem.getArg 0;
auxDo ← `(do { let x ← $term; $(Syntax.missing) });
let doElemNew := (getDoElems auxDo).get! 0;
let doElems := doElems.set! i doElemNew;
expandDoElems true doElems (i+2)
else
expandDoElems modified doElems (i+2)
else if modified then
`(do { $doElems* })
else
Macro.throwUnsupported
structure ProcessedDoElem :=
(action : Expr)
(var : Expr)
instance ProcessedDoElem.inhabited : Inhabited ProcessedDoElem := ⟨⟨arbitrary _, arbitrary _⟩⟩
private def extractTypeFormerAppArg (type : Expr) : TermElabM Expr := do
type ← withReducible $ whnf type;
match type with
| Expr.app _ a _ => pure a
| _ => throwError ("type former application expected" ++ indentExpr type)
/-
HasBind.bind : ∀ {m : Type u_1 → Type u_2} [self : HasBind m] {α β : Type u_1}, m α → (α → m β) → m β
-/
private def mkBind (m bindInstVal : Expr) (elems : Array ProcessedDoElem) (body : Expr) : TermElabM Expr :=
if elems.isEmpty then
pure body
else do
let x := elems.back.var; -- any variable would work since they must be in the same universe
xType ← inferType x;
u_1 ← getDecLevel xType;
bodyType ← inferType body;
u_2 ← getDecLevel bodyType;
let bindAndInst := mkApp2 (Lean.mkConst `HasBind.bind [u_1, u_2]) m bindInstVal;
elems.foldrM
(fun elem body => do
-- dbgTrace (">>> " ++ toString body);
let var := elem.var;
let action := elem.action;
α ← inferType var;
mβ ← inferType body;
β ← extractTypeFormerAppArg mβ;
f ← mkLambdaFVars #[var] body;
-- dbgTrace (">>> f: " ++ toString f);
let body := mkAppN bindAndInst #[α, β, action, f];
pure body)
body
private partial def processDoElemsAux (doElems : Array Syntax) (m bindInstVal : Expr) (expectedType : Expr) : Nat → Array ProcessedDoElem → TermElabM Expr
| i, elems =>
let doElem := doElems.get! i;
let k := doElem.getKind;
withRef doElem $
if k == `Lean.Parser.Term.doLetArrow then do
when (i == doElems.size - 1) $
throwError "the last statement in a 'do' block must be an expression";
let doElem := doElem.getArg 1;
-- try (ident >> optType >> leftArrow) >> termParser
let id := doElem.getIdAt 0;
let typeStx := expandOptType doElem (doElem.getArg 1);
let actionStx := doElem.getArg 3;
type ← elabType typeStx;
let actionExpectedType := mkApp m type;
action ← elabTermEnsuringType actionStx actionExpectedType;
withLocalDecl id BinderInfo.default type $ fun x =>
processDoElemsAux (i+1) (elems.push { action := action, var := x })
else if doElem.getKind == `Lean.Parser.Term.doExpr then do
when (i != doElems.size - 1) $
throwError ("unexpected 'do' expression element" ++ Format.line ++ doElem);
let bodyStx := doElem.getArg 0;
body ← elabTermEnsuringType bodyStx expectedType;
mkBind m bindInstVal elems body
else
throwError ("unexpected 'do' expression element" ++ Format.line ++ doElem)
private def processDoElems (doElems : Array Syntax) (m bindInstVal : Expr) (expectedType : Expr) : TermElabM Expr :=
processDoElemsAux doElems m bindInstVal expectedType 0 #[]
def expandDo? (stx : Syntax) : MacroM (Option Syntax) :=
let doElems := getDoElems stx;
catch
(do stx ← expandDoElems false doElems 0; pure $ some stx)
(fun _ => pure none)
@[builtinTermElab «do»]
def elabDo : TermElab :=
fun stx expectedType? => do
stxNew? ← liftMacroM $ expandDo? stx;
match stxNew? with
| some stxNew => withMacroExpansion stx stxNew $ elabTerm stxNew expectedType?
| none => do
tryPostponeIfNoneOrMVar expectedType?;
let doElems := getDoElems stx;
trace `Elab.do $ fun _ => stx;
let doElems := doElems.getSepElems;
trace `Elab.do $ fun _ => "doElems: " ++ toString doElems;
{ m := m, hasBindInst := bindInstVal, .. } ← extractBind expectedType?;
processDoElems doElems m bindInstVal expectedType?.get!
@[init] private def regTraceClasses : IO Unit := do
registerTraceClass `Elab.do;
pure ()
end Term
end Elab
end Lean
|
e5a94201faf6ce57213930c8a2edd5653759fb9e | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/ring_theory/free_comm_ring.lean | 31b6112224ef68d8d054bdf6cdb2748c686c3871 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 14,067 | lean | /-
Copyright (c) 2019 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Johan Commelin
-/
import data.mv_polynomial.equiv
import data.mv_polynomial.comm_ring
import logic.equiv.functor
import ring_theory.free_ring
/-!
# Free commutative rings
The theory of the free commutative ring generated by a type `α`.
It is isomorphic to the polynomial ring over ℤ with variables
in `α`
## Main definitions
* `free_comm_ring α` : the free commutative ring on a type α
* `lift (f : α → R)` : the ring hom `free_comm_ring α →+* R` induced by functoriality from `f`.
* `map (f : α → β)` : the ring hom `free_comm_ring α →*+ free_comm_ring β` induced by
functoriality from f.
## Main results
`free_comm_ring` has functorial properties (it is an adjoint to the forgetful functor).
In this file we have:
* `of : α → free_comm_ring α`
* `lift (f : α → R) : free_comm_ring α →+* R`
* `map (f : α → β) : free_comm_ring α →+* free_comm_ring β`
* `free_comm_ring_equiv_mv_polynomial_int : free_comm_ring α ≃+* mv_polynomial α ℤ` :
`free_comm_ring α` is isomorphic to a polynomial ring.
## Implementation notes
`free_comm_ring α` is implemented not using `mv_polynomial` but
directly as the free abelian group on `multiset α`, the type
of monomials in this free commutative ring.
## Tags
free commutative ring, free ring
-/
noncomputable theory
open_locale classical polynomial
universes u v
variables (α : Type u)
/-- `free_comm_ring α` is the free commutative ring on the type `α`. -/
@[derive [comm_ring, inhabited]]
def free_comm_ring (α : Type u) : Type u :=
free_abelian_group $ multiplicative $ multiset α
namespace free_comm_ring
variables {α}
/-- The canonical map from `α` to the free commutative ring on `α`. -/
def of (x : α) : free_comm_ring α :=
free_abelian_group.of $ multiplicative.of_add ({x} : multiset α)
lemma of_injective : function.injective (of : α → free_comm_ring α) :=
free_abelian_group.of_injective.comp (λ x y,
(multiset.coe_eq_coe.trans list.singleton_perm_singleton).mp)
@[elab_as_eliminator] protected lemma induction_on
{C : free_comm_ring α → Prop} (z : free_comm_ring α)
(hn1 : C (-1)) (hb : ∀ b, C (of b))
(ha : ∀ x y, C x → C y → C (x + y))
(hm : ∀ x y, C x → C y → C (x * y)) : C z :=
have hn : ∀ x, C x → C (-x), from λ x ih, neg_one_mul x ▸ hm _ _ hn1 ih,
have h1 : C 1, from neg_neg (1 : free_comm_ring α) ▸ hn _ hn1,
free_abelian_group.induction_on z
(add_left_neg (1 : free_comm_ring α) ▸ ha _ _ hn1 h1)
(λ m, multiset.induction_on m h1 $ λ a m ih, hm _ _ (hb a) ih)
(λ m ih, hn _ ih)
ha
section lift
variables {R : Type v} [comm_ring R] (f : α → R)
/-- A helper to implement `lift`. This is essentially `free_comm_monoid.lift`, but this does not
currently exist. -/
private def lift_to_multiset : (α → R) ≃ (multiplicative (multiset α) →* R) :=
{ to_fun := λ f,
{ to_fun := λ s, (s.to_add.map f).prod,
map_mul' := λ x y, calc _ = multiset.prod ((multiset.map f x) + (multiset.map f y)) :
by {congr' 1, exact multiset.map_add _ _ _}
... = _ : multiset.prod_add _ _,
map_one' := rfl},
inv_fun := λ F x, F (multiplicative.of_add ({x} : multiset α)),
left_inv := λ f, funext $ λ x, show (multiset.map f {x}).prod = _, by simp,
right_inv := λ F, monoid_hom.ext $ λ x,
let F' := F.to_additive'', x' := x.to_add in show (multiset.map (λ a, F' {a}) x').sum = F' x',
begin
rw [←multiset.map_map, ←add_monoid_hom.map_multiset_sum],
exact F.congr_arg (multiset.sum_map_singleton x'),
end }
/-- Lift a map `α → R` to a additive group homomorphism `free_comm_ring α → R`.
For a version producing a bundled homomorphism, see `lift_hom`. -/
def lift : (α → R) ≃ (free_comm_ring α →+* R) :=
equiv.trans lift_to_multiset free_abelian_group.lift_monoid
@[simp] lemma lift_of (x : α) : lift f (of x) = f x :=
(free_abelian_group.lift.of _ _).trans $ mul_one _
@[simp] lemma lift_comp_of (f : free_comm_ring α →+* R) : lift (f ∘ of) = f :=
ring_hom.ext $ λ x, free_comm_ring.induction_on x
(by rw [ring_hom.map_neg, ring_hom.map_one, f.map_neg, f.map_one])
(lift_of _)
(λ x y ihx ihy, by rw [ring_hom.map_add, f.map_add, ihx, ihy])
(λ x y ihx ihy, by rw [ring_hom.map_mul, f.map_mul, ihx, ihy])
@[ext]
lemma hom_ext ⦃f g : free_comm_ring α →+* R⦄ (h : ∀ x, f (of x) = g (of x)) :
f = g :=
lift.symm.injective (funext h)
end lift
variables {β : Type v} (f : α → β)
/-- A map `f : α → β` produces a ring homomorphism `free_comm_ring α →+* free_comm_ring β`. -/
def map : free_comm_ring α →+* free_comm_ring β :=
lift $ of ∘ f
@[simp]
lemma map_of (x : α) : map f (of x) = of (f x) := lift_of _ _
/-- `is_supported x s` means that all monomials showing up in `x` have variables in `s`. -/
def is_supported (x : free_comm_ring α) (s : set α) : Prop :=
x ∈ subring.closure (of '' s)
section is_supported
variables {x y : free_comm_ring α} {s t : set α}
theorem is_supported_upwards (hs : is_supported x s) (hst : s ⊆ t) :
is_supported x t :=
subring.closure_mono (set.monotone_image hst) hs
theorem is_supported_add (hxs : is_supported x s) (hys : is_supported y s) :
is_supported (x + y) s :=
subring.add_mem _ hxs hys
theorem is_supported_neg (hxs : is_supported x s) :
is_supported (-x) s :=
subring.neg_mem _ hxs
theorem is_supported_sub (hxs : is_supported x s) (hys : is_supported y s) :
is_supported (x - y) s :=
subring.sub_mem _ hxs hys
theorem is_supported_mul (hxs : is_supported x s) (hys : is_supported y s) :
is_supported (x * y) s :=
subring.mul_mem _ hxs hys
theorem is_supported_zero : is_supported 0 s :=
subring.zero_mem _
theorem is_supported_one : is_supported 1 s :=
subring.one_mem _
theorem is_supported_int {i : ℤ} {s : set α} : is_supported ↑i s :=
int.induction_on i is_supported_zero
(λ i hi, by rw [int.cast_add, int.cast_one]; exact is_supported_add hi is_supported_one)
(λ i hi, by rw [int.cast_sub, int.cast_one]; exact is_supported_sub hi is_supported_one)
end is_supported
/-- The restriction map from `free_comm_ring α` to `free_comm_ring s` where `s : set α`, defined
by sending all variables not in `s` to zero. -/
def restriction (s : set α) [decidable_pred (∈ s)] : free_comm_ring α →+* free_comm_ring s :=
lift (λ p, if H : p ∈ s then of (⟨p, H⟩ : s) else 0)
section restriction
variables (s : set α) [decidable_pred (∈ s)] (x y : free_comm_ring α)
@[simp] lemma restriction_of (p) :
restriction s (of p) = if H : p ∈ s then of ⟨p, H⟩ else 0 := lift_of _ _
end restriction
theorem is_supported_of {p} {s : set α} : is_supported (of p) s ↔ p ∈ s :=
suffices is_supported (of p) s → p ∈ s, from ⟨this, λ hps, subring.subset_closure ⟨p, hps, rfl⟩⟩,
assume hps : is_supported (of p) s, begin
haveI := classical.dec_pred s,
have : ∀ x, is_supported x s →
∃ (n : ℤ), lift (λ a, if a ∈ s then (0 : ℤ[X]) else polynomial.X) x = n,
{ intros x hx, refine subring.in_closure.rec_on hx _ _ _ _,
{ use 1, rw [ring_hom.map_one], norm_cast },
{ use -1, rw [ring_hom.map_neg, ring_hom.map_one, int.cast_neg, int.cast_one] },
{ rintros _ ⟨z, hzs, rfl⟩ _ _, use 0, rw [ring_hom.map_mul, lift_of, if_pos hzs, zero_mul],
norm_cast },
{ rintros x y ⟨q, hq⟩ ⟨r, hr⟩, refine ⟨q+r, _⟩, rw [ring_hom.map_add, hq, hr], norm_cast } },
specialize this (of p) hps, rw [lift_of] at this, split_ifs at this, { exact h },
exfalso, apply ne.symm int.zero_ne_one,
rcases this with ⟨w, H⟩, rw ←polynomial.C_eq_int_cast at H,
have : polynomial.X.coeff 1 = (polynomial.C ↑w).coeff 1, by rw H,
rwa [polynomial.coeff_C, if_neg (one_ne_zero : 1 ≠ 0), polynomial.coeff_X, if_pos rfl] at this
end
theorem map_subtype_val_restriction {x} (s : set α) [decidable_pred (∈ s)]
(hxs : is_supported x s) :
map (subtype.val : s → α) (restriction s x) = x :=
begin
refine subring.in_closure.rec_on hxs _ _ _ _,
{ rw ring_hom.map_one, refl },
{ rw [ring_hom.map_neg, ring_hom.map_neg, ring_hom.map_one], refl },
{ rintros _ ⟨p, hps, rfl⟩ n ih,
rw [ring_hom.map_mul, restriction_of, dif_pos hps, ring_hom.map_mul, map_of, ih] },
{ intros x y ihx ihy, rw [ring_hom.map_add, ring_hom.map_add, ihx, ihy] }
end
theorem exists_finite_support (x : free_comm_ring α) :
∃ s : set α, set.finite s ∧ is_supported x s :=
free_comm_ring.induction_on x
⟨∅, set.finite_empty, is_supported_neg is_supported_one⟩
(λ p, ⟨{p}, set.finite_singleton p, is_supported_of.2 $ set.mem_singleton _⟩)
(λ x y ⟨s, hfs, hxs⟩ ⟨t, hft, hxt⟩, ⟨s ∪ t, hfs.union hft, is_supported_add
(is_supported_upwards hxs $ set.subset_union_left s t)
(is_supported_upwards hxt $ set.subset_union_right s t)⟩)
(λ x y ⟨s, hfs, hxs⟩ ⟨t, hft, hxt⟩, ⟨s ∪ t, hfs.union hft, is_supported_mul
(is_supported_upwards hxs $ set.subset_union_left s t)
(is_supported_upwards hxt $ set.subset_union_right s t)⟩)
theorem exists_finset_support (x : free_comm_ring α) : ∃ s : finset α, is_supported x ↑s :=
let ⟨s, hfs, hxs⟩ := exists_finite_support x in ⟨hfs.to_finset, by rwa set.finite.coe_to_finset⟩
end free_comm_ring
namespace free_ring
open function
variable (α)
/-- The canonical ring homomorphism from the free ring generated by `α` to the free commutative ring
generated by `α`. -/
def to_free_comm_ring {α} : free_ring α →+* free_comm_ring α :=
free_ring.lift free_comm_ring.of
instance : has_coe (free_ring α) (free_comm_ring α) := ⟨to_free_comm_ring⟩
/-- The natural map `free_ring α → free_comm_ring α`, as a `ring_hom`. -/
def coe_ring_hom : free_ring α →+* free_comm_ring α := to_free_comm_ring
@[simp, norm_cast] protected lemma coe_zero : ↑(0 : free_ring α) = (0 : free_comm_ring α) := rfl
@[simp, norm_cast] protected lemma coe_one : ↑(1 : free_ring α) = (1 : free_comm_ring α) := rfl
variable {α}
@[simp] protected lemma coe_of (a : α) : ↑(free_ring.of a) = free_comm_ring.of a :=
free_ring.lift_of _ _
@[simp, norm_cast] protected lemma coe_neg (x : free_ring α) : ↑(-x) = -(x : free_comm_ring α) :=
(free_ring.lift _).map_neg _
@[simp, norm_cast] protected lemma coe_add (x y : free_ring α) :
↑(x + y) = (x : free_comm_ring α) + y :=
(free_ring.lift _).map_add _ _
@[simp, norm_cast] protected lemma coe_sub (x y : free_ring α) :
↑(x - y) = (x : free_comm_ring α) - y :=
(free_ring.lift _).map_sub _ _
@[simp, norm_cast] protected lemma coe_mul (x y : free_ring α) :
↑(x * y) = (x : free_comm_ring α) * y :=
(free_ring.lift _).map_mul _ _
variable (α)
protected lemma coe_surjective : surjective (coe : free_ring α → free_comm_ring α) :=
λ x,
begin
apply free_comm_ring.induction_on x,
{ use -1, refl },
{ intro x, use free_ring.of x, refl },
{ rintros _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, use x + y, exact (free_ring.lift _).map_add _ _ },
{ rintros _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, use x * y, exact (free_ring.lift _).map_mul _ _ }
end
lemma coe_eq :
(coe : free_ring α → free_comm_ring α) =
@functor.map free_abelian_group _ _ _ (λ (l : list α), (l : multiset α)) :=
funext $ λ x, free_abelian_group.lift.unique _ _ $ λ L,
by { simp_rw [free_abelian_group.lift.of, (∘)], exact free_monoid.rec_on L rfl
(λ hd tl ih, by { rw [(free_monoid.lift _).map_mul, free_monoid.lift_eval_of, ih], refl }) }
/-- If α has size at most 1 then the natural map from the free ring on `α` to the
free commutative ring on `α` is an isomorphism of rings. -/
def subsingleton_equiv_free_comm_ring [subsingleton α] :
free_ring α ≃+* free_comm_ring α :=
ring_equiv.of_bijective (coe_ring_hom _)
begin
have : (coe_ring_hom _ : free_ring α → free_comm_ring α) =
(functor.map_equiv free_abelian_group (multiset.subsingleton_equiv α)) := coe_eq α,
rw this,
apply equiv.bijective,
end
instance [subsingleton α] : comm_ring (free_ring α) :=
{ mul_comm := λ x y,
by { rw [← (subsingleton_equiv_free_comm_ring α).symm_apply_apply (y * x),
((subsingleton_equiv_free_comm_ring α)).map_mul,
mul_comm,
← ((subsingleton_equiv_free_comm_ring α)).map_mul,
(subsingleton_equiv_free_comm_ring α).symm_apply_apply], },
.. free_ring.ring α }
end free_ring
/-- The free commutative ring on `α` is isomorphic to the polynomial ring over ℤ with
variables in `α` -/
def free_comm_ring_equiv_mv_polynomial_int :
free_comm_ring α ≃+* mv_polynomial α ℤ :=
ring_equiv.of_hom_inv
(free_comm_ring.lift $ (λ a, mv_polynomial.X a : α → mv_polynomial α ℤ))
(mv_polynomial.eval₂_hom (int.cast_ring_hom (free_comm_ring α)) free_comm_ring.of)
(by { ext, simp })
(by ext; simp)
/-- The free commutative ring on the empty type is isomorphic to `ℤ`. -/
def free_comm_ring_pempty_equiv_int : free_comm_ring pempty.{u+1} ≃+* ℤ :=
ring_equiv.trans (free_comm_ring_equiv_mv_polynomial_int _)
(mv_polynomial.is_empty_ring_equiv _ pempty)
/-- The free commutative ring on a type with one term is isomorphic to `ℤ[X]`. -/
def free_comm_ring_punit_equiv_polynomial_int : free_comm_ring punit.{u+1} ≃+* polynomial ℤ :=
(free_comm_ring_equiv_mv_polynomial_int _).trans (mv_polynomial.punit_alg_equiv ℤ).to_ring_equiv
open free_ring
/-- The free ring on the empty type is isomorphic to `ℤ`. -/
def free_ring_pempty_equiv_int : free_ring pempty.{u+1} ≃+* ℤ :=
ring_equiv.trans (subsingleton_equiv_free_comm_ring _) free_comm_ring_pempty_equiv_int
/-- The free ring on a type with one term is isomorphic to `ℤ[X]`. -/
def free_ring_punit_equiv_polynomial_int : free_ring punit.{u+1} ≃+* polynomial ℤ :=
ring_equiv.trans (subsingleton_equiv_free_comm_ring _) free_comm_ring_punit_equiv_polynomial_int
|
7d6a3a8355fca899ef65cd9150abbd289e5631ae | a047a4718edfa935d17231e9e6ecec8c7b701e05 | /src/algebra/big_operators.lean | b2a66b2886cd268542103b72e290869b3f222717 | [
"Apache-2.0"
] | permissive | utensil-contrib/mathlib | bae0c9fafe5e2bdb516efc89d6f8c1502ecc9767 | b91909e77e219098a2f8cc031f89d595fe274bd2 | refs/heads/master | 1,668,048,976,965 | 1,592,442,701,000 | 1,592,442,701,000 | 273,197,855 | 0 | 0 | null | 1,592,472,812,000 | 1,592,472,811,000 | null | UTF-8 | Lean | false | false | 56,608 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import data.finset
import data.nat.enat
import tactic.omega
/-!
# Big operators
In this file we define products and sums indexed by finite sets (specifically, `finset`).
## Notation
We introduce the following notation, localized in `big_operators`.
To enable the notation, use `open_locale big_operators`.
Let `s` be a `finset α`, and `f : α → β` a function.
* `∏ x in s, f x` is notation for `finset.prod s f` (assuming `β` is a `comm_monoid`)
* `∑ x in s, f x` is notation for `finset.sum s f` (assuming `β` is an `add_comm_monoid`)
* `∏ x, f x` is notation for `finset.prod finset.univ f`
(assuming `α` is a `fintype` and `β` is a `comm_monoid`)
* `∑ x, f x` is notation for `finset.sum finset.univ f`
(assuming `α` is a `fintype` and `β` is an `add_comm_monoid`)
-/
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
theorem directed.finset_le {r : α → α → Prop} [is_trans α r]
{ι} (hι : nonempty ι) {f : ι → α} (D : directed r f) (s : finset ι) :
∃ z, ∀ i ∈ s, r (f i) (f z) :=
show ∃ z, ∀ i ∈ s.1, r (f i) (f z), from
multiset.induction_on s.1 (let ⟨z⟩ := hι in ⟨z, λ _, false.elim⟩) $
λ i s ⟨j, H⟩, let ⟨k, h₁, h₂⟩ := D i j in
⟨k, λ a h, or.cases_on (multiset.mem_cons.1 h)
(λ h, h.symm ▸ h₁)
(λ h, trans (H _ h) h₂)⟩
theorem finset.exists_le {α : Type u} [nonempty α] [directed_order α] (s : finset α) :
∃ M, ∀ i ∈ s, i ≤ M :=
directed.finset_le (by apply_instance) directed_order.directed s
namespace finset
/-- `∏ x in s, f x` is the product of `f x` as `x` ranges over the elements of the finite set `s`. -/
@[to_additive "`∑ x in s, f` is the sum of `f x` as `x` ranges over the elements
of the finite set `s`."]
protected def prod [comm_monoid β] (s : finset α) (f : α → β) : β := (s.1.map f).prod
end finset
/-
## Operator precedence of `∏` and `∑`
There is no established mathematical convention
for the operator precedence of big operators like `∏` and `∑`.
We will have to make a choice.
Online discussions, such as https://math.stackexchange.com/q/185538/30839
seem to suggest that `∏` and `∑` should have the same precedence,
and that this should be somewhere between `*` and `+`.
The latter have precedence levels `70` and `65` respectively,
and we therefore choose the level `67`.
In practice, this means that parentheses should be placed as follows:
```lean
∑ k in K, (a k + b k) = ∑ k in K, a k + ∑ k in K, b k →
∏ k in K, a k * b k = (∏ k in K, a k) * (∏ k in K, b k)
```
(Example taken from page 490 of Knuth's *Concrete Mathematics*.)
-/
localized "notation `∑` binders `, ` r:(scoped:67 f, finset.sum finset.univ f) := r" in big_operators
localized "notation `∏` binders `, ` r:(scoped:67 f, finset.prod finset.univ f) := r" in big_operators
localized "notation `∑` binders ` in ` s `, ` r:(scoped:67 f, finset.sum s f) := r" in big_operators
localized "notation `∏` binders ` in ` s `, ` r:(scoped:67 f, finset.prod s f) := r" in big_operators
open_locale big_operators
namespace finset
variables {s s₁ s₂ : finset α} {a : α} {f g : α → β}
@[to_additive] lemma prod_eq_multiset_prod [comm_monoid β] (s : finset α) (f : α → β) :
∏ x in s, f x = (s.1.map f).prod := rfl
@[to_additive]
theorem prod_eq_fold [comm_monoid β] (s : finset α) (f : α → β) : (∏ x in s, f x) = s.fold (*) 1 f := rfl
end finset
@[to_additive]
lemma monoid_hom.map_prod [comm_monoid β] [comm_monoid γ] (g : β →* γ) (f : α → β) (s : finset α) :
g (∏ x in s, f x) = ∏ x in s, g (f x) :=
by simp only [finset.prod_eq_multiset_prod, g.map_multiset_prod, multiset.map_map]
lemma ring_hom.map_list_prod [semiring β] [semiring γ] (f : β →+* γ) (l : list β) :
f l.prod = (l.map f).prod :=
f.to_monoid_hom.map_list_prod l
lemma ring_hom.map_list_sum [semiring β] [semiring γ] (f : β →+* γ) (l : list β) :
f l.sum = (l.map f).sum :=
f.to_add_monoid_hom.map_list_sum l
lemma ring_hom.map_multiset_prod [comm_semiring β] [comm_semiring γ] (f : β →+* γ)
(s : multiset β) :
f s.prod = (s.map f).prod :=
f.to_monoid_hom.map_multiset_prod s
lemma ring_hom.map_multiset_sum [semiring β] [semiring γ] (f : β →+* γ) (s : multiset β) :
f s.sum = (s.map f).sum :=
f.to_add_monoid_hom.map_multiset_sum s
lemma ring_hom.map_prod [comm_semiring β] [comm_semiring γ]
(g : β →+* γ) (f : α → β) (s : finset α) :
g (∏ x in s, f x) = ∏ x in s, g (f x) :=
g.to_monoid_hom.map_prod f s
lemma ring_hom.map_sum [semiring β] [semiring γ]
(g : β →+* γ) (f : α → β) (s : finset α) :
g (∑ x in s, f x) = ∑ x in s, g (f x) :=
g.to_add_monoid_hom.map_sum f s
namespace finset
variables {s s₁ s₂ : finset α} {a : α} {f g : α → β}
section comm_monoid
variables [comm_monoid β]
@[simp, to_additive]
lemma prod_empty {α : Type u} {f : α → β} : (∏ x in (∅:finset α), f x) = 1 := rfl
@[simp, to_additive]
lemma prod_insert [decidable_eq α] :
a ∉ s → (∏ x in (insert a s), f x) = f a * ∏ x in s, f x := fold_insert
@[simp, to_additive]
lemma prod_singleton : (∏ x in (singleton a), f x) = f a :=
eq.trans fold_singleton $ mul_one _
@[to_additive]
lemma prod_pair [decidable_eq α] {a b : α} (h : a ≠ b) :
(∏ x in ({a, b} : finset α), f x) = f a * f b :=
by rw [prod_insert (not_mem_singleton.2 h), prod_singleton]
@[simp, priority 1100] lemma prod_const_one : (∏ x in s, (1 : β)) = 1 :=
by simp only [finset.prod, multiset.map_const, multiset.prod_repeat, one_pow]
@[simp, priority 1100] lemma sum_const_zero {β} {s : finset α} [add_comm_monoid β] :
(∑ x in s, (0 : β)) = 0 :=
@prod_const_one _ (multiplicative β) _ _
attribute [to_additive] prod_const_one
@[simp, to_additive]
lemma prod_image [decidable_eq α] {s : finset γ} {g : γ → α} :
(∀x∈s, ∀y∈s, g x = g y → x = y) → (∏ x in (s.image g), f x) = ∏ x in s, f (g x) :=
fold_image
@[simp, to_additive]
lemma prod_map (s : finset α) (e : α ↪ γ) (f : γ → β) :
(∏ x in (s.map e), f x) = ∏ x in s, f (e x) :=
by rw [finset.prod, finset.map_val, multiset.map_map]; refl
@[congr, to_additive]
lemma prod_congr (h : s₁ = s₂) : (∀x∈s₂, f x = g x) → s₁.prod f = s₂.prod g :=
by rw [h]; exact fold_congr
attribute [congr] finset.sum_congr
@[to_additive]
lemma prod_union_inter [decidable_eq α] :
(∏ x in (s₁ ∪ s₂), f x) * (∏ x in (s₁ ∩ s₂), f x) = (∏ x in s₁, f x) * (∏ x in s₂, f x) :=
fold_union_inter
@[to_additive]
lemma prod_union [decidable_eq α] (h : disjoint s₁ s₂) :
(∏ x in (s₁ ∪ s₂), f x) = (∏ x in s₁, f x) * (∏ x in s₂, f x) :=
by rw [←prod_union_inter, (disjoint_iff_inter_eq_empty.mp h)]; exact (mul_one _).symm
@[to_additive]
lemma prod_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) :
(∏ x in (s₂ \ s₁), f x) * (∏ x in s₁, f x) = (∏ x in s₂, f x) :=
by rw [←prod_union sdiff_disjoint, sdiff_union_of_subset h]
@[simp, to_additive]
lemma prod_sum_elim [decidable_eq (α ⊕ γ)]
(s : finset α) (t : finset γ) (f : α → β) (g : γ → β) :
∏ x in s.image sum.inl ∪ t.image sum.inr, sum.elim f g x = (∏ x in s, f x) * (∏ x in t, g x) :=
begin
rw [prod_union, prod_image, prod_image],
{ simp only [sum.elim_inl, sum.elim_inr] },
{ exact λ _ _ _ _, sum.inr.inj },
{ exact λ _ _ _ _, sum.inl.inj },
{ rintros i hi,
erw [finset.mem_inter, finset.mem_image, finset.mem_image] at hi,
rcases hi with ⟨⟨i, hi, rfl⟩, ⟨j, hj, H⟩⟩,
cases H }
end
@[to_additive]
lemma prod_bind [decidable_eq α] {s : finset γ} {t : γ → finset α} :
(∀x∈s, ∀y∈s, x ≠ y → disjoint (t x) (t y)) → (∏ x in (s.bind t), f x) = ∏ x in s, ∏ i in t x, f i :=
by haveI := classical.dec_eq γ; exact
finset.induction_on s (λ _, by simp only [bind_empty, prod_empty])
(assume x s hxs ih hd,
have hd' : ∀x∈s, ∀y∈s, x ≠ y → disjoint (t x) (t y),
from assume _ hx _ hy, hd _ (mem_insert_of_mem hx) _ (mem_insert_of_mem hy),
have ∀y∈s, x ≠ y,
from assume _ hy h, by rw [←h] at hy; contradiction,
have ∀y∈s, disjoint (t x) (t y),
from assume _ hy, hd _ (mem_insert_self _ _) _ (mem_insert_of_mem hy) (this _ hy),
have disjoint (t x) (finset.bind s t),
from (disjoint_bind_right _ _ _).mpr this,
by simp only [bind_insert, prod_insert hxs, prod_union this, ih hd'])
@[to_additive]
lemma prod_product {s : finset γ} {t : finset α} {f : γ×α → β} :
(∏ x in s.product t, f x) = ∏ x in s, ∏ y in t, f (x, y) :=
begin
haveI := classical.dec_eq α, haveI := classical.dec_eq γ,
rw [product_eq_bind, prod_bind],
{ congr, funext, exact prod_image (λ _ _ _ _ H, (prod.mk.inj H).2) },
simp only [disjoint_iff_ne, mem_image],
rintros _ _ _ _ h ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ _,
apply h, cc
end
@[to_additive]
lemma prod_sigma {σ : α → Type*}
{s : finset α} {t : Πa, finset (σ a)} {f : sigma σ → β} :
(∏ x in s.sigma t, f x) = ∏ a in s, ∏ s in (t a), f ⟨a, s⟩ :=
by haveI := classical.dec_eq α; haveI := (λ a, classical.dec_eq (σ a)); exact
calc (∏ x in s.sigma t, f x) =
∏ x in s.bind (λa, (t a).image (λs, sigma.mk a s)), f x : by rw sigma_eq_bind
... = ∏ a in s, ∏ x in (t a).image (λs, sigma.mk a s), f x :
prod_bind $ assume a₁ ha a₂ ha₂ h,
by simp only [disjoint_iff_ne, mem_image];
rintro ⟨_, _⟩ ⟨_, _, _⟩ ⟨_, _⟩ ⟨_, _, _⟩ ⟨_, _⟩; apply h; cc
... = ∏ a in s, ∏ s in t a, f ⟨a, s⟩ :
prod_congr rfl $ λ _ _, prod_image $ λ _ _ _ _ _, by cc
@[to_additive]
lemma prod_image' [decidable_eq α] {s : finset γ} {g : γ → α} (h : γ → β)
(eq : ∀c∈s, f (g c) = ∏ x in s.filter (λc', g c' = g c), h x) :
(∏ x in s.image g, f x) = ∏ x in s, h x :=
begin
letI := classical.dec_eq γ,
rw [← image_bind_filter_eq s g] {occs := occurrences.pos [2]},
rw [finset.prod_bind],
{ refine finset.prod_congr rfl (assume a ha, _),
rcases finset.mem_image.1 ha with ⟨b, hb, rfl⟩,
exact eq b hb },
assume a₀ _ a₁ _ ne,
refine (disjoint_iff_ne.2 _),
assume c₀ h₀ c₁ h₁,
rcases mem_filter.1 h₀ with ⟨h₀, rfl⟩,
rcases mem_filter.1 h₁ with ⟨h₁, rfl⟩,
exact mt (congr_arg g) ne
end
@[to_additive]
lemma prod_mul_distrib : ∏ x in s, (f x * g x) = (∏ x in s, f x) * (∏ x in s, g x) :=
eq.trans (by rw one_mul; refl) fold_op_distrib
@[to_additive]
lemma prod_comm {s : finset γ} {t : finset α} {f : γ → α → β} :
(∏ x in s, ∏ y in t, f x y) = (∏ y in t, ∏ x in s, f x y) :=
begin
classical,
apply finset.induction_on s,
{ simp only [prod_empty, prod_const_one] },
{ intros _ _ H ih,
simp only [prod_insert H, prod_mul_distrib, ih] }
end
@[to_additive]
lemma prod_hom [comm_monoid γ] (s : finset α) {f : α → β} (g : β → γ) [is_monoid_hom g] :
(∏ x in s, g (f x)) = g (∏ x in s, f x) :=
((monoid_hom.of g).map_prod f s).symm
@[to_additive]
lemma prod_hom_rel [comm_monoid γ] {r : β → γ → Prop} {f : α → β} {g : α → γ} {s : finset α}
(h₁ : r 1 1) (h₂ : ∀a b c, r b c → r (f a * b) (g a * c)) : r (∏ x in s, f x) (∏ x in s, g x) :=
by { delta finset.prod, apply multiset.prod_hom_rel; assumption }
@[to_additive]
lemma prod_subset (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → f x = 1) : (∏ x in s₁, f x) = ∏ x in s₂, f x :=
by haveI := classical.dec_eq α; exact
have ∏ x in s₂ \ s₁, f x = ∏ x in s₂ \ s₁, 1,
from prod_congr rfl $ by simpa only [mem_sdiff, and_imp],
by rw [←prod_sdiff h]; simp only [this, prod_const_one, one_mul]
-- If we use `[decidable_eq β]` here, some rewrites fail because they find a wrong `decidable`
-- instance first; `{∀x, decidable (f x ≠ 1)}` doesn't work with `rw ← prod_filter_ne_one`
@[to_additive]
lemma prod_filter_ne_one [∀ x, decidable (f x ≠ 1)] :
(∏ x in (s.filter $ λx, f x ≠ 1), f x) = (∏ x in s, f x) :=
prod_subset (filter_subset _) $ λ x,
by { classical, rw [not_imp_comm, mem_filter], exact and.intro }
@[to_additive]
lemma prod_filter (p : α → Prop) [decidable_pred p] (f : α → β) :
(∏ a in s.filter p, f a) = (∏ a in s, if p a then f a else 1) :=
calc (∏ a in s.filter p, f a) = ∏ a in s.filter p, if p a then f a else 1 :
prod_congr rfl (assume a h, by rw [if_pos (mem_filter.1 h).2])
... = ∏ a in s, if p a then f a else 1 :
begin
refine prod_subset (filter_subset s) (assume x hs h, _),
rw [mem_filter, not_and] at h,
exact if_neg (h hs)
end
@[to_additive]
lemma prod_eq_single {s : finset α} {f : α → β} (a : α)
(h₀ : ∀b∈s, b ≠ a → f b = 1) (h₁ : a ∉ s → f a = 1) : (∏ x in s, f x) = f a :=
by haveI := classical.dec_eq α;
from classical.by_cases
(assume : a ∈ s,
calc (∏ x in s, f x) = ∏ x in {a}, f x :
begin
refine (prod_subset _ _).symm,
{ intros _ H, rwa mem_singleton.1 H },
{ simpa only [mem_singleton] }
end
... = f a : prod_singleton)
(assume : a ∉ s,
(prod_congr rfl $ λ b hb, h₀ b hb $ by rintro rfl; cc).trans $
prod_const_one.trans (h₁ this).symm)
@[to_additive] lemma prod_apply_ite {s : finset α}
{p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (h : γ → β) :
(∏ x in s, h (if p x then f x else g x)) =
(∏ x in s.filter p, h (f x)) * (∏ x in s.filter (λ x, ¬ p x), h (g x)) :=
by letI := classical.dec_eq α; exact
calc ∏ x in s, h (if p x then f x else g x)
= ∏ x in s.filter p ∪ s.filter (λ x, ¬ p x), h (if p x then f x else g x) :
by rw [filter_union_filter_neg_eq]
... = (∏ x in s.filter p, h (if p x then f x else g x)) *
(∏ x in s.filter (λ x, ¬ p x), h (if p x then f x else g x)) :
prod_union (by simp [disjoint_right] {contextual := tt})
... = (∏ x in s.filter p, h (f x)) * (∏ x in s.filter (λ x, ¬ p x), h (g x)) :
congr_arg2 _
(prod_congr rfl (by simp {contextual := tt}))
(prod_congr rfl (by simp {contextual := tt}))
@[to_additive] lemma prod_ite {s : finset α}
{p : α → Prop} {hp : decidable_pred p} (f g : α → β) :
(∏ x in s, if p x then f x else g x) =
(∏ x in s.filter p, f x) * (∏ x in s.filter (λ x, ¬ p x), g x) :=
by simp [prod_apply_ite _ _ (λ x, x)]
@[simp, to_additive] lemma prod_ite_eq [decidable_eq α] (s : finset α) (a : α) (b : α → β) :
(∏ x in s, (ite (a = x) (b x) 1)) = ite (a ∈ s) (b a) 1 :=
begin
rw ←finset.prod_filter,
split_ifs;
simp only [filter_eq, if_true, if_false, h, prod_empty, prod_singleton],
end
/--
When a product is taken over a conditional whose condition is an equality test on the index
and whose alternative is 1, then the product's value is either the term at that index or `1`.
The difference with `prod_ite_eq` is that the arguments to `eq` are swapped.
-/
@[simp, to_additive] lemma prod_ite_eq' [decidable_eq α] (s : finset α) (a : α) (b : α → β) :
(∏ x in s, (ite (x = a) (b x) 1)) = ite (a ∈ s) (b a) 1 :=
begin
rw ←prod_ite_eq,
congr, ext x,
by_cases x = a; finish
end
@[to_additive]
lemma prod_attach {f : α → β} : (∏ x in s.attach, f x.val) = (∏ x in s, f x) :=
by haveI := classical.dec_eq α; exact
calc (∏ x in s.attach, f x.val) = (∏ x in (s.attach).image subtype.val, f x) :
by rw [prod_image]; exact assume x _ y _, subtype.eq
... = _ : by rw [attach_image_val]
/--
Reorder a product.
The difference with `prod_bij'` is that the bijection is specified as a surjective injection,
rather than by an inverse function.
-/
@[to_additive]
lemma prod_bij {s : finset α} {t : finset γ} {f : α → β} {g : γ → β}
(i : Πa∈s, γ) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha))
(i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀b∈t, ∃a ha, b = i a ha) :
(∏ x in s, f x) = (∏ x in t, g x) :=
congr_arg multiset.prod
(multiset.map_eq_map_of_bij_of_nodup f g s.2 t.2 i hi h i_inj i_surj)
/--
Reorder a product.
The difference with `prod_bij` is that the bijection is specified with an inverse, rather than
as a surjective injection.
-/
@[to_additive]
lemma prod_bij' {s : finset α} {t : finset γ} {f : α → β} {g : γ → β}
(i : Πa∈s, γ) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha))
(j : Πa∈t, α) (hj : ∀a ha, j a ha ∈ s) (left_inv : ∀ a ha, j (i a ha) (hi a ha) = a)
(right_inv : ∀ a ha, i (j a ha) (hj a ha) = a) :
(∏ x in s, f x) = (∏ x in t, g x) :=
begin
refine prod_bij i hi h _ _,
{intros a1 a2 h1 h2 eq, rw [←left_inv a1 h1, ←left_inv a2 h2], cc,},
{intros b hb, use j b hb, use hj b hb, exact (right_inv b hb).symm,},
end
@[to_additive]
lemma prod_bij_ne_one {s : finset α} {t : finset γ} {f : α → β} {g : γ → β}
(i : Πa∈s, f a ≠ 1 → γ) (hi₁ : ∀a h₁ h₂, i a h₁ h₂ ∈ t)
(hi₂ : ∀a₁ a₂ h₁₁ h₁₂ h₂₁ h₂₂, i a₁ h₁₁ h₁₂ = i a₂ h₂₁ h₂₂ → a₁ = a₂)
(hi₃ : ∀b∈t, g b ≠ 1 → ∃a h₁ h₂, b = i a h₁ h₂)
(h : ∀a h₁ h₂, f a = g (i a h₁ h₂)) :
(∏ x in s, f x) = (∏ x in t, g x) :=
by classical; exact
calc (∏ x in s, f x) = ∏ x in (s.filter $ λx, f x ≠ 1), f x : prod_filter_ne_one.symm
... = ∏ x in (t.filter $ λx, g x ≠ 1), g x :
prod_bij (assume a ha, i a (mem_filter.mp ha).1 (mem_filter.mp ha).2)
(assume a ha, (mem_filter.mp ha).elim $ λh₁ h₂, mem_filter.mpr
⟨hi₁ a h₁ h₂, λ hg, h₂ (hg ▸ h a h₁ h₂)⟩)
(assume a ha, (mem_filter.mp ha).elim $ h a)
(assume a₁ a₂ ha₁ ha₂,
(mem_filter.mp ha₁).elim $ λha₁₁ ha₁₂, (mem_filter.mp ha₂).elim $ λha₂₁ ha₂₂, hi₂ a₁ a₂ _ _ _ _)
(assume b hb, (mem_filter.mp hb).elim $ λh₁ h₂,
let ⟨a, ha₁, ha₂, eq⟩ := hi₃ b h₁ h₂ in ⟨a, mem_filter.mpr ⟨ha₁, ha₂⟩, eq⟩)
... = (∏ x in t, g x) : prod_filter_ne_one
@[to_additive]
lemma nonempty_of_prod_ne_one (h : (∏ x in s, f x) ≠ 1) : s.nonempty :=
s.eq_empty_or_nonempty.elim (λ H, false.elim $ h $ H.symm ▸ prod_empty) id
@[to_additive]
lemma exists_ne_one_of_prod_ne_one (h : (∏ x in s, f x) ≠ 1) : ∃a∈s, f a ≠ 1 :=
begin
classical,
rw ← prod_filter_ne_one at h,
rcases nonempty_of_prod_ne_one h with ⟨x, hx⟩,
exact ⟨x, (mem_filter.1 hx).1, (mem_filter.1 hx).2⟩
end
lemma sum_range_succ {β} [add_comm_monoid β] (f : ℕ → β) (n : ℕ) :
(∑ x in range (n + 1), f x) = f n + (∑ x in range n, f x) :=
by rw [range_succ, sum_insert not_mem_range_self]
@[to_additive]
lemma prod_range_succ (f : ℕ → β) (n : ℕ) :
(∏ x in range (n + 1), f x) = f n * (∏ x in range n, f x) :=
by rw [range_succ, prod_insert not_mem_range_self]
lemma prod_range_succ' (f : ℕ → β) :
∀ n : ℕ, (∏ k in range (n + 1), f k) = (∏ k in range n, f (k+1)) * f 0
| 0 := (prod_range_succ _ _).trans $ mul_comm _ _
| (n + 1) := by rw [prod_range_succ (λ m, f (nat.succ m)), mul_assoc, ← prod_range_succ'];
exact prod_range_succ _ _
lemma sum_Ico_add {δ : Type*} [add_comm_monoid δ] (f : ℕ → δ) (m n k : ℕ) :
(∑ l in Ico m n, f (k + l)) = (∑ l in Ico (m + k) (n + k), f l) :=
Ico.image_add m n k ▸ eq.symm $ sum_image $ λ x hx y hy h, nat.add_left_cancel h
@[to_additive]
lemma prod_Ico_add (f : ℕ → β) (m n k : ℕ) :
(∏ l in Ico m n, f (k + l)) = (∏ l in Ico (m + k) (n + k), f l) :=
@sum_Ico_add (additive β) _ f m n k
lemma sum_Ico_succ_top {δ : Type*} [add_comm_monoid δ] {a b : ℕ}
(hab : a ≤ b) (f : ℕ → δ) : (∑ k in Ico a (b + 1), f k) = (∑ k in Ico a b, f k) + f b :=
by rw [Ico.succ_top hab, sum_insert Ico.not_mem_top, add_comm]
@[to_additive]
lemma prod_Ico_succ_top {a b : ℕ} (hab : a ≤ b) (f : ℕ → β) :
(∏ k in Ico a (b + 1), f k) = (∏ k in Ico a b, f k) * f b :=
@sum_Ico_succ_top (additive β) _ _ _ hab _
lemma sum_eq_sum_Ico_succ_bot {δ : Type*} [add_comm_monoid δ] {a b : ℕ}
(hab : a < b) (f : ℕ → δ) : (∑ k in Ico a b, f k) = f a + (∑ k in Ico (a + 1) b, f k) :=
have ha : a ∉ Ico (a + 1) b, by simp,
by rw [← sum_insert ha, Ico.insert_succ_bot hab]
@[to_additive]
lemma prod_eq_prod_Ico_succ_bot {a b : ℕ} (hab : a < b) (f : ℕ → β) :
(∏ k in Ico a b, f k) = f a * (∏ k in Ico (a + 1) b, f k) :=
@sum_eq_sum_Ico_succ_bot (additive β) _ _ _ hab _
@[to_additive]
lemma prod_Ico_consecutive (f : ℕ → β) {m n k : ℕ} (hmn : m ≤ n) (hnk : n ≤ k) :
(∏ i in Ico m n, f i) * (∏ i in Ico n k, f i) = (∏ i in Ico m k, f i) :=
Ico.union_consecutive hmn hnk ▸ eq.symm $ prod_union $ Ico.disjoint_consecutive m n k
@[to_additive]
lemma prod_range_mul_prod_Ico (f : ℕ → β) {m n : ℕ} (h : m ≤ n) :
(∏ k in range m, f k) * (∏ k in Ico m n, f k) = (∏ k in range n, f k) :=
Ico.zero_bot m ▸ Ico.zero_bot n ▸ prod_Ico_consecutive f (nat.zero_le m) h
@[to_additive]
lemma prod_Ico_eq_mul_inv {δ : Type*} [comm_group δ] (f : ℕ → δ) {m n : ℕ} (h : m ≤ n) :
(∏ k in Ico m n, f k) = (∏ k in range n, f k) * (∏ k in range m, f k)⁻¹ :=
eq_mul_inv_iff_mul_eq.2 $ by rw [mul_comm]; exact prod_range_mul_prod_Ico f h
lemma sum_Ico_eq_sub {δ : Type*} [add_comm_group δ] (f : ℕ → δ) {m n : ℕ} (h : m ≤ n) :
(∑ k in Ico m n, f k) = (∑ k in range n, f k) - (∑ k in range m, f k) :=
sum_Ico_eq_add_neg f h
@[to_additive]
lemma prod_Ico_eq_prod_range (f : ℕ → β) (m n : ℕ) :
(∏ k in Ico m n, f k) = (∏ k in range (n - m), f (m + k)) :=
begin
by_cases h : m ≤ n,
{ rw [← Ico.zero_bot, prod_Ico_add, zero_add, nat.sub_add_cancel h] },
{ replace h : n ≤ m := le_of_not_ge h,
rw [Ico.eq_empty_of_le h, nat.sub_eq_zero_of_le h, range_zero, prod_empty, prod_empty] }
end
@[to_additive]
lemma prod_range_zero (f : ℕ → β) :
(∏ k in range 0, f k) = 1 :=
by rw [range_zero, prod_empty]
lemma prod_range_one (f : ℕ → β) :
(∏ k in range 1, f k) = f 0 :=
by { rw [range_one], apply @prod_singleton ℕ β 0 f }
lemma sum_range_one {δ : Type*} [add_comm_monoid δ] (f : ℕ → δ) :
(∑ k in range 1, f k) = f 0 :=
@prod_range_one (multiplicative δ) _ f
attribute [to_additive finset.sum_range_one] prod_range_one
/-- For any product along `{0, ..., n-1}` of a commutative-monoid-valued function, we can verify that
it's equal to a different function just by checking ratios of adjacent terms.
This is a multiplicative discrete analogue of the fundamental theorem of calculus. -/
lemma prod_range_induction {M : Type*} [comm_monoid M]
(f s : ℕ → M) (h0 : s 0 = 1) (h : ∀ n, s (n + 1) = s n * f n) (n : ℕ) :
∏ k in finset.range n, f k = s n :=
begin
induction n with k hk,
{ simp only [h0, finset.prod_range_zero] },
{ simp only [hk, finset.prod_range_succ, h, mul_comm] }
end
/-- For any sum along `{0, ..., n-1}` of a commutative-monoid-valued function, we can verify that it's equal
to a different function just by checking differences of adjacent terms. This is a discrete analogue
of the fundamental theorem of calculus. -/
lemma sum_range_induction {M : Type*} [add_comm_monoid M]
(f s : ℕ → M) (h0 : s 0 = 0) (h : ∀ n, s (n + 1) = s n + f n) (n : ℕ) :
∑ k in finset.range n, f k = s n :=
@prod_range_induction (multiplicative M) _ f s h0 h n
/-- A telescoping sum along `{0, ..., n-1}` of an `ℕ`-valued function reduces to the difference of
the last and first terms when the function we are summing is monotone. -/
lemma sum_range_sub_of_monotone {f : ℕ → ℕ} (h : monotone f) (n : ℕ) :
∑ i in range n, (f (i+1) - f i) = f n - f 0 :=
begin
refine sum_range_induction _ _ (nat.sub_self _) (λ n, _) _,
have : f n ≤ f (n+1) := h (nat.le_succ _),
have : f 0 ≤ f n := h (nat.zero_le _),
omega
end
lemma prod_Ico_reflect (f : ℕ → β) (k : ℕ) {m n : ℕ} (h : m ≤ n + 1) :
∏ j in Ico k m, f (n - j) = ∏ j in Ico (n + 1 - m) (n + 1 - k), f j :=
begin
have : ∀ i < m, i ≤ n,
{ intros i hi,
exact (add_le_add_iff_right 1).1 (le_trans (nat.lt_iff_add_one_le.1 hi) h) },
cases lt_or_le k m with hkm hkm,
{ rw [← finset.Ico.image_const_sub (this _ hkm)],
refine (prod_image _).symm,
simp only [Ico.mem],
rintros i ⟨ki, im⟩ j ⟨kj, jm⟩ Hij,
rw [← nat.sub_sub_self (this _ im), Hij, nat.sub_sub_self (this _ jm)] },
{ simp [Ico.eq_empty_of_le, nat.sub_le_sub_left, hkm] }
end
lemma sum_Ico_reflect {δ : Type*} [add_comm_monoid δ] (f : ℕ → δ) (k : ℕ) {m n : ℕ}
(h : m ≤ n + 1) :
∑ j in Ico k m, f (n - j) = ∑ j in Ico (n + 1 - m) (n + 1 - k), f j :=
@prod_Ico_reflect (multiplicative δ) _ f k m n h
lemma prod_range_reflect (f : ℕ → β) (n : ℕ) :
∏ j in range n, f (n - 1 - j) = ∏ j in range n, f j :=
begin
cases n,
{ simp },
{ simp only [range_eq_Ico, nat.succ_sub_succ_eq_sub, nat.sub_zero],
rw [prod_Ico_reflect _ _ (le_refl _)],
simp }
end
lemma sum_range_reflect {δ : Type*} [add_comm_monoid δ] (f : ℕ → δ) (n : ℕ) :
∑ j in range n, f (n - 1 - j) = ∑ j in range n, f j :=
@prod_range_reflect (multiplicative δ) _ f n
@[simp] lemma prod_const (b : β) : (∏ x in s, b) = b ^ s.card :=
by haveI := classical.dec_eq α; exact
finset.induction_on s rfl (λ a s has ih,
by rw [prod_insert has, card_insert_of_not_mem has, pow_succ, ih])
lemma prod_pow (s : finset α) (n : ℕ) (f : α → β) :
(∏ x in s, f x ^ n) = (∏ x in s, f x) ^ n :=
by haveI := classical.dec_eq α; exact
finset.induction_on s (by simp) (by simp [_root_.mul_pow] {contextual := tt})
lemma prod_nat_pow (s : finset α) (n : ℕ) (f : α → ℕ) :
(∏ x in s, f x ^ n) = (∏ x in s, f x) ^ n :=
by haveI := classical.dec_eq α; exact
finset.induction_on s (by simp) (by simp [nat.mul_pow] {contextual := tt})
-- `to_additive` fails on this lemma, so we prove it manually below
lemma prod_flip {n : ℕ} (f : ℕ → β) :
(∏ r in range (n + 1), f (n - r)) = (∏ k in range (n + 1), f k) :=
begin
induction n with n ih,
{ rw [prod_range_one, prod_range_one] },
{ rw [prod_range_succ', prod_range_succ _ (nat.succ n), mul_comm],
simp [← ih] }
end
@[to_additive]
lemma prod_involution {s : finset α} {f : α → β} :
∀ (g : Π a ∈ s, α)
(h₁ : ∀ a ha, f a * f (g a ha) = 1)
(h₂ : ∀ a ha, f a ≠ 1 → g a ha ≠ a)
(h₃ : ∀ a ha, g a ha ∈ s)
(h₄ : ∀ a ha, g (g a ha) (h₃ a ha) = a),
(∏ x in s, f x) = 1 :=
by haveI := classical.dec_eq α;
haveI := classical.dec_eq β; exact
finset.strong_induction_on s
(λ s ih g h₁ h₂ h₃ h₄,
s.eq_empty_or_nonempty.elim (λ hs, hs.symm ▸ rfl)
(λ ⟨x, hx⟩,
have hmem : ∀ y ∈ (s.erase x).erase (g x hx), y ∈ s,
from λ y hy, (mem_of_mem_erase (mem_of_mem_erase hy)),
have g_inj : ∀ {x hx y hy}, g x hx = g y hy → x = y,
from λ x hx y hy h, by rw [← h₄ x hx, ← h₄ y hy]; simp [h],
have ih': ∏ y in erase (erase s x) (g x hx), f y = (1 : β) :=
ih ((s.erase x).erase (g x hx))
⟨subset.trans (erase_subset _ _) (erase_subset _ _),
λ h, not_mem_erase (g x hx) (s.erase x) (h (h₃ x hx))⟩
(λ y hy, g y (hmem y hy))
(λ y hy, h₁ y (hmem y hy))
(λ y hy, h₂ y (hmem y hy))
(λ y hy, mem_erase.2 ⟨λ (h : g y _ = g x hx), by simpa [g_inj h] using hy,
mem_erase.2 ⟨λ (h : g y _ = x),
have y = g x hx, from h₄ y (hmem y hy) ▸ by simp [h],
by simpa [this] using hy, h₃ y (hmem y hy)⟩⟩)
(λ y hy, h₄ y (hmem y hy)),
if hx1 : f x = 1
then ih' ▸ eq.symm (prod_subset hmem
(λ y hy hy₁,
have y = x ∨ y = g x hx, by simp [hy] at hy₁; tauto,
this.elim (λ h, h.symm ▸ hx1)
(λ h, h₁ x hx ▸ h ▸ hx1.symm ▸ (one_mul _).symm)))
else by rw [← insert_erase hx, prod_insert (not_mem_erase _ _),
← insert_erase (mem_erase.2 ⟨h₂ x hx hx1, h₃ x hx⟩),
prod_insert (not_mem_erase _ _), ih', mul_one, h₁ x hx]))
/-- The product of the composition of functions `f` and `g`, is the product
over `b ∈ s.image g` of `f b` to the power of the cardinality of the fibre of `b` -/
lemma prod_comp [decidable_eq γ] {s : finset α} (f : γ → β) (g : α → γ) :
∏ a in s, f (g a) = ∏ b in s.image g, f b ^ (s.filter (λ a, g a = b)).card :=
calc ∏ a in s, f (g a)
= ∏ x in (s.image g).sigma (λ b : γ, s.filter (λ a, g a = b)), f (g x.2) :
prod_bij (λ a ha, ⟨g a, a⟩) (by simp; tauto) (λ _ _, rfl) (by simp) (by finish)
... = ∏ b in s.image g, ∏ a in s.filter (λ a, g a = b), f (g a) : prod_sigma
... = ∏ b in s.image g, ∏ a in s.filter (λ a, g a = b), f b :
prod_congr rfl (λ b hb, prod_congr rfl (by simp {contextual := tt}))
... = ∏ b in s.image g, f b ^ (s.filter (λ a, g a = b)).card :
prod_congr rfl (λ _ _, prod_const _)
@[to_additive]
lemma prod_eq_one {f : α → β} {s : finset α} (h : ∀x∈s, f x = 1) : (∏ x in s, f x) = 1 :=
calc (∏ x in s, f x) = ∏ x in s, 1 : finset.prod_congr rfl h
... = 1 : finset.prod_const_one
/-- 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`. -/
@[to_additive]
lemma prod_powerset_insert [decidable_eq α] {s : finset α} {x : α} (h : x ∉ s) (f : finset α → β) :
(∏ a in (insert x s).powerset, f a) =
(∏ a in s.powerset, f a) * (∏ t in s.powerset, f (insert x t)) :=
begin
rw [powerset_insert, finset.prod_union, finset.prod_image],
{ assume t₁ h₁ t₂ h₂ heq,
rw [← finset.erase_insert (not_mem_of_mem_powerset_of_not_mem h₁ h),
← finset.erase_insert (not_mem_of_mem_powerset_of_not_mem h₂ h), heq] },
{ rw finset.disjoint_iff_ne,
assume t₁ h₁ t₂ h₂,
rcases finset.mem_image.1 h₂ with ⟨t₃, h₃, H₃₂⟩,
rw ← H₃₂,
exact ne_insert_of_not_mem _ _ (not_mem_of_mem_powerset_of_not_mem h₁ h) }
end
@[to_additive]
lemma prod_piecewise [decidable_eq α] (s t : finset α) (f g : α → β) :
(∏ x in s, (t.piecewise f g) x) = (∏ x in s ∩ t, f x) * (∏ x in s \ t, g x) :=
by { rw [piecewise, prod_ite, filter_mem_eq_inter, ← sdiff_eq_filter], }
/-- If we can partition a product into subsets that cancel out, then the whole product cancels. -/
@[to_additive]
lemma prod_cancels_of_partition_cancels (R : setoid α) [decidable_rel R.r]
(h : ∀ x ∈ s, (∏ a in s.filter (λy, y ≈ x), f a) = 1) : (∏ x in s, f x) = 1 :=
begin
suffices : ∏ xbar in s.image quotient.mk, ∏ y in s.filter (λ y, ⟦y⟧ = xbar), f y = (∏ x in s, f x),
{ rw [←this, ←finset.prod_eq_one],
intros xbar xbar_in_s,
rcases (mem_image).mp xbar_in_s with ⟨x, x_in_s, xbar_eq_x⟩,
rw [←xbar_eq_x, filter_congr (λ y _, @quotient.eq _ R y x)],
apply h x x_in_s },
apply finset.prod_image' f,
intros,
refl
end
@[to_additive]
lemma prod_update_of_not_mem [decidable_eq α] {s : finset α} {i : α}
(h : i ∉ s) (f : α → β) (b : β) : (∏ x in s, function.update f i b x) = (∏ x in s, f x) :=
begin
apply prod_congr rfl (λj hj, _),
have : j ≠ i, by { assume eq, rw eq at hj, exact h hj },
simp [this]
end
lemma prod_update_of_mem [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) (b : β) :
(∏ x in s, function.update f i b x) = b * (∏ x in s \ (singleton i), f x) :=
by { rw [update_eq_piecewise, prod_piecewise], simp [h] }
end comm_monoid
lemma sum_update_of_mem [add_comm_monoid β] [decidable_eq α] {s : finset α} {i : α}
(h : i ∈ s) (f : α → β) (b : β) :
(∑ x in s, function.update f i b x) = b + (∑ x in s \ (singleton i), f x) :=
by { rw [update_eq_piecewise, sum_piecewise], simp [h] }
attribute [to_additive] prod_update_of_mem
lemma sum_nsmul [add_comm_monoid β] (s : finset α) (n : ℕ) (f : α → β) :
(∑ x in s, n •ℕ (f x)) = n •ℕ ((∑ x in s, f x)) :=
@prod_pow _ (multiplicative β) _ _ _ _
attribute [to_additive sum_nsmul] prod_pow
@[simp] lemma sum_const [add_comm_monoid β] (b : β) :
(∑ x in s, b) = s.card •ℕ b :=
@prod_const _ (multiplicative β) _ _ _
attribute [to_additive] prod_const
lemma sum_comp [add_comm_monoid β] [decidable_eq γ] {s : finset α} (f : γ → β) (g : α → γ) :
∑ a in s, f (g a) = ∑ b in s.image g, (s.filter (λ a, g a = b)).card •ℕ (f b) :=
@prod_comp _ (multiplicative β) _ _ _ _ _ _
attribute [to_additive "The sum of the composition of functions `f` and `g`, is the sum
over `b ∈ s.image g` of `f b` times of the cardinality of the fibre of `b`"] prod_comp
lemma sum_const_nat {m : ℕ} {f : α → ℕ} (h₁ : ∀x ∈ s, f x = m) :
(∑ x in s, f x) = card s * m :=
begin
rw [← nat.nsmul_eq_mul, ← sum_const],
apply sum_congr rfl h₁
end
@[simp]
lemma sum_boole {s : finset α} {p : α → Prop} [semiring β] {hp : decidable_pred p} :
(∑ x in s, if p x then (1 : β) else (0 : β)) = (s.filter p).card :=
by simp [sum_ite]
lemma sum_range_succ' [add_comm_monoid β] (f : ℕ → β) :
∀ n : ℕ, (∑ i in range (n + 1), f i) = (∑ i in range n, f (i + 1)) + f 0 :=
@prod_range_succ' (multiplicative β) _ _
attribute [to_additive] prod_range_succ'
lemma sum_flip [add_comm_monoid β] {n : ℕ} (f : ℕ → β) :
(∑ i in range (n + 1), f (n - i)) = (∑ i in range (n + 1), f i) :=
@prod_flip (multiplicative β) _ _ _
attribute [to_additive] prod_flip
@[norm_cast]
lemma sum_nat_cast [add_comm_monoid β] [has_one β] (s : finset α) (f : α → ℕ) :
↑(∑ x in s, f x : ℕ) = (∑ x in s, (f x : β)) :=
(nat.cast_add_monoid_hom β).map_sum f s
@[norm_cast]
lemma prod_nat_cast [comm_semiring β] (s : finset α) (f : α → ℕ) :
↑(∏ x in s, f x : ℕ) = (∏ x in s, (f x : β)) :=
(nat.cast_ring_hom β).map_prod f s
protected lemma sum_nat_coe_enat (s : finset α) (f : α → ℕ) :
(∑ x in s, (f x : enat)) = (∑ x in s, f x : ℕ) :=
begin
classical,
induction s using finset.induction with a s has ih h,
{ simp },
{ simp [has, ih] }
end
theorem dvd_sum [comm_semiring α] {a : α} {s : finset β} {f : β → α}
(h : ∀ x ∈ s, a ∣ f x) : a ∣ ∑ x in s, f x :=
multiset.dvd_sum (λ y hy, by rcases multiset.mem_map.1 hy with ⟨x, hx, rfl⟩; exact h x hx)
lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_add_comm_monoid β]
(f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : finset γ) (g : γ → α) :
f (∑ x in s, g x) ≤ ∑ x in s, f (g x) :=
begin
refine le_trans (multiset.le_sum_of_subadditive f h_zero h_add _) _,
rw [multiset.map_map],
refl
end
lemma abs_sum_le_sum_abs [discrete_linear_ordered_field α] {f : β → α} {s : finset β} :
abs (∑ x in s, f x) ≤ ∑ x in s, abs (f x) :=
le_sum_of_subadditive _ abs_zero abs_add s f
section comm_group
variables [comm_group β]
@[simp, to_additive]
lemma prod_inv_distrib : (∏ x in s, (f x)⁻¹) = (∏ x in s, f x)⁻¹ :=
s.prod_hom has_inv.inv
end comm_group
@[simp] theorem card_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) :
card (s.sigma t) = ∑ a in s, card (t a) :=
multiset.card_sigma _ _
lemma card_bind [decidable_eq β] {s : finset α} {t : α → finset β}
(h : ∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y)) :
(s.bind t).card = ∑ u in s, card (t u) :=
calc (s.bind t).card = ∑ i in s.bind t, 1 : by simp
... = ∑ a in s, ∑ i in t a, 1 : finset.sum_bind h
... = ∑ u in s, card (t u) : by simp
lemma card_bind_le [decidable_eq β] {s : finset α} {t : α → finset β} :
(s.bind t).card ≤ ∑ a in s, (t a).card :=
by haveI := classical.dec_eq α; exact
finset.induction_on s (by simp)
(λ a s has ih,
calc ((insert a s).bind t).card ≤ (t a).card + (s.bind t).card :
by rw bind_insert; exact finset.card_union_le _ _
... ≤ ∑ a in insert a s, card (t a) :
by rw sum_insert has; exact add_le_add_left ih _)
theorem card_eq_sum_card_image [decidable_eq β] (f : α → β) (s : finset α) :
s.card = ∑ a in s.image f, (s.filter (λ x, f x = a)).card :=
by letI := classical.dec_eq α; exact
calc s.card = ((s.image f).bind (λ a, s.filter (λ x, f x = a))).card :
congr_arg _ (finset.ext $ λ x,
⟨λ hs, mem_bind.2 ⟨f x, mem_image_of_mem _ hs,
mem_filter.2 ⟨hs, rfl⟩⟩,
λ h, let ⟨a, ha₁, ha₂⟩ := mem_bind.1 h in by convert filter_subset s ha₂⟩)
... = ∑ a in s.image f, (s.filter (λ x, f x = a)).card :
card_bind (by simp [disjoint_left, finset.ext_iff] {contextual := tt})
lemma gsmul_sum [add_comm_group β] {f : α → β} {s : finset α} (z : ℤ) :
gsmul z (∑ a in s, f a) = ∑ a in s, gsmul z (f a) :=
(s.sum_hom (gsmul z)).symm
end finset
namespace finset
variables {s s₁ s₂ : finset α} {f g : α → β} {b : β} {a : α}
@[simp] lemma sum_sub_distrib [add_comm_group β] :
∑ x in s, (f x - g x) = (∑ x in s, f x) - (∑ x in s, g x) :=
sum_add_distrib.trans $ congr_arg _ sum_neg_distrib
section comm_monoid
variables [comm_monoid β]
lemma prod_pow_boole [decidable_eq α] (s : finset α) (f : α → β) (a : α) :
(∏ x in s, (f x)^(ite (a = x) 1 0)) = ite (a ∈ s) (f a) 1 :=
by simp
end comm_monoid
section semiring
variables [semiring β]
lemma sum_mul : (∑ x in s, f x) * b = ∑ x in s, f x * b :=
(s.sum_hom (λ x, x * b)).symm
lemma mul_sum : b * (∑ x in s, f x) = ∑ x in s, b * f x :=
(s.sum_hom _).symm
lemma sum_mul_boole [decidable_eq α] (s : finset α) (f : α → β) (a : α) :
(∑ x in s, (f x * ite (a = x) 1 0)) = ite (a ∈ s) (f a) 0 :=
by simp
lemma sum_boole_mul [decidable_eq α] (s : finset α) (f : α → β) (a : α) :
(∑ x in s, (ite (a = x) 1 0) * f x) = ite (a ∈ s) (f a) 0 :=
by simp
end semiring
lemma sum_div [division_ring β] {s : finset α} {f : α → β} {b : β} :
(∑ x in s, f x) / b = ∑ x in s, f x / b :=
calc (∑ x in s, f x) / b = ∑ x in s, f x * (1 / b) : by rw [div_eq_mul_one_div, sum_mul]
... = ∑ x in s, f x / b : by { congr, ext, rw ← div_eq_mul_one_div (f x) b }
section comm_semiring
variables [comm_semiring β]
lemma prod_eq_zero (ha : a ∈ s) (h : f a = 0) : (∏ x in s, f x) = 0 :=
by haveI := classical.dec_eq α;
calc (∏ x in s, f x) = ∏ x in insert a (erase s a), f x : by rw insert_erase ha
... = 0 : by rw [prod_insert (not_mem_erase _ _), h, zero_mul]
/-- 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`. -/
lemma prod_sum {δ : α → Type*} [decidable_eq α] [∀a, decidable_eq (δ a)]
{s : finset α} {t : Πa, finset (δ a)} {f : Πa, δ a → β} :
(∏ a in s, ∑ b in (t a), f a b) =
∑ p in (s.pi t), ∏ x in s.attach, f x.1 (p x.1 x.2) :=
begin
induction s using finset.induction with a s ha ih,
{ rw [pi_empty, sum_singleton], refl },
{ have h₁ : ∀x ∈ t a, ∀y ∈ t a, ∀h : x ≠ y,
disjoint (image (pi.cons s a x) (pi s t)) (image (pi.cons s a y) (pi s t)),
{ assume x hx y hy h,
simp only [disjoint_iff_ne, mem_image],
rintros _ ⟨p₂, hp, eq₂⟩ _ ⟨p₃, hp₃, eq₃⟩ eq,
have : pi.cons s a x p₂ a (mem_insert_self _ _) = pi.cons s a y p₃ a (mem_insert_self _ _),
{ rw [eq₂, eq₃, eq] },
rw [pi.cons_same, pi.cons_same] at this,
exact h this },
rw [prod_insert ha, pi_insert ha, ih, sum_mul, sum_bind h₁],
refine sum_congr rfl (λ b _, _),
have h₂ : ∀p₁∈pi s t, ∀p₂∈pi s t, pi.cons s a b p₁ = pi.cons s a b p₂ → p₁ = p₂, from
assume p₁ h₁ p₂ h₂ eq, injective_pi_cons ha eq,
rw [sum_image h₂, mul_sum],
refine sum_congr rfl (λ g _, _),
rw [attach_insert, prod_insert, prod_image],
{ simp only [pi.cons_same],
congr', ext ⟨v, hv⟩, congr',
exact (pi.cons_ne (by rintro rfl; exact ha hv)).symm },
{ exact λ _ _ _ _, subtype.eq ∘ subtype.mk.inj },
{ simp only [mem_image], rintro ⟨⟨_, hm⟩, _, rfl⟩, exact ha hm } }
end
lemma sum_mul_sum {ι₁ : Type*} {ι₂ : Type*} (s₁ : finset ι₁) (s₂ : finset ι₂)
(f₁ : ι₁ → β) (f₂ : ι₂ → β) :
(∑ x₁ in s₁, f₁ x₁) * (∑ x₂ in s₂, f₂ x₂) = ∑ p in s₁.product s₂, f₁ p.1 * f₂ p.2 :=
by { rw [sum_product, sum_mul, sum_congr rfl], intros, rw mul_sum }
open_locale classical
/-- 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` -/
lemma prod_add (f g : α → β) (s : finset α) :
∏ a in s, (f a + g a) = ∑ t in s.powerset, ((∏ a in t, f a) * (∏ a in (s \ t), g a)) :=
calc ∏ a in s, (f a + g a)
= ∏ a in s, ∑ p in ({true, false} : finset Prop), if p then f a else g a : by simp
... = ∑ p in (s.pi (λ _, {true, false}) : finset (Π a ∈ s, Prop)),
∏ a in s.attach, if p a.1 a.2 then f a.1 else g a.1 : prod_sum
... = ∑ t in s.powerset, (∏ a in t, f a) * (∏ a in (s \ t), g a) : begin
refine eq.symm (sum_bij (λ t _ a _, a ∈ t) _ _ _ _),
{ simp [subset_iff]; tauto },
{ intros t ht,
erw [prod_ite (λ a : {a // a ∈ s}, f a.1) (λ a : {a // a ∈ s}, g a.1)],
refine congr_arg2 _
(prod_bij (λ (a : α) (ha : a ∈ t), ⟨a, mem_powerset.1 ht ha⟩)
_ _ _
(λ b hb, ⟨b, by cases b; finish⟩))
(prod_bij (λ (a : α) (ha : a ∈ s \ t), ⟨a, by simp * at *⟩)
_ _ _
(λ b hb, ⟨b, by cases b; finish⟩));
intros; simp * at *; simp * at * },
{ finish [function.funext_iff, finset.ext_iff, subset_iff] },
{ assume f hf,
exact ⟨s.filter (λ a : α, ∃ h : a ∈ s, f a h),
by simp, by funext; intros; simp *⟩ }
end
/-- Summing `a^s.card * b^(n-s.card)` over all finite subsets `s` of a `finset`
gives `(a + b)^s.card`.-/
lemma sum_pow_mul_eq_add_pow
{α R : Type*} [comm_semiring R] (a b : R) (s : finset α) :
(∑ t in s.powerset, a ^ t.card * b ^ (s.card - t.card)) = (a + b) ^ s.card :=
begin
rw [← prod_const, prod_add],
refine finset.sum_congr rfl (λ t ht, _),
rw [prod_const, prod_const, ← card_sdiff (mem_powerset.1 ht)]
end
lemma prod_pow_eq_pow_sum {x : β} {f : α → ℕ} :
∀ {s : finset α}, (∏ i in s, x ^ (f i)) = x ^ (∑ x in s, f x) :=
begin
apply finset.induction,
{ simp },
{ assume a s has H,
rw [finset.prod_insert has, finset.sum_insert has, pow_add, H] }
end
end comm_semiring
section integral_domain /- add integral_semi_domain to support nat and ennreal -/
variables [integral_domain β]
lemma prod_eq_zero_iff : (∏ x in s, f x) = 0 ↔ (∃a∈s, f a = 0) :=
begin
classical,
apply finset.induction_on s,
exact ⟨not.elim one_ne_zero, λ ⟨_, H, _⟩, H.elim⟩,
assume a s ha ih,
rw [prod_insert ha, mul_eq_zero_iff_eq_zero_or_eq_zero, bex_def, exists_mem_insert, ih, ← bex_def]
end
theorem prod_ne_zero_iff : (∏ x in s, f x) ≠ 0 ↔ (∀ a ∈ s, f a ≠ 0) :=
by { rw [ne, prod_eq_zero_iff], push_neg }
end integral_domain
section ordered_add_comm_monoid
variables [ordered_add_comm_monoid β]
lemma sum_le_sum : (∀x∈s, f x ≤ g x) → (∑ x in s, f x) ≤ (∑ x in s, g x) :=
begin
classical,
apply finset.induction_on s,
exact (λ _, le_refl _),
assume a s ha ih h,
have : f a + (∑ x in s, f x) ≤ g a + (∑ x in s, g x),
from add_le_add' (h _ (mem_insert_self _ _)) (ih $ assume x hx, h _ $ mem_insert_of_mem hx),
by simpa only [sum_insert ha]
end
lemma sum_nonneg (h : ∀x∈s, 0 ≤ f x) : 0 ≤ (∑ x in s, f x) :=
le_trans (by rw [sum_const_zero]) (sum_le_sum h)
lemma sum_nonpos (h : ∀x∈s, f x ≤ 0) : (∑ x in s, f x) ≤ 0 :=
le_trans (sum_le_sum h) (by rw [sum_const_zero])
lemma sum_le_sum_of_subset_of_nonneg
(h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → 0 ≤ f x) : (∑ x in s₁, f x) ≤ (∑ x in s₂, f x) :=
by classical;
calc (∑ x in s₁, f x) ≤ (∑ x in s₂ \ s₁, f x) + (∑ x in s₁, f x) :
le_add_of_nonneg_left' $ sum_nonneg $ by simpa only [mem_sdiff, and_imp]
... = ∑ x in s₂ \ s₁ ∪ s₁, f x : (sum_union sdiff_disjoint).symm
... = (∑ x in s₂, f x) : by rw [sdiff_union_of_subset h]
lemma sum_mono_set_of_nonneg (hf : ∀ x, 0 ≤ f x) : monotone (λ s, ∑ x in s, f x) :=
λ s₁ s₂ hs, sum_le_sum_of_subset_of_nonneg hs $ λ x _ _, hf x
lemma sum_eq_zero_iff_of_nonneg : (∀x∈s, 0 ≤ f x) → ((∑ x in s, f x) = 0 ↔ ∀x∈s, f x = 0) :=
begin
classical,
apply finset.induction_on s,
exact λ _, ⟨λ _ _, false.elim, λ _, rfl⟩,
assume a s ha ih H,
have : ∀ x ∈ s, 0 ≤ f x, from λ _, H _ ∘ mem_insert_of_mem,
rw [sum_insert ha, add_eq_zero_iff' (H _ $ mem_insert_self _ _) (sum_nonneg this),
forall_mem_insert, ih this]
end
lemma sum_eq_zero_iff_of_nonpos : (∀x∈s, f x ≤ 0) → ((∑ x in s, f x) = 0 ↔ ∀x∈s, f x = 0) :=
@sum_eq_zero_iff_of_nonneg _ (order_dual β) _ _ _
lemma single_le_sum (hf : ∀x∈s, 0 ≤ f x) {a} (h : a ∈ s) : f a ≤ (∑ x in s, f x) :=
have ∑ x in {a}, f x ≤ (∑ x in s, f x),
from sum_le_sum_of_subset_of_nonneg
(λ x e, (mem_singleton.1 e).symm ▸ h) (λ x h _, hf x h),
by rwa sum_singleton at this
end ordered_add_comm_monoid
section canonically_ordered_add_monoid
variables [canonically_ordered_add_monoid β]
@[simp] lemma sum_eq_zero_iff : ∑ x in s, f x = 0 ↔ ∀ x ∈ s, f x = 0 :=
sum_eq_zero_iff_of_nonneg $ λ x hx, zero_le (f x)
lemma sum_le_sum_of_subset (h : s₁ ⊆ s₂) : (∑ x in s₁, f x) ≤ (∑ x in s₂, f x) :=
sum_le_sum_of_subset_of_nonneg h $ assume x h₁ h₂, zero_le _
lemma sum_mono_set (f : α → β) : monotone (λ s, ∑ x in s, f x) :=
λ s₁ s₂ hs, sum_le_sum_of_subset hs
lemma sum_le_sum_of_ne_zero (h : ∀x∈s₁, f x ≠ 0 → x ∈ s₂) :
(∑ x in s₁, f x) ≤ (∑ x in s₂, f x) :=
by classical;
calc (∑ x in s₁, f x) = ∑ x in s₁.filter (λx, f x = 0), f x + ∑ x in s₁.filter (λx, f x ≠ 0), f x :
by rw [←sum_union, filter_union_filter_neg_eq];
exact disjoint_filter.2 (assume _ _ h n_h, n_h h)
... ≤ (∑ x in s₂, f x) : add_le_of_nonpos_of_le'
(sum_nonpos $ by simp only [mem_filter, and_imp]; exact λ _ _, le_of_eq)
(sum_le_sum_of_subset $ by simpa only [subset_iff, mem_filter, and_imp])
end canonically_ordered_add_monoid
section ordered_cancel_comm_monoid
variables [ordered_cancel_add_comm_monoid β]
theorem sum_lt_sum (Hle : ∀ i ∈ s, f i ≤ g i) (Hlt : ∃ i ∈ s, f i < g i) :
(∑ x in s, f x) < (∑ x in s, g x) :=
begin
classical,
rcases Hlt with ⟨i, hi, hlt⟩,
rw [← insert_erase hi, sum_insert (not_mem_erase _ _), sum_insert (not_mem_erase _ _)],
exact add_lt_add_of_lt_of_le hlt (sum_le_sum $ λ j hj, Hle j $ mem_of_mem_erase hj)
end
lemma sum_lt_sum_of_nonempty (hs : s.nonempty) (Hlt : ∀ x ∈ s, f x < g x) :
(∑ x in s, f x) < (∑ x in s, g x) :=
begin
apply sum_lt_sum,
{ intros i hi, apply le_of_lt (Hlt i hi) },
cases hs with i hi,
exact ⟨i, hi, Hlt i hi⟩,
end
lemma sum_lt_sum_of_subset [decidable_eq α]
(h : s₁ ⊆ s₂) {i : α} (hi : i ∈ s₂ \ s₁) (hpos : 0 < f i) (hnonneg : ∀ j ∈ s₂ \ s₁, 0 ≤ f j) :
(∑ x in s₁, f x) < (∑ x in s₂, f x) :=
calc (∑ x in s₁, f x) < (∑ x in insert i s₁, f x) :
begin
simp only [mem_sdiff] at hi,
rw sum_insert hi.2,
exact lt_add_of_pos_left (∑ x in s₁, f x) hpos,
end
... ≤ (∑ x in s₂, f x) :
begin
simp only [mem_sdiff] at hi,
apply sum_le_sum_of_subset_of_nonneg,
{ simp [finset.insert_subset, h, hi.1] },
{ assume x hx h'x,
apply hnonneg x,
simp [mem_insert, not_or_distrib] at h'x,
rw mem_sdiff,
simp [hx, h'x] }
end
end ordered_cancel_comm_monoid
section decidable_linear_ordered_cancel_comm_monoid
variables [decidable_linear_ordered_cancel_add_comm_monoid β]
theorem exists_le_of_sum_le (hs : s.nonempty) (Hle : (∑ x in s, f x) ≤ ∑ x in s, g x) :
∃ i ∈ s, f i ≤ g i :=
begin
classical,
contrapose! Hle with Hlt,
rcases hs with ⟨i, hi⟩,
exact sum_lt_sum (λ i hi, le_of_lt (Hlt i hi)) ⟨i, hi, Hlt i hi⟩
end
lemma exists_pos_of_sum_zero_of_exists_nonzero (f : α → β)
(h₁ : ∑ e in s, f e = 0) (h₂ : ∃ x ∈ s, f x ≠ 0) :
∃ x ∈ s, 0 < f x :=
begin
contrapose! h₁,
obtain ⟨x, m, x_nz⟩ : ∃ x ∈ s, f x ≠ 0 := h₂,
apply ne_of_lt,
calc ∑ e in s, f e < ∑ e in s, 0 : by { apply sum_lt_sum h₁ ⟨x, m, lt_of_le_of_ne (h₁ x m) x_nz⟩ }
... = 0 : by rw [finset.sum_const, nsmul_zero],
end
end decidable_linear_ordered_cancel_comm_monoid
section linear_ordered_comm_ring
variables [linear_ordered_comm_ring β]
open_locale classical
/- this is also true for a ordered commutative multiplicative monoid -/
lemma prod_nonneg {s : finset α} {f : α → β}
(h0 : ∀(x ∈ s), 0 ≤ f x) : 0 ≤ (∏ x in s, f x) :=
begin
induction s using finset.induction with a s has ih h,
{ simp [zero_le_one] },
{ simp [has], apply mul_nonneg, apply h0 a (mem_insert_self a s),
exact ih (λ x H, h0 x (mem_insert_of_mem H)) }
end
/- this is also true for a ordered commutative multiplicative monoid -/
lemma prod_pos {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 < f x) : 0 < (∏ x in s, f x) :=
begin
induction s using finset.induction with a s has ih h,
{ simp [zero_lt_one] },
{ simp [has], apply mul_pos, apply h0 a (mem_insert_self a s),
exact ih (λ x H, h0 x (mem_insert_of_mem H)) }
end
/- this is also true for a ordered commutative multiplicative monoid -/
lemma prod_le_prod {s : finset α} {f g : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x)
(h1 : ∀(x ∈ s), f x ≤ g x) : (∏ x in s, f x) ≤ (∏ x in s, g x) :=
begin
induction s using finset.induction with a s has ih h,
{ simp },
{ simp [has], apply mul_le_mul,
exact h1 a (mem_insert_self a s),
apply ih (λ x H, h0 _ _) (λ x H, h1 _ _); exact (mem_insert_of_mem H),
apply prod_nonneg (λ x H, h0 x (mem_insert_of_mem H)),
apply le_trans (h0 a (mem_insert_self a s)) (h1 a (mem_insert_self a s)) }
end
end linear_ordered_comm_ring
section canonically_ordered_comm_semiring
variables [canonically_ordered_comm_semiring β]
lemma prod_le_prod' {s : finset α} {f g : α → β} (h : ∀ i ∈ s, f i ≤ g i) :
(∏ x in s, f x) ≤ (∏ x in s, g x) :=
begin
classical,
induction s using finset.induction with a s has ih h,
{ simp },
{ rw [finset.prod_insert has, finset.prod_insert has],
apply canonically_ordered_semiring.mul_le_mul,
{ exact h _ (finset.mem_insert_self a s) },
{ exact ih (λ i hi, h _ (finset.mem_insert_of_mem hi)) } }
end
end canonically_ordered_comm_semiring
@[simp] lemma card_pi [decidable_eq α] {δ : α → Type*}
(s : finset α) (t : Π a, finset (δ a)) :
(s.pi t).card = ∏ a in s, card (t a) :=
multiset.card_pi _ _
theorem card_le_mul_card_image [decidable_eq β] {f : α → β} (s : finset α)
(n : ℕ) (hn : ∀ a ∈ s.image f, (s.filter (λ x, f x = a)).card ≤ n) :
s.card ≤ n * (s.image f).card :=
calc s.card = (∑ a in s.image f, (s.filter (λ x, f x = a)).card) :
card_eq_sum_card_image _ _
... ≤ (∑ _ in s.image f, n) : sum_le_sum hn
... = _ : by simp [mul_comm]
@[simp] lemma prod_Ico_id_eq_fact : ∀ n : ℕ, ∏ x in Ico 1 (n + 1), x = nat.fact n
| 0 := rfl
| (n+1) := by rw [prod_Ico_succ_top $ nat.succ_le_succ $ zero_le n,
nat.fact_succ, prod_Ico_id_eq_fact n, nat.succ_eq_add_one, mul_comm]
end finset
namespace finset
section gauss_sum
/-- Gauss' summation formula -/
lemma sum_range_id_mul_two (n : ℕ) :
(∑ i in range n, i) * 2 = n * (n - 1) :=
calc (∑ i in range n, i) * 2 = (∑ i in range n, i) + (∑ i in range n, (n - 1 - i)) :
by rw [sum_range_reflect (λ i, i) n, mul_two]
... = ∑ i in range n, (i + (n - 1 - i)) : sum_add_distrib.symm
... = ∑ i in range n, (n - 1) : sum_congr rfl $ λ i hi, nat.add_sub_cancel' $
nat.le_pred_of_lt $ mem_range.1 hi
... = n * (n - 1) : by rw [sum_const, card_range, nat.nsmul_eq_mul]
/-- Gauss' summation formula -/
lemma sum_range_id (n : ℕ) : (∑ i in range n, i) = (n * (n - 1)) / 2 :=
by rw [← sum_range_id_mul_two n, nat.mul_div_cancel]; exact dec_trivial
end gauss_sum
lemma card_eq_sum_ones (s : finset α) : s.card = ∑ _ in s, 1 :=
by simp
end finset
section group
open list
variables [group α] [group β]
theorem is_group_anti_hom.map_prod (f : α → β) [is_group_anti_hom f] (l : list α) :
f (prod l) = prod (map f (reverse l)) :=
by induction l with hd tl ih; [exact is_group_anti_hom.map_one f,
simp only [prod_cons, is_group_anti_hom.map_mul f, ih, reverse_cons, map_append, prod_append,
map_singleton, prod_cons, prod_nil, mul_one]]
theorem inv_prod : ∀ l : list α, (prod l)⁻¹ = prod (map (λ x, x⁻¹) (reverse l)) :=
-- TODO there is probably a cleaner proof of this
λ l, @is_group_anti_hom.map_prod _ _ _ _ _ inv_is_group_anti_hom l
end group
@[to_additive is_add_group_hom_finset_sum]
lemma is_group_hom_finset_prod {α β γ} [group α] [comm_group β] (s : finset γ)
(f : γ → α → β) [∀c, is_group_hom (f c)] : is_group_hom (λa, ∏ c in s, f c a) :=
{ map_mul := assume a b, by simp only [λc, is_mul_hom.map_mul (f c), finset.prod_mul_distrib] }
attribute [instance] is_group_hom_finset_prod is_add_group_hom_finset_sum
namespace multiset
variables [decidable_eq α]
@[simp] lemma to_finset_sum_count_eq (s : multiset α) :
(∑ a in s.to_finset, s.count a) = s.card :=
multiset.induction_on s rfl
(assume a s ih,
calc (∑ x in to_finset (a :: s), count x (a :: s)) =
∑ x in to_finset (a :: s), ((if x = a then 1 else 0) + count x s) :
finset.sum_congr rfl $ λ _ _, by split_ifs;
[simp only [h, count_cons_self, nat.one_add], simp only [count_cons_of_ne h, zero_add]]
... = card (a :: s) :
begin
by_cases a ∈ s.to_finset,
{ have : ∑ x in s.to_finset, ite (x = a) 1 0 = ∑ x in {a}, ite (x = a) 1 0,
{ rw [finset.sum_ite_eq', if_pos h, finset.sum_singleton, if_pos rfl], },
rw [to_finset_cons, finset.insert_eq_of_mem h, finset.sum_add_distrib, ih, this,
finset.sum_singleton, if_pos rfl, add_comm, card_cons] },
{ have ha : a ∉ s, by rwa mem_to_finset at h,
have : ∑ x in to_finset s, ite (x = a) 1 0 = ∑ x in to_finset s, 0, from
finset.sum_congr rfl (λ x hx, if_neg $ by rintro rfl; cc),
rw [to_finset_cons, finset.sum_insert h, if_pos rfl, finset.sum_add_distrib, this,
finset.sum_const_zero, ih, count_eq_zero_of_not_mem ha, zero_add, add_comm, card_cons] }
end)
end multiset
namespace with_top
open finset
open_locale classical
/-- A sum of finite numbers is still finite -/
lemma sum_lt_top [ordered_add_comm_monoid β] {s : finset α} {f : α → with_top β} :
(∀a∈s, f a < ⊤) → (∑ x in s, f x) < ⊤ :=
finset.induction_on s (by { intro h, rw sum_empty, exact coe_lt_top _ })
(λa s ha ih h,
begin
rw [sum_insert ha, add_lt_top], split,
{ apply h, apply mem_insert_self },
{ apply ih, intros a ha, apply h, apply mem_insert_of_mem ha }
end)
/-- A sum of finite numbers is still finite -/
lemma sum_lt_top_iff [canonically_ordered_add_monoid β] {s : finset α} {f : α → with_top β} :
(∑ x in s, f x) < ⊤ ↔ (∀a∈s, f a < ⊤) :=
iff.intro (λh a ha, lt_of_le_of_lt (single_le_sum (λa ha, zero_le _) ha) h) sum_lt_top
/-- A sum of numbers is infinite iff one of them is infinite -/
lemma sum_eq_top_iff [canonically_ordered_add_monoid β] {s : finset α} {f : α → with_top β} :
(∑ x in s, f x) = ⊤ ↔ (∃a∈s, f a = ⊤) :=
begin
rw ← not_iff_not,
push_neg,
simp only [← lt_top_iff_ne_top],
exact sum_lt_top_iff
end
end with_top
|
cd549149541f947c61026f3d4b5e14d61b1ef22c | 4727251e0cd73359b15b664c3170e5d754078599 | /src/model_theory/elementary_maps.lean | 3a32fae56b587951dd784e47bed664dd9cc73c2b | [
"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 | 13,432 | lean | /-
Copyright (c) 2022 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson
-/
import data.fintype.basic
import model_theory.substructures
/-!
# Elementary Maps Between First-Order Structures
## Main Definitions
* A `first_order.language.elementary_embedding` is an embedding that commutes with the
realizations of formulas.
* A `first_order.language.elementary_substructure` is a substructure where the realization of each
formula agrees with the realization in the larger model.
* The `first_order.language.elementary_diagram` of a structure is the set of all sentences with
parameters that the structure satisfies.
* `first_order.language.elementary_embedding.of_models_elementary_diagram` is the canonical
elementary embedding of any structure into a model of its elementary diagram.
## Main Results
* The Tarski-Vaught Test for embeddings: `first_order.language.embedding.is_elementary_of_exists`
gives a simple criterion for an embedding to be elementary.
* The Tarski-Vaught Test for substructures: `first_order.language.embedding.is_elementary_of_exists`
gives a simple criterion for a substructure to be elementary.
-/
open_locale first_order
namespace first_order
namespace language
open Structure
variables (L : language) (M : Type*) (N : Type*) {P : Type*} {Q : Type*}
variables [L.Structure M] [L.Structure N] [L.Structure P] [L.Structure Q]
/-- An elementary embedding of first-order structures is an embedding that commutes with the
realizations of formulas. -/
structure elementary_embedding :=
(to_fun : M → N)
(map_formula' : ∀{n} (φ : L.formula (fin n)) (x : fin n → M),
φ.realize (to_fun ∘ x) ↔ φ.realize x . obviously)
localized "notation A ` ↪ₑ[`:25 L `] ` B := first_order.language.elementary_embedding L A B"
in first_order
variables {L} {M} {N}
namespace elementary_embedding
instance fun_like : fun_like (M ↪ₑ[L] N) M (λ _, N) :=
{ coe := λ f, f.to_fun,
coe_injective' := λ f g h, begin
cases f,
cases g,
simp only,
ext x,
exact function.funext_iff.1 h x end }
@[simp] lemma map_formula (f : M ↪ₑ[L] N) {α : Type} [fintype α] (φ : L.formula α) (x : α → M) :
φ.realize (f ∘ x) ↔ φ.realize x :=
begin
have g := fintype.equiv_fin α,
have h := f.map_formula' (φ.relabel g) (x ∘ g.symm),
rw [formula.realize_relabel, formula.realize_relabel, function.comp.assoc x g.symm g,
g.symm_comp_self, function.comp.right_id] at h,
rw [← h, iff_eq_eq],
congr,
ext y,
simp,
end
@[simp] lemma injective (φ : M ↪ₑ[L] N) :
function.injective φ :=
begin
intros x y,
have h := φ.map_formula ((var 0).equal (var 1) : L.formula (fin 2)) (λ i, if i = 0 then x else y),
rw [formula.realize_equal, formula.realize_equal] at h,
simp only [nat.one_ne_zero, term.realize, fin.one_eq_zero_iff, if_true, eq_self_iff_true,
function.comp_app, if_false] at h,
exact h.1,
end
instance embedding_like : embedding_like (M ↪ₑ[L] N) M N :=
{ injective' := injective }
instance has_coe_to_fun : has_coe_to_fun (M ↪ₑ[L] N) (λ _, M → N) :=
⟨λ f, f.to_fun⟩
@[simp] lemma map_fun (φ : M ↪ₑ[L] N) {n : ℕ} (f : L.functions n) (x : fin n → M) :
φ (fun_map f x) = fun_map f (φ ∘ x) :=
begin
have h := φ.map_formula (formula.graph f) (fin.cons (fun_map f x) x),
rw [formula.realize_graph, fin.comp_cons, formula.realize_graph] at h,
rw [eq_comm, h]
end
@[simp] lemma map_rel (φ : M ↪ₑ[L] N) {n : ℕ} (r : L.relations n) (x : fin n → M) :
rel_map r (φ ∘ x) ↔ rel_map r x :=
begin
have h := φ.map_formula (r.formula var) x,
exact h
end
instance strong_hom_class : strong_hom_class L (M ↪ₑ[L] N) M N :=
{ map_fun := map_fun,
map_rel := map_rel }
@[simp] lemma map_constants (φ : M ↪ₑ[L] N) (c : L.constants) : φ c = c :=
hom_class.map_constants φ c
/-- An elementary embedding is also a first-order embedding. -/
def to_embedding (f : M ↪ₑ[L] N) : M ↪[L] N :=
{ to_fun := f,
inj' := f.injective, }
/-- An elementary embedding is also a first-order homomorphism. -/
def to_hom (f : M ↪ₑ[L] N) : M →[L] N :=
{ to_fun := f }
@[simp] lemma to_embedding_to_hom (f : M ↪ₑ[L] N) : f.to_embedding.to_hom = f.to_hom := rfl
@[simp]
lemma coe_to_hom {f : M ↪ₑ[L] N} : (f.to_hom : M → N) = (f : M → N) := rfl
@[simp] lemma coe_to_embedding (f : M ↪ₑ[L] N) : (f.to_embedding : M → N) = (f : M → N) := rfl
lemma coe_injective : @function.injective (M ↪ₑ[L] N) (M → N) coe_fn :=
fun_like.coe_injective
@[ext]
lemma ext ⦃f g : M ↪ₑ[L] N⦄ (h : ∀ x, f x = g x) : f = g :=
fun_like.ext f g h
lemma ext_iff {f g : M ↪ₑ[L] N} : f = g ↔ ∀ x, f x = g x :=
fun_like.ext_iff
variables (L) (M)
/-- The identity elementary embedding from a structure to itself -/
@[refl] def refl : M ↪ₑ[L] M :=
{ to_fun := id }
variables {L} {M}
instance : inhabited (M ↪ₑ[L] M) := ⟨refl L M⟩
@[simp] lemma refl_apply (x : M) :
refl L M x = x := rfl
/-- Composition of elementary embeddings -/
@[trans] def comp (hnp : N ↪ₑ[L] P) (hmn : M ↪ₑ[L] N) : M ↪ₑ[L] P :=
{ to_fun := hnp ∘ hmn }
@[simp] lemma comp_apply (g : N ↪ₑ[L] P) (f : M ↪ₑ[L] N) (x : M) :
g.comp f x = g (f x) := rfl
/-- Composition of elementary embeddings is associative. -/
lemma comp_assoc (f : M ↪ₑ[L] N) (g : N ↪ₑ[L] P) (h : P ↪ₑ[L] Q) :
(h.comp g).comp f = h.comp (g.comp f) := rfl
end elementary_embedding
variables (L) (M)
/-- The elementary diagram of an `L`-structure is the set of all sentences with parameters it
satisfies. -/
abbreviation elementary_diagram : L[[M]].Theory := L[[M]].complete_theory M
/-- The canonical elementary embedding of an `L`-structure into any model of its elementary diagram
-/
@[simps] def elementary_embedding.of_models_elementary_diagram
(N : Type*) [L.Structure N] [L[[M]].Structure N]
[(Lhom_with_constants L M).is_expansion_on N] [N ⊨ L.elementary_diagram M] :
M ↪ₑ[L] N :=
⟨(coe : L[[M]].constants → N) ∘ sum.inr, λ n φ x, begin
refine trans _ ((realize_iff_of_model_complete_theory M N (((L.Lhom_with_constants
M).on_bounded_formula φ).subst (constants.term ∘ sum.inr ∘ x)).alls).trans _),
{ simp_rw [sentence.realize, bounded_formula.realize_alls, bounded_formula.realize_subst,
Lhom.realize_on_bounded_formula, formula.realize, unique.forall_iff, realize_constants] },
{ simp_rw [sentence.realize, bounded_formula.realize_alls, bounded_formula.realize_subst,
Lhom.realize_on_bounded_formula, formula.realize, unique.forall_iff],
refl }
end⟩
variables {L M}
namespace embedding
/-- The Tarski-Vaught test for elementarity of an embedding. -/
theorem is_elementary_of_exists (f : M ↪[L] N)
(htv : ∀ (n : ℕ) (φ : L.bounded_formula empty (n + 1)) (x : fin n → M) (a : N),
φ.realize default (fin.snoc (f ∘ x) a : _ → N) →
∃ b : M, φ.realize default (fin.snoc (f ∘ x) (f b) : _ → N)) :
∀{n} (φ : L.formula (fin n)) (x : fin n → M), φ.realize (f ∘ x) ↔ φ.realize x :=
begin
suffices h : ∀ (n : ℕ) (φ : L.bounded_formula empty n) (xs : fin n → M),
φ.realize (f ∘ default) (f ∘ xs) ↔ φ.realize default xs,
{ intros n φ x,
refine φ.realize_relabel_sum_inr.symm.trans (trans (h n _ _) φ.realize_relabel_sum_inr), },
refine λ n φ, φ.rec_on _ _ _ _ _,
{ exact λ _ _, iff.rfl },
{ intros,
simp [bounded_formula.realize, ← sum.comp_elim, embedding.realize_term] },
{ intros,
simp [bounded_formula.realize, ← sum.comp_elim, embedding.realize_term] },
{ intros _ _ _ ih1 ih2 _,
simp [ih1, ih2] },
{ intros n φ ih xs,
simp only [bounded_formula.realize_all],
refine ⟨λ h a, _, _⟩,
{ rw [← ih, fin.comp_snoc],
exact h (f a) },
{ contrapose!,
rintro ⟨a, ha⟩,
obtain ⟨b, hb⟩ := htv n φ.not xs a _,
{ refine ⟨b, λ h, hb (eq.mp _ ((ih _).2 h))⟩,
rw [unique.eq_default (f ∘ default), fin.comp_snoc], },
{ rw [bounded_formula.realize_not, ← unique.eq_default (f ∘ default)],
exact ha } } },
end
/-- Bundles an embedding satisfying the Tarski-Vaught test as an elementary embedding. -/
@[simps] def to_elementary_embedding (f : M ↪[L] N)
(htv : ∀ (n : ℕ) (φ : L.bounded_formula empty (n + 1)) (x : fin n → M) (a : N),
φ.realize default (fin.snoc (f ∘ x) a : _ → N) →
∃ b : M, φ.realize default (fin.snoc (f ∘ x) (f b) : _ → N)) :
M ↪ₑ[L] N :=
⟨f, λ _, f.is_elementary_of_exists htv⟩
end embedding
namespace equiv
/-- A first-order equivalence is also an elementary embedding. -/
def to_elementary_embedding (f : M ≃[L] N) : M ↪ₑ[L] N :=
{ to_fun := f }
@[simp] lemma to_elementary_embedding_to_embedding (f : M ≃[L] N) :
f.to_elementary_embedding.to_embedding = f.to_embedding := rfl
@[simp] lemma coe_to_elementary_embedding (f : M ≃[L] N) :
(f.to_elementary_embedding : M → N) = (f : M → N) := rfl
end equiv
@[simp] lemma realize_term_substructure {α : Type*} {S : L.substructure M} (v : α → S)
(t : L.term α) :
t.realize (coe ∘ v) = (↑(t.realize v) : M) :=
S.subtype.realize_term t
namespace substructure
@[simp] lemma realize_bounded_formula_top {α : Type*} {n : ℕ} {φ : L.bounded_formula α n}
{v : α → (⊤ : L.substructure M)} {xs : fin n → (⊤ : L.substructure M)} :
φ.realize v xs ↔ φ.realize ((coe : _ → M) ∘ v) (coe ∘ xs) :=
begin
rw ← substructure.top_equiv.realize_bounded_formula φ,
simp,
end
@[simp] lemma realize_formula_top {α : Type*} {φ : L.formula α} {v : α → (⊤ : L.substructure M)} :
φ.realize v ↔ φ.realize ((coe : (⊤ : L.substructure M) → M) ∘ v) :=
begin
rw ← substructure.top_equiv.realize_formula φ,
simp,
end
/-- A substructure is elementary when every formula applied to a tuple in the subtructure
agrees with its value in the overall structure. -/
def is_elementary (S : L.substructure M) : Prop :=
∀{n} (φ : L.formula (fin n)) (x : fin n → S), φ.realize ((coe : _ → M) ∘ x) ↔ φ.realize x
end substructure
variables (L) (M)
/-- An elementary substructure is one in which every formula applied to a tuple in the subtructure
agrees with its value in the overall structure. -/
structure elementary_substructure :=
(to_substructure : L.substructure M)
(is_elementary' : to_substructure.is_elementary)
variables {L} {M}
namespace elementary_substructure
instance : has_coe (L.elementary_substructure M) (L.substructure M) :=
⟨elementary_substructure.to_substructure⟩
instance : set_like (L.elementary_substructure M) M :=
⟨λ x, x.to_substructure.carrier, λ ⟨⟨s, hs1⟩, hs2⟩ ⟨⟨t, ht1⟩, ht2⟩ h, begin
congr,
exact h,
end⟩
@[simp] lemma is_elementary (S : L.elementary_substructure M) :
(S : L.substructure M).is_elementary := S.is_elementary'
/-- The natural embedding of an `L.substructure` of `M` into `M`. -/
def subtype (S : L.elementary_substructure M) : S ↪ₑ[L] M :=
{ to_fun := coe,
map_formula' := λ n, S.is_elementary }
@[simp] theorem coe_subtype {S : L.elementary_substructure M} : ⇑S.subtype = coe := rfl
/-- The substructure `M` of the structure `M` is elementary. -/
instance : has_top (L.elementary_substructure M) :=
⟨⟨⊤, λ n φ x, substructure.realize_formula_top.symm⟩⟩
instance : inhabited (L.elementary_substructure M) := ⟨⊤⟩
@[simp] lemma mem_top (x : M) : x ∈ (⊤ : L.elementary_substructure M) := set.mem_univ x
@[simp] lemma coe_top : ((⊤ : L.elementary_substructure M) : set M) = set.univ := rfl
@[simp] lemma realize_sentence (S : L.elementary_substructure M) (φ : L.sentence) :
S ⊨ φ ↔ M ⊨ φ :=
begin
have h := S.is_elementary (φ.relabel (empty.elim : empty → fin 0)) default,
rw [formula.realize_relabel, formula.realize_relabel] at h,
exact (congr (congr rfl (congr rfl (unique.eq_default _))) (congr rfl (unique.eq_default _))).mp
h.symm,
end
@[simp] lemma Theory_model_iff (S : L.elementary_substructure M) (T : L.Theory) :
S ⊨ T ↔ M ⊨ T :=
by simp only [Theory.model_iff, realize_sentence]
instance Theory_model {T : L.Theory} [h : M ⊨ T] {S : L.elementary_substructure M} : S ⊨ T :=
(Theory_model_iff S T).2 h
instance [h : nonempty M] {S : L.elementary_substructure M} : nonempty S :=
(model_nonempty_theory_iff L).1 infer_instance
end elementary_substructure
namespace substructure
/-- The Tarski-Vaught test for elementarity of a substructure. -/
theorem is_elementary_of_exists (S : L.substructure M)
(htv : ∀ (n : ℕ) (φ : L.bounded_formula empty (n + 1)) (x : fin n → S) (a : M),
φ.realize default (fin.snoc (coe ∘ x) a : _ → M) →
∃ b : S, φ.realize default (fin.snoc (coe ∘ x) b : _ → M)) :
S.is_elementary :=
λ n, S.subtype.is_elementary_of_exists htv
/-- Bundles a substructure satisfying the Tarski-Vaught test as an elementary substructure. -/
@[simps] def to_elementary_substructure (S : L.substructure M)
(htv : ∀ (n : ℕ) (φ : L.bounded_formula empty (n + 1)) (x : fin n → S) (a : M),
φ.realize default (fin.snoc (coe ∘ x) a : _ → M) →
∃ b : S, φ.realize default (fin.snoc (coe ∘ x) b : _ → M)) :
L.elementary_substructure M :=
⟨S, λ _, S.is_elementary_of_exists htv⟩
end substructure
end language
end first_order
|
42786bf809993a6502fb91a3def540e78282155b | e19b506b59d98b1469dd0023680087d321d0293d | /src/command/where/default.lean | 9f48a57496d72e31fd3a39d2fe29b1a4f2d71ef0 | [] | no_license | khoek/lean-where | ea28c2a63b0c28159f9363ee5f3101348b2b4744 | d2550de8655ece1cafbb9bf1beafe4d1c4481913 | refs/heads/master | 1,586,277,232,465 | 1,542,797,636,000 | 1,542,797,636,000 | 158,533,733 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 16 | lean | import .command
|
dc18827af56b8e3a1f389b74053efbde0d35c293 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/linear_algebra/affine_space/combination.lean | e58d5cd4e5ae4ecab234c254e6ecf1f0489d6fb3 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 42,858 | 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 algebra.invertible
import algebra.indicator_function
import linear_algebra.affine_space.affine_map
import linear_algebra.affine_space.affine_subspace
import linear_algebra.finsupp
import tactic.fin_cases
/-!
# Affine combinations of points
This file defines affine combinations of points.
## Main definitions
* `weighted_vsub_of_point` is a general weighted combination of
subtractions with an explicit base point, yielding a vector.
* `weighted_vsub` uses an arbitrary choice of base point and is intended
to be used when the sum of weights is 0, in which case the result is
independent of the choice of base point.
* `affine_combination` adds the weighted combination to the arbitrary
base point, yielding a point rather than a vector, and is intended
to be used when the sum of weights is 1, in which case the result is
independent of the choice of base point.
These definitions are for sums over a `finset`; versions for a
`fintype` may be obtained using `finset.univ`, while versions for a
`finsupp` may be obtained using `finsupp.support`.
## References
* https://en.wikipedia.org/wiki/Affine_space
-/
noncomputable theory
open_locale big_operators classical affine
namespace finset
lemma univ_fin2 : (univ : finset (fin 2)) = {0, 1} :=
by { ext x, fin_cases x; simp }
variables {k : Type*} {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V]
variables [S : affine_space V P]
include S
variables {ι : Type*} (s : finset ι)
variables {ι₂ : Type*} (s₂ : finset ι₂)
/-- A weighted sum of the results of subtracting a base point from the
given points, as a linear map on the weights. The main cases of
interest are where the sum of the weights is 0, in which case the sum
is independent of the choice of base point, and where the sum of the
weights is 1, in which case the sum added to the base point is
independent of the choice of base point. -/
def weighted_vsub_of_point (p : ι → P) (b : P) : (ι → k) →ₗ[k] V :=
∑ i in s, (linear_map.proj i : (ι → k) →ₗ[k] k).smul_right (p i -ᵥ b)
@[simp] lemma weighted_vsub_of_point_apply (w : ι → k) (p : ι → P) (b : P) :
s.weighted_vsub_of_point p b w = ∑ i in s, w i • (p i -ᵥ b) :=
by simp [weighted_vsub_of_point, linear_map.sum_apply]
/-- The value of `weighted_vsub_of_point`, where the given points are equal. -/
@[simp] lemma weighted_vsub_of_point_apply_const (w : ι → k) (p : P) (b : P) :
s.weighted_vsub_of_point (λ _, p) b w = (∑ i in s, w i) • (p -ᵥ b) :=
by rw [weighted_vsub_of_point_apply, sum_smul]
/-- Given a family of points, if we use a member of the family as a base point, the
`weighted_vsub_of_point` does not depend on the value of the weights at this point. -/
lemma weighted_vsub_of_point_eq_of_weights_eq
(p : ι → P) (j : ι) (w₁ w₂ : ι → k) (hw : ∀ i, i ≠ j → w₁ i = w₂ i) :
s.weighted_vsub_of_point p (p j) w₁ = s.weighted_vsub_of_point p (p j) w₂ :=
begin
simp only [finset.weighted_vsub_of_point_apply],
congr,
ext i,
cases eq_or_ne i j with h h,
{ simp [h], },
{ simp [hw i h], },
end
/-- The weighted sum is independent of the base point when the sum of
the weights is 0. -/
lemma weighted_vsub_of_point_eq_of_sum_eq_zero (w : ι → k) (p : ι → P) (h : ∑ i in s, w i = 0)
(b₁ b₂ : P) : s.weighted_vsub_of_point p b₁ w = s.weighted_vsub_of_point p b₂ w :=
begin
apply eq_of_sub_eq_zero,
rw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply, ←sum_sub_distrib],
conv_lhs
{ congr,
skip,
funext,
rw [←smul_sub, vsub_sub_vsub_cancel_left] },
rw [←sum_smul, h, zero_smul]
end
/-- The weighted sum, added to the base point, is independent of the
base point when the sum of the weights is 1. -/
lemma weighted_vsub_of_point_vadd_eq_of_sum_eq_one (w : ι → k) (p : ι → P) (h : ∑ i in s, w i = 1)
(b₁ b₂ : P) :
s.weighted_vsub_of_point p b₁ w +ᵥ b₁ = s.weighted_vsub_of_point p b₂ w +ᵥ b₂ :=
begin
erw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply, ←@vsub_eq_zero_iff_eq V,
vadd_vsub_assoc, vsub_vadd_eq_vsub_sub, ←add_sub_assoc, add_comm, add_sub_assoc,
←sum_sub_distrib],
conv_lhs
{ congr,
skip,
congr,
skip,
funext,
rw [←smul_sub, vsub_sub_vsub_cancel_left] },
rw [←sum_smul, h, one_smul, vsub_add_vsub_cancel, vsub_self]
end
/-- The weighted sum is unaffected by removing the base point, if
present, from the set of points. -/
@[simp] lemma weighted_vsub_of_point_erase (w : ι → k) (p : ι → P) (i : ι) :
(s.erase i).weighted_vsub_of_point p (p i) w = s.weighted_vsub_of_point p (p i) w :=
begin
rw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply],
apply sum_erase,
rw [vsub_self, smul_zero]
end
/-- The weighted sum is unaffected by adding the base point, whether
or not present, to the set of points. -/
@[simp] lemma weighted_vsub_of_point_insert [decidable_eq ι] (w : ι → k) (p : ι → P) (i : ι) :
(insert i s).weighted_vsub_of_point p (p i) w = s.weighted_vsub_of_point p (p i) w :=
begin
rw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply],
apply sum_insert_zero,
rw [vsub_self, smul_zero]
end
/-- The weighted sum is unaffected by changing the weights to the
corresponding indicator function and adding points to the set. -/
lemma weighted_vsub_of_point_indicator_subset (w : ι → k) (p : ι → P) (b : P) {s₁ s₂ : finset ι}
(h : s₁ ⊆ s₂) :
s₁.weighted_vsub_of_point p b w = s₂.weighted_vsub_of_point p b (set.indicator ↑s₁ w) :=
begin
rw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply],
exact set.sum_indicator_subset_of_eq_zero w (λ i wi, wi • (p i -ᵥ b : V)) h (λ i, zero_smul k _)
end
/-- A weighted sum, over the image of an embedding, equals a weighted
sum with the same points and weights over the original
`finset`. -/
lemma weighted_vsub_of_point_map (e : ι₂ ↪ ι) (w : ι → k) (p : ι → P) (b : P) :
(s₂.map e).weighted_vsub_of_point p b w = s₂.weighted_vsub_of_point (p ∘ e) b (w ∘ e) :=
begin
simp_rw [weighted_vsub_of_point_apply],
exact finset.sum_map _ _ _
end
/-- A weighted sum of pairwise subtractions, expressed as a subtraction of two
`weighted_vsub_of_point` expressions. -/
lemma sum_smul_vsub_eq_weighted_vsub_of_point_sub (w : ι → k) (p₁ p₂ : ι → P) (b : P) :
∑ i in s, w i • (p₁ i -ᵥ p₂ i) =
s.weighted_vsub_of_point p₁ b w - s.weighted_vsub_of_point p₂ b w :=
by simp_rw [weighted_vsub_of_point_apply, ←sum_sub_distrib, ←smul_sub, vsub_sub_vsub_cancel_right]
/-- A weighted sum of pairwise subtractions, where the point on the right is constant,
expressed as a subtraction involving a `weighted_vsub_of_point` expression. -/
lemma sum_smul_vsub_const_eq_weighted_vsub_of_point_sub (w : ι → k) (p₁ : ι → P) (p₂ b : P) :
∑ i in s, w i • (p₁ i -ᵥ p₂) = s.weighted_vsub_of_point p₁ b w - (∑ i in s, w i) • (p₂ -ᵥ b) :=
by rw [sum_smul_vsub_eq_weighted_vsub_of_point_sub, weighted_vsub_of_point_apply_const]
/-- A weighted sum of pairwise subtractions, where the point on the left is constant,
expressed as a subtraction involving a `weighted_vsub_of_point` expression. -/
lemma sum_smul_const_vsub_eq_sub_weighted_vsub_of_point (w : ι → k) (p₂ : ι → P) (p₁ b : P) :
∑ i in s, w i • (p₁ -ᵥ p₂ i) = (∑ i in s, w i) • (p₁ -ᵥ b) - s.weighted_vsub_of_point p₂ b w :=
by rw [sum_smul_vsub_eq_weighted_vsub_of_point_sub, weighted_vsub_of_point_apply_const]
/-- A weighted sum of the results of subtracting a default base point
from the given points, as a linear map on the weights. This is
intended to be used when the sum of the weights is 0; that condition
is specified as a hypothesis on those lemmas that require it. -/
def weighted_vsub (p : ι → P) : (ι → k) →ₗ[k] V :=
s.weighted_vsub_of_point p (classical.choice S.nonempty)
/-- Applying `weighted_vsub` with given weights. This is for the case
where a result involving a default base point is OK (for example, when
that base point will cancel out later); a more typical use case for
`weighted_vsub` would involve selecting a preferred base point with
`weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero` and then
using `weighted_vsub_of_point_apply`. -/
lemma weighted_vsub_apply (w : ι → k) (p : ι → P) :
s.weighted_vsub p w = ∑ i in s, w i • (p i -ᵥ (classical.choice S.nonempty)) :=
by simp [weighted_vsub, linear_map.sum_apply]
/-- `weighted_vsub` gives the sum of the results of subtracting any
base point, when the sum of the weights is 0. -/
lemma weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero (w : ι → k) (p : ι → P)
(h : ∑ i in s, w i = 0) (b : P) : s.weighted_vsub p w = s.weighted_vsub_of_point p b w :=
s.weighted_vsub_of_point_eq_of_sum_eq_zero w p h _ _
/-- The value of `weighted_vsub`, where the given points are equal and the sum of the weights
is 0. -/
@[simp] lemma weighted_vsub_apply_const (w : ι → k) (p : P) (h : ∑ i in s, w i = 0) :
s.weighted_vsub (λ _, p) w = 0 :=
by rw [weighted_vsub, weighted_vsub_of_point_apply_const, h, zero_smul]
/-- The `weighted_vsub` for an empty set is 0. -/
@[simp] lemma weighted_vsub_empty (w : ι → k) (p : ι → P) :
(∅ : finset ι).weighted_vsub p w = (0:V) :=
by simp [weighted_vsub_apply]
/-- The weighted sum is unaffected by changing the weights to the
corresponding indicator function and adding points to the set. -/
lemma weighted_vsub_indicator_subset (w : ι → k) (p : ι → P) {s₁ s₂ : finset ι} (h : s₁ ⊆ s₂) :
s₁.weighted_vsub p w = s₂.weighted_vsub p (set.indicator ↑s₁ w) :=
weighted_vsub_of_point_indicator_subset _ _ _ h
/-- A weighted subtraction, over the image of an embedding, equals a
weighted subtraction with the same points and weights over the
original `finset`. -/
lemma weighted_vsub_map (e : ι₂ ↪ ι) (w : ι → k) (p : ι → P) :
(s₂.map e).weighted_vsub p w = s₂.weighted_vsub (p ∘ e) (w ∘ e) :=
s₂.weighted_vsub_of_point_map _ _ _ _
/-- A weighted sum of pairwise subtractions, expressed as a subtraction of two `weighted_vsub`
expressions. -/
lemma sum_smul_vsub_eq_weighted_vsub_sub (w : ι → k) (p₁ p₂ : ι → P) :
∑ i in s, w i • (p₁ i -ᵥ p₂ i) = s.weighted_vsub p₁ w - s.weighted_vsub p₂ w :=
s.sum_smul_vsub_eq_weighted_vsub_of_point_sub _ _ _ _
/-- A weighted sum of pairwise subtractions, where the point on the right is constant and the
sum of the weights is 0. -/
lemma sum_smul_vsub_const_eq_weighted_vsub (w : ι → k) (p₁ : ι → P) (p₂ : P)
(h : ∑ i in s, w i = 0) :
∑ i in s, w i • (p₁ i -ᵥ p₂) = s.weighted_vsub p₁ w :=
by rw [sum_smul_vsub_eq_weighted_vsub_sub, s.weighted_vsub_apply_const _ _ h, sub_zero]
/-- A weighted sum of pairwise subtractions, where the point on the left is constant and the
sum of the weights is 0. -/
lemma sum_smul_const_vsub_eq_neg_weighted_vsub (w : ι → k) (p₂ : ι → P) (p₁ : P)
(h : ∑ i in s, w i = 0) :
∑ i in s, w i • (p₁ -ᵥ p₂ i) = -s.weighted_vsub p₂ w :=
by rw [sum_smul_vsub_eq_weighted_vsub_sub, s.weighted_vsub_apply_const _ _ h, zero_sub]
/-- A weighted sum of the results of subtracting a default base point
from the given points, added to that base point, as an affine map on
the weights. This is intended to be used when the sum of the weights
is 1, in which case it is an affine combination (barycenter) of the
points with the given weights; that condition is specified as a
hypothesis on those lemmas that require it. -/
def affine_combination (p : ι → P) : (ι → k) →ᵃ[k] P :=
{ to_fun := λ w,
s.weighted_vsub_of_point p (classical.choice S.nonempty) w +ᵥ (classical.choice S.nonempty),
linear := s.weighted_vsub p,
map_vadd' := λ w₁ w₂, by simp_rw [vadd_vadd, weighted_vsub, vadd_eq_add, linear_map.map_add] }
/-- The linear map corresponding to `affine_combination` is
`weighted_vsub`. -/
@[simp] lemma affine_combination_linear (p : ι → P) :
(s.affine_combination p : (ι → k) →ᵃ[k] P).linear = s.weighted_vsub p :=
rfl
/-- Applying `affine_combination` with given weights. This is for the
case where a result involving a default base point is OK (for example,
when that base point will cancel out later); a more typical use case
for `affine_combination` would involve selecting a preferred base
point with
`affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one` and
then using `weighted_vsub_of_point_apply`. -/
lemma affine_combination_apply (w : ι → k) (p : ι → P) :
s.affine_combination p w =
s.weighted_vsub_of_point p (classical.choice S.nonempty) w +ᵥ (classical.choice S.nonempty) :=
rfl
/-- The value of `affine_combination`, where the given points are equal. -/
@[simp] lemma affine_combination_apply_const (w : ι → k) (p : P) (h : ∑ i in s, w i = 1) :
s.affine_combination (λ _, p) w = p :=
by rw [affine_combination_apply, s.weighted_vsub_of_point_apply_const, h, one_smul, vsub_vadd]
/-- `affine_combination` gives the sum with any base point, when the
sum of the weights is 1. -/
lemma affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one (w : ι → k) (p : ι → P)
(h : ∑ i in s, w i = 1) (b : P) :
s.affine_combination p w = s.weighted_vsub_of_point p b w +ᵥ b :=
s.weighted_vsub_of_point_vadd_eq_of_sum_eq_one w p h _ _
/-- Adding a `weighted_vsub` to an `affine_combination`. -/
lemma weighted_vsub_vadd_affine_combination (w₁ w₂ : ι → k) (p : ι → P) :
s.weighted_vsub p w₁ +ᵥ s.affine_combination p w₂ = s.affine_combination p (w₁ + w₂) :=
by rw [←vadd_eq_add, affine_map.map_vadd, affine_combination_linear]
/-- Subtracting two `affine_combination`s. -/
lemma affine_combination_vsub (w₁ w₂ : ι → k) (p : ι → P) :
s.affine_combination p w₁ -ᵥ s.affine_combination p w₂ = s.weighted_vsub p (w₁ - w₂) :=
by rw [←affine_map.linear_map_vsub, affine_combination_linear, vsub_eq_sub]
lemma attach_affine_combination_of_injective
(s : finset P) (w : P → k) (f : s → P) (hf : function.injective f) :
s.attach.affine_combination f (w ∘ f) = (image f univ).affine_combination id w :=
begin
simp only [affine_combination, weighted_vsub_of_point_apply, id.def, vadd_right_cancel_iff,
function.comp_app, affine_map.coe_mk],
let g₁ : s → V := λ i, w (f i) • (f i -ᵥ classical.choice S.nonempty),
let g₂ : P → V := λ i, w i • (i -ᵥ classical.choice S.nonempty),
change univ.sum g₁ = (image f univ).sum g₂,
have hgf : g₁ = g₂ ∘ f, { ext, simp, },
rw [hgf, sum_image],
exact λ _ _ _ _ hxy, hf hxy,
end
lemma attach_affine_combination_coe (s : finset P) (w : P → k) :
s.attach.affine_combination (coe : s → P) (w ∘ coe) = s.affine_combination id w :=
by rw [attach_affine_combination_of_injective s w (coe : s → P) subtype.coe_injective,
univ_eq_attach, attach_image_coe]
omit S
/-- Viewing a module as an affine space modelled on itself, a `weighted_vsub` is just a linear
combination. -/
@[simp] lemma weighted_vsub_eq_linear_combination
{ι} (s : finset ι) {w : ι → k} {p : ι → V} (hw : s.sum w = 0) :
s.weighted_vsub p w = ∑ i in s, w i • p i :=
by simp [s.weighted_vsub_apply, vsub_eq_sub, smul_sub, ← finset.sum_smul, hw]
/-- Viewing a module as an affine space modelled on itself, affine combinations are just linear
combinations. -/
@[simp] lemma affine_combination_eq_linear_combination (s : finset ι) (p : ι → V) (w : ι → k)
(hw : ∑ i in s, w i = 1) :
s.affine_combination p w = ∑ i in s, w i • p i :=
by simp [s.affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one w p hw 0]
include S
/-- An `affine_combination` equals a point if that point is in the set
and has weight 1 and the other points in the set have weight 0. -/
@[simp] lemma affine_combination_of_eq_one_of_eq_zero (w : ι → k) (p : ι → P) {i : ι}
(his : i ∈ s) (hwi : w i = 1) (hw0 : ∀ i2 ∈ s, i2 ≠ i → w i2 = 0) :
s.affine_combination p w = p i :=
begin
have h1 : ∑ i in s, w i = 1 := hwi ▸ sum_eq_single i hw0 (λ h, false.elim (h his)),
rw [s.affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one w p h1 (p i),
weighted_vsub_of_point_apply],
convert zero_vadd V (p i),
convert sum_eq_zero _,
intros i2 hi2,
by_cases h : i2 = i,
{ simp [h] },
{ simp [hw0 i2 hi2 h] }
end
/-- An affine combination is unaffected by changing the weights to the
corresponding indicator function and adding points to the set. -/
lemma affine_combination_indicator_subset (w : ι → k) (p : ι → P) {s₁ s₂ : finset ι}
(h : s₁ ⊆ s₂) :
s₁.affine_combination p w = s₂.affine_combination p (set.indicator ↑s₁ w) :=
by rw [affine_combination_apply, affine_combination_apply,
weighted_vsub_of_point_indicator_subset _ _ _ h]
/-- An affine combination, over the image of an embedding, equals an
affine combination with the same points and weights over the original
`finset`. -/
lemma affine_combination_map (e : ι₂ ↪ ι) (w : ι → k) (p : ι → P) :
(s₂.map e).affine_combination p w = s₂.affine_combination (p ∘ e) (w ∘ e) :=
by simp_rw [affine_combination_apply, weighted_vsub_of_point_map]
/-- A weighted sum of pairwise subtractions, expressed as a subtraction of two `affine_combination`
expressions. -/
lemma sum_smul_vsub_eq_affine_combination_vsub (w : ι → k) (p₁ p₂ : ι → P) :
∑ i in s, w i • (p₁ i -ᵥ p₂ i) = s.affine_combination p₁ w -ᵥ s.affine_combination p₂ w :=
begin
simp_rw [affine_combination_apply, vadd_vsub_vadd_cancel_right],
exact s.sum_smul_vsub_eq_weighted_vsub_of_point_sub _ _ _ _
end
/-- A weighted sum of pairwise subtractions, where the point on the right is constant and the
sum of the weights is 1. -/
lemma sum_smul_vsub_const_eq_affine_combination_vsub (w : ι → k) (p₁ : ι → P) (p₂ : P)
(h : ∑ i in s, w i = 1) :
∑ i in s, w i • (p₁ i -ᵥ p₂) = s.affine_combination p₁ w -ᵥ p₂ :=
by rw [sum_smul_vsub_eq_affine_combination_vsub, affine_combination_apply_const _ _ _ h]
/-- A weighted sum of pairwise subtractions, where the point on the left is constant and the
sum of the weights is 1. -/
lemma sum_smul_const_vsub_eq_vsub_affine_combination (w : ι → k) (p₂ : ι → P) (p₁ : P)
(h : ∑ i in s, w i = 1) :
∑ i in s, w i • (p₁ -ᵥ p₂ i) = p₁ -ᵥ s.affine_combination p₂ w :=
by rw [sum_smul_vsub_eq_affine_combination_vsub, affine_combination_apply_const _ _ _ h]
variables {V}
/-- Suppose an indexed family of points is given, along with a subset
of the index type. A vector can be expressed as
`weighted_vsub_of_point` using a `finset` lying within that subset and
with a given sum of weights if and only if it can be expressed as
`weighted_vsub_of_point` with that sum of weights for the
corresponding indexed family whose index type is the subtype
corresponding to that subset. -/
lemma eq_weighted_vsub_of_point_subset_iff_eq_weighted_vsub_of_point_subtype {v : V} {x : k}
{s : set ι} {p : ι → P} {b : P} :
(∃ (fs : finset ι) (hfs : ↑fs ⊆ s) (w : ι → k) (hw : ∑ i in fs, w i = x),
v = fs.weighted_vsub_of_point p b w) ↔
∃ (fs : finset s) (w : s → k) (hw : ∑ i in fs, w i = x),
v = fs.weighted_vsub_of_point (λ (i : s), p i) b w :=
begin
simp_rw weighted_vsub_of_point_apply,
split,
{ rintros ⟨fs, hfs, w, rfl, rfl⟩,
use [fs.subtype s, λ i, w i, sum_subtype_of_mem _ hfs, (sum_subtype_of_mem _ hfs).symm] },
{ rintros ⟨fs, w, rfl, rfl⟩,
refine ⟨fs.map (function.embedding.subtype _), map_subtype_subset _,
λ i, if h : i ∈ s then w ⟨i, h⟩ else 0, _, _⟩;
simp }
end
variables (k)
/-- Suppose an indexed family of points is given, along with a subset
of the index type. A vector can be expressed as `weighted_vsub` using
a `finset` lying within that subset and with sum of weights 0 if and
only if it can be expressed as `weighted_vsub` with sum of weights 0
for the corresponding indexed family whose index type is the subtype
corresponding to that subset. -/
lemma eq_weighted_vsub_subset_iff_eq_weighted_vsub_subtype {v : V} {s : set ι} {p : ι → P} :
(∃ (fs : finset ι) (hfs : ↑fs ⊆ s) (w : ι → k) (hw : ∑ i in fs, w i = 0),
v = fs.weighted_vsub p w) ↔
∃ (fs : finset s) (w : s → k) (hw : ∑ i in fs, w i = 0),
v = fs.weighted_vsub (λ (i : s), p i) w :=
eq_weighted_vsub_of_point_subset_iff_eq_weighted_vsub_of_point_subtype
variables (V)
/-- Suppose an indexed family of points is given, along with a subset
of the index type. A point can be expressed as an
`affine_combination` using a `finset` lying within that subset and
with sum of weights 1 if and only if it can be expressed an
`affine_combination` with sum of weights 1 for the corresponding
indexed family whose index type is the subtype corresponding to that
subset. -/
lemma eq_affine_combination_subset_iff_eq_affine_combination_subtype {p0 : P} {s : set ι}
{p : ι → P} :
(∃ (fs : finset ι) (hfs : ↑fs ⊆ s) (w : ι → k) (hw : ∑ i in fs, w i = 1),
p0 = fs.affine_combination p w) ↔
∃ (fs : finset s) (w : s → k) (hw : ∑ i in fs, w i = 1),
p0 = fs.affine_combination (λ (i : s), p i) w :=
begin
simp_rw [affine_combination_apply, eq_vadd_iff_vsub_eq],
exact eq_weighted_vsub_of_point_subset_iff_eq_weighted_vsub_of_point_subtype
end
variables {k V}
/-- Affine maps commute with affine combinations. -/
lemma map_affine_combination {V₂ P₂ : Type*} [add_comm_group V₂] [module k V₂] [affine_space V₂ P₂]
(p : ι → P) (w : ι → k) (hw : s.sum w = 1) (f : P →ᵃ[k] P₂) :
f (s.affine_combination p w) = s.affine_combination (f ∘ p) w :=
begin
have b := classical.choice (infer_instance : affine_space V P).nonempty,
have b₂ := classical.choice (infer_instance : affine_space V₂ P₂).nonempty,
rw [s.affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one w p hw b,
s.affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one w (f ∘ p) hw b₂,
← s.weighted_vsub_of_point_vadd_eq_of_sum_eq_one w (f ∘ p) hw (f b) b₂],
simp only [weighted_vsub_of_point_apply, ring_hom.id_apply, affine_map.map_vadd,
linear_map.map_smulₛₗ, affine_map.linear_map_vsub, linear_map.map_sum],
end
end finset
namespace finset
variables (k : Type*) {V : Type*} {P : Type*} [division_ring k] [add_comm_group V] [module k V]
variables [affine_space V P] {ι : Type*} (s : finset ι) {ι₂ : Type*} (s₂ : finset ι₂)
/-- The weights for the centroid of some points. -/
def centroid_weights : ι → k := function.const ι (card s : k) ⁻¹
/-- `centroid_weights` at any point. -/
@[simp] lemma centroid_weights_apply (i : ι) : s.centroid_weights k i = (card s : k) ⁻¹ :=
rfl
/-- `centroid_weights` equals a constant function. -/
lemma centroid_weights_eq_const :
s.centroid_weights k = function.const ι ((card s : k) ⁻¹) :=
rfl
variables {k}
/-- The weights in the centroid sum to 1, if the number of points,
converted to `k`, is not zero. -/
lemma sum_centroid_weights_eq_one_of_cast_card_ne_zero (h : (card s : k) ≠ 0) :
∑ i in s, s.centroid_weights k i = 1 :=
by simp [h]
variables (k)
/-- In the characteristic zero case, the weights in the centroid sum
to 1 if the number of points is not zero. -/
lemma sum_centroid_weights_eq_one_of_card_ne_zero [char_zero k] (h : card s ≠ 0) :
∑ i in s, s.centroid_weights k i = 1 :=
by simp [h]
/-- In the characteristic zero case, the weights in the centroid sum
to 1 if the set is nonempty. -/
lemma sum_centroid_weights_eq_one_of_nonempty [char_zero k] (h : s.nonempty) :
∑ i in s, s.centroid_weights k i = 1 :=
s.sum_centroid_weights_eq_one_of_card_ne_zero k (ne_of_gt (card_pos.2 h))
/-- In the characteristic zero case, the weights in the centroid sum
to 1 if the number of points is `n + 1`. -/
lemma sum_centroid_weights_eq_one_of_card_eq_add_one [char_zero k] {n : ℕ}
(h : card s = n + 1) : ∑ i in s, s.centroid_weights k i = 1 :=
s.sum_centroid_weights_eq_one_of_card_ne_zero k (h.symm ▸ nat.succ_ne_zero n)
include V
/-- The centroid of some points. Although defined for any `s`, this
is intended to be used in the case where the number of points,
converted to `k`, is not zero. -/
def centroid (p : ι → P) : P :=
s.affine_combination p (s.centroid_weights k)
/-- The definition of the centroid. -/
lemma centroid_def (p : ι → P) :
s.centroid k p = s.affine_combination p (s.centroid_weights k) :=
rfl
lemma centroid_univ (s : finset P) :
univ.centroid k (coe : s → P) = s.centroid k id :=
by { rw [centroid, centroid, ← s.attach_affine_combination_coe], congr, ext, simp, }
/-- The centroid of a single point. -/
@[simp] lemma centroid_singleton (p : ι → P) (i : ι) :
({i} : finset ι).centroid k p = p i :=
by simp [centroid_def, affine_combination_apply]
/-- The centroid of two points, expressed directly as adding a vector
to a point. -/
lemma centroid_pair [invertible (2 : k)] (p : ι → P) (i₁ i₂ : ι) :
({i₁, i₂} : finset ι).centroid k p = (2 ⁻¹ : k) • (p i₂ -ᵥ p i₁) +ᵥ p i₁ :=
begin
by_cases h : i₁ = i₂,
{ simp [h] },
{ have hc : (card ({i₁, i₂} : finset ι) : k) ≠ 0,
{ rw [card_insert_of_not_mem (not_mem_singleton.2 h), card_singleton],
norm_num,
exact nonzero_of_invertible _ },
rw [centroid_def,
affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one _ _ _
(sum_centroid_weights_eq_one_of_cast_card_ne_zero _ hc) (p i₁)],
simp [h] }
end
/-- The centroid of two points indexed by `fin 2`, expressed directly
as adding a vector to the first point. -/
lemma centroid_pair_fin [invertible (2 : k)] (p : fin 2 → P) :
univ.centroid k p = (2 ⁻¹ : k) • (p 1 -ᵥ p 0) +ᵥ p 0 :=
begin
rw univ_fin2,
convert centroid_pair k p 0 1
end
/-- A centroid, over the image of an embedding, equals a centroid with
the same points and weights over the original `finset`. -/
lemma centroid_map (e : ι₂ ↪ ι) (p : ι → P) : (s₂.map e).centroid k p = s₂.centroid k (p ∘ e) :=
by simp [centroid_def, affine_combination_map, centroid_weights]
omit V
/-- `centroid_weights` gives the weights for the centroid as a
constant function, which is suitable when summing over the points
whose centroid is being taken. This function gives the weights in a
form suitable for summing over a larger set of points, as an indicator
function that is zero outside the set whose centroid is being taken.
In the case of a `fintype`, the sum may be over `univ`. -/
def centroid_weights_indicator : ι → k := set.indicator ↑s (s.centroid_weights k)
/-- The definition of `centroid_weights_indicator`. -/
lemma centroid_weights_indicator_def :
s.centroid_weights_indicator k = set.indicator ↑s (s.centroid_weights k) :=
rfl
/-- The sum of the weights for the centroid indexed by a `fintype`. -/
lemma sum_centroid_weights_indicator [fintype ι] :
∑ i, s.centroid_weights_indicator k i = ∑ i in s, s.centroid_weights k i :=
(set.sum_indicator_subset _ (subset_univ _)).symm
/-- In the characteristic zero case, the weights in the centroid
indexed by a `fintype` sum to 1 if the number of points is not
zero. -/
lemma sum_centroid_weights_indicator_eq_one_of_card_ne_zero [char_zero k] [fintype ι]
(h : card s ≠ 0) : ∑ i, s.centroid_weights_indicator k i = 1 :=
begin
rw sum_centroid_weights_indicator,
exact s.sum_centroid_weights_eq_one_of_card_ne_zero k h
end
/-- In the characteristic zero case, the weights in the centroid
indexed by a `fintype` sum to 1 if the set is nonempty. -/
lemma sum_centroid_weights_indicator_eq_one_of_nonempty [char_zero k] [fintype ι]
(h : s.nonempty) : ∑ i, s.centroid_weights_indicator k i = 1 :=
begin
rw sum_centroid_weights_indicator,
exact s.sum_centroid_weights_eq_one_of_nonempty k h
end
/-- In the characteristic zero case, the weights in the centroid
indexed by a `fintype` sum to 1 if the number of points is `n + 1`. -/
lemma sum_centroid_weights_indicator_eq_one_of_card_eq_add_one [char_zero k] [fintype ι] {n : ℕ}
(h : card s = n + 1) : ∑ i, s.centroid_weights_indicator k i = 1 :=
begin
rw sum_centroid_weights_indicator,
exact s.sum_centroid_weights_eq_one_of_card_eq_add_one k h
end
include V
/-- The centroid as an affine combination over a `fintype`. -/
lemma centroid_eq_affine_combination_fintype [fintype ι] (p : ι → P) :
s.centroid k p = univ.affine_combination p (s.centroid_weights_indicator k) :=
affine_combination_indicator_subset _ _ (subset_univ _)
/-- An indexed family of points that is injective on the given
`finset` has the same centroid as the image of that `finset`. This is
stated in terms of a set equal to the image to provide control of
definitional equality for the index type used for the centroid of the
image. -/
lemma centroid_eq_centroid_image_of_inj_on {p : ι → P} (hi : ∀ i j ∈ s, p i = p j → i = j)
{ps : set P} [fintype ps] (hps : ps = p '' ↑s) :
s.centroid k p = (univ : finset ps).centroid k (λ x, x) :=
begin
let f : p '' ↑s → ι := λ x, x.property.some,
have hf : ∀ x, f x ∈ s ∧ p (f x) = x := λ x, x.property.some_spec,
let f' : ps → ι := λ x, f ⟨x, hps ▸ x.property⟩,
have hf' : ∀ x, f' x ∈ s ∧ p (f' x) = x := λ x, hf ⟨x, hps ▸ x.property⟩,
have hf'i : function.injective f',
{ intros x y h,
rw [subtype.ext_iff, ←(hf' x).2, ←(hf' y).2, h] },
let f'e : ps ↪ ι := ⟨f', hf'i⟩,
have hu : finset.univ.map f'e = s,
{ ext x,
rw mem_map,
split,
{ rintros ⟨i, _, rfl⟩,
exact (hf' i).1 },
{ intro hx,
use [⟨p x, hps.symm ▸ set.mem_image_of_mem _ hx⟩, mem_univ _],
refine hi _ (hf' _).1 _ hx _,
rw (hf' _).2,
refl } },
rw [←hu, centroid_map],
congr' with x,
change p (f' x) = ↑x,
rw (hf' x).2
end
/-- Two indexed families of points that are injective on the given
`finset`s and with the same points in the image of those `finset`s
have the same centroid. -/
lemma centroid_eq_of_inj_on_of_image_eq {p : ι → P} (hi : ∀ i j ∈ s, p i = p j → i = j)
{p₂ : ι₂ → P} (hi₂ : ∀ i j ∈ s₂, p₂ i = p₂ j → i = j) (he : p '' ↑s = p₂ '' ↑s₂) :
s.centroid k p = s₂.centroid k p₂ :=
by rw [s.centroid_eq_centroid_image_of_inj_on k hi rfl,
s₂.centroid_eq_centroid_image_of_inj_on k hi₂ he]
end finset
section affine_space'
variables {k : Type*} {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V]
[affine_space V P]
variables {ι : Type*}
include V
/-- A `weighted_vsub` with sum of weights 0 is in the `vector_span` of
an indexed family. -/
lemma weighted_vsub_mem_vector_span {s : finset ι} {w : ι → k}
(h : ∑ i in s, w i = 0) (p : ι → P) :
s.weighted_vsub p w ∈ vector_span k (set.range p) :=
begin
rcases is_empty_or_nonempty ι with hι|⟨⟨i0⟩⟩,
{ resetI, simp [finset.eq_empty_of_is_empty s] },
{ rw [vector_span_range_eq_span_range_vsub_right k p i0, ←set.image_univ,
finsupp.mem_span_image_iff_total,
finset.weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero s w p h (p i0),
finset.weighted_vsub_of_point_apply],
let w' := set.indicator ↑s w,
have hwx : ∀ i, w' i ≠ 0 → i ∈ s := λ i, set.mem_of_indicator_ne_zero,
use [finsupp.on_finset s w' hwx, set.subset_univ _],
rw [finsupp.total_apply, finsupp.on_finset_sum hwx],
{ apply finset.sum_congr rfl,
intros i hi,
simp [w', set.indicator_apply, if_pos hi] },
{ exact λ _, zero_smul k _ } },
end
/-- An `affine_combination` with sum of weights 1 is in the
`affine_span` of an indexed family, if the underlying ring is
nontrivial. -/
lemma affine_combination_mem_affine_span [nontrivial k] {s : finset ι} {w : ι → k}
(h : ∑ i in s, w i = 1) (p : ι → P) :
s.affine_combination p w ∈ affine_span k (set.range p) :=
begin
have hnz : ∑ i in s, w i ≠ 0 := h.symm ▸ one_ne_zero,
have hn : s.nonempty := finset.nonempty_of_sum_ne_zero hnz,
cases hn with i1 hi1,
let w1 : ι → k := function.update (function.const ι 0) i1 1,
have hw1 : ∑ i in s, w1 i = 1,
{ rw [finset.sum_update_of_mem hi1, finset.sum_const_zero, add_zero] },
have hw1s : s.affine_combination p w1 = p i1 :=
s.affine_combination_of_eq_one_of_eq_zero w1 p hi1 (function.update_same _ _ _)
(λ _ _ hne, function.update_noteq hne _ _),
have hv : s.affine_combination p w -ᵥ p i1 ∈ (affine_span k (set.range p)).direction,
{ rw [direction_affine_span, ←hw1s, finset.affine_combination_vsub],
apply weighted_vsub_mem_vector_span,
simp [pi.sub_apply, h, hw1] },
rw ←vsub_vadd (s.affine_combination p w) (p i1),
exact affine_subspace.vadd_mem_of_mem_direction hv (mem_affine_span k (set.mem_range_self _))
end
variables (k) {V}
/-- A vector is in the `vector_span` of an indexed family if and only
if it is a `weighted_vsub` with sum of weights 0. -/
lemma mem_vector_span_iff_eq_weighted_vsub {v : V} {p : ι → P} :
v ∈ vector_span k (set.range p) ↔
∃ (s : finset ι) (w : ι → k) (h : ∑ i in s, w i = 0), v = s.weighted_vsub p w :=
begin
split,
{ rcases is_empty_or_nonempty ι with hι|⟨⟨i0⟩⟩, swap,
{ rw [vector_span_range_eq_span_range_vsub_right k p i0, ←set.image_univ,
finsupp.mem_span_image_iff_total],
rintros ⟨l, hl, hv⟩,
use insert i0 l.support,
set w := (l : ι → k) -
function.update (function.const ι 0 : ι → k) i0 (∑ i in l.support, l i) with hwdef,
use w,
have hw : ∑ i in insert i0 l.support, w i = 0,
{ rw hwdef,
simp_rw [pi.sub_apply, finset.sum_sub_distrib,
finset.sum_update_of_mem (finset.mem_insert_self _ _), finset.sum_const_zero,
finset.sum_insert_of_eq_zero_if_not_mem finsupp.not_mem_support_iff.1,
add_zero, sub_self] },
use hw,
have hz : w i0 • (p i0 -ᵥ p i0 : V) = 0 := (vsub_self (p i0)).symm ▸ smul_zero _,
change (λ i, w i • (p i -ᵥ p i0 : V)) i0 = 0 at hz,
rw [finset.weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero _ w p hw (p i0),
finset.weighted_vsub_of_point_apply, ←hv, finsupp.total_apply,
finset.sum_insert_zero hz],
change ∑ i in l.support, l i • _ = _,
congr' with i,
by_cases h : i = i0,
{ simp [h] },
{ simp [hwdef, h] } },
{ resetI,
rw [set.range_eq_empty, vector_span_empty, submodule.mem_bot],
rintro rfl,
use [∅],
simp } },
{ rintros ⟨s, w, hw, rfl⟩,
exact weighted_vsub_mem_vector_span hw p }
end
variables {k}
/-- A point in the `affine_span` of an indexed family is an
`affine_combination` with sum of weights 1. See also
`eq_affine_combination_of_mem_affine_span_of_fintype`. -/
lemma eq_affine_combination_of_mem_affine_span {p1 : P} {p : ι → P}
(h : p1 ∈ affine_span k (set.range p)) :
∃ (s : finset ι) (w : ι → k) (hw : ∑ i in s, w i = 1), p1 = s.affine_combination p w :=
begin
have hn : ((affine_span k (set.range p)) : set P).nonempty := ⟨p1, h⟩,
rw [affine_span_nonempty, set.range_nonempty_iff_nonempty] at hn,
cases hn with i0,
have h0 : p i0 ∈ affine_span k (set.range p) := mem_affine_span k (set.mem_range_self i0),
have hd : p1 -ᵥ p i0 ∈ (affine_span k (set.range p)).direction :=
affine_subspace.vsub_mem_direction h h0,
rw [direction_affine_span, mem_vector_span_iff_eq_weighted_vsub] at hd,
rcases hd with ⟨s, w, h, hs⟩,
let s' := insert i0 s,
let w' := set.indicator ↑s w,
have h' : ∑ i in s', w' i = 0,
{ rw [←h, set.sum_indicator_subset _ (finset.subset_insert i0 s)] },
have hs' : s'.weighted_vsub p w' = p1 -ᵥ p i0,
{ rw hs,
exact (finset.weighted_vsub_indicator_subset _ _ (finset.subset_insert i0 s)).symm },
let w0 : ι → k := function.update (function.const ι 0) i0 1,
have hw0 : ∑ i in s', w0 i = 1,
{ rw [finset.sum_update_of_mem (finset.mem_insert_self _ _), finset.sum_const_zero, add_zero] },
have hw0s : s'.affine_combination p w0 = p i0 :=
s'.affine_combination_of_eq_one_of_eq_zero w0 p
(finset.mem_insert_self _ _)
(function.update_same _ _ _)
(λ _ _ hne, function.update_noteq hne _ _),
use [s', w0 + w'],
split,
{ simp [pi.add_apply, finset.sum_add_distrib, hw0, h'] },
{ rw [add_comm, ←finset.weighted_vsub_vadd_affine_combination, hw0s, hs', vsub_vadd] }
end
lemma eq_affine_combination_of_mem_affine_span_of_fintype [fintype ι] {p1 : P} {p : ι → P}
(h : p1 ∈ affine_span k (set.range p)) :
∃ (w : ι → k) (hw : ∑ i, w i = 1), p1 = finset.univ.affine_combination p w :=
begin
obtain ⟨s, w, hw, rfl⟩ := eq_affine_combination_of_mem_affine_span h,
refine ⟨(s : set ι).indicator w, _, finset.affine_combination_indicator_subset w p s.subset_univ⟩,
simp only [finset.mem_coe, set.indicator_apply, ← hw],
rw fintype.sum_extend_by_zero s w,
end
variables (k V)
/-- A point is in the `affine_span` of an indexed family if and only
if it is an `affine_combination` with sum of weights 1, provided the
underlying ring is nontrivial. -/
lemma mem_affine_span_iff_eq_affine_combination [nontrivial k] {p1 : P} {p : ι → P} :
p1 ∈ affine_span k (set.range p) ↔
∃ (s : finset ι) (w : ι → k) (hw : ∑ i in s, w i = 1), p1 = s.affine_combination p w :=
begin
split,
{ exact eq_affine_combination_of_mem_affine_span },
{ rintros ⟨s, w, hw, rfl⟩,
exact affine_combination_mem_affine_span hw p }
end
/-- Given a family of points together with a chosen base point in that family, membership of the
affine span of this family corresponds to an identity in terms of `weighted_vsub_of_point`, with
weights that are not required to sum to 1. -/
lemma mem_affine_span_iff_eq_weighted_vsub_of_point_vadd
[nontrivial k] (p : ι → P) (j : ι) (q : P) :
q ∈ affine_span k (set.range p) ↔
∃ (s : finset ι) (w : ι → k), q = s.weighted_vsub_of_point p (p j) w +ᵥ (p j) :=
begin
split,
{ intros hq,
obtain ⟨s, w, hw, rfl⟩ := eq_affine_combination_of_mem_affine_span hq,
exact ⟨s, w, s.affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one w p hw (p j)⟩, },
{ rintros ⟨s, w, rfl⟩,
classical,
let w' : ι → k := function.update w j (1 - (s \ {j}).sum w),
have h₁ : (insert j s).sum w' = 1,
{ by_cases hj : j ∈ s,
{ simp [finset.sum_update_of_mem hj, finset.insert_eq_of_mem hj], },
{ simp [w', finset.sum_insert hj, finset.sum_update_of_not_mem hj, hj], }, },
have hww : ∀ i, i ≠ j → w i = w' i, { intros i hij, simp [w', hij], },
rw [s.weighted_vsub_of_point_eq_of_weights_eq p j w w' hww,
← s.weighted_vsub_of_point_insert w' p j,
← (insert j s).affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one w' p h₁ (p j)],
exact affine_combination_mem_affine_span h₁ p, },
end
variables {k V}
/-- Given a set of points, together with a chosen base point in this set, if we affinely transport
all other members of the set along the line joining them to this base point, the affine span is
unchanged. -/
lemma affine_span_eq_affine_span_line_map_units [nontrivial k]
{s : set P} {p : P} (hp : p ∈ s) (w : s → units k) :
affine_span k (set.range (λ (q : s), affine_map.line_map p ↑q (w q : k))) = affine_span k s :=
begin
have : s = set.range (coe : s → P), { simp, },
conv_rhs { rw this, },
apply le_antisymm;
intros q hq;
erw mem_affine_span_iff_eq_weighted_vsub_of_point_vadd k V _ (⟨p, hp⟩ : s) q at hq ⊢;
obtain ⟨t, μ, rfl⟩ := hq;
use t;
[use λ x, (μ x) * ↑(w x), use λ x, (μ x) * ↑(w x)⁻¹];
simp [smul_smul],
end
end affine_space'
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
open set finset
/-- The centroid lies in the affine span if the number of points,
converted to `k`, is not zero. -/
lemma centroid_mem_affine_span_of_cast_card_ne_zero {s : finset ι} (p : ι → P)
(h : (card s : k) ≠ 0) : s.centroid k p ∈ affine_span k (range p) :=
affine_combination_mem_affine_span (s.sum_centroid_weights_eq_one_of_cast_card_ne_zero h) p
variables (k)
/-- In the characteristic zero case, the centroid lies in the affine
span if the number of points is not zero. -/
lemma centroid_mem_affine_span_of_card_ne_zero [char_zero k] {s : finset ι} (p : ι → P)
(h : card s ≠ 0) : s.centroid k p ∈ affine_span k (range p) :=
affine_combination_mem_affine_span (s.sum_centroid_weights_eq_one_of_card_ne_zero k h) p
/-- In the characteristic zero case, the centroid lies in the affine
span if the set is nonempty. -/
lemma centroid_mem_affine_span_of_nonempty [char_zero k] {s : finset ι} (p : ι → P)
(h : s.nonempty) : s.centroid k p ∈ affine_span k (range p) :=
affine_combination_mem_affine_span (s.sum_centroid_weights_eq_one_of_nonempty k h) p
/-- In the characteristic zero case, the centroid lies in the affine
span if the number of points is `n + 1`. -/
lemma centroid_mem_affine_span_of_card_eq_add_one [char_zero k] {s : finset ι} (p : ι → P)
{n : ℕ} (h : card s = n + 1) : s.centroid k p ∈ affine_span k (range p) :=
affine_combination_mem_affine_span (s.sum_centroid_weights_eq_one_of_card_eq_add_one k h) p
end division_ring
namespace affine_map
variables {k : Type*} {V : Type*} (P : Type*) [comm_ring k] [add_comm_group V] [module k V]
variables [affine_space V P] {ι : Type*} (s : finset ι)
include V
-- TODO: define `affine_map.proj`, `affine_map.fst`, `affine_map.snd`
/-- A weighted sum, as an affine map on the points involved. -/
def weighted_vsub_of_point (w : ι → k) : ((ι → P) × P) →ᵃ[k] V :=
{ to_fun := λ p, s.weighted_vsub_of_point p.fst p.snd w,
linear := ∑ i in s,
w i • ((linear_map.proj i).comp (linear_map.fst _ _ _) - linear_map.snd _ _ _),
map_vadd' := begin
rintros ⟨p, b⟩ ⟨v, b'⟩,
simp [linear_map.sum_apply, finset.weighted_vsub_of_point, vsub_vadd_eq_vsub_sub,
vadd_vsub_assoc, add_sub, ← sub_add_eq_add_sub, smul_add, finset.sum_add_distrib]
end }
end affine_map
|
8ad1d7215c1764968e2e0aced03ec245189b9596 | 957a80ea22c5abb4f4670b250d55534d9db99108 | /library/init/data/set.lean | fd664192de72292ebb7e4241a162705d5fdc3d3b | [
"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 | 2,307 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.meta.interactive
universes u v
def set (α : Type u) := α → Prop
def set_of {α : Type u} (p : α → Prop) : set α :=
p
namespace set
variables {α : Type u} {β : Type v}
protected def mem (a : α) (s : set α) :=
s a
instance : has_mem α (set α) :=
⟨set.mem⟩
protected def subset (s₁ s₂ : set α) :=
∀ ⦃a⦄, a ∈ s₁ → a ∈ s₂
instance : has_subset (set α) :=
⟨set.subset⟩
protected def sep (p : α → Prop) (s : set α) : set α :=
{a | a ∈ s ∧ p a}
instance : has_sep α (set α) :=
⟨set.sep⟩
instance : has_emptyc (set α) :=
⟨λ a, false⟩
def univ : set α :=
λ a, true
protected def insert (a : α) (s : set α) : set α :=
{b | b = a ∨ b ∈ s}
instance : has_insert α (set α) :=
⟨set.insert⟩
protected def union (s₁ s₂ : set α) : set α :=
{a | a ∈ s₁ ∨ a ∈ s₂}
instance : has_union (set α) :=
⟨set.union⟩
protected def inter (s₁ s₂ : set α) : set α :=
{a | a ∈ s₁ ∧ a ∈ s₂}
instance : has_inter (set α) :=
⟨set.inter⟩
def compl (s : set α) : set α :=
{a | a ∉ s}
instance : has_neg (set α) :=
⟨compl⟩
protected def diff (s t : set α) : set α :=
{a ∈ s | a ∉ t}
instance : has_sdiff (set α) :=
⟨set.diff⟩
def powerset (s : set α) : set (set α) :=
{t | t ⊆ s}
prefix `𝒫`:100 := powerset
@[reducible]
def sUnion (s : set (set α)) : set α := {t | ∃ a ∈ s, t ∈ a}
prefix `⋃₀`:110 := sUnion
def image (f : α → β) (s : set α) : set β :=
{b | ∃ a, a ∈ s ∧ f a = b}
instance : functor set :=
{map := @set.image,
id_map := begin
intros _ s, apply funext, intro b,
dsimp [image, set_of],
exact propext ⟨λ ⟨b', ⟨_, _⟩⟩, ‹b' = b› ▸ ‹s b'›,
λ _, ⟨b, ⟨‹s b›, rfl⟩⟩⟩,
end,
map_comp := begin
intros, apply funext, intro c,
dsimp [image, set_of, function.comp],
exact propext ⟨λ ⟨a, ⟨h₁, h₂⟩⟩, ⟨g a, ⟨⟨a, ⟨h₁, rfl⟩⟩, h₂⟩⟩,
λ ⟨b, ⟨⟨a, ⟨h₁, h₂⟩⟩, h₃⟩⟩, ⟨a, ⟨h₁, h₂.symm ▸ h₃⟩⟩⟩
end}
end set
|
0551ecfd9514761c339b6a9e820d31bb629c7aa2 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /src/tests/shell/file1.lean | 4c2183f59c4cc0678bda525374a433eb89950d1b | [
"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 | 121 | lean | import data.nat
check nat
check nat.add_zero
check nat.zero_add
-- check finset
inductive foo : Type :=
mk : foo → foo
|
9b4ce8004bcb143b6f9cba1091e3fb008bcc1767 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/complex/module_auto.lean | 141c0e8a31d11a0b23696f80aa3c8b01c2f203d5 | [] | 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 | 3,675 | lean | /-
Copyright (c) 2020 Alexander Bentkamp, Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alexander Bentkamp, Sébastien Gouëzel
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.complex.basic
import Mathlib.data.matrix.notation
import Mathlib.field_theory.tower
import Mathlib.linear_algebra.finite_dimensional
import Mathlib.PostPort
universes u u_1
namespace Mathlib
/-!
# Complex number as a vector space over `ℝ`
This file contains three instances:
* `ℂ` is an `ℝ` algebra;
* any complex vector space is a real vector space;
* any finite dimensional complex vector space is a finite dimesional real vector space;
* the space of `ℝ`-linear maps from a real vector space to a complex vector space is a complex
vector space.
It also defines three linear maps:
* `complex.linear_map.re`;
* `complex.linear_map.im`;
* `complex.linear_map.of_real`.
They are bundled versions of the real part, the imaginary part, and the embedding of `ℝ` in `ℂ`,
as `ℝ`-linear maps.
-/
namespace complex
protected instance algebra_over_reals : algebra ℝ ℂ := ring_hom.to_algebra of_real
@[simp] theorem coe_algebra_map : ⇑(algebra_map ℝ ℂ) = ⇑of_real := rfl
@[simp] theorem re_smul (a : ℝ) (z : ℂ) : re (a • z) = a * re z := sorry
@[simp] theorem im_smul (a : ℝ) (z : ℂ) : im (a • z) = a * im z := sorry
theorem is_basis_one_I : is_basis ℝ (matrix.vec_cons 1 (matrix.vec_cons I matrix.vec_empty)) :=
sorry
protected instance finite_dimensional : finite_dimensional ℝ ℂ :=
finite_dimensional.of_fintype_basis is_basis_one_I
@[simp] theorem findim_real_complex : finite_dimensional.findim ℝ ℂ = bit0 1 := sorry
@[simp] theorem dim_real_complex : vector_space.dim ℝ ℂ = bit0 1 := sorry
theorem dim_real_complex' : cardinal.lift (vector_space.dim ℝ ℂ) = bit0 1 := sorry
end complex
/- Register as an instance (with low priority) the fact that a complex vector space is also a real
vector space. -/
protected instance module.complex_to_real (E : Type u_1) [add_comm_group E] [module ℂ E] :
module ℝ E :=
restrict_scalars.semimodule ℝ ℂ E
protected instance module.real_complex_tower (E : Type u_1) [add_comm_group E] [module ℂ E] :
is_scalar_tower ℝ ℂ E :=
restrict_scalars.is_scalar_tower ℝ ℂ E
protected instance finite_dimensional.complex_to_real (E : Type u_1) [add_comm_group E] [module ℂ E]
[finite_dimensional ℂ E] : finite_dimensional ℝ E :=
finite_dimensional.trans ℝ ℂ E
theorem dim_real_of_complex (E : Type u_1) [add_comm_group E] [module ℂ E] :
vector_space.dim ℝ E = bit0 1 * vector_space.dim ℂ E :=
sorry
theorem findim_real_of_complex (E : Type u_1) [add_comm_group E] [module ℂ E] :
finite_dimensional.findim ℝ E = bit0 1 * finite_dimensional.findim ℂ E :=
sorry
namespace complex
/-- Linear map version of the real part function, from `ℂ` to `ℝ`. -/
def linear_map.re : linear_map ℝ ℂ ℝ := linear_map.mk (fun (x : ℂ) => re x) add_re re_smul
@[simp] theorem linear_map.coe_re : ⇑linear_map.re = re := rfl
/-- Linear map version of the imaginary part function, from `ℂ` to `ℝ`. -/
def linear_map.im : linear_map ℝ ℂ ℝ := linear_map.mk (fun (x : ℂ) => im x) add_im im_smul
@[simp] theorem linear_map.coe_im : ⇑linear_map.im = im := rfl
/-- Linear map version of the canonical embedding of `ℝ` in `ℂ`. -/
def linear_map.of_real : linear_map ℝ ℝ ℂ := linear_map.mk coe of_real_add sorry
@[simp] theorem linear_map.coe_of_real : ⇑linear_map.of_real = coe := rfl
end Mathlib |
c705c8073784332c445241a95b1a2caaa245a2c7 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/run/class2.lean | 11c764d7b5c61f68ce0aa6fb1f17ce155daeccdf | [
"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 | 132 | lean | open tactic
theorem H {A B : Type} (H1 : inhabited A) : inhabited (Prop × A × (B → num))
:= by apply_instance
reveal H
print H
|
29e32f2937f6921058b7a69e20181bc40d096794 | 618003631150032a5676f229d13a079ac875ff77 | /src/data/nat/totient.lean | e1b4639f72ddbe54534f62af9ab4ad5fe5a81edb | [
"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 | 3,558 | 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 algebra.big_operators
open finset
namespace nat
def totient (n : ℕ) : ℕ := ((range n).filter (nat.coprime n)).card
localized "notation `φ` := nat.totient" in nat
@[simp] theorem totient_zero : φ 0 = 0 := rfl
lemma totient_le (n : ℕ) : φ n ≤ n :=
calc totient n ≤ (range n).card : card_le_of_subset (filter_subset _)
... = n : card_range _
lemma totient_pos : ∀ {n : ℕ}, 0 < n → 0 < φ n
| 0 := dec_trivial
| 1 := dec_trivial
| (n+2) := λ h, card_pos.2 ⟨1, mem_filter.2 ⟨mem_range.2 dec_trivial, coprime_one_right _⟩⟩
lemma sum_totient (n : ℕ) : ((range n.succ).filter (∣ n)).sum φ = n :=
if hn0 : n = 0 then by rw hn0; refl
else
calc ((range n.succ).filter (∣ n)).sum φ
= ((range n.succ).filter (∣ n)).sum (λ d, ((range (n / d)).filter (λ m, gcd (n / d) m = 1)).card) :
eq.symm $ sum_bij (λ d _, n / d)
(λ d hd, mem_filter.2 ⟨mem_range.2 $ lt_succ_of_le $ nat.div_le_self _ _,
by conv {to_rhs, rw ← nat.mul_div_cancel' (mem_filter.1 hd).2}; simp⟩)
(λ _ _, rfl)
(λ a b ha hb h,
have ha : a * (n / a) = n, from nat.mul_div_cancel' (mem_filter.1 ha).2,
have 0 < (n / a), from nat.pos_of_ne_zero (λ h, by simp [*, lt_irrefl] at *),
by rw [← nat.mul_left_inj this, ha, h, nat.mul_div_cancel' (mem_filter.1 hb).2])
(λ b hb,
have hb : b < n.succ ∧ b ∣ n, by simpa [-range_succ] using hb,
have hbn : (n / b) ∣ n, from ⟨b, by rw nat.div_mul_cancel hb.2⟩,
have hnb0 : (n / b) ≠ 0, from λ h, by simpa [h, ne.symm hn0] using nat.div_mul_cancel hbn,
⟨n / b, mem_filter.2 ⟨mem_range.2 $ lt_succ_of_le $ nat.div_le_self _ _, hbn⟩,
by rw [← nat.mul_left_inj (nat.pos_of_ne_zero hnb0),
nat.mul_div_cancel' hb.2, nat.div_mul_cancel hbn]⟩)
... = ((range n.succ).filter (∣ n)).sum (λ d, ((range n).filter (λ m, gcd n m = d)).card) :
sum_congr rfl (λ d hd,
have hd : d ∣ n, from (mem_filter.1 hd).2,
have hd0 : 0 < d, from nat.pos_of_ne_zero (λ h, hn0 (eq_zero_of_zero_dvd $ h ▸ hd)),
card_congr (λ m hm, d * m)
(λ m hm, have hm : m < n / d ∧ gcd (n / d) m = 1, by simpa using hm,
mem_filter.2 ⟨mem_range.2 $ nat.mul_div_cancel' hd ▸
(mul_lt_mul_left hd0).2 hm.1,
by rw [← nat.mul_div_cancel' hd, gcd_mul_left, hm.2, mul_one]⟩)
(λ a b ha hb h, (nat.mul_right_inj hd0).1 h)
(λ b hb, have hb : b < n ∧ gcd n b = d, by simpa using hb,
⟨b / d, mem_filter.2 ⟨mem_range.2 ((mul_lt_mul_left (show 0 < d, from hb.2 ▸ hb.2.symm ▸ hd0)).1
(by rw [← hb.2, nat.mul_div_cancel' (gcd_dvd_left _ _),
nat.mul_div_cancel' (gcd_dvd_right _ _)]; exact hb.1)),
hb.2 ▸ coprime_div_gcd_div_gcd (hb.2.symm ▸ hd0)⟩,
hb.2 ▸ nat.mul_div_cancel' (gcd_dvd_right _ _)⟩))
... = ((filter (∣ n) (range n.succ)).bind (λ d, (range n).filter (λ m, gcd n m = d))).card :
(card_bind (by intros; apply disjoint_filter.2; cc)).symm
... = (range n).card :
congr_arg card (finset.ext.2 (λ m, ⟨by finish,
λ hm, have h : m < n, from mem_range.1 hm,
mem_bind.2 ⟨gcd n m, mem_filter.2 ⟨mem_range.2 (lt_succ_of_le (le_of_dvd (lt_of_le_of_lt (nat.zero_le _) h)
(gcd_dvd_left _ _))), gcd_dvd_left _ _⟩, mem_filter.2 ⟨hm, rfl⟩⟩⟩))
... = n : card_range _
end nat
|
37fa553e6c2f6fa2f95050c0fef642687a3e8d86 | ebbdcbd7ddc89a9ef7c3b397b301d5f5272a918f | /qp/p1_categories/c4_topoi/s1_subobjects.lean | 09578d64cc7726fa877b69e401d5667f4dfe7f6d | [] | no_license | intoverflow/qvr | 34b9ef23604738381ca20b7d622fd0399d88f2dd | 0cfcd33fe4bf8d93851a00cec5bfd21e77105d74 | refs/heads/master | 1,616,591,570,371 | 1,492,575,772,000 | 1,492,575,772,000 | 80,061,627 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,819 | lean | /- -----------------------------------------------------------------------
Subobject classifiers.
----------------------------------------------------------------------- -/
import ..c2_limits
namespace qp
open stdaux
universe variables ℓ ℓobj ℓhom ℓobj₁ ℓhom₁ ℓobj₂ ℓhom₂
/-! #brief A subobject classifier.
-/
class HasSubobjClass (C : Cat.{ℓobj ℓhom})
:= (prop : ∀ [C_HasFinal : HasFinal C], C^.obj)
(true : ∀ [C_HasFinal : HasFinal C]
, C^.hom (final C) prop)
(char
: ∀ [C_HasFinal : HasFinal C]
{U X : C^.obj}
{m : C^.hom U X}
(m_Monic : Monic m)
, C^.hom X prop)
(char_pullback
: ∀ [C_HasFinal : HasFinal C]
{U X : C^.obj}
{m : C^.hom U X}
(m_Monic : Monic m)
, IsPullback (char m_Monic) m true (final_hom U))
(char_uniq
: ∀ [C_HasFinal : HasFinal C]
{U X : C^.obj}
{m : C^.hom U X}
(m_Monic : Monic m)
(char' : C^.hom X prop)
(ω : IsPullback char' m true (final_hom U))
, char' = char m_Monic)
/-! #brief Helper for showing a category has a subobject classifier.
-/
definition HasSubobjClass.show {C : Cat.{ℓobj ℓhom}}
(prop
: ∀ [C_HasFinal : HasFinal C]
, C^.obj)
(true
: ∀ [C_HasFinal : HasFinal C]
, C^.hom (final C) prop)
(char
: ∀ [C_HasFinal : HasFinal C]
{U X : C^.obj} {m : C^.hom U X}
(m_Monic : Monic m)
, C^.hom X prop)
(univ
: ∀ [C_HasFinal : HasFinal C]
{U V X : C^.obj} {m : C^.hom U X}
(m_Monic : Monic m)
(h : C^.hom V X)
(ωh : char m_Monic ∘∘ h = true∘∘final_hom V)
, C^.hom V U)
(ωchar_comm
: ∀ [C_HasFinal : HasFinal C]
{U X : C^.obj} {m : C^.hom U X}
(m_Monic : Monic m)
, char m_Monic ∘∘ m = true ∘∘ final_hom U)
(ωuniv
: ∀ [C_HasFinal : HasFinal C]
{U V X : C^.obj} {m : C^.hom U X}
(m_Monic : Monic m)
(h : C^.hom V X)
(ωh : char m_Monic ∘∘ h = true∘∘final_hom V)
, h = m ∘∘ univ m_Monic h ωh)
(ωuniv_uniq
: ∀ [C_HasFinal : HasFinal C]
{U V X : C^.obj} {m : C^.hom U X}
(m_Monic : Monic m)
(h : C^.hom V U)
(ω : char m_Monic ∘∘ (m ∘∘ h) = true ∘∘ final_hom V)
, h = univ m_Monic (m ∘∘ h) ω)
(ωchar_uniq
: ∀ [C_HasFinal : HasFinal C]
{U X : C^.obj} {m : C^.hom U X}
(m_Monic : Monic m)
(char' : C^.hom X prop)
(char'_IsPullback : IsPullback char' m true (final_hom U))
, char' = char m_Monic)
: HasSubobjClass C
:= { prop := @prop
, true := @true
, char := @char
, char_pullback
:= λ C_HasFinal U X m m_Monic
, IsPullback.show
(λ V h₁ h₂ ωsquare
, @univ C_HasFinal U V X m m_Monic h₁
begin
assert ωh₂ : h₂ = final_hom V,
{ apply final_hom.uniq },
subst ωh₂,
exact ωsquare
end)
(@ωchar_comm C_HasFinal U X m m_Monic)
(λ V h₁ h₂ ωsquare
, @ωuniv C_HasFinal U V X m m_Monic h₁
begin
assert ωh₂ : h₂ = final_hom V,
{ apply final_hom.uniq },
subst ωh₂,
exact ωsquare
end)
(λ V h₁ h₂ ωsquare
, eq.trans (final_hom.uniq C) (eq.symm (final_hom.uniq C)))
(λ V h₁ h₂ ωsquare h ωh₁ ωh₂
, begin
subst ωh₁,
apply ωuniv_uniq
end)
, char_uniq := @ωchar_uniq
}
/-! #brief Functor categories have pointwise subobject classifiers.
-/
definition FunCat.HasSubobjClass.char {C : Cat.{ℓobj₁ ℓhom₁}} {D : Cat.{ℓobj₂ ℓhom₂}}
[D_HasFinal : HasFinal D]
[D_HasSubobjClass : HasSubobjClass D]
{U F : Fun C D}
{η : NatTrans U F}
(η_Monic : @Monic (FunCat C D) U F η)
: NatTrans F (ConstFun C (HasSubobjClass.prop D))
:= { com := λ c, HasSubobjClass.char (NatTrans.com.Monic η_Monic c)
, natural
:= λ x y f
, sorry
}
/-! #brief Functor categories have pointwise subobject classifiers.
-/
definition FunCat.HasSubobjClass.univ {C : Cat.{ℓobj₁ ℓhom₁}} {D : Cat.{ℓobj₂ ℓhom₂}}
[D_HasFinal : HasFinal D]
[D_HasSubobjClass : HasSubobjClass D]
(FunCat_HasFinal : HasFinal (FunCat C D))
{U F G : Fun C D}
{ηUG : NatTrans U G}
(ηUG_Monic : @Monic (FunCat C D) U G ηUG)
(ηFG : NatTrans F G)
(ωη : FunCat.HasSubobjClass.char ηUG_Monic ◇◇ ηFG
= ConstTrans C (HasSubobjClass.true D)
◇◇ final.iso FunCat_HasFinal FunCat.HasFinal
◇◇ @final_hom (FunCat C D) FunCat_HasFinal F)
: NatTrans F U
:= { com := λ c, ispullback.univ
(HasSubobjClass.char_pullback (NatTrans.com.Monic ηUG_Monic c))
(ηFG^.com c)
(final_hom (F^.obj c))
(begin
refine eq.trans (NatTrans.congr_com ωη) _,
dsimp [NatTrans.comp, ConstTrans],
rw -D^.circ_assoc,
apply Cat.circ.congr_right,
apply final_hom.uniq
end)
, natural
:= λ x y f
, sorry
}
/-! #brief Functor categories have pointwise subobject classifiers.
-/
instance FunCat.HasSubobjClass {C : Cat.{ℓobj₁ ℓhom₁}} {D : Cat.{ℓobj₂ ℓhom₂}}
[D_HasFinal : HasFinal D]
[D_HasSubobjClass : HasSubobjClass D]
: HasSubobjClass (FunCat C D)
:= HasSubobjClass.show
(λ FunCat_HasFinal, ConstFun C (HasSubobjClass.prop D))
(λ FunCat_HasFinal
, (FunCat C D)^.circ
(ConstTrans C (HasSubobjClass.true D))
(final.iso FunCat_HasFinal FunCat.HasFinal))
(λ FunCat_HasFinal U F η η_Monic
, FunCat.HasSubobjClass.char η_Monic)
(λ FunCat_HasFinal U F G ηUG ηUG_Monic ηFG ω
, FunCat.HasSubobjClass.univ FunCat_HasFinal ηUG_Monic ηFG ω)
(λ FunCat_HasFinal U F η η_Monic
, begin
apply NatTrans.eq,
apply funext, intro c,
dsimp [FunCat, NatTrans.comp, FunCat.HasSubobjClass.char, ConstTrans],
exact sorry
end)
(λ FunCat_HasFinal U F G η η_Monic h ωh
, begin exact sorry end)
(λ FunCat_HasFinal U X V m m_Monic h ωh
, begin exact sorry end)
(λ FunCat_HasFinal U X m m_Monic char' char'_IsPullback
, begin exact sorry end)
end qp
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.