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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2aa80189639d31d56d6cf397594f4fa050454e17 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/data/num/lemmas.lean | 85256d0ba0769ad36c3f69f560267d685a646758 | [
"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 | 50,721 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.num.bitwise
import data.int.char_zero
import data.nat.gcd
import data.nat.psub
/-!
# Properties of the binary representation of integers
-/
local attribute [simp] add_assoc
namespace pos_num
variables {α : Type*}
@[simp, norm_cast] theorem cast_one [has_one α] [has_add α] :
((1 : pos_num) : α) = 1 := rfl
@[simp] theorem cast_one' [has_one α] [has_add α] : (pos_num.one : α) = 1 := rfl
@[simp, norm_cast] theorem cast_bit0 [has_one α] [has_add α] (n : pos_num) :
(n.bit0 : α) = _root_.bit0 n := rfl
@[simp, norm_cast] theorem cast_bit1 [has_one α] [has_add α] (n : pos_num) :
(n.bit1 : α) = _root_.bit1 n := rfl
@[simp, norm_cast] theorem cast_to_nat [add_monoid α] [has_one α] :
∀ n : pos_num, ((n : ℕ) : α) = n
| 1 := nat.cast_one
| (bit0 p) := (nat.cast_bit0 _).trans $ congr_arg _root_.bit0 p.cast_to_nat
| (bit1 p) := (nat.cast_bit1 _).trans $ congr_arg _root_.bit1 p.cast_to_nat
@[simp, norm_cast] theorem to_nat_to_int (n : pos_num) : ((n : ℕ) : ℤ) = n :=
by rw [← int.nat_cast_eq_coe_nat, cast_to_nat]
@[simp, norm_cast] theorem cast_to_int [add_group α] [has_one α] (n : pos_num) :
((n : ℤ) : α) = n :=
by rw [← to_nat_to_int, int.cast_coe_nat, cast_to_nat]
theorem succ_to_nat : ∀ n, (succ n : ℕ) = n + 1
| 1 := rfl
| (bit0 p) := rfl
| (bit1 p) := (congr_arg _root_.bit0 (succ_to_nat p)).trans $
show ↑p + 1 + ↑p + 1 = ↑p + ↑p + 1 + 1, by simp [add_left_comm]
theorem one_add (n : pos_num) : 1 + n = succ n := by cases n; refl
theorem add_one (n : pos_num) : n + 1 = succ n := by cases n; refl
@[norm_cast]
theorem add_to_nat : ∀ m n, ((m + n : pos_num) : ℕ) = m + n
| 1 b := by rw [one_add b, succ_to_nat, add_comm]; refl
| a 1 := by rw [add_one a, succ_to_nat]; refl
| (bit0 a) (bit0 b) := (congr_arg _root_.bit0 (add_to_nat a b)).trans $
show ((a + b) + (a + b) : ℕ) = (a + a) + (b + b), by simp [add_left_comm]
| (bit0 a) (bit1 b) := (congr_arg _root_.bit1 (add_to_nat a b)).trans $
show ((a + b) + (a + b) + 1 : ℕ) = (a + a) + (b + b + 1), by simp [add_left_comm]
| (bit1 a) (bit0 b) := (congr_arg _root_.bit1 (add_to_nat a b)).trans $
show ((a + b) + (a + b) + 1 : ℕ) = (a + a + 1) + (b + b), by simp [add_comm, add_left_comm]
| (bit1 a) (bit1 b) :=
show (succ (a + b) + succ (a + b) : ℕ) = (a + a + 1) + (b + b + 1),
by rw [succ_to_nat, add_to_nat]; simp [add_left_comm]
theorem add_succ : ∀ (m n : pos_num), m + succ n = succ (m + n)
| 1 b := by simp [one_add]
| (bit0 a) 1 := congr_arg bit0 (add_one a)
| (bit1 a) 1 := congr_arg bit1 (add_one a)
| (bit0 a) (bit0 b) := rfl
| (bit0 a) (bit1 b) := congr_arg bit0 (add_succ a b)
| (bit1 a) (bit0 b) := rfl
| (bit1 a) (bit1 b) := congr_arg bit1 (add_succ a b)
theorem bit0_of_bit0 : Π n, _root_.bit0 n = bit0 n
| 1 := rfl
| (bit0 p) := congr_arg bit0 (bit0_of_bit0 p)
| (bit1 p) := show bit0 (succ (_root_.bit0 p)) = _, by rw bit0_of_bit0; refl
theorem bit1_of_bit1 (n : pos_num) : _root_.bit1 n = bit1 n :=
show _root_.bit0 n + 1 = bit1 n, by rw [add_one, bit0_of_bit0]; refl
@[norm_cast]
theorem mul_to_nat (m) : ∀ n, ((m * n : pos_num) : ℕ) = m * n
| 1 := (mul_one _).symm
| (bit0 p) := show (↑(m * p) + ↑(m * p) : ℕ) = ↑m * (p + p), by rw [mul_to_nat, left_distrib]
| (bit1 p) := (add_to_nat (bit0 (m * p)) m).trans $
show (↑(m * p) + ↑(m * p) + ↑m : ℕ) = ↑m * (p + p) + m, by rw [mul_to_nat, left_distrib]
theorem to_nat_pos : ∀ n : pos_num, 0 < (n : ℕ)
| 1 := zero_lt_one
| (bit0 p) := let h := to_nat_pos p in add_pos h h
| (bit1 p) := nat.succ_pos _
theorem cmp_to_nat_lemma {m n : pos_num} : (m:ℕ) < n → (bit1 m : ℕ) < bit0 n :=
show (m:ℕ) < n → (m + m + 1 + 1 : ℕ) ≤ n + n,
by intro h; rw [nat.add_right_comm m m 1, add_assoc]; exact add_le_add h h
theorem cmp_swap (m) : ∀n, (cmp m n).swap = cmp n m :=
by induction m with m IH m IH; intro n;
cases n with n n; try {unfold cmp}; try {refl}; rw ←IH; cases cmp m n; refl
theorem cmp_to_nat : ∀ (m n), (ordering.cases_on (cmp m n) ((m:ℕ) < n) (m = n) ((n:ℕ) < m) : Prop)
| 1 1 := rfl
| (bit0 a) 1 := let h : (1:ℕ) ≤ a := to_nat_pos a in add_le_add h h
| (bit1 a) 1 := nat.succ_lt_succ $ to_nat_pos $ bit0 a
| 1 (bit0 b) := let h : (1:ℕ) ≤ b := to_nat_pos b in add_le_add h h
| 1 (bit1 b) := nat.succ_lt_succ $ to_nat_pos $ bit0 b
| (bit0 a) (bit0 b) := begin
have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro,
{ exact add_lt_add this this },
{ rw this },
{ exact add_lt_add this this }
end
| (bit0 a) (bit1 b) := begin dsimp [cmp],
have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro,
{ exact nat.le_succ_of_le (add_lt_add this this) },
{ rw this, apply nat.lt_succ_self },
{ exact cmp_to_nat_lemma this }
end
| (bit1 a) (bit0 b) := begin dsimp [cmp],
have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro,
{ exact cmp_to_nat_lemma this },
{ rw this, apply nat.lt_succ_self },
{ exact nat.le_succ_of_le (add_lt_add this this) },
end
| (bit1 a) (bit1 b) := begin
have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro,
{ exact nat.succ_lt_succ (add_lt_add this this) },
{ rw this },
{ exact nat.succ_lt_succ (add_lt_add this this) }
end
@[norm_cast]
theorem lt_to_nat {m n : pos_num} : (m:ℕ) < n ↔ m < n :=
show (m:ℕ) < n ↔ cmp m n = ordering.lt, from
match cmp m n, cmp_to_nat m n with
| ordering.lt, h := by simp at h; simp [h]
| ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial
| ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial
end
@[norm_cast]
theorem le_to_nat {m n : pos_num} : (m:ℕ) ≤ n ↔ m ≤ n :=
by rw ← not_lt; exact not_congr lt_to_nat
end pos_num
namespace num
variables {α : Type*}
open pos_num
theorem add_zero (n : num) : n + 0 = n := by cases n; refl
theorem zero_add (n : num) : 0 + n = n := by cases n; refl
theorem add_one : ∀ n : num, n + 1 = succ n
| 0 := rfl
| (pos p) := by cases p; refl
theorem add_succ : ∀ (m n : num), m + succ n = succ (m + n)
| 0 n := by simp [zero_add]
| (pos p) 0 := show pos (p + 1) = succ (pos p + 0),
by rw [pos_num.add_one, add_zero]; refl
| (pos p) (pos q) := congr_arg pos (pos_num.add_succ _ _)
@[simp, norm_cast] theorem add_of_nat (m) : ∀ n, ((m + n : ℕ) : num) = m + n
| 0 := (add_zero _).symm
| (n+1) := show ((m + n : ℕ) + 1 : num) = m + (↑ n + 1),
by rw [add_one, add_one, add_succ, add_of_nat]
theorem bit0_of_bit0 : ∀ n : num, bit0 n = n.bit0
| 0 := rfl
| (pos p) := congr_arg pos p.bit0_of_bit0
theorem bit1_of_bit1 : ∀ n : num, bit1 n = n.bit1
| 0 := rfl
| (pos p) := congr_arg pos p.bit1_of_bit1
@[simp, norm_cast] theorem cast_zero [has_zero α] [has_one α] [has_add α] :
((0 : num) : α) = 0 := rfl
@[simp] theorem cast_zero' [has_zero α] [has_one α] [has_add α] :
(num.zero : α) = 0 := rfl
@[simp, norm_cast] theorem cast_one [has_zero α] [has_one α] [has_add α] :
((1 : num) : α) = 1 := rfl
@[simp] theorem cast_pos [has_zero α] [has_one α] [has_add α]
(n : pos_num) : (num.pos n : α) = n := rfl
theorem succ'_to_nat : ∀ n, (succ' n : ℕ) = n + 1
| 0 := (_root_.zero_add _).symm
| (pos p) := pos_num.succ_to_nat _
theorem succ_to_nat (n) : (succ n : ℕ) = n + 1 := succ'_to_nat n
@[simp, norm_cast] theorem cast_to_nat [add_monoid α] [has_one α] : ∀ n : num, ((n : ℕ) : α) = n
| 0 := nat.cast_zero
| (pos p) := p.cast_to_nat
@[simp, norm_cast] theorem to_nat_to_int (n : num) : ((n : ℕ) : ℤ) = n :=
by rw [← int.nat_cast_eq_coe_nat, cast_to_nat]
@[simp, norm_cast] theorem cast_to_int [add_group α] [has_one α] (n : num) : ((n : ℤ) : α) = n :=
by rw [← to_nat_to_int, int.cast_coe_nat, cast_to_nat]
@[norm_cast]
theorem to_of_nat : Π (n : ℕ), ((n : num) : ℕ) = n
| 0 := rfl
| (n+1) := by rw [nat.cast_add_one, add_one, succ_to_nat, to_of_nat]
@[simp, norm_cast]
theorem of_nat_cast [add_monoid α] [has_one α] (n : ℕ) : ((n : num) : α) = n :=
by rw [← cast_to_nat, to_of_nat]
@[norm_cast] theorem of_nat_inj {m n : ℕ} : (m : num) = n ↔ m = n :=
⟨λ h, function.left_inverse.injective to_of_nat h, congr_arg _⟩
@[norm_cast]
theorem add_to_nat : ∀ m n, ((m + n : num) : ℕ) = m + n
| 0 0 := rfl
| 0 (pos q) := (_root_.zero_add _).symm
| (pos p) 0 := rfl
| (pos p) (pos q) := pos_num.add_to_nat _ _
@[norm_cast]
theorem mul_to_nat : ∀ m n, ((m * n : num) : ℕ) = m * n
| 0 0 := rfl
| 0 (pos q) := (zero_mul _).symm
| (pos p) 0 := rfl
| (pos p) (pos q) := pos_num.mul_to_nat _ _
theorem cmp_to_nat : ∀ (m n), (ordering.cases_on (cmp m n) ((m:ℕ) < n) (m = n) ((n:ℕ) < m) : Prop)
| 0 0 := rfl
| 0 (pos b) := to_nat_pos _
| (pos a) 0 := to_nat_pos _
| (pos a) (pos b) :=
by { have := pos_num.cmp_to_nat a b; revert this; dsimp [cmp];
cases pos_num.cmp a b, exacts [id, congr_arg pos, id] }
@[norm_cast]
theorem lt_to_nat {m n : num} : (m:ℕ) < n ↔ m < n :=
show (m:ℕ) < n ↔ cmp m n = ordering.lt, from
match cmp m n, cmp_to_nat m n with
| ordering.lt, h := by simp at h; simp [h]
| ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial
| ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial
end
@[norm_cast]
theorem le_to_nat {m n : num} : (m:ℕ) ≤ n ↔ m ≤ n :=
by rw ← not_lt; exact not_congr lt_to_nat
end num
namespace pos_num
@[simp] theorem of_to_nat : Π (n : pos_num), ((n : ℕ) : num) = num.pos n
| 1 := rfl
| (bit0 p) :=
show ↑(p + p : ℕ) = num.pos p.bit0,
by rw [num.add_of_nat, of_to_nat];
exact congr_arg num.pos p.bit0_of_bit0
| (bit1 p) :=
show ((p + p : ℕ) : num) + 1 = num.pos p.bit1,
by rw [num.add_of_nat, of_to_nat];
exact congr_arg num.pos p.bit1_of_bit1
end pos_num
namespace num
@[simp, norm_cast] theorem of_to_nat : Π (n : num), ((n : ℕ) : num) = n
| 0 := rfl
| (pos p) := p.of_to_nat
@[norm_cast] theorem to_nat_inj {m n : num} : (m : ℕ) = n ↔ m = n :=
⟨λ h, function.left_inverse.injective of_to_nat h, congr_arg _⟩
/--
This tactic tries to turn an (in)equality about `num`s to one about `nat`s by rewriting.
```lean
example (n : num) (m : num) : n ≤ n + m :=
begin
num.transfer_rw,
exact nat.le_add_right _ _
end
```
-/
meta def transfer_rw : tactic unit :=
`[repeat {rw ← to_nat_inj <|> rw ← lt_to_nat <|> rw ← le_to_nat},
repeat {rw add_to_nat <|> rw mul_to_nat <|> rw cast_one <|> rw cast_zero}]
/--
This tactic tries to prove (in)equalities about `num`s by transfering them to the `nat` world and
then trying to call `simp`.
```lean
example (n : num) (m : num) : n ≤ n + m := by num.transfer
```
-/
meta def transfer : tactic unit := `[intros, transfer_rw, try {simp}]
instance : comm_semiring num :=
by refine_struct {
add := (+),
zero := 0,
zero_add := zero_add,
add_zero := add_zero,
mul := (*),
one := 1,
nsmul := @nsmul_rec _ ⟨0⟩ ⟨(+)⟩,
npow := @npow_rec _ ⟨1⟩ ⟨(*)⟩ };
try { intros, refl }; try { transfer }; simp [mul_add, mul_left_comm, mul_comm, add_comm]
instance : ordered_cancel_add_comm_monoid num :=
{ add_left_cancel := by {intros a b c, transfer_rw, apply add_left_cancel},
lt := (<),
lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le},
le := (≤),
le_refl := by transfer,
le_trans := by {intros a b c, transfer_rw, apply le_trans},
le_antisymm := by {intros a b, transfer_rw, apply le_antisymm},
add_le_add_left := by {intros a b h c, revert h, transfer_rw,
exact λ h, add_le_add_left h c},
le_of_add_le_add_left := by {intros a b c, transfer_rw, apply le_of_add_le_add_left},
..num.comm_semiring }
instance : linear_ordered_semiring num :=
{ le_total := by {intros a b, transfer_rw, apply le_total},
zero_le_one := dec_trivial,
mul_lt_mul_of_pos_left := by {intros a b c, transfer_rw, apply mul_lt_mul_of_pos_left},
mul_lt_mul_of_pos_right := by {intros a b c, transfer_rw, apply mul_lt_mul_of_pos_right},
decidable_lt := num.decidable_lt,
decidable_le := num.decidable_le,
decidable_eq := num.decidable_eq,
exists_pair_ne := ⟨0, 1, dec_trivial⟩,
..num.comm_semiring, ..num.ordered_cancel_add_comm_monoid }
@[norm_cast]
theorem dvd_to_nat (m n : num) : (m : ℕ) ∣ n ↔ m ∣ n :=
⟨λ ⟨k, e⟩, ⟨k, by rw [← of_to_nat n, e]; simp⟩,
λ ⟨k, e⟩, ⟨k, by simp [e, mul_to_nat]⟩⟩
end num
namespace pos_num
variables {α : Type*}
open num
@[norm_cast] theorem to_nat_inj {m n : pos_num} : (m : ℕ) = n ↔ m = n :=
⟨λ h, num.pos.inj $ by rw [← pos_num.of_to_nat, ← pos_num.of_to_nat, h],
congr_arg _⟩
theorem pred'_to_nat : ∀ n, (pred' n : ℕ) = nat.pred n
| 1 := rfl
| (bit0 n) :=
have nat.succ ↑(pred' n) = ↑n,
by rw [pred'_to_nat n, nat.succ_pred_eq_of_pos (to_nat_pos n)],
match pred' n, this : ∀ k : num, nat.succ ↑k = ↑n →
↑(num.cases_on k 1 bit1 : pos_num) = nat.pred (_root_.bit0 n) with
| 0, (h : ((1:num):ℕ) = n) := by rw ← to_nat_inj.1 h; refl
| num.pos p, (h : nat.succ ↑p = n) :=
by rw ← h; exact (nat.succ_add p p).symm
end
| (bit1 n) := rfl
@[simp] theorem pred'_succ' (n) : pred' (succ' n) = n :=
num.to_nat_inj.1 $ by rw [pred'_to_nat, succ'_to_nat,
nat.add_one, nat.pred_succ]
@[simp] theorem succ'_pred' (n) : succ' (pred' n) = n :=
to_nat_inj.1 $ by rw [succ'_to_nat, pred'_to_nat,
nat.add_one, nat.succ_pred_eq_of_pos (to_nat_pos _)]
instance : has_dvd pos_num := ⟨λ m n, pos m ∣ pos n⟩
@[norm_cast] theorem dvd_to_nat {m n : pos_num} : (m:ℕ) ∣ n ↔ m ∣ n :=
num.dvd_to_nat (pos m) (pos n)
theorem size_to_nat : ∀ n, (size n : ℕ) = nat.size n
| 1 := nat.size_one.symm
| (bit0 n) := by rw [size, succ_to_nat, size_to_nat, cast_bit0,
nat.size_bit0 $ ne_of_gt $ to_nat_pos n]
| (bit1 n) := by rw [size, succ_to_nat, size_to_nat, cast_bit1,
nat.size_bit1]
theorem size_eq_nat_size : ∀ n, (size n : ℕ) = nat_size n
| 1 := rfl
| (bit0 n) := by rw [size, succ_to_nat, nat_size, size_eq_nat_size]
| (bit1 n) := by rw [size, succ_to_nat, nat_size, size_eq_nat_size]
theorem nat_size_to_nat (n) : nat_size n = nat.size n :=
by rw [← size_eq_nat_size, size_to_nat]
theorem nat_size_pos (n) : 0 < nat_size n :=
by cases n; apply nat.succ_pos
/--
This tactic tries to turn an (in)equality about `pos_num`s to one about `nat`s by rewriting.
```lean
example (n : pos_num) (m : pos_num) : n ≤ n + m :=
begin
pos_num.transfer_rw,
exact nat.le_add_right _ _
end
```
-/
meta def transfer_rw : tactic unit :=
`[repeat {rw ← to_nat_inj <|> rw ← lt_to_nat <|> rw ← le_to_nat},
repeat {rw add_to_nat <|> rw mul_to_nat <|> rw cast_one <|> rw cast_zero}]
/--
This tactic tries to prove (in)equalities about `pos_num`s by transferring them to the `nat` world
and then trying to call `simp`.
```lean
example (n : pos_num) (m : pos_num) : n ≤ n + m := by pos_num.transfer
```
-/
meta def transfer : tactic unit :=
`[intros, transfer_rw, try {simp [add_comm, add_left_comm, mul_comm, mul_left_comm]}]
instance : add_comm_semigroup pos_num :=
by refine {add := (+), ..}; transfer
instance : comm_monoid pos_num :=
by refine_struct {mul := (*), one := (1 : pos_num), npow := @npow_rec _ ⟨1⟩ ⟨(*)⟩};
try { intros, refl }; transfer
instance : distrib pos_num :=
by refine {add := (+), mul := (*), ..}; {transfer, simp [mul_add, mul_comm]}
instance : linear_order pos_num :=
{ lt := (<),
lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le},
le := (≤),
le_refl := by transfer,
le_trans := by {intros a b c, transfer_rw, apply le_trans},
le_antisymm := by {intros a b, transfer_rw, apply le_antisymm},
le_total := by {intros a b, transfer_rw, apply le_total},
decidable_lt := by apply_instance,
decidable_le := by apply_instance,
decidable_eq := by apply_instance }
@[simp] theorem cast_to_num (n : pos_num) : ↑n = num.pos n :=
by rw [← cast_to_nat, ← of_to_nat n]
@[simp, norm_cast]
theorem bit_to_nat (b n) : (bit b n : ℕ) = nat.bit b n :=
by cases b; refl
@[simp, norm_cast]
theorem cast_add [add_monoid α] [has_one α] (m n) : ((m + n : pos_num) : α) = m + n :=
by rw [← cast_to_nat, add_to_nat, nat.cast_add, cast_to_nat, cast_to_nat]
@[simp, norm_cast, priority 500]
theorem cast_succ [add_monoid α] [has_one α] (n : pos_num) : (succ n : α) = n + 1 :=
by rw [← add_one, cast_add, cast_one]
@[simp, norm_cast]
theorem cast_inj [add_monoid α] [has_one α] [char_zero α] {m n : pos_num} : (m:α) = n ↔ m = n :=
by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_inj, to_nat_inj]
@[simp]
theorem one_le_cast [linear_ordered_semiring α] (n : pos_num) : (1 : α) ≤ n :=
by rw [← cast_to_nat, ← nat.cast_one, nat.cast_le]; apply to_nat_pos
@[simp]
theorem cast_pos [linear_ordered_semiring α] (n : pos_num) : 0 < (n : α) :=
lt_of_lt_of_le zero_lt_one (one_le_cast n)
@[simp, norm_cast]
theorem cast_mul [semiring α] (m n) : ((m * n : pos_num) : α) = m * n :=
by rw [← cast_to_nat, mul_to_nat, nat.cast_mul, cast_to_nat, cast_to_nat]
@[simp]
theorem cmp_eq (m n) : cmp m n = ordering.eq ↔ m = n :=
begin
have := cmp_to_nat m n,
cases cmp m n; simp at this ⊢; try {exact this};
{ simp [show m ≠ n, from λ e, by rw e at this; exact lt_irrefl _ this] }
end
@[simp, norm_cast]
theorem cast_lt [linear_ordered_semiring α] {m n : pos_num} : (m:α) < n ↔ m < n :=
by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_lt, lt_to_nat]
@[simp, norm_cast]
theorem cast_le [linear_ordered_semiring α] {m n : pos_num} : (m:α) ≤ n ↔ m ≤ n :=
by rw ← not_lt; exact not_congr cast_lt
end pos_num
namespace num
variables {α : Type*}
open pos_num
theorem bit_to_nat (b n) : (bit b n : ℕ) = nat.bit b n :=
by cases b; cases n; refl
theorem cast_succ' [add_monoid α] [has_one α] (n) : (succ' n : α) = n + 1 :=
by rw [← pos_num.cast_to_nat, succ'_to_nat, nat.cast_add_one, cast_to_nat]
theorem cast_succ [add_monoid α] [has_one α] (n) : (succ n : α) = n + 1 := cast_succ' n
@[simp, norm_cast] theorem cast_add [semiring α] (m n) : ((m + n : num) : α) = m + n :=
by rw [← cast_to_nat, add_to_nat, nat.cast_add, cast_to_nat, cast_to_nat]
@[simp, norm_cast] theorem cast_bit0 [semiring α] (n : num) : (n.bit0 : α) = _root_.bit0 n :=
by rw [← bit0_of_bit0, _root_.bit0, cast_add]; refl
@[simp, norm_cast] theorem cast_bit1 [semiring α] (n : num) : (n.bit1 : α) = _root_.bit1 n :=
by rw [← bit1_of_bit1, _root_.bit1, bit0_of_bit0, cast_add, cast_bit0]; refl
@[simp, norm_cast] theorem cast_mul [semiring α] : ∀ m n, ((m * n : num) : α) = m * n
| 0 0 := (zero_mul _).symm
| 0 (pos q) := (zero_mul _).symm
| (pos p) 0 := (mul_zero _).symm
| (pos p) (pos q) := pos_num.cast_mul _ _
theorem size_to_nat : ∀ n, (size n : ℕ) = nat.size n
| 0 := nat.size_zero.symm
| (pos p) := p.size_to_nat
theorem size_eq_nat_size : ∀ n, (size n : ℕ) = nat_size n
| 0 := rfl
| (pos p) := p.size_eq_nat_size
theorem nat_size_to_nat (n) : nat_size n = nat.size n :=
by rw [← size_eq_nat_size, size_to_nat]
@[simp] theorem of_nat'_zero : num.of_nat' 0 = 0 :=
by simp [num.of_nat']
@[simp, priority 999] theorem of_nat'_eq : ∀ n, num.of_nat' n = n :=
nat.binary_rec (by simp) $ λ b n IH, begin
rw of_nat' at IH ⊢,
rw [nat.binary_rec_eq, IH],
{ cases b; simp [nat.bit, bit0_of_bit0, bit1_of_bit1] },
{ refl }
end
theorem zneg_to_znum (n : num) : -n.to_znum = n.to_znum_neg := by cases n; refl
theorem zneg_to_znum_neg (n : num) : -n.to_znum_neg = n.to_znum := by cases n; refl
theorem to_znum_inj {m n : num} : m.to_znum = n.to_znum ↔ m = n :=
⟨λ h, by cases m; cases n; cases h; refl, congr_arg _⟩
@[simp, norm_cast squash] theorem cast_to_znum [has_zero α] [has_one α] [has_add α] [has_neg α] :
∀ n : num, (n.to_znum : α) = n
| 0 := rfl
| (num.pos p) := rfl
@[simp] theorem cast_to_znum_neg [add_group α] [has_one α] :
∀ n : num, (n.to_znum_neg : α) = -n
| 0 := neg_zero.symm
| (num.pos p) := rfl
@[simp] theorem add_to_znum (m n : num) : num.to_znum (m + n) = m.to_znum + n.to_znum :=
by cases m; cases n; refl
end num
namespace pos_num
open num
theorem pred_to_nat {n : pos_num} (h : 1 < n) : (pred n : ℕ) = nat.pred n :=
begin
unfold pred,
have := pred'_to_nat n,
cases e : pred' n,
{ have : (1:ℕ) ≤ nat.pred n :=
nat.pred_le_pred ((@cast_lt ℕ _ _ _).2 h),
rw [← pred'_to_nat, e] at this,
exact absurd this dec_trivial },
{ rw [← pred'_to_nat, e], refl }
end
theorem sub'_one (a : pos_num) : sub' a 1 = (pred' a).to_znum :=
by cases a; refl
theorem one_sub' (a : pos_num) : sub' 1 a = (pred' a).to_znum_neg :=
by cases a; refl
theorem lt_iff_cmp {m n} : m < n ↔ cmp m n = ordering.lt := iff.rfl
theorem le_iff_cmp {m n} : m ≤ n ↔ cmp m n ≠ ordering.gt :=
not_congr $ lt_iff_cmp.trans $
by rw ← cmp_swap; cases cmp m n; exact dec_trivial
end pos_num
namespace num
variables {α : Type*}
open pos_num
theorem pred_to_nat : ∀ (n : num), (pred n : ℕ) = nat.pred n
| 0 := rfl
| (pos p) := by rw [pred, pos_num.pred'_to_nat]; refl
theorem ppred_to_nat : ∀ (n : num), coe <$> ppred n = nat.ppred n
| 0 := rfl
| (pos p) := by rw [ppred, option.map_some, nat.ppred_eq_some.2];
rw [pos_num.pred'_to_nat, nat.succ_pred_eq_of_pos (pos_num.to_nat_pos _)]; refl
theorem cmp_swap (m n) : (cmp m n).swap = cmp n m :=
by cases m; cases n; try {unfold cmp}; try {refl}; apply pos_num.cmp_swap
theorem cmp_eq (m n) : cmp m n = ordering.eq ↔ m = n :=
begin
have := cmp_to_nat m n,
cases cmp m n; simp at this ⊢; try {exact this};
{ simp [show m ≠ n, from λ e, by rw e at this; exact lt_irrefl _ this] }
end
@[simp, norm_cast]
theorem cast_lt [linear_ordered_semiring α] {m n : num} : (m:α) < n ↔ m < n :=
by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_lt, lt_to_nat]
@[simp, norm_cast]
theorem cast_le [linear_ordered_semiring α] {m n : num} : (m:α) ≤ n ↔ m ≤ n :=
by rw ← not_lt; exact not_congr cast_lt
@[simp, norm_cast]
theorem cast_inj [linear_ordered_semiring α] {m n : num} : (m:α) = n ↔ m = n :=
by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_inj, to_nat_inj]
theorem lt_iff_cmp {m n} : m < n ↔ cmp m n = ordering.lt := iff.rfl
theorem le_iff_cmp {m n} : m ≤ n ↔ cmp m n ≠ ordering.gt :=
not_congr $ lt_iff_cmp.trans $
by rw ← cmp_swap; cases cmp m n; exact dec_trivial
theorem bitwise_to_nat {f : num → num → num} {g : bool → bool → bool}
(p : pos_num → pos_num → num)
(gff : g ff ff = ff)
(f00 : f 0 0 = 0)
(f0n : ∀ n, f 0 (pos n) = cond (g ff tt) (pos n) 0)
(fn0 : ∀ n, f (pos n) 0 = cond (g tt ff) (pos n) 0)
(fnn : ∀ m n, f (pos m) (pos n) = p m n)
(p11 : p 1 1 = cond (g tt tt) 1 0)
(p1b : ∀ b n, p 1 (pos_num.bit b n) = bit (g tt b) (cond (g ff tt) (pos n) 0))
(pb1 : ∀ a m, p (pos_num.bit a m) 1 = bit (g a tt) (cond (g tt ff) (pos m) 0))
(pbb : ∀ a b m n, p (pos_num.bit a m) (pos_num.bit b n) = bit (g a b) (p m n))
: ∀ m n : num, (f m n : ℕ) = nat.bitwise g m n :=
begin
intros, cases m with m; cases n with n;
try { change zero with 0 };
try { change ((0:num):ℕ) with 0 },
{ rw [f00, nat.bitwise_zero]; refl },
{ unfold nat.bitwise, rw [f0n, nat.binary_rec_zero],
cases g ff tt; refl },
{ unfold nat.bitwise,
generalize h : (pos m : ℕ) = m', revert h,
apply nat.bit_cases_on m' _, intros b m' h,
rw [fn0, nat.binary_rec_eq, nat.binary_rec_zero, ←h],
cases g tt ff; refl,
apply nat.bitwise_bit_aux gff },
{ rw fnn,
have : ∀b (n : pos_num), (cond b ↑n 0 : ℕ) = ↑(cond b (pos n) 0 : num) :=
by intros; cases b; refl,
induction m with m IH m IH generalizing n; cases n with n n,
any_goals { change one with 1 },
any_goals { change pos 1 with 1 },
any_goals { change pos_num.bit0 with pos_num.bit ff },
any_goals { change pos_num.bit1 with pos_num.bit tt },
any_goals { change ((1:num):ℕ) with nat.bit tt 0 },
all_goals {
repeat {
rw show ∀ b n, (pos (pos_num.bit b n) : ℕ) = nat.bit b ↑n,
by intros; cases b; refl },
rw nat.bitwise_bit },
any_goals { assumption },
any_goals { rw [nat.bitwise_zero, p11], cases g tt tt; refl },
any_goals { rw [nat.bitwise_zero_left, this, ← bit_to_nat, p1b] },
any_goals { rw [nat.bitwise_zero_right _ gff, this, ← bit_to_nat, pb1] },
all_goals { rw [← show ∀ n, ↑(p m n) = nat.bitwise g ↑m ↑n, from IH],
rw [← bit_to_nat, pbb] } }
end
@[simp, norm_cast] theorem lor_to_nat : ∀ m n, (lor m n : ℕ) = nat.lor m n :=
by apply bitwise_to_nat (λx y, pos (pos_num.lor x y)); intros; try {cases a}; try {cases b}; refl
@[simp, norm_cast] theorem land_to_nat : ∀ m n, (land m n : ℕ) = nat.land m n :=
by apply bitwise_to_nat pos_num.land; intros; try {cases a}; try {cases b}; refl
@[simp, norm_cast] theorem ldiff_to_nat : ∀ m n, (ldiff m n : ℕ) = nat.ldiff m n :=
by apply bitwise_to_nat pos_num.ldiff; intros; try {cases a}; try {cases b}; refl
@[simp, norm_cast] theorem lxor_to_nat : ∀ m n, (lxor m n : ℕ) = nat.lxor m n :=
by apply bitwise_to_nat pos_num.lxor; intros; try {cases a}; try {cases b}; refl
@[simp, norm_cast] theorem shiftl_to_nat (m n) : (shiftl m n : ℕ) = nat.shiftl m n :=
begin
cases m; dunfold shiftl, {symmetry, apply nat.zero_shiftl},
simp, induction n with n IH, {refl},
simp [pos_num.shiftl, nat.shiftl_succ], rw ←IH
end
@[simp, norm_cast] theorem shiftr_to_nat (m n) : (shiftr m n : ℕ) = nat.shiftr m n :=
begin
cases m with m; dunfold shiftr, {symmetry, apply nat.zero_shiftr},
induction n with n IH generalizing m, {cases m; refl},
cases m with m m; dunfold pos_num.shiftr,
{ rw [nat.shiftr_eq_div_pow], symmetry, apply nat.div_eq_of_lt,
exact @nat.pow_lt_pow_of_lt_right 2 dec_trivial 0 (n+1) (nat.succ_pos _) },
{ transitivity, apply IH,
change nat.shiftr m n = nat.shiftr (bit1 m) (n+1),
rw [add_comm n 1, nat.shiftr_add],
apply congr_arg (λx, nat.shiftr x n), unfold nat.shiftr,
change (bit1 ↑m : ℕ) with nat.bit tt m,
rw nat.div2_bit },
{ transitivity, apply IH,
change nat.shiftr m n = nat.shiftr (bit0 m) (n + 1),
rw [add_comm n 1, nat.shiftr_add],
apply congr_arg (λx, nat.shiftr x n), unfold nat.shiftr,
change (bit0 ↑m : ℕ) with nat.bit ff m,
rw nat.div2_bit }
end
@[simp] theorem test_bit_to_nat (m n) : test_bit m n = nat.test_bit m n :=
begin
cases m with m; unfold test_bit nat.test_bit,
{ change (zero : nat) with 0, rw nat.zero_shiftr, refl },
induction n with n IH generalizing m;
cases m; dunfold pos_num.test_bit, {refl},
{ exact (nat.bodd_bit _ _).symm },
{ exact (nat.bodd_bit _ _).symm },
{ change ff = nat.bodd (nat.shiftr 1 (n + 1)),
rw [add_comm, nat.shiftr_add], change nat.shiftr 1 1 with 0,
rw nat.zero_shiftr; refl },
{ change pos_num.test_bit m n = nat.bodd (nat.shiftr (nat.bit tt m) (n + 1)),
rw [add_comm, nat.shiftr_add], unfold nat.shiftr,
rw nat.div2_bit, apply IH },
{ change pos_num.test_bit m n = nat.bodd (nat.shiftr (nat.bit ff m) (n + 1)),
rw [add_comm, nat.shiftr_add], unfold nat.shiftr,
rw nat.div2_bit, apply IH },
end
end num
namespace znum
variables {α : Type*}
open pos_num
@[simp, norm_cast] theorem cast_zero [has_zero α] [has_one α] [has_add α] [has_neg α] :
((0 : znum) : α) = 0 := rfl
@[simp] theorem cast_zero' [has_zero α] [has_one α] [has_add α] [has_neg α] :
(znum.zero : α) = 0 := rfl
@[simp, norm_cast] theorem cast_one [has_zero α] [has_one α] [has_add α] [has_neg α] :
((1 : znum) : α) = 1 := rfl
@[simp] theorem cast_pos [has_zero α] [has_one α] [has_add α] [has_neg α]
(n : pos_num) : (pos n : α) = n := rfl
@[simp] theorem cast_neg [has_zero α] [has_one α] [has_add α] [has_neg α]
(n : pos_num) : (neg n : α) = -n := rfl
@[simp, norm_cast] theorem cast_zneg [add_group α] [has_one α] : ∀ n, ((-n : znum) : α) = -n
| 0 := neg_zero.symm
| (pos p) := rfl
| (neg p) := (neg_neg _).symm
theorem neg_zero : (-0 : znum) = 0 := rfl
theorem zneg_pos (n : pos_num) : -pos n = neg n := rfl
theorem zneg_neg (n : pos_num) : -neg n = pos n := rfl
theorem zneg_zneg (n : znum) : - -n = n := by cases n; refl
theorem zneg_bit1 (n : znum) : -n.bit1 = (-n).bitm1 := by cases n; refl
theorem zneg_bitm1 (n : znum) : -n.bitm1 = (-n).bit1 := by cases n; refl
theorem zneg_succ (n : znum) : -n.succ = (-n).pred :=
by cases n; try {refl}; rw [succ, num.zneg_to_znum_neg]; refl
theorem zneg_pred (n : znum) : -n.pred = (-n).succ :=
by rw [← zneg_zneg (succ (-n)), zneg_succ, zneg_zneg]
@[simp, norm_cast] theorem neg_of_int : ∀ n, ((-n : ℤ) : znum) = -n
| (n+1:ℕ) := rfl
| 0 := rfl
| -[1+n] := (zneg_zneg _).symm
@[simp] theorem abs_to_nat : ∀ n, (abs n : ℕ) = int.nat_abs n
| 0 := rfl
| (pos p) := congr_arg int.nat_abs p.to_nat_to_int
| (neg p) := show int.nat_abs ((p:ℕ):ℤ) = int.nat_abs (- p),
by rw [p.to_nat_to_int, int.nat_abs_neg]
@[simp] theorem abs_to_znum : ∀ n : num, abs n.to_znum = n
| 0 := rfl
| (num.pos p) := rfl
@[simp, norm_cast] theorem cast_to_int [add_group α] [has_one α] : ∀ n : znum, ((n : ℤ) : α) = n
| 0 := rfl
| (pos p) := by rw [cast_pos, cast_pos, pos_num.cast_to_int]
| (neg p) := by rw [cast_neg, cast_neg, int.cast_neg, pos_num.cast_to_int]
theorem bit0_of_bit0 : ∀ n : znum, _root_.bit0 n = n.bit0
| 0 := rfl
| (pos a) := congr_arg pos a.bit0_of_bit0
| (neg a) := congr_arg neg a.bit0_of_bit0
theorem bit1_of_bit1 : ∀ n : znum, _root_.bit1 n = n.bit1
| 0 := rfl
| (pos a) := congr_arg pos a.bit1_of_bit1
| (neg a) := show pos_num.sub' 1 (_root_.bit0 a) = _,
by rw [pos_num.one_sub', a.bit0_of_bit0]; refl
@[simp, norm_cast] theorem cast_bit0 [add_group α] [has_one α] :
∀ n : znum, (n.bit0 : α) = bit0 n
| 0 := (add_zero _).symm
| (pos p) := by rw [znum.bit0, cast_pos, cast_pos]; refl
| (neg p) := by rw [znum.bit0, cast_neg, cast_neg, pos_num.cast_bit0,
_root_.bit0, _root_.bit0, neg_add_rev]
@[simp, norm_cast] theorem cast_bit1 [add_group α] [has_one α] :
∀ n : znum, (n.bit1 : α) = bit1 n
| 0 := by simp [znum.bit1, _root_.bit1, _root_.bit0]
| (pos p) := by rw [znum.bit1, cast_pos, cast_pos]; refl
| (neg p) := begin
rw [znum.bit1, cast_neg, cast_neg],
cases e : pred' p with a;
have : p = _ := (succ'_pred' p).symm.trans
(congr_arg num.succ' e),
{ change p=1 at this, subst p,
simp [_root_.bit1, _root_.bit0] },
{ rw [num.succ'] at this, subst p,
have : (↑(-↑a:ℤ) : α) = -1 + ↑(-↑a + 1 : ℤ), {simp [add_comm]},
simpa [_root_.bit1, _root_.bit0, -add_comm] },
end
@[simp] theorem cast_bitm1 [add_group α] [has_one α]
(n : znum) : (n.bitm1 : α) = bit0 n - 1 :=
begin
conv { to_lhs, rw ← zneg_zneg n },
rw [← zneg_bit1, cast_zneg, cast_bit1],
have : ((-1 + n + n : ℤ) : α) = (n + n + -1 : ℤ), {simp [add_comm, add_left_comm]},
simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg, -int.add_neg_one]
end
theorem add_zero (n : znum) : n + 0 = n := by cases n; refl
theorem zero_add (n : znum) : 0 + n = n := by cases n; refl
theorem add_one : ∀ n : znum, n + 1 = succ n
| 0 := rfl
| (pos p) := congr_arg pos p.add_one
| (neg p) := by cases p; refl
end znum
namespace pos_num
variables {α : Type*}
theorem cast_to_znum : ∀ n : pos_num, (n : znum) = znum.pos n
| 1 := rfl
| (bit0 p) := (znum.bit0_of_bit0 p).trans $ congr_arg _ (cast_to_znum p)
| (bit1 p) := (znum.bit1_of_bit1 p).trans $ congr_arg _ (cast_to_znum p)
local attribute [-simp] int.add_neg_one
theorem cast_sub' [add_group α] [has_one α] : ∀ m n : pos_num, (sub' m n : α) = m - n
| a 1 := by rw [sub'_one, num.cast_to_znum,
← num.cast_to_nat, pred'_to_nat, ← nat.sub_one];
simp [pos_num.cast_pos]
| 1 b := by rw [one_sub', num.cast_to_znum_neg, ← neg_sub, neg_inj,
← num.cast_to_nat, pred'_to_nat, ← nat.sub_one];
simp [pos_num.cast_pos]
| (bit0 a) (bit0 b) := begin
rw [sub', znum.cast_bit0, cast_sub'],
have : ((a + -b + (a + -b) : ℤ) : α) = a + a + (-b + -b), {simp [add_left_comm]},
simpa [_root_.bit0, sub_eq_add_neg]
end
| (bit0 a) (bit1 b) := begin
rw [sub', znum.cast_bitm1, cast_sub'],
have : ((-b + (a + (-b + -1)) : ℤ) : α) = (a + -1 + (-b + -b):ℤ),
{ simp [add_comm, add_left_comm] },
simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg]
end
| (bit1 a) (bit0 b) := begin
rw [sub', znum.cast_bit1, cast_sub'],
have : ((-b + (a + (-b + 1)) : ℤ) : α) = (a + 1 + (-b + -b):ℤ),
{ simp [add_comm, add_left_comm] },
simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg]
end
| (bit1 a) (bit1 b) := begin
rw [sub', znum.cast_bit0, cast_sub'],
have : ((-b + (a + -b) : ℤ) : α) = a + (-b + -b), {simp [add_left_comm]},
simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg]
end
theorem to_nat_eq_succ_pred (n : pos_num) : (n:ℕ) = n.pred' + 1 :=
by rw [← num.succ'_to_nat, n.succ'_pred']
theorem to_int_eq_succ_pred (n : pos_num) : (n:ℤ) = (n.pred' : ℕ) + 1 :=
by rw [← n.to_nat_to_int, to_nat_eq_succ_pred]; refl
end pos_num
namespace num
variables {α : Type*}
@[simp] theorem cast_sub' [add_group α] [has_one α] : ∀ m n : num, (sub' m n : α) = m - n
| 0 0 := (sub_zero _).symm
| (pos a) 0 := (sub_zero _).symm
| 0 (pos b) := (zero_sub _).symm
| (pos a) (pos b) := pos_num.cast_sub' _ _
@[simp] theorem of_nat_to_znum : ∀ n : ℕ, to_znum n = n
| 0 := rfl
| (n+1) := by rw [nat.cast_add_one, nat.cast_add_one,
znum.add_one, add_one, ← of_nat_to_znum]; cases (n:num); refl
@[simp] theorem of_nat_to_znum_neg (n : ℕ) : to_znum_neg n = -n :=
by rw [← of_nat_to_znum, zneg_to_znum]
theorem mem_of_znum' : ∀ {m : num} {n : znum}, m ∈ of_znum' n ↔ n = to_znum m
| 0 0 := ⟨λ _, rfl, λ _, rfl⟩
| (pos m) 0 := ⟨λ h, by cases h, λ h, by cases h⟩
| m (znum.pos p) := option.some_inj.trans $
by cases m; split; intro h; try {cases h}; refl
| m (znum.neg p) := ⟨λ h, by cases h, λ h, by cases m; cases h⟩
theorem of_znum'_to_nat : ∀ (n : znum), coe <$> of_znum' n = int.to_nat' n
| 0 := rfl
| (znum.pos p) := show _ = int.to_nat' p, by rw [← pos_num.to_nat_to_int p]; refl
| (znum.neg p) := congr_arg (λ x, int.to_nat' (-x)) $
show ((p.pred' + 1 : ℕ) : ℤ) = p, by rw ← succ'_to_nat; simp
@[simp] theorem of_znum_to_nat : ∀ (n : znum), (of_znum n : ℕ) = int.to_nat n
| 0 := rfl
| (znum.pos p) := show _ = int.to_nat p, by rw [← pos_num.to_nat_to_int p]; refl
| (znum.neg p) := congr_arg (λ x, int.to_nat (-x)) $
show ((p.pred' + 1 : ℕ) : ℤ) = p, by rw ← succ'_to_nat; simp
@[simp] theorem cast_of_znum [add_group α] [has_one α] (n : znum) :
(of_znum n : α) = int.to_nat n :=
by rw [← cast_to_nat, of_znum_to_nat]
@[simp, norm_cast] theorem sub_to_nat (m n) : ((m - n : num) : ℕ) = m - n :=
show (of_znum _ : ℕ) = _, by rw [of_znum_to_nat, cast_sub',
← to_nat_to_int, ← to_nat_to_int, int.to_nat_sub]
end num
namespace znum
variables {α : Type*}
@[simp, norm_cast] theorem cast_add [add_group α] [has_one α] : ∀ m n, ((m + n : znum) : α) = m + n
| 0 a := by cases a; exact (_root_.zero_add _).symm
| b 0 := by cases b; exact (_root_.add_zero _).symm
| (pos a) (pos b) := pos_num.cast_add _ _
| (pos a) (neg b) := by simpa only [sub_eq_add_neg] using pos_num.cast_sub' _ _
| (neg a) (pos b) :=
have (↑b + -↑a : α) = -↑a + ↑b, by rw [← pos_num.cast_to_int a, ← pos_num.cast_to_int b,
← int.cast_neg, ← int.cast_add (-a)]; simp [add_comm],
(pos_num.cast_sub' _ _).trans $ (sub_eq_add_neg _ _).trans this
| (neg a) (neg b) := show -(↑(a + b) : α) = -a + -b, by rw [
pos_num.cast_add, neg_eq_iff_neg_eq, neg_add_rev, neg_neg, neg_neg,
← pos_num.cast_to_int a, ← pos_num.cast_to_int b, ← int.cast_add]; simp [add_comm]
@[simp] theorem cast_succ [add_group α] [has_one α] (n) : ((succ n : znum) : α) = n + 1 :=
by rw [← add_one, cast_add, cast_one]
@[simp, norm_cast] theorem mul_to_int : ∀ m n, ((m * n : znum) : ℤ) = m * n
| 0 a := by cases a; exact (_root_.zero_mul _).symm
| b 0 := by cases b; exact (_root_.mul_zero _).symm
| (pos a) (pos b) := pos_num.cast_mul a b
| (pos a) (neg b) := show -↑(a * b) = ↑a * -↑b, by rw [pos_num.cast_mul, neg_mul_eq_mul_neg]
| (neg a) (pos b) := show -↑(a * b) = -↑a * ↑b, by rw [pos_num.cast_mul, neg_mul_eq_neg_mul]
| (neg a) (neg b) := show ↑(a * b) = -↑a * -↑b, by rw [pos_num.cast_mul, neg_mul_neg]
theorem cast_mul [ring α] (m n) : ((m * n : znum) : α) = m * n :=
by rw [← cast_to_int, mul_to_int, int.cast_mul, cast_to_int, cast_to_int]
@[simp, norm_cast] theorem of_to_int : Π (n : znum), ((n : ℤ) : znum) = n
| 0 := rfl
| (pos a) := by rw [cast_pos, ← pos_num.cast_to_nat,
int.cast_coe_nat', ← num.of_nat_to_znum, pos_num.of_to_nat]; refl
| (neg a) := by rw [cast_neg, neg_of_int, ← pos_num.cast_to_nat,
int.cast_coe_nat', ← num.of_nat_to_znum_neg, pos_num.of_to_nat]; refl
@[norm_cast]
theorem to_of_int : Π (n : ℤ), ((n : znum) : ℤ) = n
| (n : ℕ) := by rw [int.cast_coe_nat,
← num.of_nat_to_znum, num.cast_to_znum, ← num.cast_to_nat,
int.nat_cast_eq_coe_nat, num.to_of_nat]
| -[1+ n] := by rw [int.cast_neg_succ_of_nat, cast_zneg,
add_one, cast_succ, int.neg_succ_of_nat_eq,
← num.of_nat_to_znum, num.cast_to_znum, ← num.cast_to_nat,
int.nat_cast_eq_coe_nat, num.to_of_nat]
theorem to_int_inj {m n : znum} : (m : ℤ) = n ↔ m = n :=
⟨λ h, function.left_inverse.injective of_to_int h, congr_arg _⟩
@[simp, norm_cast] theorem of_int_cast [add_group α] [has_one α] (n : ℤ) : ((n : znum) : α) = n :=
by rw [← cast_to_int, to_of_int]
@[simp, norm_cast] theorem of_nat_cast [add_group α] [has_one α] (n : ℕ) : ((n : znum) : α) = n :=
of_int_cast n
@[simp] theorem of_int'_eq : ∀ n, znum.of_int' n = n
| (n : ℕ) := to_int_inj.1 $ by simp [znum.of_int']
| -[1+ n] := to_int_inj.1 $ by simp [znum.of_int']
theorem cmp_to_int : ∀ (m n), (ordering.cases_on (cmp m n) ((m:ℤ) < n) (m = n) ((n:ℤ) < m) : Prop)
| 0 0 := rfl
| (pos a) (pos b) := begin
have := pos_num.cmp_to_nat a b; revert this; dsimp [cmp];
cases pos_num.cmp a b; dsimp;
[simp, exact congr_arg pos, simp [gt]]
end
| (neg a) (neg b) := begin
have := pos_num.cmp_to_nat b a; revert this; dsimp [cmp];
cases pos_num.cmp b a; dsimp;
[simp, simp {contextual := tt}, simp [gt]]
end
| (pos a) 0 := pos_num.cast_pos _
| (pos a) (neg b) := lt_trans (neg_lt_zero.2 $ pos_num.cast_pos _) (pos_num.cast_pos _)
| 0 (neg b) := neg_lt_zero.2 $ pos_num.cast_pos _
| (neg a) 0 := neg_lt_zero.2 $ pos_num.cast_pos _
| (neg a) (pos b) := lt_trans (neg_lt_zero.2 $ pos_num.cast_pos _) (pos_num.cast_pos _)
| 0 (pos b) := pos_num.cast_pos _
@[norm_cast]
theorem lt_to_int {m n : znum} : (m:ℤ) < n ↔ m < n :=
show (m:ℤ) < n ↔ cmp m n = ordering.lt, from
match cmp m n, cmp_to_int m n with
| ordering.lt, h := by simp at h; simp [h]
| ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial
| ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial
end
theorem le_to_int {m n : znum} : (m:ℤ) ≤ n ↔ m ≤ n :=
by rw ← not_lt; exact not_congr lt_to_int
@[simp, norm_cast]
theorem cast_lt [linear_ordered_ring α] {m n : znum} : (m:α) < n ↔ m < n :=
by rw [← cast_to_int m, ← cast_to_int n, int.cast_lt, lt_to_int]
@[simp, norm_cast]
theorem cast_le [linear_ordered_ring α] {m n : znum} : (m:α) ≤ n ↔ m ≤ n :=
by rw ← not_lt; exact not_congr cast_lt
@[simp, norm_cast]
theorem cast_inj [linear_ordered_ring α] {m n : znum} : (m:α) = n ↔ m = n :=
by rw [← cast_to_int m, ← cast_to_int n, int.cast_inj, to_int_inj]
/--
This tactic tries to turn an (in)equality about `znum`s to one about `int`s by rewriting.
```lean
example (n : znum) (m : znum) : n ≤ n + m * m :=
begin
znum.transfer_rw,
exact le_add_of_nonneg_right (mul_self_nonneg _)
end
```
-/
meta def transfer_rw : tactic unit :=
`[repeat {rw ← to_int_inj <|> rw ← lt_to_int <|> rw ← le_to_int},
repeat {rw cast_add <|> rw mul_to_int <|> rw cast_one <|> rw cast_zero}]
/--
This tactic tries to prove (in)equalities about `znum`s by transfering them to the `int` world and
then trying to call `simp`.
```lean
example (n : znum) (m : znum) : n ≤ n + m * m :=
begin
znum.transfer,
exact mul_self_nonneg _
end
```
-/
meta def transfer : tactic unit :=
`[intros, transfer_rw, try {simp [add_comm, add_left_comm, mul_comm, mul_left_comm]}]
instance : linear_order znum :=
{ lt := (<),
lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le},
le := (≤),
le_refl := by transfer,
le_trans := by {intros a b c, transfer_rw, apply le_trans},
le_antisymm := by {intros a b, transfer_rw, apply le_antisymm},
le_total := by {intros a b, transfer_rw, apply le_total},
decidable_eq := znum.decidable_eq,
decidable_le := znum.decidable_le,
decidable_lt := znum.decidable_lt }
instance : add_comm_group znum :=
{ add := (+),
add_assoc := by transfer,
zero := 0,
zero_add := zero_add,
add_zero := add_zero,
add_comm := by transfer,
neg := has_neg.neg,
add_left_neg := by transfer }
instance : linear_ordered_comm_ring znum :=
{ mul := (*),
mul_assoc := by transfer,
one := 1,
one_mul := by transfer,
mul_one := by transfer,
left_distrib := by {transfer, simp [mul_add]},
right_distrib := by {transfer, simp [mul_add, mul_comm]},
mul_comm := by transfer,
exists_pair_ne := ⟨0, 1, dec_trivial⟩,
add_le_add_left := by {intros a b h c, revert h, transfer_rw, exact λ h, add_le_add_left h c},
mul_pos := λ a b, show 0 < a → 0 < b → 0 < a * b, by {transfer_rw, apply mul_pos},
zero_le_one := dec_trivial,
..znum.linear_order, ..znum.add_comm_group }
@[simp, norm_cast] theorem dvd_to_int (m n : znum) : (m : ℤ) ∣ n ↔ m ∣ n :=
⟨λ ⟨k, e⟩, ⟨k, by rw [← of_to_int n, e]; simp⟩,
λ ⟨k, e⟩, ⟨k, by simp [e]⟩⟩
end znum
namespace pos_num
theorem divmod_to_nat_aux {n d : pos_num} {q r : num}
(h₁ : (r:ℕ) + d * _root_.bit0 q = n)
(h₂ : (r:ℕ) < 2 * d) :
((divmod_aux d q r).2 + d * (divmod_aux d q r).1 : ℕ) = ↑n ∧
((divmod_aux d q r).2 : ℕ) < d :=
begin
unfold divmod_aux,
have : ∀ {r₂}, num.of_znum' (num.sub' r (num.pos d)) = some r₂ ↔ (r : ℕ) = r₂ + d,
{ intro r₂,
apply num.mem_of_znum'.trans,
rw [← znum.to_int_inj, num.cast_to_znum,
num.cast_sub', sub_eq_iff_eq_add, ← int.coe_nat_inj'],
simp },
cases e : num.of_znum' (num.sub' r (num.pos d)) with r₂;
simp [divmod_aux],
{ refine ⟨h₁, lt_of_not_ge (λ h, _)⟩,
cases nat.le.dest h with r₂ e',
rw [← num.to_of_nat r₂, add_comm] at e',
cases e.symm.trans (this.2 e'.symm) },
{ have := this.1 e,
split,
{ rwa [_root_.bit1, add_comm _ 1, mul_add, mul_one,
← add_assoc, ← this] },
{ rwa [this, two_mul, add_lt_add_iff_right] at h₂ } }
end
theorem divmod_to_nat (d n : pos_num) :
(n / d : ℕ) = (divmod d n).1 ∧
(n % d : ℕ) = (divmod d n).2 :=
begin
rw nat.div_mod_unique (pos_num.cast_pos _),
induction n with n IH n IH,
{ exact divmod_to_nat_aux (by simp; refl)
(nat.mul_le_mul_left 2
(pos_num.cast_pos d : (0 : ℕ) < d)) },
{ unfold divmod,
cases divmod d n with q r, simp only [divmod] at IH ⊢,
apply divmod_to_nat_aux; simp,
{ rw [_root_.bit1, _root_.bit1, add_right_comm,
bit0_eq_two_mul ↑n, ← IH.1,
mul_add, ← bit0_eq_two_mul,
mul_left_comm, ← bit0_eq_two_mul] },
{ rw ← bit0_eq_two_mul,
exact nat.bit1_lt_bit0 IH.2 } },
{ unfold divmod,
cases divmod d n with q r, simp only [divmod] at IH ⊢,
apply divmod_to_nat_aux; simp,
{ rw [bit0_eq_two_mul ↑n, ← IH.1,
mul_add, ← bit0_eq_two_mul,
mul_left_comm, ← bit0_eq_two_mul] },
{ rw ← bit0_eq_two_mul,
exact nat.bit0_lt IH.2 } }
end
@[simp] theorem div'_to_nat (n d) : (div' n d : ℕ) = n / d :=
(divmod_to_nat _ _).1.symm
@[simp] theorem mod'_to_nat (n d) : (mod' n d : ℕ) = n % d :=
(divmod_to_nat _ _).2.symm
end pos_num
namespace num
@[simp] protected lemma div_zero (n : num) : n / 0 = 0 :=
show n.div 0 = 0, by { cases n, refl, simp [num.div] }
@[simp, norm_cast] theorem div_to_nat : ∀ n d, ((n / d : num) : ℕ) = n / d
| 0 0 := by simp
| 0 (pos d) := (nat.zero_div _).symm
| (pos n) 0 := (nat.div_zero _).symm
| (pos n) (pos d) := pos_num.div'_to_nat _ _
@[simp] protected lemma mod_zero (n : num) : n % 0 = n :=
show n.mod 0 = n, by { cases n, refl, simp [num.mod] }
@[simp, norm_cast] theorem mod_to_nat : ∀ n d, ((n % d : num) : ℕ) = n % d
| 0 0 := by simp
| 0 (pos d) := (nat.zero_mod _).symm
| (pos n) 0 := (nat.mod_zero _).symm
| (pos n) (pos d) := pos_num.mod'_to_nat _ _
theorem gcd_to_nat_aux : ∀ {n} {a b : num},
a ≤ b → (a * b).nat_size ≤ n → (gcd_aux n a b : ℕ) = nat.gcd a b
| 0 0 b ab h := (nat.gcd_zero_left _).symm
| 0 (pos a) 0 ab h := (not_lt_of_ge ab).elim rfl
| 0 (pos a) (pos b) ab h :=
(not_lt_of_le h).elim $ pos_num.nat_size_pos _
| (nat.succ n) 0 b ab h := (nat.gcd_zero_left _).symm
| (nat.succ n) (pos a) b ab h := begin
simp [gcd_aux],
rw [nat.gcd_rec, gcd_to_nat_aux, mod_to_nat], {refl},
{ rw [← le_to_nat, mod_to_nat],
exact le_of_lt (nat.mod_lt _ (pos_num.cast_pos _)) },
rw [nat_size_to_nat, mul_to_nat, nat.size_le] at h ⊢,
rw [mod_to_nat, mul_comm],
rw [pow_succ', ← nat.mod_add_div b (pos a)] at h,
refine lt_of_mul_lt_mul_right (lt_of_le_of_lt _ h) (nat.zero_le 2),
rw [mul_two, mul_add],
refine add_le_add_left (nat.mul_le_mul_left _
(le_trans (le_of_lt (nat.mod_lt _ (pos_num.cast_pos _))) _)) _,
suffices : 1 ≤ _, simpa using nat.mul_le_mul_left (pos a) this,
rw [nat.le_div_iff_mul_le _ _ a.cast_pos, one_mul],
exact le_to_nat.2 ab
end
@[simp] theorem gcd_to_nat : ∀ a b, (gcd a b : ℕ) = nat.gcd a b :=
have ∀ a b : num, (a * b).nat_size ≤ a.nat_size + b.nat_size,
begin
intros,
simp [nat_size_to_nat],
rw [nat.size_le, pow_add],
exact mul_lt_mul'' (nat.lt_size_self _)
(nat.lt_size_self _) (nat.zero_le _) (nat.zero_le _)
end,
begin
intros, unfold gcd, split_ifs,
{ exact gcd_to_nat_aux h (this _ _) },
{ rw nat.gcd_comm,
exact gcd_to_nat_aux (le_of_not_le h) (this _ _) }
end
theorem dvd_iff_mod_eq_zero {m n : num} : m ∣ n ↔ n % m = 0 :=
by rw [← dvd_to_nat, nat.dvd_iff_mod_eq_zero,
← to_nat_inj, mod_to_nat]; refl
instance decidable_dvd : decidable_rel ((∣) : num → num → Prop)
| a b := decidable_of_iff' _ dvd_iff_mod_eq_zero
end num
instance pos_num.decidable_dvd : decidable_rel ((∣) : pos_num → pos_num → Prop)
| a b := num.decidable_dvd _ _
namespace znum
@[simp] protected lemma div_zero (n : znum) : n / 0 = 0 :=
show n.div 0 = 0, by cases n; refl <|> simp [znum.div]
@[simp, norm_cast] theorem div_to_int : ∀ n d, ((n / d : znum) : ℤ) = n / d
| 0 0 := by simp [int.div_zero]
| 0 (pos d) := (int.zero_div _).symm
| 0 (neg d) := (int.zero_div _).symm
| (pos n) 0 := (int.div_zero _).symm
| (neg n) 0 := (int.div_zero _).symm
| (pos n) (pos d) := (num.cast_to_znum _).trans $
by rw ← num.to_nat_to_int; simp
| (pos n) (neg d) := (num.cast_to_znum_neg _).trans $
by rw ← num.to_nat_to_int; simp
| (neg n) (pos d) := show - _ = (-_/↑d), begin
rw [n.to_int_eq_succ_pred, d.to_int_eq_succ_pred,
← pos_num.to_nat_to_int, num.succ'_to_nat,
num.div_to_nat],
change -[1+ n.pred' / ↑d] = -[1+ n.pred' / (d.pred' + 1)],
rw d.to_nat_eq_succ_pred
end
| (neg n) (neg d) := show ↑(pos_num.pred' n / num.pos d).succ' = (-_ / -↑d), begin
rw [n.to_int_eq_succ_pred, d.to_int_eq_succ_pred,
← pos_num.to_nat_to_int, num.succ'_to_nat,
num.div_to_nat],
change (nat.succ (_/d) : ℤ) = nat.succ (n.pred'/(d.pred' + 1)),
rw d.to_nat_eq_succ_pred
end
@[simp, norm_cast] theorem mod_to_int : ∀ n d, ((n % d : znum) : ℤ) = n % d
| 0 d := (int.zero_mod _).symm
| (pos n) d := (num.cast_to_znum _).trans $
by rw [← num.to_nat_to_int, cast_pos, num.mod_to_nat,
← pos_num.to_nat_to_int, abs_to_nat]; refl
| (neg n) d := (num.cast_sub' _ _).trans $
by rw [← num.to_nat_to_int, cast_neg, ← num.to_nat_to_int,
num.succ_to_nat, num.mod_to_nat, abs_to_nat,
← int.sub_nat_nat_eq_coe, n.to_int_eq_succ_pred]; refl
@[simp] theorem gcd_to_nat (a b) : (gcd a b : ℕ) = int.gcd a b :=
(num.gcd_to_nat _ _).trans $ by simpa
theorem dvd_iff_mod_eq_zero {m n : znum} : m ∣ n ↔ n % m = 0 :=
by rw [← dvd_to_int, int.dvd_iff_mod_eq_zero,
← to_int_inj, mod_to_int]; refl
instance : decidable_rel ((∣) : znum → znum → Prop)
| a b := decidable_of_iff' _ dvd_iff_mod_eq_zero
end znum
namespace int
/-- Cast a `snum` to the corresponding integer. -/
def of_snum : snum → ℤ :=
snum.rec' (λ a, cond a (-1) 0) (λa p IH, cond a (bit1 IH) (bit0 IH))
instance snum_coe : has_coe snum ℤ := ⟨of_snum⟩
end int
instance : has_lt snum := ⟨λa b, (a : ℤ) < b⟩
instance : has_le snum := ⟨λa b, (a : ℤ) ≤ b⟩
|
1c8579ebacb4f7055bdd8c5aa9364b7a3399b899 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/analysis/normed_space/star/basic.lean | 2302c5b624236804c8e44e93b5ae9c0f43340e9b | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 7,547 | lean | /-
Copyright (c) 2021 Frédéric Dupuis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Frédéric Dupuis
-/
import analysis.normed.group.hom
import analysis.normed_space.basic
import analysis.normed_space.linear_isometry
import algebra.star.unitary
/-!
# Normed star rings and algebras
A normed star monoid is a `star_add_monoid` endowed with a norm such that the star operation is
isometric.
A C⋆-ring is a normed star monoid that is also a ring and that verifies the stronger
condition `∥x⋆ * x∥ = ∥x∥^2` for all `x`. If a C⋆-ring is also a star algebra, then it is a
C⋆-algebra.
To get a C⋆-algebra `E` over field `𝕜`, use
`[normed_field 𝕜] [star_ring 𝕜] [normed_ring E] [star_ring E] [cstar_ring E]
[normed_algebra 𝕜 E] [star_module 𝕜 E]`.
## TODO
- Show that `∥x⋆ * x∥ = ∥x∥^2` is equivalent to `∥x⋆ * x∥ = ∥x⋆∥ * ∥x∥`, which is used as the
definition of C*-algebras in some sources (e.g. Wikipedia).
-/
open_locale topological_space
local postfix `⋆`:std.prec.max_plus := star
/-- A normed star ring is a star ring endowed with a norm such that `star` is isometric. -/
class normed_star_monoid (E : Type*) [normed_group E] [star_add_monoid E] :=
(norm_star : ∀ {x : E}, ∥x⋆∥ = ∥x∥)
export normed_star_monoid (norm_star)
attribute [simp] norm_star
/-- A C*-ring is a normed star ring that satifies the stronger condition `∥x⋆ * x∥ = ∥x∥^2`
for every `x`. -/
class cstar_ring (E : Type*) [normed_ring E] [star_ring E] :=
(norm_star_mul_self : ∀ {x : E}, ∥x⋆ * x∥ = ∥x∥ * ∥x∥)
noncomputable instance : cstar_ring ℝ :=
{ norm_star_mul_self := λ x, by simp only [star, id.def, normed_field.norm_mul] }
variables {𝕜 E α : Type*}
section normed_star_monoid
variables [normed_group E] [star_add_monoid E] [normed_star_monoid E]
/-- The `star` map in a normed star group is a normed group homomorphism. -/
def star_normed_group_hom : normed_group_hom E E :=
{ bound' := ⟨1, λ v, le_trans (norm_star.le) (one_mul _).symm.le⟩,
.. star_add_equiv }
/-- The `star` map in a normed star group is an isometry -/
lemma star_isometry : isometry (star : E → E) :=
star_add_equiv.to_add_monoid_hom.isometry_of_norm (λ _, norm_star)
lemma continuous_star : continuous (star : E → E) := star_isometry.continuous
lemma continuous_on_star {s : set E} : continuous_on star s := continuous_star.continuous_on
lemma continuous_at_star {x : E} : continuous_at star x := continuous_star.continuous_at
lemma continuous_within_at_star {s : set E} {x : E} : continuous_within_at star s x :=
continuous_star.continuous_within_at
lemma tendsto_star (x : E) : filter.tendsto star (𝓝 x) (𝓝 x⋆) := continuous_star.tendsto x
lemma filter.tendsto.star {f : α → E} {l : filter α} {y : E} (h : filter.tendsto f l (𝓝 y)) :
filter.tendsto (λ x, (f x)⋆) l (𝓝 y⋆) :=
(continuous_star.tendsto y).comp h
variables [topological_space α]
lemma continuous.star {f : α → E} (hf : continuous f) : continuous (λ y, star (f y)) :=
continuous_star.comp hf
lemma continuous_at.star {f : α → E} {x : α} (hf : continuous_at f x) :
continuous_at (λ x, (f x)⋆) x :=
continuous_at_star.comp hf
lemma continuous_on.star {f : α → E} {s : set α} (hf : continuous_on f s) :
continuous_on (λ x, (f x)⋆) s :=
continuous_star.comp_continuous_on hf
lemma continuous_within_at.star {f : α → E} {s : set α} {x : α}
(hf : continuous_within_at f s x) : continuous_within_at (λ x, (f x)⋆) s x := hf.star
end normed_star_monoid
instance ring_hom_isometric.star_ring_end [normed_comm_ring E] [star_ring E]
[normed_star_monoid E] : ring_hom_isometric (star_ring_end E) :=
⟨λ _, norm_star⟩
namespace cstar_ring
variables [normed_ring E] [star_ring E] [cstar_ring E]
/-- In a C*-ring, star preserves the norm. -/
@[priority 100] -- see Note [lower instance priority]
instance to_normed_star_monoid : normed_star_monoid E :=
⟨begin
intro x,
by_cases htriv : x = 0,
{ simp only [htriv, star_zero] },
{ have hnt : 0 < ∥x∥ := norm_pos_iff.mpr htriv,
have hnt_star : 0 < ∥x⋆∥ :=
norm_pos_iff.mpr ((add_equiv.map_ne_zero_iff star_add_equiv).mpr htriv),
have h₁ := calc
∥x∥ * ∥x∥ = ∥x⋆ * x∥ : norm_star_mul_self.symm
... ≤ ∥x⋆∥ * ∥x∥ : norm_mul_le _ _,
have h₂ := calc
∥x⋆∥ * ∥x⋆∥ = ∥x * x⋆∥ : by rw [←norm_star_mul_self, star_star]
... ≤ ∥x∥ * ∥x⋆∥ : norm_mul_le _ _,
exact le_antisymm (le_of_mul_le_mul_right h₂ hnt_star) (le_of_mul_le_mul_right h₁ hnt) },
end⟩
lemma norm_self_mul_star {x : E} : ∥x * x⋆∥ = ∥x∥ * ∥x∥ :=
by { nth_rewrite 0 [←star_star x], simp only [norm_star_mul_self, norm_star] }
lemma norm_star_mul_self' {x : E} : ∥x⋆ * x∥ = ∥x⋆∥ * ∥x∥ :=
by rw [norm_star_mul_self, norm_star]
@[simp] lemma norm_one [nontrivial E] : ∥(1 : E)∥ = 1 :=
begin
have : 0 < ∥(1 : E)∥ := norm_pos_iff.mpr one_ne_zero,
rw [←mul_left_inj' this.ne', ←norm_star_mul_self, mul_one, star_one, one_mul],
end
@[priority 100] -- see Note [lower instance priority]
instance [nontrivial E] : norm_one_class E := ⟨norm_one⟩
lemma norm_coe_unitary [nontrivial E] (U : unitary E) : ∥(U : E)∥ = 1 :=
begin
rw [←sq_eq_sq (norm_nonneg _) zero_le_one, one_pow 2, sq, ←cstar_ring.norm_star_mul_self,
unitary.coe_star_mul_self, cstar_ring.norm_one],
end
@[simp] lemma norm_of_mem_unitary [nontrivial E] {U : E} (hU : U ∈ unitary E) : ∥U∥ = 1 :=
norm_coe_unitary ⟨U, hU⟩
@[simp] lemma norm_coe_unitary_mul (U : unitary E) (A : E) : ∥(U : E) * A∥ = ∥A∥ :=
begin
nontriviality E,
refine le_antisymm _ _,
{ calc _ ≤ ∥(U : E)∥ * ∥A∥ : norm_mul_le _ _
... = ∥A∥ : by rw [norm_coe_unitary, one_mul] },
{ calc _ = ∥(U : E)⋆ * U * A∥ : by rw [unitary.coe_star_mul_self U, one_mul]
... ≤ ∥(U : E)⋆∥ * ∥(U : E) * A∥ : by { rw [mul_assoc], exact norm_mul_le _ _ }
... = ∥(U : E) * A∥ : by rw [norm_star, norm_coe_unitary, one_mul] },
end
@[simp] lemma norm_unitary_smul (U : unitary E) (A : E) : ∥U • A∥ = ∥A∥ :=
norm_coe_unitary_mul U A
lemma norm_mem_unitary_mul {U : E} (A : E) (hU : U ∈ unitary E) : ∥U * A∥ = ∥A∥ :=
norm_coe_unitary_mul ⟨U, hU⟩ A
@[simp] lemma norm_mul_coe_unitary (A : E) (U : unitary E) : ∥A * U∥ = ∥A∥ :=
calc _ = ∥((U : E)⋆ * A⋆)⋆∥ : by simp only [star_star, star_mul]
... = ∥(U : E)⋆ * A⋆∥ : by rw [norm_star]
... = ∥A⋆∥ : norm_mem_unitary_mul (star A) (unitary.star_mem U.prop)
... = ∥A∥ : norm_star
lemma norm_mul_mem_unitary (A : E) {U : E} (hU : U ∈ unitary E) : ∥A * U∥ = ∥A∥ :=
norm_mul_coe_unitary A ⟨U, hU⟩
end cstar_ring
section starₗᵢ
variables [comm_semiring 𝕜] [star_ring 𝕜] [normed_ring E] [star_ring E] [normed_star_monoid E]
variables [module 𝕜 E] [star_module 𝕜 E]
variables (𝕜)
/-- `star` bundled as a linear isometric equivalence -/
def starₗᵢ : E ≃ₗᵢ⋆[𝕜] E :=
{ map_smul' := star_smul,
norm_map' := λ x, norm_star,
.. star_add_equiv }
variables {𝕜}
@[simp] lemma coe_starₗᵢ : (starₗᵢ 𝕜 : E → E) = star := rfl
lemma starₗᵢ_apply {x : E} : starₗᵢ 𝕜 x = star x := rfl
end starₗᵢ
|
c84e608ff6452fc982cc3a961b02489b4cb77290 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/category_theory/limits/colimit_limit.lean | 8a2ab702d589f957262c40d71302146fc612e417 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 4,547 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.limits.types
import category_theory.functor.currying
import category_theory.limits.functor_category
/-!
# The morphism comparing a colimit of limits with the corresponding limit of colimits.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
For `F : J × K ⥤ C` there is always a morphism $\colim_k \lim_j F(j,k) → \lim_j \colim_k F(j, k)$.
While it is not usually an isomorphism, with additional hypotheses on `J` and `K` it may be,
in which case we say that "colimits commute with limits".
The prototypical example, proved in `category_theory.limits.filtered_colimit_commutes_finite_limit`,
is that when `C = Type`, filtered colimits commute with finite limits.
## References
* Borceux, Handbook of categorical algebra 1, Section 2.13
* [Stacks: Filtered colimits](https://stacks.math.columbia.edu/tag/002W)
-/
universes v u
open category_theory
namespace category_theory.limits
variables {J K : Type v} [small_category J] [small_category K]
variables {C : Type u} [category.{v} C]
variables (F : J × K ⥤ C)
open category_theory.prod
lemma map_id_left_eq_curry_map {j : J} {k k' : K} {f : k ⟶ k'} :
F.map ((𝟙 j, f) : (j, k) ⟶ (j, k')) = ((curry.obj F).obj j).map f :=
rfl
lemma map_id_right_eq_curry_swap_map {j j' : J} {f : j ⟶ j'} {k : K} :
F.map ((f, 𝟙 k) : (j, k) ⟶ (j', k)) = ((curry.obj (swap K J ⋙ F)).obj k).map f :=
rfl
variables [has_limits_of_shape J C]
variables [has_colimits_of_shape K C]
/--
The universal morphism
$\colim_k \lim_j F(j,k) → \lim_j \colim_k F(j, k)$.
-/
noncomputable
def colimit_limit_to_limit_colimit :
colimit ((curry.obj (swap K J ⋙ F)) ⋙ lim) ⟶ limit ((curry.obj F) ⋙ colim) :=
limit.lift ((curry.obj F) ⋙ colim)
{ X := _,
π :=
{ app := λ j, colimit.desc ((curry.obj (swap K J ⋙ F)) ⋙ lim)
{ X := _,
ι :=
{ app := λ k,
limit.π ((curry.obj (swap K J ⋙ F)).obj k) j ≫ colimit.ι ((curry.obj F).obj j) k,
naturality' :=
begin
dsimp,
intros k k' f,
simp only [functor.comp_map, curry_obj_map_app, limits.lim_map_π_assoc, swap_map,
category.comp_id, map_id_left_eq_curry_map, colimit.w],
end }, },
naturality' :=
begin
dsimp,
intros j j' f,
ext k,
simp only [limits.colimit.ι_map, curry_obj_map_app, limits.colimit.ι_desc_assoc,
limits.colimit.ι_desc, category.id_comp, category.assoc, map_id_right_eq_curry_swap_map,
limit.w_assoc],
end } }
/--
Since `colimit_limit_to_limit_colimit` is a morphism from a colimit to a limit,
this lemma characterises it.
-/
@[simp, reassoc] lemma ι_colimit_limit_to_limit_colimit_π (j) (k) :
colimit.ι _ k ≫ colimit_limit_to_limit_colimit F ≫ limit.π _ j =
limit.π ((curry.obj (swap K J ⋙ F)).obj k) j ≫ colimit.ι ((curry.obj F).obj j) k :=
by { dsimp [colimit_limit_to_limit_colimit], simp, }
@[simp] lemma ι_colimit_limit_to_limit_colimit_π_apply (F : J × K ⥤ Type v) (j) (k) (f) :
limit.π ((curry.obj F) ⋙ colim) j
(colimit_limit_to_limit_colimit F (colimit.ι ((curry.obj (swap K J ⋙ F)) ⋙ lim) k f)) =
colimit.ι ((curry.obj F).obj j) k (limit.π ((curry.obj (swap K J ⋙ F)).obj k) j f) :=
by { dsimp [colimit_limit_to_limit_colimit], simp, }
/-- The map `colimit_limit_to_limit_colimit` realized as a map of cones. -/
@[simps] noncomputable def colimit_limit_to_limit_colimit_cone (G : J ⥤ K ⥤ C) [has_limit G] :
colim.map_cone (limit.cone G) ⟶ limit.cone (G ⋙ colim) :=
{ hom := colim.map (limit_iso_swap_comp_lim G).hom ≫
colimit_limit_to_limit_colimit (uncurry.obj G : _) ≫
lim.map (whisker_right (currying.unit_iso.app G).inv colim),
w' := λ j,
begin
ext1 k,
simp only [limit_obj_iso_limit_comp_evaluation_hom_π_assoc, iso.app_inv,
ι_colimit_limit_to_limit_colimit_π_assoc, whisker_right_app,
colimit.ι_map, functor.map_cone_π_app, category.id_comp,
eq_to_hom_refl, eq_to_hom_app, colimit.ι_map_assoc, limit.cone_π,
lim_map_π_assoc, lim_map_π, category.assoc, currying_unit_iso_inv_app_app_app,
limit_iso_swap_comp_lim_hom_app, lim_map_eq_lim_map],
dsimp,
simp only [category.id_comp],
erw limit_obj_iso_limit_comp_evaluation_hom_π_assoc,
end }
end category_theory.limits
|
5222da40f9fe95267ffb14c2864a292cd0747f03 | 88fb7558b0636ec6b181f2a548ac11ad3919f8a5 | /tests/lean/run/declare_axiom.lean | 54270fba253c98bda7f970c835c430679ae0d56b | [
"Apache-2.0"
] | permissive | moritayasuaki/lean | 9f666c323cb6fa1f31ac597d777914aed41e3b7a | ae96ebf6ee953088c235ff7ae0e8c95066ba8001 | refs/heads/master | 1,611,135,440,814 | 1,493,852,869,000 | 1,493,852,869,000 | 90,269,903 | 0 | 0 | null | 1,493,906,291,000 | 1,493,906,291,000 | null | UTF-8 | Lean | false | false | 104 | lean | open tactic
run_cmd (do
e ← to_expr `(false),
add_decl $ declaration.ax `useful_assumption [] e)
|
129b052a04eacf376a07ea8a2cb32073fbe3fbcb | 432d948a4d3d242fdfb44b81c9e1b1baacd58617 | /src/category_theory/subobject/limits.lean | 8c284fdac17a48acf2690ccf30548c14eaa836f6 | [
"Apache-2.0"
] | permissive | JLimperg/aesop3 | 306cc6570c556568897ed2e508c8869667252e8a | a4a116f650cc7403428e72bd2e2c4cda300fe03f | refs/heads/master | 1,682,884,916,368 | 1,620,320,033,000 | 1,620,320,033,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,845 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta, Scott Morrison
-/
import category_theory.subobject.lattice
/-!
# Specific subobjects
We define `equalizer_subobject`, `kernel_subobject` and `image_subobject`, which are the subobjects
represented by the equalizer, kernel and image of (a pair of) morphism(s) and provide conditions
for `P.factors f`, where `P` is one of these special subobjects.
TODO: Add conditions for when `P` is a pullback subobject.
TODO: an iff characterisation of `(image_subobject f).factors h`
-/
universes v u
noncomputable theory
open category_theory category_theory.category category_theory.limits category_theory.subobject
variables {C : Type u} [category.{v} C] {X Y Z : C}
namespace category_theory
namespace limits
section equalizer
variables (f g : X ⟶ Y) [has_equalizer f g]
/-- The equalizer of morphisms `f g : X ⟶ Y` as a `subobject X`. -/
abbreviation equalizer_subobject : subobject X :=
subobject.mk (equalizer.ι f g)
/-- The underlying object of `equalizer_subobject f g` is (up to isomorphism!)
the same as the chosen object `equalizer f g`. -/
def equalizer_subobject_iso : (equalizer_subobject f g : C) ≅ equalizer f g :=
subobject.underlying_iso (equalizer.ι f g)
@[simp, reassoc]
lemma equalizer_subobject_arrow :
(equalizer_subobject_iso f g).hom ≫ equalizer.ι f g = (equalizer_subobject f g).arrow :=
by simp [equalizer_subobject_iso]
@[simp, reassoc]
lemma equalizer_subobject_arrow' :
(equalizer_subobject_iso f g).inv ≫ (equalizer_subobject f g).arrow = equalizer.ι f g :=
by simp [equalizer_subobject_iso]
@[reassoc]
lemma equalizer_subobject_arrow_comp :
(equalizer_subobject f g).arrow ≫ f = (equalizer_subobject f g).arrow ≫ g :=
by rw [←equalizer_subobject_arrow, category.assoc, category.assoc, equalizer.condition]
lemma equalizer_subobject_factors {W : C} (h : W ⟶ X) (w : h ≫ f = h ≫ g) :
(equalizer_subobject f g).factors h :=
⟨equalizer.lift h w, by simp⟩
lemma equalizer_subobject_factors_iff {W : C} (h : W ⟶ X) :
(equalizer_subobject f g).factors h ↔ h ≫ f = h ≫ g :=
⟨λ w, by rw [←subobject.factor_thru_arrow _ _ w, category.assoc,
equalizer_subobject_arrow_comp, category.assoc],
equalizer_subobject_factors f g h⟩
end equalizer
section kernel
variables [has_zero_morphisms C] (f : X ⟶ Y) [has_kernel f]
/-- The kernel of a morphism `f : X ⟶ Y` as a `subobject X`. -/
abbreviation kernel_subobject : subobject X :=
subobject.mk (kernel.ι f)
/-- The underlying object of `kernel_subobject f` is (up to isomorphism!)
the same as the chosen object `kernel f`. -/
def kernel_subobject_iso :
(kernel_subobject f : C) ≅ kernel f :=
subobject.underlying_iso (kernel.ι f)
@[simp, reassoc]
lemma kernel_subobject_arrow :
(kernel_subobject_iso f).hom ≫ kernel.ι f = (kernel_subobject f).arrow :=
by simp [kernel_subobject_iso]
@[simp, reassoc]
lemma kernel_subobject_arrow' :
(kernel_subobject_iso f).inv ≫ (kernel_subobject f).arrow = kernel.ι f :=
by simp [kernel_subobject_iso]
@[simp, reassoc]
lemma kernel_subobject_arrow_comp :
(kernel_subobject f).arrow ≫ f = 0 :=
by { rw [←kernel_subobject_arrow], simp only [category.assoc, kernel.condition, comp_zero], }
lemma kernel_subobject_factors {W : C} (h : W ⟶ X) (w : h ≫ f = 0) :
(kernel_subobject f).factors h :=
⟨kernel.lift _ h w, by simp⟩
lemma kernel_subobject_factors_iff {W : C} (h : W ⟶ X) :
(kernel_subobject f).factors h ↔ h ≫ f = 0 :=
⟨λ w, by rw [←subobject.factor_thru_arrow _ _ w, category.assoc,
kernel_subobject_arrow_comp, comp_zero],
kernel_subobject_factors f h⟩
@[simp]
lemma kernel_subobject_zero {A B : C} : kernel_subobject (0 : A ⟶ B) = ⊤ :=
(is_iso_iff_mk_eq_top _).mp (by apply_instance)
instance is_iso_kernel_subobject_zero_arrow : is_iso (kernel_subobject (0 : X ⟶ Y)).arrow :=
(is_iso_arrow_iff_eq_top _).mpr kernel_subobject_zero
lemma le_kernel_subobject (A : subobject X) (h : A.arrow ≫ f = 0) : A ≤ kernel_subobject f :=
subobject.le_mk_of_comm (kernel.lift f A.arrow h) (by simp)
/--
The isomorphism between the kernel of `f ≫ g` and the kernel of `g`,
when `f` is an isomorphism.
-/
def kernel_subobject_iso_comp
{X' : C} (f : X' ⟶ X) [is_iso f] (g : X ⟶ Y) [has_kernel g] :
(kernel_subobject (f ≫ g) : C) ≅ (kernel_subobject g : C) :=
(kernel_subobject_iso _) ≪≫ (kernel_is_iso_comp f g) ≪≫ (kernel_subobject_iso _).symm
@[simp]
lemma kernel_subobject_iso_comp_hom_arrow
{X' : C} (f : X' ⟶ X) [is_iso f] (g : X ⟶ Y) [has_kernel g] :
(kernel_subobject_iso_comp f g).hom ≫ (kernel_subobject g).arrow =
(kernel_subobject (f ≫ g)).arrow ≫ f :=
by { simp [kernel_subobject_iso_comp], }
@[simp]
lemma kernel_subobject_iso_comp_inv_arrow
{X' : C} (f : X' ⟶ X) [is_iso f] (g : X ⟶ Y) [has_kernel g] :
(kernel_subobject_iso_comp f g).inv ≫ (kernel_subobject (f ≫ g)).arrow =
(kernel_subobject g).arrow ≫ inv f :=
by { simp [kernel_subobject_iso_comp], }
/-- The kernel of `f` is always a smaller subobject than the kernel of `f ≫ h`. -/
lemma kernel_subobject_comp_le
(f : X ⟶ Y) [has_kernel f] {Z : C} (h : Y ⟶ Z) [has_kernel (f ≫ h)]:
kernel_subobject f ≤ kernel_subobject (f ≫ h) :=
le_kernel_subobject _ _ (by simp)
/-- Postcomposing by an monomorphism does not change the kernel subobject. -/
@[simp]
lemma kernel_subobject_comp_mono
(f : X ⟶ Y) [has_kernel f] {Z : C} (h : Y ⟶ Z) [mono h] :
kernel_subobject (f ≫ h) = kernel_subobject f :=
le_antisymm
(le_kernel_subobject _ _ ((cancel_mono h).mp (by simp)))
(kernel_subobject_comp_le f h)
end kernel
section image
variables (f : X ⟶ Y) [has_image f]
/-- The image of a morphism `f g : X ⟶ Y` as a `subobject Y`. -/
abbreviation image_subobject : subobject Y :=
subobject.mk (image.ι f)
/-- The underlying object of `image_subobject f` is (up to isomorphism!)
the same as the chosen object `image f`. -/
def image_subobject_iso :
(image_subobject f : C) ≅ image f :=
subobject.underlying_iso (image.ι f)
@[simp, reassoc]
lemma image_subobject_arrow :
(image_subobject_iso f).hom ≫ image.ι f = (image_subobject f).arrow :=
by simp [image_subobject_iso]
@[simp, reassoc]
lemma image_subobject_arrow' :
(image_subobject_iso f).inv ≫ (image_subobject f).arrow = image.ι f :=
by simp [image_subobject_iso]
/-- A factorisation of `f : X ⟶ Y` through `image_subobject f`. -/
def factor_thru_image_subobject : X ⟶ image_subobject f :=
factor_thru_image f ≫ (image_subobject_iso f).inv
@[simp, reassoc]
lemma image_subobject_arrow_comp :
factor_thru_image_subobject f ≫ (image_subobject f).arrow = f :=
by simp [factor_thru_image_subobject, image_subobject_arrow]
lemma image_subobject_factors_comp_self {W : C} (k : W ⟶ X) :
(image_subobject f).factors (k ≫ f) :=
⟨k ≫ factor_thru_image f, by simp⟩
@[simp]
lemma factor_thru_image_subobject_comp_self {W : C} (k : W ⟶ X) (h) :
(image_subobject f).factor_thru (k ≫ f) h = k ≫ factor_thru_image_subobject f :=
by { ext, simp, }
@[simp]
lemma factor_thru_image_subobject_comp_self_assoc {W W' : C} (k : W ⟶ W') (k' : W' ⟶ X) (h) :
(image_subobject f).factor_thru (k ≫ k' ≫ f) h = k ≫ k' ≫ factor_thru_image_subobject f :=
by { ext, simp, }
@[simp]
lemma image_subobject_zero_arrow [has_zero_morphisms C] [has_zero_object C] :
(image_subobject (0 : X ⟶ Y)).arrow = 0 :=
by { rw ←image_subobject_arrow, simp, }
@[simp]
lemma image_subobject_zero [has_zero_morphisms C] [has_zero_object C]{A B : C} :
image_subobject (0 : A ⟶ B) = ⊥ :=
subobject.eq_of_comm
(image_subobject_iso _ ≪≫ image_zero ≪≫ subobject.bot_coe_iso_zero.symm) (by simp)
/-- The image of `h ≫ f` is always a smaller subobject than the image of `f`. -/
lemma image_subobject_comp_le
{X' : C} (h : X' ⟶ X) (f : X ⟶ Y) [has_image f] [has_image (h ≫ f)] :
image_subobject (h ≫ f) ≤ image_subobject f :=
subobject.mk_le_mk_of_comm (image.pre_comp h f) (by simp)
section
variables [has_equalizers C]
/-- Postcomposing by an isomorphism gives an isomorphism between image subobjects. -/
def image_subobject_comp_iso
(f : X ⟶ Y) [has_image f] {Y' : C} (h : Y ⟶ Y') [is_iso h] :
(image_subobject (f ≫ h) : C) ≅ (image_subobject f : C) :=
(image_subobject_iso _) ≪≫ (image.comp_iso _ _).symm ≪≫ (image_subobject_iso _).symm
@[simp, reassoc]
lemma image_subobject_comp_iso_hom_arrow
(f : X ⟶ Y) [has_image f] {Y' : C} (h : Y ⟶ Y') [is_iso h] :
(image_subobject_comp_iso f h).hom ≫ (image_subobject f).arrow =
(image_subobject (f ≫ h)).arrow ≫ inv h :=
by simp [image_subobject_comp_iso]
@[simp, reassoc]
lemma image_subobject_comp_iso_inv_arrow
(f : X ⟶ Y) [has_image f] {Y' : C} (h : Y ⟶ Y') [is_iso h] :
(image_subobject_comp_iso f h).inv ≫ (image_subobject (f ≫ h)).arrow =
(image_subobject f).arrow ≫ h :=
by simp [image_subobject_comp_iso]
end
/-- Precomposing by an isomorphism does not change the image subobject. -/
lemma image_subobject_iso_comp [has_equalizers C]
{X' : C} (h : X' ⟶ X) [is_iso h] (f : X ⟶ Y) [has_image f] :
image_subobject (h ≫ f) = image_subobject f :=
le_antisymm
(image_subobject_comp_le h f)
(subobject.mk_le_mk_of_comm (inv (image.pre_comp h f)) (by simp))
lemma image_subobject_le {A B : C} {X : subobject B} (f : A ⟶ B) [has_image f]
(h : A ⟶ X) (w : h ≫ X.arrow = f) :
image_subobject f ≤ X :=
subobject.le_of_comm
((image_subobject_iso f).hom ≫ image.lift { I := (X : C), e := h, m := X.arrow, })
(by simp)
lemma image_subobject_le_mk {A B : C} {X : C} (g : X ⟶ B) [mono g] (f : A ⟶ B) [has_image f]
(h : A ⟶ X) (w : h ≫ g = f) :
image_subobject f ≤ subobject.mk g :=
image_subobject_le f (h ≫ (subobject.underlying_iso g).inv) (by simp [w])
/-- Given a commutative square between morphisms `f` and `g`,
we have a morphism in the category from `image_subobject f` to `image_subobject g`. -/
def image_subobject_map {W X Y Z : C} {f : W ⟶ X} [has_image f] {g : Y ⟶ Z} [has_image g]
(sq : arrow.mk f ⟶ arrow.mk g) [has_image_map sq] :
(image_subobject f : C) ⟶ (image_subobject g : C) :=
(image_subobject_iso f).hom ≫ image.map sq ≫ (image_subobject_iso g).inv
@[simp, reassoc]
lemma image_subobject_map_arrow {W X Y Z : C} {f : W ⟶ X} [has_image f] {g : Y ⟶ Z} [has_image g]
(sq : arrow.mk f ⟶ arrow.mk g) [has_image_map sq] :
image_subobject_map sq ≫ (image_subobject g).arrow = (image_subobject f).arrow ≫ sq.right :=
begin
simp only [image_subobject_map, category.assoc, image_subobject_arrow'],
erw [image.map_ι, ←category.assoc, image_subobject_arrow],
end
end image
end limits
end category_theory
|
b51aa9d1bc9bb4def70684988d7f726a3f8952bd | 8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3 | /src/measure_theory/decomposition/unsigned_hahn.lean | 18e1a709f4f323484dc59f0a8cf8733886938d25 | [
"Apache-2.0"
] | permissive | troyjlee/mathlib | e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5 | 45e7eb8447555247246e3fe91c87066506c14875 | refs/heads/master | 1,689,248,035,046 | 1,629,470,528,000 | 1,629,470,528,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,861 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import measure_theory.measure.measure_space
/-!
# Unsigned Hahn decomposition theorem
This file proves the unsigned version of the Hahn decomposition theorem.
## Main statements
* `hahn_decomposition` : Given two finite measures `μ` and `ν`, there exists a measurable set `s`
such that any measurable set `t` included in `s` satisfies `ν t ≤ μ t`, and any
measurable set `u` included in the complement of `s` satisfies `μ u ≤ ν u`.
## Tags
Hahn decomposition
-/
open set filter
open_locale classical topological_space ennreal
namespace measure_theory
variables {α : Type*} [measurable_space α] {μ ν : measure α}
-- suddenly this is necessary?!
private lemma aux {m : ℕ} {γ d : ℝ} (h : γ - (1 / 2) ^ m < d) :
γ - 2 * (1 / 2) ^ m + (1 / 2) ^ m ≤ d :=
by linarith
/-- **Hahn decomposition theorem** -/
lemma hahn_decomposition [finite_measure μ] [finite_measure ν] :
∃s, measurable_set s ∧
(∀t, measurable_set t → t ⊆ s → ν t ≤ μ t) ∧
(∀t, measurable_set t → t ⊆ sᶜ → μ t ≤ ν t) :=
begin
let d : set α → ℝ := λs, ((μ s).to_nnreal : ℝ) - (ν s).to_nnreal,
let c : set ℝ := d '' {s | measurable_set s },
let γ : ℝ := Sup c,
have hμ : ∀s, μ s < ∞ := measure_lt_top μ,
have hν : ∀s, ν s < ∞ := measure_lt_top ν,
have to_nnreal_μ : ∀s, ((μ s).to_nnreal : ℝ≥0∞) = μ s :=
(assume s, ennreal.coe_to_nnreal $ ne_top_of_lt $ hμ _),
have to_nnreal_ν : ∀s, ((ν s).to_nnreal : ℝ≥0∞) = ν s :=
(assume s, ennreal.coe_to_nnreal $ ne_top_of_lt $ hν _),
have d_empty : d ∅ = 0, { simp [d], rw [measure_empty, measure_empty], simp },
have d_split : ∀s t, measurable_set s → measurable_set t →
d s = d (s \ t) + d (s ∩ t),
{ assume s t hs ht,
simp only [d],
rw [measure_eq_inter_diff hs ht, measure_eq_inter_diff hs ht,
ennreal.to_nnreal_add (hμ _) (hμ _), ennreal.to_nnreal_add (hν _) (hν _),
nnreal.coe_add, nnreal.coe_add],
simp only [sub_eq_add_neg, neg_add],
ac_refl },
have d_Union : ∀(s : ℕ → set α), (∀n, measurable_set (s n)) → monotone s →
tendsto (λn, d (s n)) at_top (𝓝 (d (⋃n, s n))),
{ assume s hs hm,
refine tendsto.sub _ _;
refine (nnreal.tendsto_coe.2 $
(ennreal.tendsto_to_nnreal $ @ne_top_of_lt _ _ _ ∞ _).comp $ tendsto_measure_Union hs hm),
exact hμ _,
exact hν _ },
have d_Inter : ∀(s : ℕ → set α), (∀n, measurable_set (s n)) → (∀n m, n ≤ m → s m ⊆ s n) →
tendsto (λn, d (s n)) at_top (𝓝 (d (⋂n, s n))),
{ assume s hs hm,
refine tendsto.sub _ _;
refine (nnreal.tendsto_coe.2 $
(ennreal.tendsto_to_nnreal $ @ne_top_of_lt _ _ _ ∞ _).comp $ tendsto_measure_Inter hs hm _),
exact hμ _,
exact ⟨0, hμ _⟩,
exact hν _,
exact ⟨0, hν _⟩ },
have bdd_c : bdd_above c,
{ use (μ univ).to_nnreal,
rintros r ⟨s, hs, rfl⟩,
refine le_trans (sub_le_self _ $ nnreal.coe_nonneg _) _,
rw [nnreal.coe_le_coe, ← ennreal.coe_le_coe, to_nnreal_μ, to_nnreal_μ],
exact measure_mono (subset_univ _) },
have c_nonempty : c.nonempty := nonempty.image _ ⟨_, measurable_set.empty⟩,
have d_le_γ : ∀s, measurable_set s → d s ≤ γ := assume s hs, le_cSup bdd_c ⟨s, hs, rfl⟩,
have : ∀n:ℕ, ∃s : set α, measurable_set s ∧ γ - (1/2)^n < d s,
{ assume n,
have : γ - (1/2)^n < γ := sub_lt_self γ (pow_pos (half_pos zero_lt_one) n),
rcases exists_lt_of_lt_cSup c_nonempty this with ⟨r, ⟨s, hs, rfl⟩, hlt⟩,
exact ⟨s, hs, hlt⟩ },
rcases classical.axiom_of_choice this with ⟨e, he⟩,
change ℕ → set α at e,
have he₁ : ∀n, measurable_set (e n) := assume n, (he n).1,
have he₂ : ∀n, γ - (1/2)^n < d (e n) := assume n, (he n).2,
let f : ℕ → ℕ → set α := λn m, (finset.Ico n (m + 1)).inf e,
have hf : ∀n m, measurable_set (f n m),
{ assume n m,
simp only [f, finset.inf_eq_infi],
exact measurable_set.bInter (countable_encodable _) (assume i _, he₁ _) },
have f_subset_f : ∀{a b c d}, a ≤ b → c ≤ d → f a d ⊆ f b c,
{ assume a b c d hab hcd,
dsimp only [f],
rw [finset.inf_eq_infi, finset.inf_eq_infi],
refine bInter_subset_bInter_left _,
simp,
rintros j ⟨hbj, hjc⟩,
exact ⟨le_trans hab hbj, lt_of_lt_of_le hjc $ add_le_add_right hcd 1⟩ },
have f_succ : ∀n m, n ≤ m → f n (m + 1) = f n m ∩ e (m + 1),
{ assume n m hnm,
have : n ≤ m + 1 := le_of_lt (nat.succ_le_succ hnm),
simp only [f],
rw [finset.Ico.succ_top this, finset.inf_insert, set.inter_comm],
refl },
have le_d_f : ∀n m, m ≤ n → γ - 2 * ((1 / 2) ^ m) + (1 / 2) ^ n ≤ d (f m n),
{ assume n m h,
refine nat.le_induction _ _ n h,
{ have := he₂ m,
simp only [f],
rw [finset.Ico.succ_singleton, finset.inf_singleton],
exact aux this },
{ assume n (hmn : m ≤ n) ih,
have : γ + (γ - 2 * (1 / 2)^m + (1 / 2) ^ (n + 1)) ≤ γ + d (f m (n + 1)),
{ calc γ + (γ - 2 * (1 / 2)^m + (1 / 2) ^ (n+1)) ≤
γ + (γ - 2 * (1 / 2)^m + ((1 / 2) ^ n - (1/2)^(n+1))) :
begin
refine add_le_add_left (add_le_add_left _ _) γ,
simp only [pow_add, pow_one, le_sub_iff_add_le],
linarith
end
... = (γ - (1 / 2)^(n+1)) + (γ - 2 * (1 / 2)^m + (1 / 2)^n) :
by simp only [sub_eq_add_neg]; ac_refl
... ≤ d (e (n + 1)) + d (f m n) : add_le_add (le_of_lt $ he₂ _) ih
... ≤ d (e (n + 1)) + d (f m n \ e (n + 1)) + d (f m (n + 1)) :
by rw [f_succ _ _ hmn, d_split (f m n) (e (n + 1)) (hf _ _) (he₁ _), add_assoc]
... = d (e (n + 1) ∪ f m n) + d (f m (n + 1)) :
begin
rw [d_split (e (n + 1) ∪ f m n) (e (n + 1)),
union_diff_left, union_inter_cancel_left],
ac_refl,
exact (he₁ _).union (hf _ _),
exact (he₁ _)
end
... ≤ γ + d (f m (n + 1)) :
add_le_add_right (d_le_γ _ $ (he₁ _).union (hf _ _)) _ },
exact (add_le_add_iff_left γ).1 this } },
let s := ⋃ m, ⋂n, f m n,
have γ_le_d_s : γ ≤ d s,
{ have hγ : tendsto (λm:ℕ, γ - 2 * (1/2)^m) at_top (𝓝 γ),
{ suffices : tendsto (λm:ℕ, γ - 2 * (1/2)^m) at_top (𝓝 (γ - 2 * 0)), { simpa },
exact (tendsto_const_nhds.sub $ tendsto_const_nhds.mul $
tendsto_pow_at_top_nhds_0_of_lt_1
(le_of_lt $ half_pos $ zero_lt_one) (half_lt_self zero_lt_one)) },
have hd : tendsto (λm, d (⋂n, f m n)) at_top (𝓝 (d (⋃ m, ⋂ n, f m n))),
{ refine d_Union _ _ _,
{ assume n, exact measurable_set.Inter (assume m, hf _ _) },
{ exact assume n m hnm, subset_Inter
(assume i, subset.trans (Inter_subset (f n) i) $ f_subset_f hnm $ le_refl _) } },
refine le_of_tendsto_of_tendsto' hγ hd (assume m, _),
have : tendsto (λn, d (f m n)) at_top (𝓝 (d (⋂ n, f m n))),
{ refine d_Inter _ _ _,
{ assume n, exact hf _ _ },
{ assume n m hnm, exact f_subset_f (le_refl _) hnm } },
refine ge_of_tendsto this (eventually_at_top.2 ⟨m, assume n hmn, _⟩),
change γ - 2 * (1 / 2) ^ m ≤ d (f m n),
refine le_trans _ (le_d_f _ _ hmn),
exact le_add_of_le_of_nonneg (le_refl _) (pow_nonneg (le_of_lt $ half_pos $ zero_lt_one) _) },
have hs : measurable_set s :=
measurable_set.Union (assume n, measurable_set.Inter (assume m, hf _ _)),
refine ⟨s, hs, _, _⟩,
{ assume t ht hts,
have : 0 ≤ d t := ((add_le_add_iff_left γ).1 $
calc γ + 0 ≤ d s : by rw [add_zero]; exact γ_le_d_s
... = d (s \ t) + d t : by rw [d_split _ _ hs ht, inter_eq_self_of_subset_right hts]
... ≤ γ + d t : add_le_add (d_le_γ _ (hs.diff ht)) (le_refl _)),
rw [← to_nnreal_μ, ← to_nnreal_ν, ennreal.coe_le_coe, ← nnreal.coe_le_coe],
simpa only [d, le_sub_iff_add_le, zero_add] using this },
{ assume t ht hts,
have : d t ≤ 0,
exact ((add_le_add_iff_left γ).1 $
calc γ + d t ≤ d s + d t : add_le_add γ_le_d_s (le_refl _)
... = d (s ∪ t) :
begin
rw [d_split _ _ (hs.union ht) ht, union_diff_right, union_inter_cancel_right,
diff_eq_self.2],
exact assume a ⟨hat, has⟩, hts hat has
end
... ≤ γ + 0 : by rw [add_zero]; exact d_le_γ _ (hs.union ht)),
rw [← to_nnreal_μ, ← to_nnreal_ν, ennreal.coe_le_coe, ← nnreal.coe_le_coe],
simpa only [d, sub_le_iff_le_add, zero_add] using this }
end
end measure_theory
|
c37c5b549cf9beb60f193aff7f4b0bd81ba79401 | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /11_Tactic-Style_Proofs.org.18.lean | b51e732298f146c24aa100e6df25dac4a278fb4a | [] | no_license | cjmazey/lean-tutorial | ba559a49f82aa6c5848b9bf17b7389bf7f4ba645 | 381f61c9fcac56d01d959ae0fa6e376f2c4e3b34 | refs/heads/master | 1,610,286,098,832 | 1,447,124,923,000 | 1,447,124,923,000 | 43,082,433 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 267 | lean | import standard
import data.nat
open nat
variables x y z : ℕ
-- BEGIN
example : x + y + z = x + y + z :=
begin
generalize (x + y + z), -- goal is x y z : ℕ ⊢ ∀ (x : ℕ), x = x
intro w, -- goal is x y z w : ℕ ⊢ w = w
apply rfl
end
-- END
|
ddff1808271530624dcf87ce0954e8837400bf33 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/topology/instances/real.lean | 1bef704d733ae1c25aeef95376fdaff623843a29 | [
"Apache-2.0"
] | permissive | ramonfmir/mathlib | c5dc8b33155473fab97c38bd3aa6723dc289beaa | 14c52e990c17f5a00c0cc9e09847af16fabbed25 | refs/heads/master | 1,661,979,343,526 | 1,660,830,384,000 | 1,660,830,384,000 | 182,072,989 | 0 | 0 | null | 1,555,585,876,000 | 1,555,585,876,000 | null | UTF-8 | Lean | false | false | 11,038 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import topology.metric_space.basic
import topology.algebra.uniform_group
import topology.algebra.uniform_mul_action
import topology.algebra.ring
import topology.algebra.star
import ring_theory.subring.basic
import group_theory.archimedean
import algebra.periodic
import order.filter.archimedean
import topology.instances.int
/-!
# Topological properties of ℝ
-/
noncomputable theory
open classical filter int metric set topological_space
open_locale classical topological_space filter uniformity interval
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
instance : noncompact_space ℝ := int.closed_embedding_coe_real.noncompact_space
theorem real.uniform_continuous_add : uniform_continuous (λp : ℝ × ℝ, p.1 + p.2) :=
metric.uniform_continuous_iff.2 $ λ ε ε0,
let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abs ε0 in
⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ h₁ h₂⟩
theorem real.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℝ _) :=
metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h,
by rw dist_comm at h; simpa [real.dist_eq] using h⟩
instance : has_continuous_star ℝ := ⟨continuous_id⟩
instance : uniform_add_group ℝ :=
uniform_add_group.mk' real.uniform_continuous_add real.uniform_continuous_neg
-- short-circuit type class inference
instance : topological_add_group ℝ := by apply_instance
instance : proper_space ℝ :=
{ is_compact_closed_ball := λx r, by { rw real.closed_ball_eq_Icc, apply is_compact_Icc } }
instance : second_countable_topology ℝ := second_countable_of_proper
lemma real.is_topological_basis_Ioo_rat :
@is_topological_basis ℝ _ (⋃(a b : ℚ) (h : a < b), {Ioo a b}) :=
is_topological_basis_of_open_of_nhds
(by simp [is_open_Ioo] {contextual:=tt})
(assume a v hav hv,
let ⟨l, u, ⟨hl, hu⟩, h⟩ := mem_nhds_iff_exists_Ioo_subset.mp (is_open.mem_nhds hv hav),
⟨q, hlq, hqa⟩ := exists_rat_btwn hl,
⟨p, hap, hpu⟩ := exists_rat_btwn hu in
⟨Ioo q p,
by { simp only [mem_Union], exact ⟨q, p, rat.cast_lt.1 $ hqa.trans hap, rfl⟩ },
⟨hqa, hap⟩, assume a' ⟨hqa', ha'p⟩, h ⟨hlq.trans hqa', ha'p.trans hpu⟩⟩)
@[simp] lemma real.cocompact_eq : cocompact ℝ = at_bot ⊔ at_top :=
by simp only [← comap_dist_right_at_top_eq_cocompact (0 : ℝ), real.dist_eq, sub_zero,
comap_abs_at_top]
/- TODO(Mario): Prove that these are uniform isomorphisms instead of uniform embeddings
lemma uniform_embedding_add_rat {r : ℚ} : uniform_embedding (λp:ℚ, p + r) :=
_
lemma uniform_embedding_mul_rat {q : ℚ} (hq : q ≠ 0) : uniform_embedding ((*) q) :=
_ -/
lemma real.mem_closure_iff {s : set ℝ} {x : ℝ} :
x ∈ closure s ↔ ∀ ε > 0, ∃ y ∈ s, |y - x| < ε :=
by simp [mem_closure_iff_nhds_basis nhds_basis_ball, real.dist_eq]
lemma real.uniform_continuous_inv (s : set ℝ) {r : ℝ} (r0 : 0 < r) (H : ∀ x ∈ s, r ≤ |x|) :
uniform_continuous (λp:s, p.1⁻¹) :=
metric.uniform_continuous_iff.2 $ λ ε ε0,
let ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abs ε0 r0 in
⟨δ, δ0, λ a b h, Hδ (H _ a.2) (H _ b.2) h⟩
lemma real.uniform_continuous_abs : uniform_continuous (abs : ℝ → ℝ) :=
metric.uniform_continuous_iff.2 $ λ ε ε0,
⟨ε, ε0, λ a b, lt_of_le_of_lt (abs_abs_sub_abs_le_abs_sub _ _)⟩
lemma real.tendsto_inv {r : ℝ} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (𝓝 r) (𝓝 r⁻¹) :=
by rw ← abs_pos at r0; exact
tendsto_of_uniform_continuous_subtype
(real.uniform_continuous_inv {x | |r| / 2 < |x|} (half_pos r0) (λ x h, le_of_lt h))
(is_open.mem_nhds ((is_open_lt' (|r| / 2)).preimage continuous_abs) (half_lt_self r0))
lemma real.continuous_inv : continuous (λa:{r:ℝ // r ≠ 0}, a.val⁻¹) :=
continuous_iff_continuous_at.mpr $ assume ⟨r, hr⟩,
tendsto.comp (real.tendsto_inv hr) (continuous_iff_continuous_at.mp continuous_subtype_val _)
lemma real.continuous.inv [topological_space α] {f : α → ℝ} (h : ∀a, f a ≠ 0) (hf : continuous f) :
continuous (λa, (f a)⁻¹) :=
show continuous ((has_inv.inv ∘ @subtype.val ℝ (λr, r ≠ 0)) ∘ λa, ⟨f a, h a⟩),
from real.continuous_inv.comp (continuous_subtype_mk _ hf)
lemma real.uniform_continuous_const_mul {x : ℝ} : uniform_continuous ((*) x) :=
uniform_continuous_const_smul x
lemma real.uniform_continuous_mul (s : set (ℝ × ℝ))
{r₁ r₂ : ℝ} (H : ∀ x ∈ s, |(x : ℝ × ℝ).1| < r₁ ∧ |x.2| < r₂) :
uniform_continuous (λp:s, p.1.1 * p.1.2) :=
metric.uniform_continuous_iff.2 $ λ ε ε0,
let ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abs ε0 in
⟨δ, δ0, λ a b h,
let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ (H _ a.2).1 (H _ b.2).2 h₁ h₂⟩
protected lemma real.continuous_mul : continuous (λp : ℝ × ℝ, p.1 * p.2) :=
continuous_iff_continuous_at.2 $ λ ⟨a₁, a₂⟩,
tendsto_of_uniform_continuous_subtype
(real.uniform_continuous_mul
({x | |x| < |a₁| + 1} ×ˢ {x | |x| < |a₂| + 1})
(λ x, id))
(is_open.mem_nhds
(((is_open_gt' (|a₁| + 1)).preimage continuous_abs).prod
((is_open_gt' (|a₂| + 1)).preimage continuous_abs ))
⟨lt_add_one (|a₁|), lt_add_one (|a₂|)⟩)
instance : topological_ring ℝ :=
{ continuous_mul := real.continuous_mul, ..real.topological_add_group }
instance : complete_space ℝ :=
begin
apply complete_of_cauchy_seq_tendsto,
intros u hu,
let c : cau_seq ℝ abs := ⟨u, metric.cauchy_seq_iff'.1 hu⟩,
refine ⟨c.lim, λ s h, _⟩,
rcases metric.mem_nhds_iff.1 h with ⟨ε, ε0, hε⟩,
have := c.equiv_lim ε ε0,
simp only [mem_map, mem_at_top_sets, mem_set_of_eq],
refine this.imp (λ N hN n hn, hε (hN n hn))
end
lemma real.totally_bounded_ball (x ε : ℝ) : totally_bounded (ball x ε) :=
by rw real.ball_eq_Ioo; apply totally_bounded_Ioo
section
lemma closure_of_rat_image_lt {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q < x}) = {r | ↑q ≤ r} :=
subset.antisymm
((is_closed_ge' _).closure_subset_iff.2
(image_subset_iff.2 $ λ p h, le_of_lt $ (@rat.cast_lt ℝ _ _ _).2 h)) $
λ x hx, mem_closure_iff_nhds.2 $ λ t ht,
let ⟨ε, ε0, hε⟩ := metric.mem_nhds_iff.1 ht in
let ⟨p, h₁, h₂⟩ := exists_rat_btwn ((lt_add_iff_pos_right x).2 ε0) in
⟨_, hε (show abs _ < _,
by rwa [abs_of_nonneg (le_of_lt $ sub_pos.2 h₁), sub_lt_iff_lt_add']),
p, rat.cast_lt.1 (@lt_of_le_of_lt ℝ _ _ _ _ hx h₁), rfl⟩
/- TODO(Mario): Put these back only if needed later
lemma closure_of_rat_image_le_eq {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q ≤ x}) = {r | ↑q ≤ r} :=
_
lemma closure_of_rat_image_le_le_eq {a b : ℚ} (hab : a ≤ b) :
closure (of_rat '' {q:ℚ | a ≤ q ∧ q ≤ b}) = {r:ℝ | of_rat a ≤ r ∧ r ≤ of_rat b} :=
_-/
lemma real.bounded_iff_bdd_below_bdd_above {s : set ℝ} : bounded s ↔ bdd_below s ∧ bdd_above s :=
⟨begin
assume bdd,
rcases (bounded_iff_subset_ball 0).1 bdd with ⟨r, hr⟩, -- hr : s ⊆ closed_ball 0 r
rw real.closed_ball_eq_Icc at hr, -- hr : s ⊆ Icc (0 - r) (0 + r)
exact ⟨bdd_below_Icc.mono hr, bdd_above_Icc.mono hr⟩
end,
λ h, bounded_of_bdd_above_of_bdd_below h.2 h.1⟩
lemma real.subset_Icc_Inf_Sup_of_bounded {s : set ℝ} (h : bounded s) :
s ⊆ Icc (Inf s) (Sup s) :=
subset_Icc_cInf_cSup (real.bounded_iff_bdd_below_bdd_above.1 h).1
(real.bounded_iff_bdd_below_bdd_above.1 h).2
end
section periodic
namespace function
lemma periodic.compact_of_continuous' [topological_space α] {f : ℝ → α} {c : ℝ}
(hp : periodic f c) (hc : 0 < c) (hf : continuous f) :
is_compact (range f) :=
begin
convert is_compact_Icc.image hf,
ext x,
refine ⟨_, mem_range_of_mem_image f (Icc 0 c)⟩,
rintros ⟨y, h1⟩,
obtain ⟨z, hz, h2⟩ := hp.exists_mem_Ico₀ hc y,
exact ⟨z, mem_Icc_of_Ico hz, h2.symm.trans h1⟩,
end
/-- A continuous, periodic function has compact range. -/
lemma periodic.compact_of_continuous [topological_space α] {f : ℝ → α} {c : ℝ}
(hp : periodic f c) (hc : c ≠ 0) (hf : continuous f) :
is_compact (range f) :=
begin
cases lt_or_gt_of_ne hc with hneg hpos,
exacts [hp.neg.compact_of_continuous' (neg_pos.mpr hneg) hf, hp.compact_of_continuous' hpos hf],
end
/-- A continuous, periodic function is bounded. -/
lemma periodic.bounded_of_continuous [pseudo_metric_space α] {f : ℝ → α} {c : ℝ}
(hp : periodic f c) (hc : c ≠ 0) (hf : continuous f) :
bounded (range f) :=
(hp.compact_of_continuous hc hf).bounded
end function
end periodic
section subgroups
/-- Given a nontrivial subgroup `G ⊆ ℝ`, if `G ∩ ℝ_{>0}` has no minimum then `G` is dense. -/
lemma real.subgroup_dense_of_no_min {G : add_subgroup ℝ} {g₀ : ℝ} (g₀_in : g₀ ∈ G) (g₀_ne : g₀ ≠ 0)
(H' : ¬ ∃ a : ℝ, is_least {g : ℝ | g ∈ G ∧ 0 < g} a) :
dense (G : set ℝ) :=
begin
let G_pos := {g : ℝ | g ∈ G ∧ 0 < g},
push_neg at H',
intros x,
suffices : ∀ ε > (0 : ℝ), ∃ g ∈ G, |x - g| < ε,
by simpa only [real.mem_closure_iff, abs_sub_comm],
intros ε ε_pos,
obtain ⟨g₁, g₁_in, g₁_pos⟩ : ∃ g₁ : ℝ, g₁ ∈ G ∧ 0 < g₁,
{ cases lt_or_gt_of_ne g₀_ne with Hg₀ Hg₀,
{ exact ⟨-g₀, G.neg_mem g₀_in, neg_pos.mpr Hg₀⟩ },
{ exact ⟨g₀, g₀_in, Hg₀⟩ } },
obtain ⟨a, ha⟩ : ∃ a, is_glb G_pos a :=
⟨Inf G_pos, is_glb_cInf ⟨g₁, g₁_in, g₁_pos⟩ ⟨0, λ _ hx, le_of_lt hx.2⟩⟩,
have a_notin : a ∉ G_pos,
{ intros H,
exact H' a ⟨H, ha.1⟩ },
obtain ⟨g₂, g₂_in, g₂_pos, g₂_lt⟩ : ∃ g₂ : ℝ, g₂ ∈ G ∧ 0 < g₂ ∧ g₂ < ε,
{ obtain ⟨b, hb, hb', hb''⟩ := ha.exists_between_self_add' a_notin ε_pos,
obtain ⟨c, hc, hc', hc''⟩ := ha.exists_between_self_add' a_notin (sub_pos.2 hb'),
refine ⟨b - c, G.sub_mem hb.1 hc.1, _, _⟩ ;
linarith },
refine ⟨floor (x/g₂) * g₂, _, _⟩,
{ exact add_subgroup.int_mul_mem _ g₂_in },
{ rw abs_of_nonneg (sub_floor_div_mul_nonneg x g₂_pos),
linarith [sub_floor_div_mul_lt x g₂_pos] }
end
/-- Subgroups of `ℝ` are either dense or cyclic. See `real.subgroup_dense_of_no_min` and
`subgroup_cyclic_of_min` for more precise statements. -/
lemma real.subgroup_dense_or_cyclic (G : add_subgroup ℝ) :
dense (G : set ℝ) ∨ ∃ a : ℝ, G = add_subgroup.closure {a} :=
begin
cases add_subgroup.bot_or_exists_ne_zero G with H H,
{ right,
use 0,
rw [H, add_subgroup.closure_singleton_zero] },
{ let G_pos := {g : ℝ | g ∈ G ∧ 0 < g},
by_cases H' : ∃ a, is_least G_pos a,
{ right,
rcases H' with ⟨a, ha⟩,
exact ⟨a, add_subgroup.cyclic_of_min ha⟩ },
{ left,
rcases H with ⟨g₀, g₀_in, g₀_ne⟩,
exact real.subgroup_dense_of_no_min g₀_in g₀_ne H' } }
end
end subgroups
|
55494cd92c029b7a788a50e3c13d1793125146cb | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/init/control/monad_fail.lean | 5cf3384bb723163fb3b6a6e59ad7476b3cfe12d3 | [] | 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 | 722 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.control.lift
import Mathlib.Lean3Lib.init.data.string.basic
universes u v l
namespace Mathlib
class monad_fail (m : Type u → Type v)
where
fail : {a : Type u} → string → m a
def match_failed {α : Type u} {m : Type u → Type v} [monad_fail m] : m α := sorry
protected instance monad_fail_lift (m : Type u → Type v) (n : Type u → Type v) [Monad n] [monad_fail m] [has_monad_lift m n] : monad_fail n :=
monad_fail.mk fun (α : Type u) (s : string) => monad_lift (monad_fail.fail s)
|
9a7f85a3d7184c66a6407486c7e0c5f83d73e1c7 | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/algebra/category/CommRing/basic.lean | 88658cb125735248196b61a9a9d1aea97629abf0 | [
"Apache-2.0"
] | permissive | dupuisf/mathlib | 62de4ec6544bf3b79086afd27b6529acfaf2c1bb | 8582b06b0a5d06c33ee07d0bdf7c646cae22cf36 | refs/heads/master | 1,669,494,854,016 | 1,595,692,409,000 | 1,595,692,409,000 | 272,046,630 | 0 | 0 | Apache-2.0 | 1,592,066,143,000 | 1,592,066,142,000 | null | UTF-8 | Lean | false | false | 6,293 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Johannes Hölzl, Yury Kudryashov
-/
import algebra.category.Group
import data.equiv.ring
/-!
# Category instances for semiring, ring, comm_semiring, and comm_ring.
We introduce the bundled categories:
* `SemiRing`
* `Ring`
* `CommSemiRing`
* `CommRing`
along with the relevant forgetful functors between them.
-/
universes u v
open category_theory
/-- The category of semirings. -/
def SemiRing : Type (u+1) := bundled semiring
namespace SemiRing
instance bundled_hom : bundled_hom @ring_hom :=
⟨@ring_hom.to_fun, @ring_hom.id, @ring_hom.comp, @ring_hom.coe_inj⟩
attribute [derive [has_coe_to_sort, large_category, concrete_category]] SemiRing
/-- Construct a bundled SemiRing from the underlying type and typeclass. -/
def of (R : Type u) [semiring R] : SemiRing := bundled.of R
instance : inhabited SemiRing := ⟨of punit⟩
instance (R : SemiRing) : semiring R := R.str
instance has_forget_to_Mon : has_forget₂ SemiRing Mon :=
bundled_hom.mk_has_forget₂
(λ R hR, @monoid_with_zero.to_monoid R (@semiring.to_monoid_with_zero R hR))
(λ R₁ R₂, ring_hom.to_monoid_hom) (λ _ _ _, rfl)
instance has_forget_to_AddCommMon : has_forget₂ SemiRing AddCommMon :=
-- can't use bundled_hom.mk_has_forget₂, since AddCommMon is an induced category
{ forget₂ :=
{ obj := λ R, AddCommMon.of R,
map := λ R₁ R₂ f, ring_hom.to_add_monoid_hom f } }
end SemiRing
/-- The category of rings. -/
def Ring : Type (u+1) := bundled ring
namespace Ring
instance : bundled_hom.parent_projection @ring.to_semiring := ⟨⟩
attribute [derive [has_coe_to_sort, large_category, concrete_category]] Ring
/-- Construct a bundled Ring from the underlying type and typeclass. -/
def of (R : Type u) [ring R] : Ring := bundled.of R
instance : inhabited Ring := ⟨of punit⟩
instance (R : Ring) : ring R := R.str
instance has_forget_to_SemiRing : has_forget₂ Ring SemiRing := bundled_hom.forget₂ _ _
instance has_forget_to_AddCommGroup : has_forget₂ Ring AddCommGroup :=
-- can't use bundled_hom.mk_has_forget₂, since AddCommGroup is an induced category
{ forget₂ :=
{ obj := λ R, AddCommGroup.of R,
map := λ R₁ R₂ f, ring_hom.to_add_monoid_hom f } }
end Ring
/-- The category of commutative semirings. -/
def CommSemiRing : Type (u+1) := bundled comm_semiring
namespace CommSemiRing
instance : bundled_hom.parent_projection @comm_semiring.to_semiring := ⟨⟩
attribute [derive [has_coe_to_sort, large_category, concrete_category]] CommSemiRing
/-- Construct a bundled CommSemiRing from the underlying type and typeclass. -/
def of (R : Type u) [comm_semiring R] : CommSemiRing := bundled.of R
instance : inhabited CommSemiRing := ⟨of punit⟩
instance (R : CommSemiRing) : comm_semiring R := R.str
instance has_forget_to_SemiRing : has_forget₂ CommSemiRing SemiRing := bundled_hom.forget₂ _ _
/-- The forgetful functor from commutative rings to (multiplicative) commutative monoids. -/
instance has_forget_to_CommMon : has_forget₂ CommSemiRing CommMon :=
has_forget₂.mk'
(λ R : CommSemiRing, CommMon.of R) (λ R, rfl)
(λ R₁ R₂ f, f.to_monoid_hom) (by tidy)
end CommSemiRing
/-- The category of commutative rings. -/
def CommRing : Type (u+1) := bundled comm_ring
namespace CommRing
instance : bundled_hom.parent_projection @comm_ring.to_ring := ⟨⟩
attribute [derive [has_coe_to_sort, large_category, concrete_category]] CommRing
/-- Construct a bundled CommRing from the underlying type and typeclass. -/
def of (R : Type u) [comm_ring R] : CommRing := bundled.of R
instance : inhabited CommRing := ⟨of punit⟩
instance (R : CommRing) : comm_ring R := R.str
instance has_forget_to_Ring : has_forget₂ CommRing Ring := bundled_hom.forget₂ _ _
/-- The forgetful functor from commutative rings to (multiplicative) commutative monoids. -/
instance has_forget_to_CommSemiRing : has_forget₂ CommRing CommSemiRing :=
has_forget₂.mk' (λ R : CommRing, CommSemiRing.of R) (λ R, rfl) (λ R₁ R₂ f, f) (by tidy)
end CommRing
-- This example verifies an improvement possible in Lean 3.8.
-- Before that, to have `add_ring_hom.map_zero` usable by `simp` here,
-- we had to mark all the concrete category `has_coe_to_sort` instances reducible.
-- Now, it just works.
example {R S : CommRing} (i : R ⟶ S) (r : R) (h : r = 0) : i r = 0 :=
by simp [h]
namespace ring_equiv
variables {X Y : Type u}
/-- Build an isomorphism in the category `Ring` from a `ring_equiv` between `ring`s. -/
@[simps] def to_Ring_iso [ring X] [ring Y] (e : X ≃+* Y) : Ring.of X ≅ Ring.of Y :=
{ hom := e.to_ring_hom,
inv := e.symm.to_ring_hom }
/-- Build an isomorphism in the category `CommRing` from a `ring_equiv` between `comm_ring`s. -/
@[simps] def to_CommRing_iso [comm_ring X] [comm_ring Y] (e : X ≃+* Y) : CommRing.of X ≅ CommRing.of Y :=
{ hom := e.to_ring_hom,
inv := e.symm.to_ring_hom }
end ring_equiv
namespace category_theory.iso
/-- Build a `ring_equiv` from an isomorphism in the category `Ring`. -/
def Ring_iso_to_ring_equiv {X Y : Ring} (i : X ≅ Y) : X ≃+* Y :=
{ to_fun := i.hom,
inv_fun := i.inv,
left_inv := by tidy,
right_inv := by tidy,
map_add' := by tidy,
map_mul' := by tidy }.
/-- Build a `ring_equiv` from an isomorphism in the category `CommRing`. -/
def CommRing_iso_to_ring_equiv {X Y : CommRing} (i : X ≅ Y) : X ≃+* Y :=
{ to_fun := i.hom,
inv_fun := i.inv,
left_inv := by tidy,
right_inv := by tidy,
map_add' := by tidy,
map_mul' := by tidy }.
end category_theory.iso
/-- ring equivalences between `ring`s are the same as (isomorphic to) isomorphisms in `Ring`. -/
def ring_equiv_iso_Ring_iso {X Y : Type u} [ring X] [ring Y] :
(X ≃+* Y) ≅ (Ring.of X ≅ Ring.of Y) :=
{ hom := λ e, e.to_Ring_iso,
inv := λ i, i.Ring_iso_to_ring_equiv, }
/-- ring equivalences between `comm_ring`s are the same as (isomorphic to) isomorphisms in `CommRing`. -/
def ring_equiv_iso_CommRing_iso {X Y : Type u} [comm_ring X] [comm_ring Y] :
(X ≃+* Y) ≅ (CommRing.of X ≅ CommRing.of Y) :=
{ hom := λ e, e.to_CommRing_iso,
inv := λ i, i.CommRing_iso_to_ring_equiv, }
|
56f722650a5b9bd5ef062b1f2603d2db0e717913 | f2fbd9ce3f46053c664b74a5294d7d2f584e72d3 | /src/perfectoid_space.lean | d70ad0af6f9d07dcf8a0af3084ffaa012376f755 | [
"Apache-2.0"
] | permissive | jcommelin/lean-perfectoid-spaces | c656ae26a2338ee7a0072dab63baf577f079ca12 | d5ed816bcc116fd4cde5ce9aaf03905d00ee391c | refs/heads/master | 1,584,610,432,107 | 1,538,491,594,000 | 1,538,491,594,000 | 136,299,168 | 0 | 0 | null | 1,528,274,452,000 | 1,528,274,452,000 | null | UTF-8 | Lean | false | false | 748 | lean | -- definitions of adic_space, preadic_space, Huber_pair etc
import adic_space
import Tate_ring
import power_bounded
--notation
postfix `ᵒ` : 66 := power_bounded_subring
open nat.Prime power_bounded
variable [nat.Prime] -- fix a prime p
/-- A perfectoid ring, following Fontaine Sem Bourb-/
class perfectoid_ring (R : Type*) extends Tate_ring R :=
(complete : is_complete R)
(uniform : is_uniform R)
(ramified : ∃ ϖ : units R, (is_pseudo_uniformizer ϖ) ∧ ((ϖ^p : R) ∣ p))
(Frob : ∀ a : Rᵒ, ∃ b : Rᵒ, (p : R) ∣ (b^p - a))
class perfectoid_space (X : Type*) extends adic_space X :=
(perfectoid_cover : ∀ x : X, ∃ (U : opens X) (A : Huber_pair) [perfectoid_ring A.R],
(x ∈ U) ∧ is_preadic_space_equiv U (Spa A))
|
fc51b4074fcbd44bb1fe38f553f15661590ee022 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/analysis/calculus/deriv.lean | 0db145990c9b468444cbf0285cc78240a7bad801 | [
"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 | 92,447 | lean | /-
Copyright (c) 2019 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner, Sébastien Gouëzel
-/
import analysis.calculus.fderiv
import data.polynomial.derivative
import linear_algebra.affine_space.slope
/-!
# One-dimensional derivatives
This file defines the derivative of a function `f : 𝕜 → F` where `𝕜` is a
normed field and `F` is a normed space over this field. The derivative of
such a function `f` at a point `x` is given by an element `f' : F`.
The theory is developed analogously to the [Fréchet
derivatives](./fderiv.html). We first introduce predicates defined in terms
of the corresponding predicates for Fréchet derivatives:
- `has_deriv_at_filter f f' x L` states that the function `f` has the
derivative `f'` at the point `x` as `x` goes along the filter `L`.
- `has_deriv_within_at f f' s x` states that the function `f` has the
derivative `f'` at the point `x` within the subset `s`.
- `has_deriv_at f f' x` states that the function `f` has the derivative `f'`
at the point `x`.
- `has_strict_deriv_at f f' x` states that the function `f` has the derivative `f'`
at the point `x` in the sense of strict differentiability, i.e.,
`f y - f z = (y - z) • f' + o (y - z)` as `y, z → x`.
For the last two notions we also define a functional version:
- `deriv_within f s x` is a derivative of `f` at `x` within `s`. If the
derivative does not exist, then `deriv_within f s x` equals zero.
- `deriv f x` is a derivative of `f` at `x`. If the derivative does not
exist, then `deriv f x` equals zero.
The theorems `fderiv_within_deriv_within` and `fderiv_deriv` show that the
one-dimensional derivatives coincide with the general Fréchet derivatives.
We also show the existence and compute the derivatives of:
- constants
- the identity function
- linear maps
- addition
- sum of finitely many functions
- negation
- subtraction
- multiplication
- inverse `x → x⁻¹`
- multiplication of two functions in `𝕜 → 𝕜`
- multiplication of a function in `𝕜 → 𝕜` and of a function in `𝕜 → E`
- composition of a function in `𝕜 → F` with a function in `𝕜 → 𝕜`
- composition of a function in `F → E` with a function in `𝕜 → F`
- inverse function (assuming that it exists; the inverse function theorem is in `inverse.lean`)
- division
- polynomials
For most binary operations we also define `const_op` and `op_const` theorems for the cases when
the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier,
and they more frequently lead to the desired result.
We set up the simplifier so that it can compute the derivative of simple functions. For instance,
```lean
example (x : ℝ) : deriv (λ x, cos (sin x) * exp x) x = (cos(sin(x))-sin(sin(x))*cos(x))*exp(x) :=
by { simp, ring }
```
## Implementation notes
Most of the theorems are direct restatements of the corresponding theorems
for Fréchet derivatives.
The strategy to construct simp lemmas that give the simplifier the possibility to compute
derivatives is the same as the one for differentiability statements, as explained in `fderiv.lean`.
See the explanations there.
-/
universes u v w
noncomputable theory
open_locale classical topological_space big_operators filter ennreal polynomial
open filter asymptotics set
open continuous_linear_map (smul_right smul_right_one_eq_iff)
variables {𝕜 : Type u} [nontrivially_normed_field 𝕜]
section
variables {F : Type v} [normed_add_comm_group F] [normed_space 𝕜 F]
variables {E : Type w} [normed_add_comm_group E] [normed_space 𝕜 E]
/--
`f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`.
That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges along the filter `L`.
-/
def has_deriv_at_filter (f : 𝕜 → F) (f' : F) (x : 𝕜) (L : filter 𝕜) :=
has_fderiv_at_filter f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') x L
/--
`f` has the derivative `f'` at the point `x` within the subset `s`.
That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x` inside `s`.
-/
def has_deriv_within_at (f : 𝕜 → F) (f' : F) (s : set 𝕜) (x : 𝕜) :=
has_deriv_at_filter f f' x (𝓝[s] x)
/--
`f` has the derivative `f'` at the point `x`.
That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x`.
-/
def has_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) :=
has_deriv_at_filter f f' x (𝓝 x)
/-- `f` has the derivative `f'` at the point `x` in the sense of strict differentiability.
That is, `f y - f z = (y - z) • f' + o(y - z)` as `y, z → x`. -/
def has_strict_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) :=
has_strict_fderiv_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') x
/--
Derivative of `f` at the point `x` within the set `s`, if it exists. Zero otherwise.
If the derivative exists (i.e., `∃ f', has_deriv_within_at f f' s x`), then
`f x' = f x + (x' - x) • deriv_within f s x + o(x' - x)` where `x'` converges to `x` inside `s`.
-/
def deriv_within (f : 𝕜 → F) (s : set 𝕜) (x : 𝕜) :=
fderiv_within 𝕜 f s x 1
/--
Derivative of `f` at the point `x`, if it exists. Zero otherwise.
If the derivative exists (i.e., `∃ f', has_deriv_at f f' x`), then
`f x' = f x + (x' - x) • deriv f x + o(x' - x)` where `x'` converges to `x`.
-/
def deriv (f : 𝕜 → F) (x : 𝕜) :=
fderiv 𝕜 f x 1
variables {f f₀ f₁ g : 𝕜 → F}
variables {f' f₀' f₁' g' : F}
variables {x : 𝕜}
variables {s t : set 𝕜}
variables {L L₁ L₂ : filter 𝕜}
/-- Expressing `has_fderiv_at_filter f f' x L` in terms of `has_deriv_at_filter` -/
lemma has_fderiv_at_filter_iff_has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} :
has_fderiv_at_filter f f' x L ↔ has_deriv_at_filter f (f' 1) x L :=
by simp [has_deriv_at_filter]
lemma has_fderiv_at_filter.has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} :
has_fderiv_at_filter f f' x L → has_deriv_at_filter f (f' 1) x L :=
has_fderiv_at_filter_iff_has_deriv_at_filter.mp
/-- Expressing `has_fderiv_within_at f f' s x` in terms of `has_deriv_within_at` -/
lemma has_fderiv_within_at_iff_has_deriv_within_at {f' : 𝕜 →L[𝕜] F} :
has_fderiv_within_at f f' s x ↔ has_deriv_within_at f (f' 1) s x :=
has_fderiv_at_filter_iff_has_deriv_at_filter
/-- Expressing `has_deriv_within_at f f' s x` in terms of `has_fderiv_within_at` -/
lemma has_deriv_within_at_iff_has_fderiv_within_at {f' : F} :
has_deriv_within_at f f' s x ↔
has_fderiv_within_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') s x :=
iff.rfl
lemma has_fderiv_within_at.has_deriv_within_at {f' : 𝕜 →L[𝕜] F} :
has_fderiv_within_at f f' s x → has_deriv_within_at f (f' 1) s x :=
has_fderiv_within_at_iff_has_deriv_within_at.mp
lemma has_deriv_within_at.has_fderiv_within_at {f' : F} :
has_deriv_within_at f f' s x → has_fderiv_within_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') s x :=
has_deriv_within_at_iff_has_fderiv_within_at.mp
/-- Expressing `has_fderiv_at f f' x` in terms of `has_deriv_at` -/
lemma has_fderiv_at_iff_has_deriv_at {f' : 𝕜 →L[𝕜] F} :
has_fderiv_at f f' x ↔ has_deriv_at f (f' 1) x :=
has_fderiv_at_filter_iff_has_deriv_at_filter
lemma has_fderiv_at.has_deriv_at {f' : 𝕜 →L[𝕜] F} :
has_fderiv_at f f' x → has_deriv_at f (f' 1) x :=
has_fderiv_at_iff_has_deriv_at.mp
lemma has_strict_fderiv_at_iff_has_strict_deriv_at {f' : 𝕜 →L[𝕜] F} :
has_strict_fderiv_at f f' x ↔ has_strict_deriv_at f (f' 1) x :=
by simp [has_strict_deriv_at, has_strict_fderiv_at]
protected lemma has_strict_fderiv_at.has_strict_deriv_at {f' : 𝕜 →L[𝕜] F} :
has_strict_fderiv_at f f' x → has_strict_deriv_at f (f' 1) x :=
has_strict_fderiv_at_iff_has_strict_deriv_at.mp
lemma has_strict_deriv_at_iff_has_strict_fderiv_at :
has_strict_deriv_at f f' x ↔ has_strict_fderiv_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') x :=
iff.rfl
alias has_strict_deriv_at_iff_has_strict_fderiv_at ↔ has_strict_deriv_at.has_strict_fderiv_at _
/-- Expressing `has_deriv_at f f' x` in terms of `has_fderiv_at` -/
lemma has_deriv_at_iff_has_fderiv_at {f' : F} :
has_deriv_at f f' x ↔
has_fderiv_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') x :=
iff.rfl
alias has_deriv_at_iff_has_fderiv_at ↔ has_deriv_at.has_fderiv_at _
lemma deriv_within_zero_of_not_differentiable_within_at
(h : ¬ differentiable_within_at 𝕜 f s x) : deriv_within f s x = 0 :=
by { unfold deriv_within, rw fderiv_within_zero_of_not_differentiable_within_at, simp, assumption }
lemma differentiable_within_at_of_deriv_within_ne_zero (h : deriv_within f s x ≠ 0) :
differentiable_within_at 𝕜 f s x :=
not_imp_comm.1 deriv_within_zero_of_not_differentiable_within_at h
lemma deriv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : deriv f x = 0 :=
by { unfold deriv, rw fderiv_zero_of_not_differentiable_at, simp, assumption }
lemma differentiable_at_of_deriv_ne_zero (h : deriv f x ≠ 0) : differentiable_at 𝕜 f x :=
not_imp_comm.1 deriv_zero_of_not_differentiable_at h
theorem unique_diff_within_at.eq_deriv (s : set 𝕜) (H : unique_diff_within_at 𝕜 s x)
(h : has_deriv_within_at f f' s x) (h₁ : has_deriv_within_at f f₁' s x) : f' = f₁' :=
smul_right_one_eq_iff.mp $ unique_diff_within_at.eq H h h₁
theorem has_deriv_at_filter_iff_is_o :
has_deriv_at_filter f f' x L ↔ (λ x' : 𝕜, f x' - f x - (x' - x) • f') =o[L] (λ x', x' - x) :=
iff.rfl
theorem has_deriv_at_filter_iff_tendsto :
has_deriv_at_filter f f' x L ↔
tendsto (λ x' : 𝕜, ‖x' - x‖⁻¹ * ‖f x' - f x - (x' - x) • f'‖) L (𝓝 0) :=
has_fderiv_at_filter_iff_tendsto
theorem has_deriv_within_at_iff_is_o :
has_deriv_within_at f f' s x
↔ (λ x' : 𝕜, f x' - f x - (x' - x) • f') =o[𝓝[s] x] (λ x', x' - x) :=
iff.rfl
theorem has_deriv_within_at_iff_tendsto : has_deriv_within_at f f' s x ↔
tendsto (λ x', ‖x' - x‖⁻¹ * ‖f x' - f x - (x' - x) • f'‖) (𝓝[s] x) (𝓝 0) :=
has_fderiv_at_filter_iff_tendsto
theorem has_deriv_at_iff_is_o :
has_deriv_at f f' x ↔ (λ x' : 𝕜, f x' - f x - (x' - x) • f') =o[𝓝 x] (λ x', x' - x) :=
iff.rfl
theorem has_deriv_at_iff_tendsto : has_deriv_at f f' x ↔
tendsto (λ x', ‖x' - x‖⁻¹ * ‖f x' - f x - (x' - x) • f'‖) (𝓝 x) (𝓝 0) :=
has_fderiv_at_filter_iff_tendsto
theorem has_strict_deriv_at.has_deriv_at (h : has_strict_deriv_at f f' x) :
has_deriv_at f f' x :=
h.has_fderiv_at
/-- If the domain has dimension one, then Fréchet derivative is equivalent to the classical
definition with a limit. In this version we have to take the limit along the subset `-{x}`,
because for `y=x` the slope equals zero due to the convention `0⁻¹=0`. -/
lemma has_deriv_at_filter_iff_tendsto_slope {x : 𝕜} {L : filter 𝕜} :
has_deriv_at_filter f f' x L ↔ tendsto (slope f x) (L ⊓ 𝓟 {x}ᶜ) (𝓝 f') :=
begin
conv_lhs { simp only [has_deriv_at_filter_iff_tendsto, (norm_inv _).symm,
(norm_smul _ _).symm, tendsto_zero_iff_norm_tendsto_zero.symm] },
conv_rhs { rw [← nhds_translation_sub f', tendsto_comap_iff] },
refine (tendsto_inf_principal_nhds_iff_of_forall_eq $ by simp).symm.trans (tendsto_congr' _),
refine (eventually_principal.2 $ λ z hz, _).filter_mono inf_le_right,
simp only [(∘)],
rw [smul_sub, ← mul_smul, inv_mul_cancel (sub_ne_zero.2 hz), one_smul, slope_def_module]
end
lemma has_deriv_within_at_iff_tendsto_slope :
has_deriv_within_at f f' s x ↔ tendsto (slope f x) (𝓝[s \ {x}] x) (𝓝 f') :=
begin
simp only [has_deriv_within_at, nhds_within, diff_eq, inf_assoc.symm, inf_principal.symm],
exact has_deriv_at_filter_iff_tendsto_slope
end
lemma has_deriv_within_at_iff_tendsto_slope' (hs : x ∉ s) :
has_deriv_within_at f f' s x ↔ tendsto (slope f x) (𝓝[s] x) (𝓝 f') :=
begin
convert ← has_deriv_within_at_iff_tendsto_slope,
exact diff_singleton_eq_self hs
end
lemma has_deriv_at_iff_tendsto_slope :
has_deriv_at f f' x ↔ tendsto (slope f x) (𝓝[≠] x) (𝓝 f') :=
has_deriv_at_filter_iff_tendsto_slope
theorem has_deriv_within_at_congr_set {s t u : set 𝕜}
(hu : u ∈ 𝓝 x) (h : s ∩ u = t ∩ u) :
has_deriv_within_at f f' s x ↔ has_deriv_within_at f f' t x :=
by simp_rw [has_deriv_within_at, nhds_within_eq_nhds_within' hu h]
alias has_deriv_within_at_congr_set ↔ has_deriv_within_at.congr_set _
@[simp] lemma has_deriv_within_at_diff_singleton :
has_deriv_within_at f f' (s \ {x}) x ↔ has_deriv_within_at f f' s x :=
by simp only [has_deriv_within_at_iff_tendsto_slope, sdiff_idem]
@[simp] lemma has_deriv_within_at_Ioi_iff_Ici [partial_order 𝕜] :
has_deriv_within_at f f' (Ioi x) x ↔ has_deriv_within_at f f' (Ici x) x :=
by rw [← Ici_diff_left, has_deriv_within_at_diff_singleton]
alias has_deriv_within_at_Ioi_iff_Ici ↔
has_deriv_within_at.Ici_of_Ioi has_deriv_within_at.Ioi_of_Ici
@[simp] lemma has_deriv_within_at_Iio_iff_Iic [partial_order 𝕜] :
has_deriv_within_at f f' (Iio x) x ↔ has_deriv_within_at f f' (Iic x) x :=
by rw [← Iic_diff_right, has_deriv_within_at_diff_singleton]
alias has_deriv_within_at_Iio_iff_Iic ↔
has_deriv_within_at.Iic_of_Iio has_deriv_within_at.Iio_of_Iic
theorem has_deriv_within_at.Ioi_iff_Ioo [linear_order 𝕜] [order_closed_topology 𝕜] {x y : 𝕜}
(h : x < y) :
has_deriv_within_at f f' (Ioo x y) x ↔ has_deriv_within_at f f' (Ioi x) x :=
has_deriv_within_at_congr_set (is_open_Iio.mem_nhds h) $
by { rw [Ioi_inter_Iio, inter_eq_left_iff_subset], exact Ioo_subset_Iio_self }
alias has_deriv_within_at.Ioi_iff_Ioo ↔
has_deriv_within_at.Ioi_of_Ioo has_deriv_within_at.Ioo_of_Ioi
theorem has_deriv_at_iff_is_o_nhds_zero : has_deriv_at f f' x ↔
(λh, f (x + h) - f x - h • f') =o[𝓝 0] (λh, h) :=
has_fderiv_at_iff_is_o_nhds_zero
theorem has_deriv_at_filter.mono (h : has_deriv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) :
has_deriv_at_filter f f' x L₁ :=
has_fderiv_at_filter.mono h hst
theorem has_deriv_within_at.mono (h : has_deriv_within_at f f' t x) (hst : s ⊆ t) :
has_deriv_within_at f f' s x :=
has_fderiv_within_at.mono h hst
theorem has_deriv_at.has_deriv_at_filter (h : has_deriv_at f f' x) (hL : L ≤ 𝓝 x) :
has_deriv_at_filter f f' x L :=
has_fderiv_at.has_fderiv_at_filter h hL
theorem has_deriv_at.has_deriv_within_at
(h : has_deriv_at f f' x) : has_deriv_within_at f f' s x :=
has_fderiv_at.has_fderiv_within_at h
lemma has_deriv_within_at.differentiable_within_at (h : has_deriv_within_at f f' s x) :
differentiable_within_at 𝕜 f s x :=
has_fderiv_within_at.differentiable_within_at h
lemma has_deriv_at.differentiable_at (h : has_deriv_at f f' x) : differentiable_at 𝕜 f x :=
has_fderiv_at.differentiable_at h
@[simp] lemma has_deriv_within_at_univ : has_deriv_within_at f f' univ x ↔ has_deriv_at f f' x :=
has_fderiv_within_at_univ
theorem has_deriv_at.unique
(h₀ : has_deriv_at f f₀' x) (h₁ : has_deriv_at f f₁' x) : f₀' = f₁' :=
smul_right_one_eq_iff.mp $ h₀.has_fderiv_at.unique h₁
lemma has_deriv_within_at_inter' (h : t ∈ 𝓝[s] x) :
has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x :=
has_fderiv_within_at_inter' h
lemma has_deriv_within_at_inter (h : t ∈ 𝓝 x) :
has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x :=
has_fderiv_within_at_inter h
lemma has_deriv_within_at.union (hs : has_deriv_within_at f f' s x)
(ht : has_deriv_within_at f f' t x) :
has_deriv_within_at f f' (s ∪ t) x :=
hs.has_fderiv_within_at.union ht.has_fderiv_within_at
lemma has_deriv_within_at.nhds_within (h : has_deriv_within_at f f' s x)
(ht : s ∈ 𝓝[t] x) : has_deriv_within_at f f' t x :=
(has_deriv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _))
lemma has_deriv_within_at.has_deriv_at (h : has_deriv_within_at f f' s x) (hs : s ∈ 𝓝 x) :
has_deriv_at f f' x :=
has_fderiv_within_at.has_fderiv_at h hs
lemma differentiable_within_at.has_deriv_within_at (h : differentiable_within_at 𝕜 f s x) :
has_deriv_within_at f (deriv_within f s x) s x :=
h.has_fderiv_within_at.has_deriv_within_at
lemma differentiable_at.has_deriv_at (h : differentiable_at 𝕜 f x) : has_deriv_at f (deriv f x) x :=
h.has_fderiv_at.has_deriv_at
@[simp] lemma has_deriv_at_deriv_iff : has_deriv_at f (deriv f x) x ↔ differentiable_at 𝕜 f x :=
⟨λ h, h.differentiable_at, λ h, h.has_deriv_at⟩
@[simp] lemma has_deriv_within_at_deriv_within_iff :
has_deriv_within_at f (deriv_within f s x) s x ↔ differentiable_within_at 𝕜 f s x :=
⟨λ h, h.differentiable_within_at, λ h, h.has_deriv_within_at⟩
lemma differentiable_on.has_deriv_at (h : differentiable_on 𝕜 f s) (hs : s ∈ 𝓝 x) :
has_deriv_at f (deriv f x) x :=
(h.has_fderiv_at hs).has_deriv_at
lemma has_deriv_at.deriv (h : has_deriv_at f f' x) : deriv f x = f' :=
h.differentiable_at.has_deriv_at.unique h
lemma deriv_eq {f' : 𝕜 → F} (h : ∀ x, has_deriv_at f (f' x) x) : deriv f = f' :=
funext $ λ x, (h x).deriv
lemma has_deriv_within_at.deriv_within
(h : has_deriv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within f s x = f' :=
hxs.eq_deriv _ h.differentiable_within_at.has_deriv_within_at h
lemma fderiv_within_deriv_within : (fderiv_within 𝕜 f s x : 𝕜 → F) 1 = deriv_within f s x :=
rfl
lemma deriv_within_fderiv_within :
smul_right (1 : 𝕜 →L[𝕜] 𝕜) (deriv_within f s x) = fderiv_within 𝕜 f s x :=
by simp [deriv_within]
lemma fderiv_deriv : (fderiv 𝕜 f x : 𝕜 → F) 1 = deriv f x :=
rfl
lemma deriv_fderiv :
smul_right (1 : 𝕜 →L[𝕜] 𝕜) (deriv f x) = fderiv 𝕜 f x :=
by simp [deriv]
lemma differentiable_at.deriv_within (h : differentiable_at 𝕜 f x)
(hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = deriv f x :=
by { unfold deriv_within deriv, rw h.fderiv_within hxs }
theorem has_deriv_within_at.deriv_eq_zero (hd : has_deriv_within_at f 0 s x)
(H : unique_diff_within_at 𝕜 s x) : deriv f x = 0 :=
(em' (differentiable_at 𝕜 f x)).elim deriv_zero_of_not_differentiable_at $
λ h, H.eq_deriv _ h.has_deriv_at.has_deriv_within_at hd
lemma deriv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x)
(h : differentiable_within_at 𝕜 f t x) :
deriv_within f s x = deriv_within f t x :=
((differentiable_within_at.has_deriv_within_at h).mono st).deriv_within ht
@[simp] lemma deriv_within_univ : deriv_within f univ = deriv f :=
by { ext, unfold deriv_within deriv, rw fderiv_within_univ }
lemma deriv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) :
deriv_within f (s ∩ t) x = deriv_within f s x :=
by { unfold deriv_within, rw fderiv_within_inter ht hs }
lemma deriv_within_of_open (hs : is_open s) (hx : x ∈ s) :
deriv_within f s x = deriv f x :=
by { unfold deriv_within, rw fderiv_within_of_open hs hx, refl }
lemma deriv_mem_iff {f : 𝕜 → F} {s : set F} {x : 𝕜} :
deriv f x ∈ s ↔ (differentiable_at 𝕜 f x ∧ deriv f x ∈ s) ∨
(¬differentiable_at 𝕜 f x ∧ (0 : F) ∈ s) :=
by by_cases hx : differentiable_at 𝕜 f x; simp [deriv_zero_of_not_differentiable_at, *]
lemma deriv_within_mem_iff {f : 𝕜 → F} {t : set 𝕜} {s : set F} {x : 𝕜} :
deriv_within f t x ∈ s ↔ (differentiable_within_at 𝕜 f t x ∧ deriv_within f t x ∈ s) ∨
(¬differentiable_within_at 𝕜 f t x ∧ (0 : F) ∈ s) :=
by by_cases hx : differentiable_within_at 𝕜 f t x;
simp [deriv_within_zero_of_not_differentiable_within_at, *]
lemma differentiable_within_at_Ioi_iff_Ici [partial_order 𝕜] :
differentiable_within_at 𝕜 f (Ioi x) x ↔ differentiable_within_at 𝕜 f (Ici x) x :=
⟨λ h, h.has_deriv_within_at.Ici_of_Ioi.differentiable_within_at,
λ h, h.has_deriv_within_at.Ioi_of_Ici.differentiable_within_at⟩
lemma deriv_within_Ioi_eq_Ici {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] (f : ℝ → E)
(x : ℝ) :
deriv_within f (Ioi x) x = deriv_within f (Ici x) x :=
begin
by_cases H : differentiable_within_at ℝ f (Ioi x) x,
{ have A := H.has_deriv_within_at.Ici_of_Ioi,
have B := (differentiable_within_at_Ioi_iff_Ici.1 H).has_deriv_within_at,
simpa using (unique_diff_on_Ici x).eq le_rfl A B },
{ rw [deriv_within_zero_of_not_differentiable_within_at H,
deriv_within_zero_of_not_differentiable_within_at],
rwa differentiable_within_at_Ioi_iff_Ici at H }
end
section congr
/-! ### Congruence properties of derivatives -/
theorem filter.eventually_eq.has_deriv_at_filter_iff
(h₀ : f₀ =ᶠ[L] f₁) (hx : f₀ x = f₁ x) (h₁ : f₀' = f₁') :
has_deriv_at_filter f₀ f₀' x L ↔ has_deriv_at_filter f₁ f₁' x L :=
h₀.has_fderiv_at_filter_iff hx (by simp [h₁])
lemma has_deriv_at_filter.congr_of_eventually_eq (h : has_deriv_at_filter f f' x L)
(hL : f₁ =ᶠ[L] f) (hx : f₁ x = f x) : has_deriv_at_filter f₁ f' x L :=
by rwa hL.has_deriv_at_filter_iff hx rfl
lemma has_deriv_within_at.congr_mono (h : has_deriv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x)
(hx : f₁ x = f x) (h₁ : t ⊆ s) : has_deriv_within_at f₁ f' t x :=
has_fderiv_within_at.congr_mono h ht hx h₁
lemma has_deriv_within_at.congr (h : has_deriv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x)
(hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x :=
h.congr_mono hs hx (subset.refl _)
lemma has_deriv_within_at.congr_of_mem (h : has_deriv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x)
(hx : x ∈ s) : has_deriv_within_at f₁ f' s x :=
h.congr hs (hs _ hx)
lemma has_deriv_within_at.congr_of_eventually_eq (h : has_deriv_within_at f f' s x)
(h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x :=
has_deriv_at_filter.congr_of_eventually_eq h h₁ hx
lemma has_deriv_within_at.congr_of_eventually_eq_of_mem (h : has_deriv_within_at f f' s x)
(h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : x ∈ s) : has_deriv_within_at f₁ f' s x :=
h.congr_of_eventually_eq h₁ (h₁.eq_of_nhds_within hx)
lemma has_deriv_at.congr_of_eventually_eq (h : has_deriv_at f f' x)
(h₁ : f₁ =ᶠ[𝓝 x] f) : has_deriv_at f₁ f' x :=
has_deriv_at_filter.congr_of_eventually_eq h h₁ (mem_of_mem_nhds h₁ : _)
lemma filter.eventually_eq.deriv_within_eq (hs : unique_diff_within_at 𝕜 s x)
(hL : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) :
deriv_within f₁ s x = deriv_within f s x :=
by { unfold deriv_within, rw hL.fderiv_within_eq hs hx }
lemma deriv_within_congr (hs : unique_diff_within_at 𝕜 s x)
(hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) :
deriv_within f₁ s x = deriv_within f s x :=
by { unfold deriv_within, rw fderiv_within_congr hs hL hx }
lemma filter.eventually_eq.deriv_eq (hL : f₁ =ᶠ[𝓝 x] f) : deriv f₁ x = deriv f x :=
by { unfold deriv, rwa filter.eventually_eq.fderiv_eq }
protected lemma filter.eventually_eq.deriv (h : f₁ =ᶠ[𝓝 x] f) : deriv f₁ =ᶠ[𝓝 x] deriv f :=
h.eventually_eq_nhds.mono $ λ x h, h.deriv_eq
end congr
section id
/-! ### Derivative of the identity -/
variables (s x L)
theorem has_deriv_at_filter_id : has_deriv_at_filter id 1 x L :=
(has_fderiv_at_filter_id x L).has_deriv_at_filter
theorem has_deriv_within_at_id : has_deriv_within_at id 1 s x :=
has_deriv_at_filter_id _ _
theorem has_deriv_at_id : has_deriv_at id 1 x :=
has_deriv_at_filter_id _ _
theorem has_deriv_at_id' : has_deriv_at (λ (x : 𝕜), x) 1 x :=
has_deriv_at_filter_id _ _
theorem has_strict_deriv_at_id : has_strict_deriv_at id 1 x :=
(has_strict_fderiv_at_id x).has_strict_deriv_at
lemma deriv_id : deriv id x = 1 :=
has_deriv_at.deriv (has_deriv_at_id x)
@[simp] lemma deriv_id' : deriv (@id 𝕜) = λ _, 1 := funext deriv_id
@[simp] lemma deriv_id'' : deriv (λ x : 𝕜, x) = λ _, 1 := deriv_id'
lemma deriv_within_id (hxs : unique_diff_within_at 𝕜 s x) : deriv_within id s x = 1 :=
(has_deriv_within_at_id x s).deriv_within hxs
end id
section const
/-! ### Derivative of constant functions -/
variables (c : F) (s x L)
theorem has_deriv_at_filter_const : has_deriv_at_filter (λ x, c) 0 x L :=
(has_fderiv_at_filter_const c x L).has_deriv_at_filter
theorem has_strict_deriv_at_const : has_strict_deriv_at (λ x, c) 0 x :=
(has_strict_fderiv_at_const c x).has_strict_deriv_at
theorem has_deriv_within_at_const : has_deriv_within_at (λ x, c) 0 s x :=
has_deriv_at_filter_const _ _ _
theorem has_deriv_at_const : has_deriv_at (λ x, c) 0 x :=
has_deriv_at_filter_const _ _ _
lemma deriv_const : deriv (λ x, c) x = 0 :=
has_deriv_at.deriv (has_deriv_at_const x c)
@[simp] lemma deriv_const' : deriv (λ x:𝕜, c) = λ x, 0 :=
funext (λ x, deriv_const x c)
lemma deriv_within_const (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λ x, c) s x = 0 :=
(has_deriv_within_at_const _ _ _).deriv_within hxs
end const
section continuous_linear_map
/-! ### Derivative of continuous linear maps -/
variables (e : 𝕜 →L[𝕜] F)
protected lemma continuous_linear_map.has_deriv_at_filter : has_deriv_at_filter e (e 1) x L :=
e.has_fderiv_at_filter.has_deriv_at_filter
protected lemma continuous_linear_map.has_strict_deriv_at : has_strict_deriv_at e (e 1) x :=
e.has_strict_fderiv_at.has_strict_deriv_at
protected lemma continuous_linear_map.has_deriv_at : has_deriv_at e (e 1) x :=
e.has_deriv_at_filter
protected lemma continuous_linear_map.has_deriv_within_at : has_deriv_within_at e (e 1) s x :=
e.has_deriv_at_filter
@[simp] protected lemma continuous_linear_map.deriv : deriv e x = e 1 :=
e.has_deriv_at.deriv
protected lemma continuous_linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within e s x = e 1 :=
e.has_deriv_within_at.deriv_within hxs
end continuous_linear_map
section linear_map
/-! ### Derivative of bundled linear maps -/
variables (e : 𝕜 →ₗ[𝕜] F)
protected lemma linear_map.has_deriv_at_filter : has_deriv_at_filter e (e 1) x L :=
e.to_continuous_linear_map₁.has_deriv_at_filter
protected lemma linear_map.has_strict_deriv_at : has_strict_deriv_at e (e 1) x :=
e.to_continuous_linear_map₁.has_strict_deriv_at
protected lemma linear_map.has_deriv_at : has_deriv_at e (e 1) x :=
e.has_deriv_at_filter
protected lemma linear_map.has_deriv_within_at : has_deriv_within_at e (e 1) s x :=
e.has_deriv_at_filter
@[simp] protected lemma linear_map.deriv : deriv e x = e 1 :=
e.has_deriv_at.deriv
protected lemma linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within e s x = e 1 :=
e.has_deriv_within_at.deriv_within hxs
end linear_map
section add
/-! ### Derivative of the sum of two functions -/
theorem has_deriv_at_filter.add
(hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) :
has_deriv_at_filter (λ y, f y + g y) (f' + g') x L :=
by simpa using (hf.add hg).has_deriv_at_filter
theorem has_strict_deriv_at.add
(hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) :
has_strict_deriv_at (λ y, f y + g y) (f' + g') x :=
by simpa using (hf.add hg).has_strict_deriv_at
theorem has_deriv_within_at.add
(hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) :
has_deriv_within_at (λ y, f y + g y) (f' + g') s x :=
hf.add hg
theorem has_deriv_at.add
(hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) :
has_deriv_at (λ x, f x + g x) (f' + g') x :=
hf.add hg
lemma deriv_within_add (hxs : unique_diff_within_at 𝕜 s x)
(hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) :
deriv_within (λy, f y + g y) s x = deriv_within f s x + deriv_within g s x :=
(hf.has_deriv_within_at.add hg.has_deriv_within_at).deriv_within hxs
@[simp] lemma deriv_add
(hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) :
deriv (λy, f y + g y) x = deriv f x + deriv g x :=
(hf.has_deriv_at.add hg.has_deriv_at).deriv
theorem has_deriv_at_filter.add_const
(hf : has_deriv_at_filter f f' x L) (c : F) :
has_deriv_at_filter (λ y, f y + c) f' x L :=
add_zero f' ▸ hf.add (has_deriv_at_filter_const x L c)
theorem has_deriv_within_at.add_const
(hf : has_deriv_within_at f f' s x) (c : F) :
has_deriv_within_at (λ y, f y + c) f' s x :=
hf.add_const c
theorem has_deriv_at.add_const
(hf : has_deriv_at f f' x) (c : F) :
has_deriv_at (λ x, f x + c) f' x :=
hf.add_const c
lemma deriv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) :
deriv_within (λy, f y + c) s x = deriv_within f s x :=
by simp only [deriv_within, fderiv_within_add_const hxs]
lemma deriv_add_const (c : F) : deriv (λy, f y + c) x = deriv f x :=
by simp only [deriv, fderiv_add_const]
@[simp] lemma deriv_add_const' (c : F) : deriv (λ y, f y + c) = deriv f :=
funext $ λ x, deriv_add_const c
theorem has_deriv_at_filter.const_add (c : F) (hf : has_deriv_at_filter f f' x L) :
has_deriv_at_filter (λ y, c + f y) f' x L :=
zero_add f' ▸ (has_deriv_at_filter_const x L c).add hf
theorem has_deriv_within_at.const_add (c : F) (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ y, c + f y) f' s x :=
hf.const_add c
theorem has_deriv_at.const_add (c : F) (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, c + f x) f' x :=
hf.const_add c
lemma deriv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (c : F) :
deriv_within (λy, c + f y) s x = deriv_within f s x :=
by simp only [deriv_within, fderiv_within_const_add hxs]
lemma deriv_const_add (c : F) : deriv (λy, c + f y) x = deriv f x :=
by simp only [deriv, fderiv_const_add]
@[simp] lemma deriv_const_add' (c : F) : deriv (λ y, c + f y) = deriv f :=
funext $ λ x, deriv_const_add c
end add
section sum
/-! ### Derivative of a finite sum of functions -/
open_locale big_operators
variables {ι : Type*} {u : finset ι} {A : ι → (𝕜 → F)} {A' : ι → F}
theorem has_deriv_at_filter.sum (h : ∀ i ∈ u, has_deriv_at_filter (A i) (A' i) x L) :
has_deriv_at_filter (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x L :=
by simpa [continuous_linear_map.sum_apply] using (has_fderiv_at_filter.sum h).has_deriv_at_filter
theorem has_strict_deriv_at.sum (h : ∀ i ∈ u, has_strict_deriv_at (A i) (A' i) x) :
has_strict_deriv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x :=
by simpa [continuous_linear_map.sum_apply] using (has_strict_fderiv_at.sum h).has_strict_deriv_at
theorem has_deriv_within_at.sum (h : ∀ i ∈ u, has_deriv_within_at (A i) (A' i) s x) :
has_deriv_within_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) s x :=
has_deriv_at_filter.sum h
theorem has_deriv_at.sum (h : ∀ i ∈ u, has_deriv_at (A i) (A' i) x) :
has_deriv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x :=
has_deriv_at_filter.sum h
lemma deriv_within_sum (hxs : unique_diff_within_at 𝕜 s x)
(h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) :
deriv_within (λ y, ∑ i in u, A i y) s x = ∑ i in u, deriv_within (A i) s x :=
(has_deriv_within_at.sum (λ i hi, (h i hi).has_deriv_within_at)).deriv_within hxs
@[simp] lemma deriv_sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) :
deriv (λ y, ∑ i in u, A i y) x = ∑ i in u, deriv (A i) x :=
(has_deriv_at.sum (λ i hi, (h i hi).has_deriv_at)).deriv
end sum
section pi
/-! ### Derivatives of functions `f : 𝕜 → Π i, E i` -/
variables {ι : Type*} [fintype ι] {E' : ι → Type*} [Π i, normed_add_comm_group (E' i)]
[Π i, normed_space 𝕜 (E' i)] {φ : 𝕜 → Π i, E' i} {φ' : Π i, E' i}
@[simp] lemma has_strict_deriv_at_pi :
has_strict_deriv_at φ φ' x ↔ ∀ i, has_strict_deriv_at (λ x, φ x i) (φ' i) x :=
has_strict_fderiv_at_pi'
@[simp] lemma has_deriv_at_filter_pi :
has_deriv_at_filter φ φ' x L ↔
∀ i, has_deriv_at_filter (λ x, φ x i) (φ' i) x L :=
has_fderiv_at_filter_pi'
lemma has_deriv_at_pi :
has_deriv_at φ φ' x ↔ ∀ i, has_deriv_at (λ x, φ x i) (φ' i) x:=
has_deriv_at_filter_pi
lemma has_deriv_within_at_pi :
has_deriv_within_at φ φ' s x ↔ ∀ i, has_deriv_within_at (λ x, φ x i) (φ' i) s x:=
has_deriv_at_filter_pi
lemma deriv_within_pi (h : ∀ i, differentiable_within_at 𝕜 (λ x, φ x i) s x)
(hs : unique_diff_within_at 𝕜 s x) :
deriv_within φ s x = λ i, deriv_within (λ x, φ x i) s x :=
(has_deriv_within_at_pi.2 (λ i, (h i).has_deriv_within_at)).deriv_within hs
lemma deriv_pi (h : ∀ i, differentiable_at 𝕜 (λ x, φ x i) x) :
deriv φ x = λ i, deriv (λ x, φ x i) x :=
(has_deriv_at_pi.2 (λ i, (h i).has_deriv_at)).deriv
end pi
section smul
/-! ### Derivative of the multiplication of a scalar function and a vector function -/
variables {𝕜' : Type*} [nontrivially_normed_field 𝕜'] [normed_algebra 𝕜 𝕜']
[normed_space 𝕜' F] [is_scalar_tower 𝕜 𝕜' F] {c : 𝕜 → 𝕜'} {c' : 𝕜'}
theorem has_deriv_within_at.smul
(hc : has_deriv_within_at c c' s x) (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ y, c y • f y) (c x • f' + c' • f x) s x :=
by simpa using (has_fderiv_within_at.smul hc hf).has_deriv_within_at
theorem has_deriv_at.smul
(hc : has_deriv_at c c' x) (hf : has_deriv_at f f' x) :
has_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hc.smul hf
end
theorem has_strict_deriv_at.smul
(hc : has_strict_deriv_at c c' x) (hf : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x :=
by simpa using (hc.smul hf).has_strict_deriv_at
lemma deriv_within_smul (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) :
deriv_within (λ y, c y • f y) s x = c x • deriv_within f s x + (deriv_within c s x) • f x :=
(hc.has_deriv_within_at.smul hf.has_deriv_within_at).deriv_within hxs
lemma deriv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) :
deriv (λ y, c y • f y) x = c x • deriv f x + (deriv c x) • f x :=
(hc.has_deriv_at.smul hf.has_deriv_at).deriv
theorem has_strict_deriv_at.smul_const
(hc : has_strict_deriv_at c c' x) (f : F) :
has_strict_deriv_at (λ y, c y • f) (c' • f) x :=
begin
have := hc.smul (has_strict_deriv_at_const x f),
rwa [smul_zero, zero_add] at this,
end
theorem has_deriv_within_at.smul_const
(hc : has_deriv_within_at c c' s x) (f : F) :
has_deriv_within_at (λ y, c y • f) (c' • f) s x :=
begin
have := hc.smul (has_deriv_within_at_const x s f),
rwa [smul_zero, zero_add] at this
end
theorem has_deriv_at.smul_const
(hc : has_deriv_at c c' x) (f : F) :
has_deriv_at (λ y, c y • f) (c' • f) x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hc.smul_const f
end
lemma deriv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (f : F) :
deriv_within (λ y, c y • f) s x = (deriv_within c s x) • f :=
(hc.has_deriv_within_at.smul_const f).deriv_within hxs
lemma deriv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) :
deriv (λ y, c y • f) x = (deriv c x) • f :=
(hc.has_deriv_at.smul_const f).deriv
end smul
section const_smul
variables {R : Type*} [semiring R] [module R F] [smul_comm_class 𝕜 R F]
[has_continuous_const_smul R F]
theorem has_strict_deriv_at.const_smul
(c : R) (hf : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ y, c • f y) (c • f') x :=
by simpa using (hf.const_smul c).has_strict_deriv_at
theorem has_deriv_at_filter.const_smul
(c : R) (hf : has_deriv_at_filter f f' x L) :
has_deriv_at_filter (λ y, c • f y) (c • f') x L :=
by simpa using (hf.const_smul c).has_deriv_at_filter
theorem has_deriv_within_at.const_smul
(c : R) (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ y, c • f y) (c • f') s x :=
hf.const_smul c
theorem has_deriv_at.const_smul (c : R) (hf : has_deriv_at f f' x) :
has_deriv_at (λ y, c • f y) (c • f') x :=
hf.const_smul c
lemma deriv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x)
(c : R) (hf : differentiable_within_at 𝕜 f s x) :
deriv_within (λ y, c • f y) s x = c • deriv_within f s x :=
(hf.has_deriv_within_at.const_smul c).deriv_within hxs
lemma deriv_const_smul (c : R) (hf : differentiable_at 𝕜 f x) :
deriv (λ y, c • f y) x = c • deriv f x :=
(hf.has_deriv_at.const_smul c).deriv
end const_smul
section neg
/-! ### Derivative of the negative of a function -/
theorem has_deriv_at_filter.neg (h : has_deriv_at_filter f f' x L) :
has_deriv_at_filter (λ x, -f x) (-f') x L :=
by simpa using h.neg.has_deriv_at_filter
theorem has_deriv_within_at.neg (h : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, -f x) (-f') s x :=
h.neg
theorem has_deriv_at.neg (h : has_deriv_at f f' x) : has_deriv_at (λ x, -f x) (-f') x :=
h.neg
theorem has_strict_deriv_at.neg (h : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ x, -f x) (-f') x :=
by simpa using h.neg.has_strict_deriv_at
lemma deriv_within.neg (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λy, -f y) s x = - deriv_within f s x :=
by simp only [deriv_within, fderiv_within_neg hxs, continuous_linear_map.neg_apply]
lemma deriv.neg : deriv (λy, -f y) x = - deriv f x :=
by simp only [deriv, fderiv_neg, continuous_linear_map.neg_apply]
@[simp] lemma deriv.neg' : deriv (λy, -f y) = (λ x, - deriv f x) :=
funext $ λ x, deriv.neg
end neg
section neg2
/-! ### Derivative of the negation function (i.e `has_neg.neg`) -/
variables (s x L)
theorem has_deriv_at_filter_neg : has_deriv_at_filter has_neg.neg (-1) x L :=
has_deriv_at_filter.neg $ has_deriv_at_filter_id _ _
theorem has_deriv_within_at_neg : has_deriv_within_at has_neg.neg (-1) s x :=
has_deriv_at_filter_neg _ _
theorem has_deriv_at_neg : has_deriv_at has_neg.neg (-1) x :=
has_deriv_at_filter_neg _ _
theorem has_deriv_at_neg' : has_deriv_at (λ x, -x) (-1) x :=
has_deriv_at_filter_neg _ _
theorem has_strict_deriv_at_neg : has_strict_deriv_at has_neg.neg (-1) x :=
has_strict_deriv_at.neg $ has_strict_deriv_at_id _
lemma deriv_neg : deriv has_neg.neg x = -1 :=
has_deriv_at.deriv (has_deriv_at_neg x)
@[simp] lemma deriv_neg' : deriv (has_neg.neg : 𝕜 → 𝕜) = λ _, -1 :=
funext deriv_neg
@[simp] lemma deriv_neg'' : deriv (λ x : 𝕜, -x) x = -1 :=
deriv_neg x
lemma deriv_within_neg (hxs : unique_diff_within_at 𝕜 s x) : deriv_within has_neg.neg s x = -1 :=
(has_deriv_within_at_neg x s).deriv_within hxs
lemma differentiable_neg : differentiable 𝕜 (has_neg.neg : 𝕜 → 𝕜) :=
differentiable.neg differentiable_id
lemma differentiable_on_neg : differentiable_on 𝕜 (has_neg.neg : 𝕜 → 𝕜) s :=
differentiable_on.neg differentiable_on_id
end neg2
section sub
/-! ### Derivative of the difference of two functions -/
theorem has_deriv_at_filter.sub
(hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) :
has_deriv_at_filter (λ x, f x - g x) (f' - g') x L :=
by simpa only [sub_eq_add_neg] using hf.add hg.neg
theorem has_deriv_within_at.sub
(hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) :
has_deriv_within_at (λ x, f x - g x) (f' - g') s x :=
hf.sub hg
theorem has_deriv_at.sub
(hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) :
has_deriv_at (λ x, f x - g x) (f' - g') x :=
hf.sub hg
theorem has_strict_deriv_at.sub
(hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) :
has_strict_deriv_at (λ x, f x - g x) (f' - g') x :=
by simpa only [sub_eq_add_neg] using hf.add hg.neg
lemma deriv_within_sub (hxs : unique_diff_within_at 𝕜 s x)
(hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) :
deriv_within (λy, f y - g y) s x = deriv_within f s x - deriv_within g s x :=
(hf.has_deriv_within_at.sub hg.has_deriv_within_at).deriv_within hxs
@[simp] lemma deriv_sub
(hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) :
deriv (λ y, f y - g y) x = deriv f x - deriv g x :=
(hf.has_deriv_at.sub hg.has_deriv_at).deriv
theorem has_deriv_at_filter.is_O_sub (h : has_deriv_at_filter f f' x L) :
(λ x', f x' - f x) =O[L] (λ x', x' - x) :=
has_fderiv_at_filter.is_O_sub h
theorem has_deriv_at_filter.is_O_sub_rev (hf : has_deriv_at_filter f f' x L) (hf' : f' ≠ 0) :
(λ x', x' - x) =O[L] (λ x', f x' - f x) :=
suffices antilipschitz_with ‖f'‖₊⁻¹ (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f'), from hf.is_O_sub_rev this,
add_monoid_hom_class.antilipschitz_of_bound (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') $
λ x, by simp [norm_smul, ← div_eq_inv_mul, mul_div_cancel _ (mt norm_eq_zero.1 hf')]
theorem has_deriv_at_filter.sub_const
(hf : has_deriv_at_filter f f' x L) (c : F) :
has_deriv_at_filter (λ x, f x - c) f' x L :=
by simpa only [sub_eq_add_neg] using hf.add_const (-c)
theorem has_deriv_within_at.sub_const
(hf : has_deriv_within_at f f' s x) (c : F) :
has_deriv_within_at (λ x, f x - c) f' s x :=
hf.sub_const c
theorem has_deriv_at.sub_const
(hf : has_deriv_at f f' x) (c : F) :
has_deriv_at (λ x, f x - c) f' x :=
hf.sub_const c
lemma deriv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) :
deriv_within (λy, f y - c) s x = deriv_within f s x :=
by simp only [deriv_within, fderiv_within_sub_const hxs]
lemma deriv_sub_const (c : F) : deriv (λ y, f y - c) x = deriv f x :=
by simp only [deriv, fderiv_sub_const]
theorem has_deriv_at_filter.const_sub (c : F) (hf : has_deriv_at_filter f f' x L) :
has_deriv_at_filter (λ x, c - f x) (-f') x L :=
by simpa only [sub_eq_add_neg] using hf.neg.const_add c
theorem has_deriv_within_at.const_sub (c : F) (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, c - f x) (-f') s x :=
hf.const_sub c
theorem has_strict_deriv_at.const_sub (c : F) (hf : has_strict_deriv_at f f' x) :
has_strict_deriv_at (λ x, c - f x) (-f') x :=
by simpa only [sub_eq_add_neg] using hf.neg.const_add c
theorem has_deriv_at.const_sub (c : F) (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, c - f x) (-f') x :=
hf.const_sub c
lemma deriv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (c : F) :
deriv_within (λy, c - f y) s x = -deriv_within f s x :=
by simp [deriv_within, fderiv_within_const_sub hxs]
lemma deriv_const_sub (c : F) : deriv (λ y, c - f y) x = -deriv f x :=
by simp only [← deriv_within_univ,
deriv_within_const_sub (unique_diff_within_at_univ : unique_diff_within_at 𝕜 _ _)]
end sub
section continuous
/-! ### Continuity of a function admitting a derivative -/
theorem has_deriv_at_filter.tendsto_nhds
(hL : L ≤ 𝓝 x) (h : has_deriv_at_filter f f' x L) :
tendsto f L (𝓝 (f x)) :=
h.tendsto_nhds hL
theorem has_deriv_within_at.continuous_within_at
(h : has_deriv_within_at f f' s x) : continuous_within_at f s x :=
has_deriv_at_filter.tendsto_nhds inf_le_left h
theorem has_deriv_at.continuous_at (h : has_deriv_at f f' x) : continuous_at f x :=
has_deriv_at_filter.tendsto_nhds le_rfl h
protected theorem has_deriv_at.continuous_on {f f' : 𝕜 → F}
(hderiv : ∀ x ∈ s, has_deriv_at f (f' x) x) : continuous_on f s :=
λ x hx, (hderiv x hx).continuous_at.continuous_within_at
end continuous
section cartesian_product
/-! ### Derivative of the cartesian product of two functions -/
variables {G : Type w} [normed_add_comm_group G] [normed_space 𝕜 G]
variables {f₂ : 𝕜 → G} {f₂' : G}
lemma has_deriv_at_filter.prod
(hf₁ : has_deriv_at_filter f₁ f₁' x L) (hf₂ : has_deriv_at_filter f₂ f₂' x L) :
has_deriv_at_filter (λ x, (f₁ x, f₂ x)) (f₁', f₂') x L :=
hf₁.prod hf₂
lemma has_deriv_within_at.prod
(hf₁ : has_deriv_within_at f₁ f₁' s x) (hf₂ : has_deriv_within_at f₂ f₂' s x) :
has_deriv_within_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') s x :=
hf₁.prod hf₂
lemma has_deriv_at.prod (hf₁ : has_deriv_at f₁ f₁' x) (hf₂ : has_deriv_at f₂ f₂' x) :
has_deriv_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') x :=
hf₁.prod hf₂
lemma has_strict_deriv_at.prod (hf₁ : has_strict_deriv_at f₁ f₁' x)
(hf₂ : has_strict_deriv_at f₂ f₂' x) :
has_strict_deriv_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') x :=
hf₁.prod hf₂
end cartesian_product
section composition
/-!
### Derivative of the composition of a vector function and a scalar function
We use `scomp` in lemmas on composition of vector valued and scalar valued functions, and `comp`
in lemmas on composition of scalar valued functions, in analogy for `smul` and `mul` (and also
because the `comp` version with the shorter name will show up much more often in applications).
The formula for the derivative involves `smul` in `scomp` lemmas, which can be reduced to
usual multiplication in `comp` lemmas.
-/
/- For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to
get confused since there are too many possibilities for composition -/
variables {𝕜' : Type*} [nontrivially_normed_field 𝕜'] [normed_algebra 𝕜 𝕜']
[normed_space 𝕜' F] [is_scalar_tower 𝕜 𝕜' F] {s' t' : set 𝕜'}
{h : 𝕜 → 𝕜'} {h₁ : 𝕜 → 𝕜} {h₂ : 𝕜' → 𝕜'} {h' h₂' : 𝕜'} {h₁' : 𝕜}
{g₁ : 𝕜' → F} {g₁' : F} {L' : filter 𝕜'} (x)
theorem has_deriv_at_filter.scomp
(hg : has_deriv_at_filter g₁ g₁' (h x) L')
(hh : has_deriv_at_filter h h' x L) (hL : tendsto h L L'):
has_deriv_at_filter (g₁ ∘ h) (h' • g₁') x L :=
by simpa using ((hg.restrict_scalars 𝕜).comp x hh hL).has_deriv_at_filter
theorem has_deriv_within_at.scomp_has_deriv_at
(hg : has_deriv_within_at g₁ g₁' s' (h x))
(hh : has_deriv_at h h' x) (hs : ∀ x, h x ∈ s') :
has_deriv_at (g₁ ∘ h) (h' • g₁') x :=
hg.scomp x hh $ tendsto_inf.2 ⟨hh.continuous_at, tendsto_principal.2 $ eventually_of_forall hs⟩
theorem has_deriv_within_at.scomp
(hg : has_deriv_within_at g₁ g₁' t' (h x))
(hh : has_deriv_within_at h h' s x) (hst : maps_to h s t') :
has_deriv_within_at (g₁ ∘ h) (h' • g₁') s x :=
hg.scomp x hh $ hh.continuous_within_at.tendsto_nhds_within hst
/-- The chain rule. -/
theorem has_deriv_at.scomp
(hg : has_deriv_at g₁ g₁' (h x)) (hh : has_deriv_at h h' x) :
has_deriv_at (g₁ ∘ h) (h' • g₁') x :=
hg.scomp x hh hh.continuous_at
theorem has_strict_deriv_at.scomp
(hg : has_strict_deriv_at g₁ g₁' (h x)) (hh : has_strict_deriv_at h h' x) :
has_strict_deriv_at (g₁ ∘ h) (h' • g₁') x :=
by simpa using ((hg.restrict_scalars 𝕜).comp x hh).has_strict_deriv_at
theorem has_deriv_at.scomp_has_deriv_within_at
(hg : has_deriv_at g₁ g₁' (h x)) (hh : has_deriv_within_at h h' s x) :
has_deriv_within_at (g₁ ∘ h) (h' • g₁') s x :=
has_deriv_within_at.scomp x hg.has_deriv_within_at hh (maps_to_univ _ _)
lemma deriv_within.scomp
(hg : differentiable_within_at 𝕜' g₁ t' (h x)) (hh : differentiable_within_at 𝕜 h s x)
(hs : maps_to h s t') (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (g₁ ∘ h) s x = deriv_within h s x • deriv_within g₁ t' (h x) :=
(has_deriv_within_at.scomp x hg.has_deriv_within_at hh.has_deriv_within_at hs).deriv_within hxs
lemma deriv.scomp
(hg : differentiable_at 𝕜' g₁ (h x)) (hh : differentiable_at 𝕜 h x) :
deriv (g₁ ∘ h) x = deriv h x • deriv g₁ (h x) :=
(has_deriv_at.scomp x hg.has_deriv_at hh.has_deriv_at).deriv
/-! ### Derivative of the composition of a scalar and vector functions -/
theorem has_deriv_at_filter.comp_has_fderiv_at_filter {f : E → 𝕜'} {f' : E →L[𝕜] 𝕜'} (x)
{L'' : filter E} (hh₂ : has_deriv_at_filter h₂ h₂' (f x) L')
(hf : has_fderiv_at_filter f f' x L'') (hL : tendsto f L'' L') :
has_fderiv_at_filter (h₂ ∘ f) (h₂' • f') x L'' :=
by { convert (hh₂.restrict_scalars 𝕜).comp x hf hL, ext x, simp [mul_comm] }
theorem has_strict_deriv_at.comp_has_strict_fderiv_at {f : E → 𝕜'} {f' : E →L[𝕜] 𝕜'} (x)
(hh : has_strict_deriv_at h₂ h₂' (f x)) (hf : has_strict_fderiv_at f f' x) :
has_strict_fderiv_at (h₂ ∘ f) (h₂' • f') x :=
begin
rw has_strict_deriv_at at hh,
convert (hh.restrict_scalars 𝕜).comp x hf,
ext x,
simp [mul_comm]
end
theorem has_deriv_at.comp_has_fderiv_at {f : E → 𝕜'} {f' : E →L[𝕜] 𝕜'} (x)
(hh : has_deriv_at h₂ h₂' (f x)) (hf : has_fderiv_at f f' x) :
has_fderiv_at (h₂ ∘ f) (h₂' • f') x :=
hh.comp_has_fderiv_at_filter x hf hf.continuous_at
theorem has_deriv_at.comp_has_fderiv_within_at {f : E → 𝕜'} {f' : E →L[𝕜] 𝕜'} {s} (x)
(hh : has_deriv_at h₂ h₂' (f x)) (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (h₂ ∘ f) (h₂' • f') s x :=
hh.comp_has_fderiv_at_filter x hf hf.continuous_within_at
theorem has_deriv_within_at.comp_has_fderiv_within_at {f : E → 𝕜'} {f' : E →L[𝕜] 𝕜'} {s t} (x)
(hh : has_deriv_within_at h₂ h₂' t (f x)) (hf : has_fderiv_within_at f f' s x)
(hst : maps_to f s t) :
has_fderiv_within_at (h₂ ∘ f) (h₂' • f') s x :=
hh.comp_has_fderiv_at_filter x hf $ hf.continuous_within_at.tendsto_nhds_within hst
/-! ### Derivative of the composition of two scalar functions -/
theorem has_deriv_at_filter.comp
(hh₂ : has_deriv_at_filter h₂ h₂' (h x) L')
(hh : has_deriv_at_filter h h' x L) (hL : tendsto h L L') :
has_deriv_at_filter (h₂ ∘ h) (h₂' * h') x L :=
by { rw mul_comm, exact hh₂.scomp x hh hL }
theorem has_deriv_within_at.comp
(hh₂ : has_deriv_within_at h₂ h₂' s' (h x))
(hh : has_deriv_within_at h h' s x) (hst : maps_to h s s') :
has_deriv_within_at (h₂ ∘ h) (h₂' * h') s x :=
by { rw mul_comm, exact hh₂.scomp x hh hst, }
/-- The chain rule. -/
theorem has_deriv_at.comp
(hh₂ : has_deriv_at h₂ h₂' (h x)) (hh : has_deriv_at h h' x) :
has_deriv_at (h₂ ∘ h) (h₂' * h') x :=
hh₂.comp x hh hh.continuous_at
theorem has_strict_deriv_at.comp
(hh₂ : has_strict_deriv_at h₂ h₂' (h x)) (hh : has_strict_deriv_at h h' x) :
has_strict_deriv_at (h₂ ∘ h) (h₂' * h') x :=
by { rw mul_comm, exact hh₂.scomp x hh }
theorem has_deriv_at.comp_has_deriv_within_at
(hh₂ : has_deriv_at h₂ h₂' (h x)) (hh : has_deriv_within_at h h' s x) :
has_deriv_within_at (h₂ ∘ h) (h₂' * h') s x :=
hh₂.has_deriv_within_at.comp x hh (maps_to_univ _ _)
lemma deriv_within.comp
(hh₂ : differentiable_within_at 𝕜' h₂ s' (h x)) (hh : differentiable_within_at 𝕜 h s x)
(hs : maps_to h s s') (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (h₂ ∘ h) s x = deriv_within h₂ s' (h x) * deriv_within h s x :=
(hh₂.has_deriv_within_at.comp x hh.has_deriv_within_at hs).deriv_within hxs
lemma deriv.comp
(hh₂ : differentiable_at 𝕜' h₂ (h x)) (hh : differentiable_at 𝕜 h x) :
deriv (h₂ ∘ h) x = deriv h₂ (h x) * deriv h x :=
(hh₂.has_deriv_at.comp x hh.has_deriv_at).deriv
protected lemma has_deriv_at_filter.iterate {f : 𝕜 → 𝕜} {f' : 𝕜}
(hf : has_deriv_at_filter f f' x L) (hL : tendsto f L L) (hx : f x = x) (n : ℕ) :
has_deriv_at_filter (f^[n]) (f'^n) x L :=
begin
have := hf.iterate hL hx n,
rwa [continuous_linear_map.smul_right_one_pow] at this
end
protected lemma has_deriv_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜}
(hf : has_deriv_at f f' x) (hx : f x = x) (n : ℕ) :
has_deriv_at (f^[n]) (f'^n) x :=
begin
have := has_fderiv_at.iterate hf hx n,
rwa [continuous_linear_map.smul_right_one_pow] at this
end
protected lemma has_deriv_within_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜}
(hf : has_deriv_within_at f f' s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) :
has_deriv_within_at (f^[n]) (f'^n) s x :=
begin
have := has_fderiv_within_at.iterate hf hx hs n,
rwa [continuous_linear_map.smul_right_one_pow] at this
end
protected lemma has_strict_deriv_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜}
(hf : has_strict_deriv_at f f' x) (hx : f x = x) (n : ℕ) :
has_strict_deriv_at (f^[n]) (f'^n) x :=
begin
have := hf.iterate hx n,
rwa [continuous_linear_map.smul_right_one_pow] at this
end
end composition
section composition_vector
/-! ### Derivative of the composition of a function between vector spaces and a function on `𝕜` -/
open continuous_linear_map
variables {l : F → E} {l' : F →L[𝕜] E}
variable (x)
/-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative within a set
equal to the Fréchet derivative of `l` applied to the derivative of `f`. -/
theorem has_fderiv_within_at.comp_has_deriv_within_at {t : set F}
(hl : has_fderiv_within_at l l' t (f x)) (hf : has_deriv_within_at f f' s x)
(hst : maps_to f s t) :
has_deriv_within_at (l ∘ f) (l' f') s x :=
by simpa only [one_apply, one_smul, smul_right_apply, coe_comp', (∘)]
using (hl.comp x hf.has_fderiv_within_at hst).has_deriv_within_at
theorem has_fderiv_at.comp_has_deriv_within_at
(hl : has_fderiv_at l l' (f x)) (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (l ∘ f) (l' f') s x :=
hl.has_fderiv_within_at.comp_has_deriv_within_at x hf (maps_to_univ _ _)
/-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative equal to the
Fréchet derivative of `l` applied to the derivative of `f`. -/
theorem has_fderiv_at.comp_has_deriv_at (hl : has_fderiv_at l l' (f x)) (hf : has_deriv_at f f' x) :
has_deriv_at (l ∘ f) (l' f') x :=
has_deriv_within_at_univ.mp $ hl.comp_has_deriv_within_at x hf.has_deriv_within_at
theorem has_strict_fderiv_at.comp_has_strict_deriv_at
(hl : has_strict_fderiv_at l l' (f x)) (hf : has_strict_deriv_at f f' x) :
has_strict_deriv_at (l ∘ f) (l' f') x :=
by simpa only [one_apply, one_smul, smul_right_apply, coe_comp', (∘)]
using (hl.comp x hf.has_strict_fderiv_at).has_strict_deriv_at
lemma fderiv_within.comp_deriv_within {t : set F}
(hl : differentiable_within_at 𝕜 l t (f x)) (hf : differentiable_within_at 𝕜 f s x)
(hs : maps_to f s t) (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (l ∘ f) s x = (fderiv_within 𝕜 l t (f x) : F → E) (deriv_within f s x) :=
(hl.has_fderiv_within_at.comp_has_deriv_within_at x hf.has_deriv_within_at hs).deriv_within hxs
lemma fderiv.comp_deriv
(hl : differentiable_at 𝕜 l (f x)) (hf : differentiable_at 𝕜 f x) :
deriv (l ∘ f) x = (fderiv 𝕜 l (f x) : F → E) (deriv f x) :=
(hl.has_fderiv_at.comp_has_deriv_at x hf.has_deriv_at).deriv
end composition_vector
section mul
/-! ### Derivative of the multiplication of two functions -/
variables {𝕜' 𝔸 : Type*} [normed_field 𝕜'] [normed_ring 𝔸] [normed_algebra 𝕜 𝕜']
[normed_algebra 𝕜 𝔸] {c d : 𝕜 → 𝔸} {c' d' : 𝔸} {u v : 𝕜 → 𝕜'}
theorem has_deriv_within_at.mul
(hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) :
has_deriv_within_at (λ y, c y * d y) (c' * d x + c x * d') s x :=
begin
have := (has_fderiv_within_at.mul' hc hd).has_deriv_within_at,
rwa [continuous_linear_map.add_apply, continuous_linear_map.smul_apply,
continuous_linear_map.smul_right_apply, continuous_linear_map.smul_right_apply,
continuous_linear_map.smul_right_apply, continuous_linear_map.one_apply,
one_smul, one_smul, add_comm] at this,
end
theorem has_deriv_at.mul (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) :
has_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hc.mul hd
end
theorem has_strict_deriv_at.mul
(hc : has_strict_deriv_at c c' x) (hd : has_strict_deriv_at d d' x) :
has_strict_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x :=
begin
have := (has_strict_fderiv_at.mul' hc hd).has_strict_deriv_at,
rwa [continuous_linear_map.add_apply, continuous_linear_map.smul_apply,
continuous_linear_map.smul_right_apply, continuous_linear_map.smul_right_apply,
continuous_linear_map.smul_right_apply, continuous_linear_map.one_apply,
one_smul, one_smul, add_comm] at this,
end
lemma deriv_within_mul (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) :
deriv_within (λ y, c y * d y) s x = deriv_within c s x * d x + c x * deriv_within d s x :=
(hc.has_deriv_within_at.mul hd.has_deriv_within_at).deriv_within hxs
@[simp] lemma deriv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) :
deriv (λ y, c y * d y) x = deriv c x * d x + c x * deriv d x :=
(hc.has_deriv_at.mul hd.has_deriv_at).deriv
theorem has_deriv_within_at.mul_const (hc : has_deriv_within_at c c' s x) (d : 𝔸) :
has_deriv_within_at (λ y, c y * d) (c' * d) s x :=
begin
convert hc.mul (has_deriv_within_at_const x s d),
rw [mul_zero, add_zero]
end
theorem has_deriv_at.mul_const (hc : has_deriv_at c c' x) (d : 𝔸) :
has_deriv_at (λ y, c y * d) (c' * d) x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hc.mul_const d
end
theorem has_deriv_at_mul_const (c : 𝕜) : has_deriv_at (λ x, x * c) c x :=
by simpa only [one_mul] using (has_deriv_at_id' x).mul_const c
theorem has_strict_deriv_at.mul_const (hc : has_strict_deriv_at c c' x) (d : 𝔸) :
has_strict_deriv_at (λ y, c y * d) (c' * d) x :=
begin
convert hc.mul (has_strict_deriv_at_const x d),
rw [mul_zero, add_zero]
end
lemma deriv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (d : 𝔸) :
deriv_within (λ y, c y * d) s x = deriv_within c s x * d :=
(hc.has_deriv_within_at.mul_const d).deriv_within hxs
lemma deriv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝔸) :
deriv (λ y, c y * d) x = deriv c x * d :=
(hc.has_deriv_at.mul_const d).deriv
lemma deriv_mul_const_field (v : 𝕜') :
deriv (λ y, u y * v) x = deriv u x * v :=
begin
by_cases hu : differentiable_at 𝕜 u x,
{ exact deriv_mul_const hu v },
{ rw [deriv_zero_of_not_differentiable_at hu, zero_mul],
rcases eq_or_ne v 0 with rfl|hd,
{ simp only [mul_zero, deriv_const] },
{ refine deriv_zero_of_not_differentiable_at (mt (λ H, _) hu),
simpa only [mul_inv_cancel_right₀ hd] using H.mul_const v⁻¹ } }
end
@[simp] lemma deriv_mul_const_field' (v : 𝕜') : deriv (λ x, u x * v) = λ x, deriv u x * v :=
funext $ λ _, deriv_mul_const_field v
theorem has_deriv_within_at.const_mul (c : 𝔸) (hd : has_deriv_within_at d d' s x) :
has_deriv_within_at (λ y, c * d y) (c * d') s x :=
begin
convert (has_deriv_within_at_const x s c).mul hd,
rw [zero_mul, zero_add]
end
theorem has_deriv_at.const_mul (c : 𝔸) (hd : has_deriv_at d d' x) :
has_deriv_at (λ y, c * d y) (c * d') x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hd.const_mul c
end
theorem has_strict_deriv_at.const_mul (c : 𝔸) (hd : has_strict_deriv_at d d' x) :
has_strict_deriv_at (λ y, c * d y) (c * d') x :=
begin
convert (has_strict_deriv_at_const _ _).mul hd,
rw [zero_mul, zero_add]
end
lemma deriv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x)
(c : 𝔸) (hd : differentiable_within_at 𝕜 d s x) :
deriv_within (λ y, c * d y) s x = c * deriv_within d s x :=
(hd.has_deriv_within_at.const_mul c).deriv_within hxs
lemma deriv_const_mul (c : 𝔸) (hd : differentiable_at 𝕜 d x) :
deriv (λ y, c * d y) x = c * deriv d x :=
(hd.has_deriv_at.const_mul c).deriv
lemma deriv_const_mul_field (u : 𝕜') : deriv (λ y, u * v y) x = u * deriv v x :=
by simp only [mul_comm u, deriv_mul_const_field]
@[simp] lemma deriv_const_mul_field' (u : 𝕜') : deriv (λ x, u * v x) = λ x, u * deriv v x :=
funext (λ x, deriv_const_mul_field u)
end mul
section inverse
/-! ### Derivative of `x ↦ x⁻¹` -/
theorem has_strict_deriv_at_inv (hx : x ≠ 0) : has_strict_deriv_at has_inv.inv (-(x^2)⁻¹) x :=
begin
suffices : (λ p : 𝕜 × 𝕜, (p.1 - p.2) * ((x * x)⁻¹ - (p.1 * p.2)⁻¹)) =o[𝓝 (x, x)]
(λ p, (p.1 - p.2) * 1),
{ refine this.congr' _ (eventually_of_forall $ λ _, mul_one _),
refine eventually.mono (is_open.mem_nhds (is_open_ne.prod is_open_ne) ⟨hx, hx⟩) _,
rintro ⟨y, z⟩ ⟨hy, hz⟩,
simp only [mem_set_of_eq] at hy hz, -- hy : y ≠ 0, hz : z ≠ 0
field_simp [hx, hy, hz], ring, },
refine (is_O_refl (λ p : 𝕜 × 𝕜, p.1 - p.2) _).mul_is_o ((is_o_one_iff _).2 _),
rw [← sub_self (x * x)⁻¹],
exact tendsto_const_nhds.sub ((continuous_mul.tendsto (x, x)).inv₀ $ mul_ne_zero hx hx)
end
theorem has_deriv_at_inv (x_ne_zero : x ≠ 0) :
has_deriv_at (λy, y⁻¹) (-(x^2)⁻¹) x :=
(has_strict_deriv_at_inv x_ne_zero).has_deriv_at
theorem has_deriv_within_at_inv (x_ne_zero : x ≠ 0) (s : set 𝕜) :
has_deriv_within_at (λx, x⁻¹) (-(x^2)⁻¹) s x :=
(has_deriv_at_inv x_ne_zero).has_deriv_within_at
lemma differentiable_at_inv :
differentiable_at 𝕜 (λx, x⁻¹) x ↔ x ≠ 0:=
⟨λ H, normed_field.continuous_at_inv.1 H.continuous_at,
λ H, (has_deriv_at_inv H).differentiable_at⟩
lemma differentiable_within_at_inv (x_ne_zero : x ≠ 0) :
differentiable_within_at 𝕜 (λx, x⁻¹) s x :=
(differentiable_at_inv.2 x_ne_zero).differentiable_within_at
lemma differentiable_on_inv : differentiable_on 𝕜 (λx:𝕜, x⁻¹) {x | x ≠ 0} :=
λx hx, differentiable_within_at_inv hx
lemma deriv_inv : deriv (λx, x⁻¹) x = -(x^2)⁻¹ :=
begin
rcases eq_or_ne x 0 with rfl|hne,
{ simp [deriv_zero_of_not_differentiable_at (mt differentiable_at_inv.1 (not_not.2 rfl))] },
{ exact (has_deriv_at_inv hne).deriv }
end
@[simp] lemma deriv_inv' : deriv (λ x : 𝕜, x⁻¹) = λ x, -(x ^ 2)⁻¹ := funext (λ x, deriv_inv)
lemma deriv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, x⁻¹) s x = -(x^2)⁻¹ :=
begin
rw differentiable_at.deriv_within (differentiable_at_inv.2 x_ne_zero) hxs,
exact deriv_inv
end
lemma has_fderiv_at_inv (x_ne_zero : x ≠ 0) :
has_fderiv_at (λx, x⁻¹) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) x :=
has_deriv_at_inv x_ne_zero
lemma has_fderiv_within_at_inv (x_ne_zero : x ≠ 0) :
has_fderiv_within_at (λx, x⁻¹) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) s x :=
(has_fderiv_at_inv x_ne_zero).has_fderiv_within_at
lemma fderiv_inv :
fderiv 𝕜 (λx, x⁻¹) x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) :=
by rw [← deriv_fderiv, deriv_inv]
lemma fderiv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (λx, x⁻¹) s x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) :=
begin
rw differentiable_at.fderiv_within (differentiable_at_inv.2 x_ne_zero) hxs,
exact fderiv_inv
end
variables {c : 𝕜 → 𝕜} {h : E → 𝕜} {c' : 𝕜} {z : E} {S : set E}
lemma has_deriv_within_at.inv
(hc : has_deriv_within_at c c' s x) (hx : c x ≠ 0) :
has_deriv_within_at (λ y, (c y)⁻¹) (- c' / (c x)^2) s x :=
begin
convert (has_deriv_at_inv hx).comp_has_deriv_within_at x hc,
field_simp
end
lemma has_deriv_at.inv (hc : has_deriv_at c c' x) (hx : c x ≠ 0) :
has_deriv_at (λ y, (c y)⁻¹) (- c' / (c x)^2) x :=
begin
rw ← has_deriv_within_at_univ at *,
exact hc.inv hx
end
lemma differentiable_within_at.inv (hf : differentiable_within_at 𝕜 h S z) (hz : h z ≠ 0) :
differentiable_within_at 𝕜 (λx, (h x)⁻¹) S z :=
(differentiable_at_inv.mpr hz).comp_differentiable_within_at z hf
@[simp] lemma differentiable_at.inv (hf : differentiable_at 𝕜 h z) (hz : h z ≠ 0) :
differentiable_at 𝕜 (λx, (h x)⁻¹) z :=
(differentiable_at_inv.mpr hz).comp z hf
lemma differentiable_on.inv (hf : differentiable_on 𝕜 h S) (hz : ∀ x ∈ S, h x ≠ 0) :
differentiable_on 𝕜 (λx, (h x)⁻¹) S :=
λx h, (hf x h).inv (hz x h)
@[simp] lemma differentiable.inv (hf : differentiable 𝕜 h) (hz : ∀ x, h x ≠ 0) :
differentiable 𝕜 (λx, (h x)⁻¹) :=
λx, (hf x).inv (hz x)
lemma deriv_within_inv' (hc : differentiable_within_at 𝕜 c s x) (hx : c x ≠ 0)
(hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, (c x)⁻¹) s x = - (deriv_within c s x) / (c x)^2 :=
(hc.has_deriv_within_at.inv hx).deriv_within hxs
@[simp] lemma deriv_inv'' (hc : differentiable_at 𝕜 c x) (hx : c x ≠ 0) :
deriv (λx, (c x)⁻¹) x = - (deriv c x) / (c x)^2 :=
(hc.has_deriv_at.inv hx).deriv
end inverse
section division
/-! ### Derivative of `x ↦ c x / d x` -/
variables {𝕜' : Type*} [nontrivially_normed_field 𝕜'] [normed_algebra 𝕜 𝕜']
{c d : 𝕜 → 𝕜'} {c' d' : 𝕜'}
lemma has_deriv_within_at.div
(hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) (hx : d x ≠ 0) :
has_deriv_within_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) s x :=
begin
convert hc.mul ((has_deriv_at_inv hx).comp_has_deriv_within_at x hd),
{ simp only [div_eq_mul_inv] },
{ field_simp, ring }
end
lemma has_strict_deriv_at.div (hc : has_strict_deriv_at c c' x) (hd : has_strict_deriv_at d d' x)
(hx : d x ≠ 0) :
has_strict_deriv_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) x :=
begin
convert hc.mul ((has_strict_deriv_at_inv hx).comp x hd),
{ simp only [div_eq_mul_inv] },
{ field_simp, ring }
end
lemma has_deriv_at.div (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) (hx : d x ≠ 0) :
has_deriv_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) x :=
begin
rw ← has_deriv_within_at_univ at *,
exact hc.div hd hx
end
lemma differentiable_within_at.div
(hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) :
differentiable_within_at 𝕜 (λx, c x / d x) s x :=
((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).differentiable_within_at
@[simp] lemma differentiable_at.div
(hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) :
differentiable_at 𝕜 (λx, c x / d x) x :=
((hc.has_deriv_at).div (hd.has_deriv_at) hx).differentiable_at
lemma differentiable_on.div
(hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) (hx : ∀ x ∈ s, d x ≠ 0) :
differentiable_on 𝕜 (λx, c x / d x) s :=
λx h, (hc x h).div (hd x h) (hx x h)
@[simp] lemma differentiable.div
(hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) (hx : ∀ x, d x ≠ 0) :
differentiable 𝕜 (λx, c x / d x) :=
λx, (hc x).div (hd x) (hx x)
lemma deriv_within_div
(hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0)
(hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, c x / d x) s x
= ((deriv_within c s x) * d x - c x * (deriv_within d s x)) / (d x)^2 :=
((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).deriv_within hxs
@[simp] lemma deriv_div
(hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) :
deriv (λx, c x / d x) x = ((deriv c x) * d x - c x * (deriv d x)) / (d x)^2 :=
((hc.has_deriv_at).div (hd.has_deriv_at) hx).deriv
lemma has_deriv_at.div_const (hc : has_deriv_at c c' x) (d : 𝕜') :
has_deriv_at (λ x, c x / d) (c' / d) x :=
by simpa only [div_eq_mul_inv] using hc.mul_const d⁻¹
lemma has_deriv_within_at.div_const (hc : has_deriv_within_at c c' s x) (d : 𝕜') :
has_deriv_within_at (λ x, c x / d) (c' / d) s x :=
by simpa only [div_eq_mul_inv] using hc.mul_const d⁻¹
lemma has_strict_deriv_at.div_const (hc : has_strict_deriv_at c c' x) (d : 𝕜') :
has_strict_deriv_at (λ x, c x / d) (c' / d) x :=
by simpa only [div_eq_mul_inv] using hc.mul_const d⁻¹
lemma differentiable_within_at.div_const (hc : differentiable_within_at 𝕜 c s x) {d : 𝕜'} :
differentiable_within_at 𝕜 (λx, c x / d) s x :=
(hc.has_deriv_within_at.div_const _).differentiable_within_at
@[simp] lemma differentiable_at.div_const (hc : differentiable_at 𝕜 c x) {d : 𝕜'} :
differentiable_at 𝕜 (λ x, c x / d) x :=
(hc.has_deriv_at.div_const _).differentiable_at
lemma differentiable_on.div_const (hc : differentiable_on 𝕜 c s) {d : 𝕜'} :
differentiable_on 𝕜 (λx, c x / d) s :=
λ x hx, (hc x hx).div_const
@[simp] lemma differentiable.div_const (hc : differentiable 𝕜 c) {d : 𝕜'} :
differentiable 𝕜 (λx, c x / d) :=
λ x, (hc x).div_const
lemma deriv_within_div_const (hc : differentiable_within_at 𝕜 c s x) {d : 𝕜'}
(hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, c x / d) s x = (deriv_within c s x) / d :=
by simp [div_eq_inv_mul, deriv_within_const_mul, hc, hxs]
@[simp] lemma deriv_div_const (d : 𝕜') :
deriv (λx, c x / d) x = (deriv c x) / d :=
by simp only [div_eq_mul_inv, deriv_mul_const_field]
end division
section clm_comp_apply
/-! ### Derivative of the pointwise composition/application of continuous linear maps -/
open continuous_linear_map
variables {G : Type*} [normed_add_comm_group G] [normed_space 𝕜 G] {c : 𝕜 → F →L[𝕜] G}
{c' : F →L[𝕜] G} {d : 𝕜 → E →L[𝕜] F} {d' : E →L[𝕜] F} {u : 𝕜 → F} {u' : F}
lemma has_strict_deriv_at.clm_comp (hc : has_strict_deriv_at c c' x)
(hd : has_strict_deriv_at d d' x) :
has_strict_deriv_at (λ y, (c y).comp (d y)) (c'.comp (d x) + (c x).comp d') x :=
begin
have := (hc.has_strict_fderiv_at.clm_comp hd.has_strict_fderiv_at).has_strict_deriv_at,
rwa [add_apply, comp_apply, comp_apply, smul_right_apply, smul_right_apply, one_apply, one_smul,
one_smul, add_comm] at this,
end
lemma has_deriv_within_at.clm_comp (hc : has_deriv_within_at c c' s x)
(hd : has_deriv_within_at d d' s x) :
has_deriv_within_at (λ y, (c y).comp (d y)) (c'.comp (d x) + (c x).comp d') s x :=
begin
have := (hc.has_fderiv_within_at.clm_comp hd.has_fderiv_within_at).has_deriv_within_at,
rwa [add_apply, comp_apply, comp_apply, smul_right_apply, smul_right_apply, one_apply, one_smul,
one_smul, add_comm] at this,
end
lemma has_deriv_at.clm_comp (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) :
has_deriv_at (λ y, (c y).comp (d y))
(c'.comp (d x) + (c x).comp d') x :=
begin
rw [← has_deriv_within_at_univ] at *,
exact hc.clm_comp hd
end
lemma deriv_within_clm_comp (hc : differentiable_within_at 𝕜 c s x)
(hd : differentiable_within_at 𝕜 d s x) (hxs : unique_diff_within_at 𝕜 s x):
deriv_within (λ y, (c y).comp (d y)) s x =
((deriv_within c s x).comp (d x) + (c x).comp (deriv_within d s x)) :=
(hc.has_deriv_within_at.clm_comp hd.has_deriv_within_at).deriv_within hxs
lemma deriv_clm_comp (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) :
deriv (λ y, (c y).comp (d y)) x =
((deriv c x).comp (d x) + (c x).comp (deriv d x)) :=
(hc.has_deriv_at.clm_comp hd.has_deriv_at).deriv
lemma has_strict_deriv_at.clm_apply (hc : has_strict_deriv_at c c' x)
(hu : has_strict_deriv_at u u' x) :
has_strict_deriv_at (λ y, (c y) (u y)) (c' (u x) + c x u') x :=
begin
have := (hc.has_strict_fderiv_at.clm_apply hu.has_strict_fderiv_at).has_strict_deriv_at,
rwa [add_apply, comp_apply, flip_apply, smul_right_apply, smul_right_apply, one_apply, one_smul,
one_smul, add_comm] at this,
end
lemma has_deriv_within_at.clm_apply (hc : has_deriv_within_at c c' s x)
(hu : has_deriv_within_at u u' s x) :
has_deriv_within_at (λ y, (c y) (u y)) (c' (u x) + c x u') s x :=
begin
have := (hc.has_fderiv_within_at.clm_apply hu.has_fderiv_within_at).has_deriv_within_at,
rwa [add_apply, comp_apply, flip_apply, smul_right_apply, smul_right_apply, one_apply, one_smul,
one_smul, add_comm] at this,
end
lemma has_deriv_at.clm_apply (hc : has_deriv_at c c' x) (hu : has_deriv_at u u' x) :
has_deriv_at (λ y, (c y) (u y)) (c' (u x) + c x u') x :=
begin
have := (hc.has_fderiv_at.clm_apply hu.has_fderiv_at).has_deriv_at,
rwa [add_apply, comp_apply, flip_apply, smul_right_apply, smul_right_apply, one_apply, one_smul,
one_smul, add_comm] at this,
end
lemma deriv_within_clm_apply (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (hu : differentiable_within_at 𝕜 u s x) :
deriv_within (λ y, (c y) (u y)) s x = (deriv_within c s x (u x) + c x (deriv_within u s x)) :=
(hc.has_deriv_within_at.clm_apply hu.has_deriv_within_at).deriv_within hxs
lemma deriv_clm_apply (hc : differentiable_at 𝕜 c x) (hu : differentiable_at 𝕜 u x) :
deriv (λ y, (c y) (u y)) x = (deriv c x (u x) + c x (deriv u x)) :=
(hc.has_deriv_at.clm_apply hu.has_deriv_at).deriv
end clm_comp_apply
theorem has_strict_deriv_at.has_strict_fderiv_at_equiv {f : 𝕜 → 𝕜} {f' x : 𝕜}
(hf : has_strict_deriv_at f f' x) (hf' : f' ≠ 0) :
has_strict_fderiv_at f
(continuous_linear_equiv.units_equiv_aut 𝕜 (units.mk0 f' hf') : 𝕜 →L[𝕜] 𝕜) x :=
hf
theorem has_deriv_at.has_fderiv_at_equiv {f : 𝕜 → 𝕜} {f' x : 𝕜} (hf : has_deriv_at f f' x)
(hf' : f' ≠ 0) :
has_fderiv_at f (continuous_linear_equiv.units_equiv_aut 𝕜 (units.mk0 f' hf') : 𝕜 →L[𝕜] 𝕜) x :=
hf
/-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an
invertible derivative `f'` at `g a` in the strict sense, then `g` has the derivative `f'⁻¹` at `a`
in the strict sense.
This is one of the easy parts of the inverse function theorem: it assumes that we already have an
inverse function. -/
theorem has_strict_deriv_at.of_local_left_inverse {f g : 𝕜 → 𝕜} {f' a : 𝕜}
(hg : continuous_at g a) (hf : has_strict_deriv_at f f' (g a)) (hf' : f' ≠ 0)
(hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) :
has_strict_deriv_at g f'⁻¹ a :=
(hf.has_strict_fderiv_at_equiv hf').of_local_left_inverse hg hfg
/-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has a
nonzero derivative `f'` at `f.symm a` in the strict sense, then `f.symm` has the derivative `f'⁻¹`
at `a` in the strict sense.
This is one of the easy parts of the inverse function theorem: it assumes that we already have
an inverse function. -/
lemma local_homeomorph.has_strict_deriv_at_symm (f : local_homeomorph 𝕜 𝕜) {a f' : 𝕜}
(ha : a ∈ f.target) (hf' : f' ≠ 0) (htff' : has_strict_deriv_at f f' (f.symm a)) :
has_strict_deriv_at f.symm f'⁻¹ a :=
htff'.of_local_left_inverse (f.symm.continuous_at ha) hf' (f.eventually_right_inverse ha)
/-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an
invertible derivative `f'` at `g a`, then `g` has the derivative `f'⁻¹` at `a`.
This is one of the easy parts of the inverse function theorem: it assumes that we already have
an inverse function. -/
theorem has_deriv_at.of_local_left_inverse {f g : 𝕜 → 𝕜} {f' a : 𝕜}
(hg : continuous_at g a) (hf : has_deriv_at f f' (g a)) (hf' : f' ≠ 0)
(hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) :
has_deriv_at g f'⁻¹ a :=
(hf.has_fderiv_at_equiv hf').of_local_left_inverse hg hfg
/-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has an
nonzero derivative `f'` at `f.symm a`, then `f.symm` has the derivative `f'⁻¹` at `a`.
This is one of the easy parts of the inverse function theorem: it assumes that we already have
an inverse function. -/
lemma local_homeomorph.has_deriv_at_symm (f : local_homeomorph 𝕜 𝕜) {a f' : 𝕜}
(ha : a ∈ f.target) (hf' : f' ≠ 0) (htff' : has_deriv_at f f' (f.symm a)) :
has_deriv_at f.symm f'⁻¹ a :=
htff'.of_local_left_inverse (f.symm.continuous_at ha) hf' (f.eventually_right_inverse ha)
lemma has_deriv_at.eventually_ne (h : has_deriv_at f f' x) (hf' : f' ≠ 0) :
∀ᶠ z in 𝓝[≠] x, f z ≠ f x :=
(has_deriv_at_iff_has_fderiv_at.1 h).eventually_ne
⟨‖f'‖⁻¹, λ z, by field_simp [norm_smul, mt norm_eq_zero.1 hf']⟩
lemma has_deriv_at.tendsto_punctured_nhds (h : has_deriv_at f f' x) (hf' : f' ≠ 0) :
tendsto f (𝓝[≠] x) (𝓝[≠] (f x)) :=
tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _
h.continuous_at.continuous_within_at (h.eventually_ne hf')
theorem not_differentiable_within_at_of_local_left_inverse_has_deriv_within_at_zero
{f g : 𝕜 → 𝕜} {a : 𝕜} {s t : set 𝕜} (ha : a ∈ s) (hsu : unique_diff_within_at 𝕜 s a)
(hf : has_deriv_within_at f 0 t (g a)) (hst : maps_to g s t) (hfg : f ∘ g =ᶠ[𝓝[s] a] id) :
¬differentiable_within_at 𝕜 g s a :=
begin
intro hg,
have := (hf.comp a hg.has_deriv_within_at hst).congr_of_eventually_eq_of_mem hfg.symm ha,
simpa using hsu.eq_deriv _ this (has_deriv_within_at_id _ _)
end
theorem not_differentiable_at_of_local_left_inverse_has_deriv_at_zero
{f g : 𝕜 → 𝕜} {a : 𝕜} (hf : has_deriv_at f 0 (g a)) (hfg : f ∘ g =ᶠ[𝓝 a] id) :
¬differentiable_at 𝕜 g a :=
begin
intro hg,
have := (hf.comp a hg.has_deriv_at).congr_of_eventually_eq hfg.symm,
simpa using this.unique (has_deriv_at_id a)
end
end
namespace polynomial
/-! ### Derivative of a polynomial -/
variables {x : 𝕜} {s : set 𝕜}
variable (p : 𝕜[X])
/-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/
protected lemma has_strict_deriv_at (x : 𝕜) :
has_strict_deriv_at (λx, p.eval x) (p.derivative.eval x) x :=
begin
apply p.induction_on,
{ simp [has_strict_deriv_at_const] },
{ assume p q hp hq,
convert hp.add hq;
simp },
{ assume n a h,
convert h.mul (has_strict_deriv_at_id x),
{ ext y, simp [pow_add, mul_assoc] },
{ simp only [pow_add, pow_one, derivative_mul, derivative_C, zero_mul, derivative_X_pow,
derivative_X, mul_one, zero_add, eval_mul, eval_C, eval_add, eval_nat_cast, eval_pow, eval_X,
id.def], ring } }
end
/-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/
protected lemma has_deriv_at (x : 𝕜) : has_deriv_at (λx, p.eval x) (p.derivative.eval x) x :=
(p.has_strict_deriv_at x).has_deriv_at
protected theorem has_deriv_within_at (x : 𝕜) (s : set 𝕜) :
has_deriv_within_at (λx, p.eval x) (p.derivative.eval x) s x :=
(p.has_deriv_at x).has_deriv_within_at
protected lemma differentiable_at : differentiable_at 𝕜 (λx, p.eval x) x :=
(p.has_deriv_at x).differentiable_at
protected lemma differentiable_within_at : differentiable_within_at 𝕜 (λx, p.eval x) s x :=
p.differentiable_at.differentiable_within_at
protected lemma differentiable : differentiable 𝕜 (λx, p.eval x) :=
λx, p.differentiable_at
protected lemma differentiable_on : differentiable_on 𝕜 (λx, p.eval x) s :=
p.differentiable.differentiable_on
@[simp] protected lemma deriv : deriv (λx, p.eval x) x = p.derivative.eval x :=
(p.has_deriv_at x).deriv
protected lemma deriv_within (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, p.eval x) s x = p.derivative.eval x :=
begin
rw differentiable_at.deriv_within p.differentiable_at hxs,
exact p.deriv
end
protected lemma has_fderiv_at (x : 𝕜) :
has_fderiv_at (λx, p.eval x) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (p.derivative.eval x)) x :=
p.has_deriv_at x
protected lemma has_fderiv_within_at (x : 𝕜) :
has_fderiv_within_at (λx, p.eval x) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (p.derivative.eval x)) s x :=
(p.has_fderiv_at x).has_fderiv_within_at
@[simp] protected lemma fderiv :
fderiv 𝕜 (λx, p.eval x) x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (p.derivative.eval x) :=
(p.has_fderiv_at x).fderiv
protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (λx, p.eval x) s x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (p.derivative.eval x) :=
(p.has_fderiv_within_at x).fderiv_within hxs
end polynomial
section pow
/-! ### Derivative of `x ↦ x^n` for `n : ℕ` -/
variables {x : 𝕜} {s : set 𝕜} {c : 𝕜 → 𝕜} {c' : 𝕜}
variable (n : ℕ)
lemma has_strict_deriv_at_pow (n : ℕ) (x : 𝕜) :
has_strict_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x :=
begin
convert (polynomial.C (1 : 𝕜) * (polynomial.X)^n).has_strict_deriv_at x,
{ simp },
{ rw [polynomial.derivative_C_mul_X_pow], simp }
end
lemma has_deriv_at_pow (n : ℕ) (x : 𝕜) : has_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x :=
(has_strict_deriv_at_pow n x).has_deriv_at
theorem has_deriv_within_at_pow (n : ℕ) (x : 𝕜) (s : set 𝕜) :
has_deriv_within_at (λx, x^n) ((n : 𝕜) * x^(n-1)) s x :=
(has_deriv_at_pow n x).has_deriv_within_at
lemma differentiable_at_pow : differentiable_at 𝕜 (λx, x^n) x :=
(has_deriv_at_pow n x).differentiable_at
lemma differentiable_within_at_pow : differentiable_within_at 𝕜 (λx, x^n) s x :=
(differentiable_at_pow n).differentiable_within_at
lemma differentiable_pow : differentiable 𝕜 (λx:𝕜, x^n) :=
λ x, differentiable_at_pow n
lemma differentiable_on_pow : differentiable_on 𝕜 (λx, x^n) s :=
(differentiable_pow n).differentiable_on
lemma deriv_pow : deriv (λ x, x^n) x = (n : 𝕜) * x^(n-1) :=
(has_deriv_at_pow n x).deriv
@[simp] lemma deriv_pow' : deriv (λ x, x^n) = λ x, (n : 𝕜) * x^(n-1) :=
funext $ λ x, deriv_pow n
lemma deriv_within_pow (hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, x^n) s x = (n : 𝕜) * x^(n-1) :=
(has_deriv_within_at_pow n x s).deriv_within hxs
lemma has_deriv_within_at.pow (hc : has_deriv_within_at c c' s x) :
has_deriv_within_at (λ y, (c y)^n) ((n : 𝕜) * (c x)^(n-1) * c') s x :=
(has_deriv_at_pow n (c x)).comp_has_deriv_within_at x hc
lemma has_deriv_at.pow (hc : has_deriv_at c c' x) :
has_deriv_at (λ y, (c y)^n) ((n : 𝕜) * (c x)^(n-1) * c') x :=
by { rw ← has_deriv_within_at_univ at *, exact hc.pow n }
lemma deriv_within_pow' (hc : differentiable_within_at 𝕜 c s x)
(hxs : unique_diff_within_at 𝕜 s x) :
deriv_within (λx, (c x)^n) s x = (n : 𝕜) * (c x)^(n-1) * (deriv_within c s x) :=
(hc.has_deriv_within_at.pow n).deriv_within hxs
@[simp] lemma deriv_pow'' (hc : differentiable_at 𝕜 c x) :
deriv (λx, (c x)^n) x = (n : 𝕜) * (c x)^(n-1) * (deriv c x) :=
(hc.has_deriv_at.pow n).deriv
end pow
section zpow
/-! ### Derivative of `x ↦ x^m` for `m : ℤ` -/
variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] {x : 𝕜} {s : set 𝕜} {m : ℤ}
lemma has_strict_deriv_at_zpow (m : ℤ) (x : 𝕜) (h : x ≠ 0 ∨ 0 ≤ m) :
has_strict_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x :=
begin
have : ∀ m : ℤ, 0 < m → has_strict_deriv_at (λx, x^m) ((m:𝕜) * x^(m-1)) x,
{ assume m hm,
lift m to ℕ using (le_of_lt hm),
simp only [zpow_coe_nat, int.cast_coe_nat],
convert has_strict_deriv_at_pow _ _ using 2,
rw [← int.coe_nat_one, ← int.coe_nat_sub, zpow_coe_nat],
norm_cast at hm,
exact nat.succ_le_of_lt hm },
rcases lt_trichotomy m 0 with hm|hm|hm,
{ have hx : x ≠ 0, from h.resolve_right hm.not_le,
have := (has_strict_deriv_at_inv _).scomp _ (this (-m) (neg_pos.2 hm));
[skip, exact zpow_ne_zero_of_ne_zero hx _],
simp only [(∘), zpow_neg, one_div, inv_inv, smul_eq_mul] at this,
convert this using 1,
rw [sq, mul_inv, inv_inv, int.cast_neg, neg_mul, neg_mul_neg,
← zpow_add₀ hx, mul_assoc, ← zpow_add₀ hx], congr, abel },
{ simp only [hm, zpow_zero, int.cast_zero, zero_mul, has_strict_deriv_at_const] },
{ exact this m hm }
end
lemma has_deriv_at_zpow (m : ℤ) (x : 𝕜) (h : x ≠ 0 ∨ 0 ≤ m) :
has_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x :=
(has_strict_deriv_at_zpow m x h).has_deriv_at
theorem has_deriv_within_at_zpow (m : ℤ) (x : 𝕜) (h : x ≠ 0 ∨ 0 ≤ m) (s : set 𝕜) :
has_deriv_within_at (λx, x^m) ((m : 𝕜) * x^(m-1)) s x :=
(has_deriv_at_zpow m x h).has_deriv_within_at
lemma differentiable_at_zpow : differentiable_at 𝕜 (λx, x^m) x ↔ x ≠ 0 ∨ 0 ≤ m :=
⟨λ H, normed_field.continuous_at_zpow.1 H.continuous_at,
λ H, (has_deriv_at_zpow m x H).differentiable_at⟩
lemma differentiable_within_at_zpow (m : ℤ) (x : 𝕜) (h : x ≠ 0 ∨ 0 ≤ m) :
differentiable_within_at 𝕜 (λx, x^m) s x :=
(differentiable_at_zpow.mpr h).differentiable_within_at
lemma differentiable_on_zpow (m : ℤ) (s : set 𝕜) (h : (0 : 𝕜) ∉ s ∨ 0 ≤ m) :
differentiable_on 𝕜 (λx, x^m) s :=
λ x hxs, differentiable_within_at_zpow m x $ h.imp_left $ ne_of_mem_of_not_mem hxs
lemma deriv_zpow (m : ℤ) (x : 𝕜) : deriv (λ x, x ^ m) x = m * x ^ (m - 1) :=
begin
by_cases H : x ≠ 0 ∨ 0 ≤ m,
{ exact (has_deriv_at_zpow m x H).deriv },
{ rw deriv_zero_of_not_differentiable_at (mt differentiable_at_zpow.1 H),
push_neg at H, rcases H with ⟨rfl, hm⟩,
rw [zero_zpow _ ((sub_one_lt _).trans hm).ne, mul_zero] }
end
@[simp] lemma deriv_zpow' (m : ℤ) : deriv (λ x : 𝕜, x ^ m) = λ x, m * x ^ (m - 1) :=
funext $ deriv_zpow m
lemma deriv_within_zpow (hxs : unique_diff_within_at 𝕜 s x) (h : x ≠ 0 ∨ 0 ≤ m) :
deriv_within (λx, x^m) s x = (m : 𝕜) * x^(m-1) :=
(has_deriv_within_at_zpow m x h s).deriv_within hxs
@[simp] lemma iter_deriv_zpow' (m : ℤ) (k : ℕ) :
deriv^[k] (λ x : 𝕜, x ^ m) = λ x, (∏ i in finset.range k, (m - i)) * x ^ (m - k) :=
begin
induction k with k ihk,
{ simp only [one_mul, int.coe_nat_zero, id, sub_zero, finset.prod_range_zero,
function.iterate_zero] },
{ simp only [function.iterate_succ_apply', ihk, deriv_const_mul_field', deriv_zpow',
finset.prod_range_succ, int.coe_nat_succ, ← sub_sub, int.cast_sub, int.cast_coe_nat,
mul_assoc], }
end
lemma iter_deriv_zpow (m : ℤ) (x : 𝕜) (k : ℕ) :
deriv^[k] (λ y, y ^ m) x = (∏ i in finset.range k, (m - i)) * x ^ (m - k) :=
congr_fun (iter_deriv_zpow' m k) x
lemma iter_deriv_pow (n : ℕ) (x : 𝕜) (k : ℕ) :
deriv^[k] (λx:𝕜, x^n) x = (∏ i in finset.range k, (n - i)) * x^(n-k) :=
begin
simp only [← zpow_coe_nat, iter_deriv_zpow, int.cast_coe_nat],
cases le_or_lt k n with hkn hnk,
{ rw int.coe_nat_sub hkn },
{ have : ∏ i in finset.range k, (n - i : 𝕜) = 0,
from finset.prod_eq_zero (finset.mem_range.2 hnk) (sub_self _),
simp only [this, zero_mul] }
end
@[simp] lemma iter_deriv_pow' (n k : ℕ) :
deriv^[k] (λ x : 𝕜, x ^ n) = λ x, (∏ i in finset.range k, (n - i)) * x ^ (n - k) :=
funext $ λ x, iter_deriv_pow n x k
lemma iter_deriv_inv (k : ℕ) (x : 𝕜) :
deriv^[k] has_inv.inv x = (∏ i in finset.range k, (-1 - i)) * x ^ (-1 - k : ℤ) :=
by simpa only [zpow_neg_one, int.cast_neg, int.cast_one] using iter_deriv_zpow (-1) x k
@[simp] lemma iter_deriv_inv' (k : ℕ) :
deriv^[k] has_inv.inv = λ x : 𝕜, (∏ i in finset.range k, (-1 - i)) * x ^ (-1 - k : ℤ) :=
funext (iter_deriv_inv k)
variables {f : E → 𝕜} {t : set E} {a : E}
lemma differentiable_within_at.zpow (hf : differentiable_within_at 𝕜 f t a) (h : f a ≠ 0 ∨ 0 ≤ m) :
differentiable_within_at 𝕜 (λ x, f x ^ m) t a :=
(differentiable_at_zpow.2 h).comp_differentiable_within_at a hf
lemma differentiable_at.zpow (hf : differentiable_at 𝕜 f a) (h : f a ≠ 0 ∨ 0 ≤ m) :
differentiable_at 𝕜 (λ x, f x ^ m) a :=
(differentiable_at_zpow.2 h).comp a hf
lemma differentiable_on.zpow (hf : differentiable_on 𝕜 f t) (h : (∀ x ∈ t, f x ≠ 0) ∨ 0 ≤ m) :
differentiable_on 𝕜 (λ x, f x ^ m) t :=
λ x hx, (hf x hx).zpow $ h.imp_left (λ h, h x hx)
lemma differentiable.zpow (hf : differentiable 𝕜 f) (h : (∀ x, f x ≠ 0) ∨ 0 ≤ m) :
differentiable 𝕜 (λ x, f x ^ m) :=
λ x, (hf x).zpow $ h.imp_left (λ h, h x)
end zpow
/-! ### Support of derivatives -/
section support
open function
variables {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] {f : 𝕜 → F}
lemma support_deriv_subset : support (deriv f) ⊆ tsupport f :=
begin
intros x,
rw [← not_imp_not],
intro h2x,
rw [not_mem_tsupport_iff_eventually_eq] at h2x,
exact nmem_support.mpr (h2x.deriv_eq.trans (deriv_const x 0))
end
lemma has_compact_support.deriv (hf : has_compact_support f) : has_compact_support (deriv f) :=
hf.mono' support_deriv_subset
end support
/-! ### Upper estimates on liminf and limsup -/
section real
variables {f : ℝ → ℝ} {f' : ℝ} {s : set ℝ} {x : ℝ} {r : ℝ}
lemma has_deriv_within_at.limsup_slope_le (hf : has_deriv_within_at f f' s x) (hr : f' < r) :
∀ᶠ z in 𝓝[s \ {x}] x, slope f x z < r :=
has_deriv_within_at_iff_tendsto_slope.1 hf (is_open.mem_nhds is_open_Iio hr)
lemma has_deriv_within_at.limsup_slope_le' (hf : has_deriv_within_at f f' s x)
(hs : x ∉ s) (hr : f' < r) :
∀ᶠ z in 𝓝[s] x, slope f x z < r :=
(has_deriv_within_at_iff_tendsto_slope' hs).1 hf (is_open.mem_nhds is_open_Iio hr)
lemma has_deriv_within_at.liminf_right_slope_le
(hf : has_deriv_within_at f f' (Ici x) x) (hr : f' < r) :
∃ᶠ z in 𝓝[>] x, slope f x z < r :=
(hf.Ioi_of_Ici.limsup_slope_le' (lt_irrefl x) hr).frequently
end real
section real_space
open metric
variables {E : Type u} [normed_add_comm_group E] [normed_space ℝ E] {f : ℝ → E} {f' : E} {s : set ℝ}
{x r : ℝ}
/-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ‖f'‖` the ratio
`‖f z - f x‖ / ‖z - x‖` is less than `r` in some neighborhood of `x` within `s`.
In other words, the limit superior of this ratio as `z` tends to `x` along `s`
is less than or equal to `‖f'‖`. -/
lemma has_deriv_within_at.limsup_norm_slope_le
(hf : has_deriv_within_at f f' s x) (hr : ‖f'‖ < r) :
∀ᶠ z in 𝓝[s] x, ‖z - x‖⁻¹ * ‖f z - f x‖ < r :=
begin
have hr₀ : 0 < r, from lt_of_le_of_lt (norm_nonneg f') hr,
have A : ∀ᶠ z in 𝓝[s \ {x}] x, ‖(z - x)⁻¹ • (f z - f x)‖ ∈ Iio r,
from (has_deriv_within_at_iff_tendsto_slope.1 hf).norm (is_open.mem_nhds is_open_Iio hr),
have B : ∀ᶠ z in 𝓝[{x}] x, ‖(z - x)⁻¹ • (f z - f x)‖ ∈ Iio r,
from mem_of_superset self_mem_nhds_within
(singleton_subset_iff.2 $ by simp [hr₀]),
have C := mem_sup.2 ⟨A, B⟩,
rw [← nhds_within_union, diff_union_self, nhds_within_union, mem_sup] at C,
filter_upwards [C.1],
simp only [norm_smul, mem_Iio, norm_inv],
exact λ _, id
end
/-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ‖f'‖` the ratio
`(‖f z‖ - ‖f x‖) / ‖z - x‖` is less than `r` in some neighborhood of `x` within `s`.
In other words, the limit superior of this ratio as `z` tends to `x` along `s`
is less than or equal to `‖f'‖`.
This lemma is a weaker version of `has_deriv_within_at.limsup_norm_slope_le`
where `‖f z‖ - ‖f x‖` is replaced by `‖f z - f x‖`. -/
lemma has_deriv_within_at.limsup_slope_norm_le
(hf : has_deriv_within_at f f' s x) (hr : ‖f'‖ < r) :
∀ᶠ z in 𝓝[s] x, ‖z - x‖⁻¹ * (‖f z‖ - ‖f x‖) < r :=
begin
apply (hf.limsup_norm_slope_le hr).mono,
assume z hz,
refine lt_of_le_of_lt (mul_le_mul_of_nonneg_left (norm_sub_norm_le _ _) _) hz,
exact inv_nonneg.2 (norm_nonneg _)
end
/-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ‖f'‖` the ratio
`‖f z - f x‖ / ‖z - x‖` is frequently less than `r` as `z → x+0`.
In other words, the limit inferior of this ratio as `z` tends to `x+0`
is less than or equal to `‖f'‖`. See also `has_deriv_within_at.limsup_norm_slope_le`
for a stronger version using limit superior and any set `s`. -/
lemma has_deriv_within_at.liminf_right_norm_slope_le
(hf : has_deriv_within_at f f' (Ici x) x) (hr : ‖f'‖ < r) :
∃ᶠ z in 𝓝[>] x, ‖z - x‖⁻¹ * ‖f z - f x‖ < r :=
(hf.Ioi_of_Ici.limsup_norm_slope_le hr).frequently
/-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ‖f'‖` the ratio
`(‖f z‖ - ‖f x‖) / (z - x)` is frequently less than `r` as `z → x+0`.
In other words, the limit inferior of this ratio as `z` tends to `x+0`
is less than or equal to `‖f'‖`.
See also
* `has_deriv_within_at.limsup_norm_slope_le` for a stronger version using
limit superior and any set `s`;
* `has_deriv_within_at.liminf_right_norm_slope_le` for a stronger version using
`‖f z - f x‖` instead of `‖f z‖ - ‖f x‖`. -/
lemma has_deriv_within_at.liminf_right_slope_norm_le
(hf : has_deriv_within_at f f' (Ici x) x) (hr : ‖f'‖ < r) :
∃ᶠ z in 𝓝[>] x, (z - x)⁻¹ * (‖f z‖ - ‖f x‖) < r :=
begin
have := (hf.Ioi_of_Ici.limsup_slope_norm_le hr).frequently,
refine this.mp (eventually.mono self_mem_nhds_within _),
assume z hxz hz,
rwa [real.norm_eq_abs, abs_of_pos (sub_pos_of_lt hxz)] at hz
end
end real_space
|
bfdb3480fabffcdeea5e0f43a0cfb5454785cc40 | d8f6c47921aa2f4f02b5272d2ed9c99f396d3858 | /lean/src/jit.lean | 80a0efad5161e50ea45a574e9eb1471676c734c3 | [] | no_license | hongyunnchen/jitterbug | cc94e01483cdb36f9007ab978f174e5df9a65fd2 | eb5d50ef17f78c430f9033ff18472972b3588aee | refs/heads/master | 1,670,909,198,044 | 1,599,154,934,000 | 1,599,154,934,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 19,472 | lean |
import tactic.tauto
/-!
This file contains the metatheory of JIT correctness.
The main theorems are forward_simulation and backward_simulation, proved based
on the following two sets of axioms.
Three axioms are assumed to be correct (e.g., ensured by the Linux kernel):
* wf_terminates: a program that passes the checker terminates.
* wf_safe: a program that passes the checker is safe.
* emit_correct: the output of the JIT contains the output of individual parts.
Three axioms about the correctness of individal parts of the JIT are expected
to be proved separately in SMT:
* prologue_correct: running the emitted prologue from the initial target state
reaches a target state that relates to the initial source state.
* per_insn_correct: running the emitted target code preserves the relation
between source and target states and produces the same trace.
* epilogue_correct: running the emitted epilogue from a target state that
relates to the final source state reaches the final target state.
## References
* Xavier Leroy. A formally verified compiler back-end. Journal of Automated
Reasoning, 43(4):363--446, December 2009.
-/
namespace machine
section machine
parameters {EVENT NONDET INPUT RESULT PC STATE INSN : Type}
-- A trace is a list of externally visible events.
def TRACE : Type := list EVENT
instance : has_append TRACE := ⟨list.append⟩
-- Get program counter of machine.
parameter pc_of : STATE → PC
-- Step a given instruction, producing new state and trace.
parameter step_insn : NONDET → INSN → STATE → (STATE × TRACE)
-- This mimics the final state.
parameter result_of : STATE → option RESULT
-- Code is a partial map from PC to instruction. We intentionally avoid
-- using a list and favor this more abstract representation.
def CODE : Type := PC → option INSN
-- Step from code[pc]. Yields none if no instruction at PC.
-- does nothing if state already final.
def step (oracle : NONDET) (code : CODE) (s : STATE) : option (STATE × TRACE) :=
match result_of s with
| none :=
match code (pc_of s) with
| none := none
| some insn := some (step_insn oracle insn s)
end
| some _ := some (s, [])
end
-- A standard way to define reachable states.
inductive star (oracle : NONDET) (code : CODE) : STATE → STATE → TRACE → Prop
| refl :
∀ (a : STATE),
star a a []
| step :
∀ (a b c : STATE) (tr₁ tr₂ : TRACE),
step oracle code a = some (b, tr₁) →
star b c tr₂ →
star a c (tr₁ ++ tr₂)
-- If you can take one step, you can show star.
lemma star_one :
∀ (oracle : NONDET) (code : CODE) (a b : STATE) (tr : TRACE),
step oracle code a = some (b, tr) →
star oracle code a b tr :=
begin
intros,
rw ← list.append_nil tr,
constructor,
{ assumption },
{ constructor }
end
-- Star is transitive for fixed code and appending traces.
lemma star_trans :
∀ (oracle : NONDET) (code : CODE) (a b : STATE) (tr₁ : TRACE),
star oracle code a b tr₁ →
∀ (c : STATE) (tr₂ : TRACE),
star oracle code b c tr₂ →
star oracle code a c (tr₁ ++ tr₂) :=
begin
intros oracle code _ _ _ Hab,
induction Hab with _ _ _ _ _ _ _ _ Hab_ih; intros; simp,
{ assumption },
{ constructor,
{ assumption },
{ apply Hab_ih,
assumption } }
end
-- c1 is a subset of c2 if any instruction c1 has is also in c2.
def subset (c1 c2 : CODE) : Prop :=
∀ (idx : PC) (insn : INSN),
c1 idx = some insn →
c2 idx = some insn
local infix ` <+ ` := subset
lemma step_subset :
∀ (oracle : NONDET) (code₁ code₂ : CODE) (s1 s2 : STATE) (tr : TRACE),
step oracle code₁ s1 = some (s2, tr) →
code₁ <+ code₂ →
step oracle code₂ s1 = some (s2, tr) :=
begin
intros _ _ _ _ _ _ H1 H2,
simp [step, subset] at *,
cases A : (result_of s1); rw A at *; rw ← H1;
dsimp [step._match_1]; refl <|> skip,
cases h : (code₁ (pc_of s1)) with insn,
case option.none {
dsimp [step._match_1] at H1,
rw h at H1,
contradiction,
},
case option.some {
specialize H2 (pc_of s1) insn h,
rewrite H2,
},
end
-- If you can star given some code, you can always
-- add more code and preserve star.
lemma star_subset :
∀ (oracle : NONDET) (code₁ code₂ : CODE) (s1 s2 : STATE) (tr : TRACE),
star oracle code₁ s1 s2 tr →
code₁ <+ code₂ →
star oracle code₂ s1 s2 tr :=
begin
intros _ _ _ _ _ _ H1 _,
induction H1,
{ apply star.refl, },
econstructor,
{ apply step_subset, all_goals {assumption}, },
assumption,
end
lemma final_step :
∀ (oracle : NONDET) (s : STATE) (c : CODE) (r : RESULT),
result_of s = some r →
∀ (s' : STATE) (tr : TRACE),
step oracle c s = some (s', tr) →
tr = [] ∧ s' = s :=
begin
intros _ _ _ _ h1 _ _ h2,
simp [step] at h2,
rw h1 at h2,
simp [step._match_1] at h2,
split; cc,
end
lemma final_star :
∀ (oracle : NONDET) (s : STATE) (c : CODE) (r : RESULT),
result_of s = some r →
∀ (s' : STATE) (tr : TRACE),
star oracle c s s' tr →
tr = [] ∧ s' = s :=
begin
intros _ _ _ _ h1 _ _ h2,
induction h2 with s2 s1 s2 s3 tr1 tr2 h3 h4 IH, cc,
have : tr1 = [] ∧ s2 = s1,
by { apply final_step; assumption <|> skip, from h1 },
cases this, subst this_left, subst this_right, simp, cc,
end
end machine
end machine
-- Re-declare infix notation outside of machine scope.
local infix ` <+ ` := machine.subset
constants EVENT NONDET INPUT RESULT : Type
def TRACE : Type := @machine.TRACE EVENT
noncomputable instance : has_append TRACE := ⟨list.append⟩
-- This models the behavior of the source language.
namespace source
constants INSN PC STATE : Type
constant pc_of : STATE → PC
constant step_insn : NONDET → INSN → STATE → (STATE × TRACE)
constant result_of : STATE → option RESULT
def CODE : Type := @machine.CODE PC INSN
noncomputable def step := machine.step pc_of step_insn result_of
definition star := machine.star pc_of step_insn result_of
-- Initial state of a source program.
constant init_state : INPUT → STATE
-- A safe state can always fetch an instruction from any reachable state.
def safe (oracle : NONDET) (code : CODE) (s1 : STATE) : Prop :=
∀ s2 tr,
star oracle code s1 s2 tr →
∃ insn, code (pc_of s2) = some insn
-- This captures the guarantees of the checker: a well-formed program passes
-- the checker.
constant wf : CODE → Prop
-- A well-formed program terminates.
--
-- This is assumed to hold.
axiom wf_terminates :
∀ (oracle : NONDET) (i : INPUT) (code : CODE),
wf code →
∃ (s' : STATE) (tr : TRACE) (res : RESULT),
star oracle code (init_state i) s' tr ∧
result_of s' = some res
-- A well-formed program is safe from the initial state.
--
-- This is assumed to hold.
axiom wf_safe :
∀ (code : CODE) (i : INPUT),
wf code →
∀ (oracle : NONDET),
safe oracle code (init_state i)
-- A safe state can always take a step.
lemma safe_self :
∀ (oracle : NONDET) (code : CODE) (s : STATE),
safe oracle code s →
∃ (insn : INSN),
code (pc_of s) = some insn :=
begin
intros _ _ _ H1,
unfold safe at *,
apply H1, constructor,
end
-- A safe state is still safe after one step.
lemma safe_step :
∀ (oracle : NONDET) (code : CODE) (s₁ s₂ : STATE) (tr : TRACE),
safe oracle code s₁ →
step oracle code s₁ = some (s₂, tr) →
safe oracle code s₂ :=
begin
intros _ _ _ _ _ H1 _,
simp [safe] at *,
intros _ _ _,
specialize H1 _ (tr ++ tr_1),
apply H1,
constructor; assumption,
end
end source
-- This models the behavior of the target language.
namespace target
constants INSN PC STATE : Type
constant pc_of : STATE → PC
constant step_insn : NONDET → INSN → STATE → (STATE × TRACE)
constant result_of : STATE → option RESULT
def CODE : Type := @machine.CODE PC INSN
noncomputable def step := machine.step pc_of step_insn result_of
def star := machine.star pc_of step_insn result_of
end target
-- This models the JIT implementation.
namespace jit
-- This represents the JIT state.
constant CONTEXT : Type
-- Emit target code for a single source instruction.
constant emit_insn : CONTEXT → source.CODE → source.PC → option target.CODE
constant emit_prologue : CONTEXT → target.CODE
constant emit_epilogue : CONTEXT → target.CODE
-- Emit target code for an entire source program, including
-- epilogue and prologue.
constant emit : CONTEXT → source.CODE → option target.CODE
-- The initial state to run target from. Unlike src, this
-- can depend on the JIT mapping context.
constant init_target_state : CONTEXT → INPUT → target.STATE
-- If the JIT suceeds for an entire source program,
-- it must have succeeded for each (valid) source instruction,
-- and the produced code must contain the prologue and epilogue.
--
-- This is assumed to hold.
axiom emit_correct :
∀ (ctx : jit.CONTEXT) (code_S : source.CODE) (code_T : target.CODE),
source.wf code_S →
jit.emit ctx code_S = some code_T →
(∀ (i : source.PC) (insn : source.INSN),
code_S i = some insn →
∃ (f_T : target.CODE),
jit.emit_insn ctx code_S i = some f_T ∧ f_T <+ code_T) ∧
emit_prologue ctx <+ code_T ∧
emit_epilogue ctx <+ code_T
end jit
-- JIT correctness
-- This relates source and target states, parameterized by a JIT context.
constant related : jit.CONTEXT → source.STATE → target.STATE → Prop
notation s1 `~[`:50 ctx `]` s2:50 := related ctx s1 s2
-- Running the prologue from an initial state produces a target
-- state related to the initial source state (with no trace).
--
-- This is proved in SMT.
axiom prologue_correct :
∀ (oracle : NONDET) (ctx : jit.CONTEXT) (i : INPUT),
∃ (t2 : target.STATE),
target.star oracle (jit.emit_prologue ctx) (jit.init_target_state ctx i) t2 [] ∧
(source.init_state i) ~[ctx] t2
-- If the source state has reached a result, then executing
-- the epilogue in a related target state reaches a state
-- with the same result (and no trace).
--
-- This is proved in SMT.
axiom epilogue_correct :
∀ (oracle : NONDET) (ctx : jit.CONTEXT) (s1 : source.STATE) (t1 : target.STATE),
s1 ~[ctx] t1 →
(∃ res, source.result_of s1 = some res) →
∃ (t2 : target.STATE),
target.star oracle (jit.emit_epilogue ctx) t1 t2 [] ∧
source.result_of s1 = target.result_of t2
-- If the JIT produces some code for one source instruction,
-- then starting from related source and target states,
-- stepping the source instruction is related to some
-- state reachable from the target state, for the jited code.
--
-- This is proved in SMT.
axiom per_insn_correct :
∀ (oracle : NONDET) (ctx : jit.CONTEXT) (i : source.PC) (code_S : source.CODE)
(f_T : target.CODE) (σ_S σ_S' : source.STATE) (σ_T : target.STATE)
(tr : TRACE) (code_T : target.CODE),
jit.emit_insn ctx code_S i = some f_T →
σ_S ~[ctx] σ_T →
source.pc_of σ_S = i →
source.step oracle code_S σ_S = some (σ_S', tr) →
∃ (σ_T' : target.STATE),
target.star oracle f_T σ_T σ_T' tr ∧ σ_S' ~[ctx] σ_T'
lemma star_src_correct :
∀ (oracle : NONDET) (code_S : source.CODE) (σ_S σ_S' : source.STATE) (tr : TRACE),
source.wf code_S →
source.safe oracle code_S σ_S →
source.star oracle code_S σ_S σ_S' tr →
∀ (ctx : jit.CONTEXT) (σ_T : target.STATE) (code_T : target.CODE),
σ_S ~[ctx] σ_T →
jit.emit ctx code_S = some code_T →
∃ (σ_T' : target.STATE),
target.star oracle code_T σ_T σ_T' tr ∧ σ_S' ~[ctx] σ_T' :=
begin
intros _ _ _ _ _ wf_S safe_S star_S,
induction star_S with s1 s1 s2 s3 tr1 tr2 step_S star_S' IH,
{ intros _ _ _ related emitted,
existsi σ_T, split, constructor, assumption, },
intros _ _ _ related emitted,
have hinsn : ∃ insn, code_S (source.pc_of s1) = some insn,
{
apply source.safe_self; assumption,
},
cases hinsn with insn hinsn,
have hemit : ∃ f_T, jit.emit_insn ctx code_S (source.pc_of s1) = some f_T ∧ f_T <+ code_T,
{
let c := jit.emit_correct,
specialize c _ _ _ (by assumption) _,
cases c,
apply c_left; assumption,
apply emitted,
},
cases hemit with f_T hemit,
cases hemit with hemit_left hemit_right,
have hstep_T : ∃ t2, target.star oracle f_T σ_T t2 tr1 ∧ s2 ~[ctx] t2,
{
apply per_insn_correct; assumption <|> refl,
},
cases hstep_T with t2 hstep_T,
cases hstep_T with hstep_T_left hstep_T_right,
have hstar_T : ∃ t3, target.star oracle code_T t2 t3 tr2 ∧ s3 ~[ctx] t3,
{
apply IH; try{assumption},
apply source.safe_step; assumption,
},
cases hstar_T with t3 hstar_T,
cases hstar_T with hstar_T_left hstar_T_right,
existsi t3,
split, tactic.swap, assumption,
apply machine.star_trans; try{assumption},
apply machine.star_subset; assumption,
end
-- The behavior of the source program is implemented by the jited target code.
theorem forward_simulation :
∀ (oracle : NONDET) (code_S : source.CODE) (σ_S' : source.STATE) (tr : TRACE) (i : INPUT) (res : RESULT),
source.wf code_S →
source.star oracle code_S (source.init_state i) σ_S' tr →
source.result_of σ_S' = some res →
∀ (ctx : jit.CONTEXT) (code_T : target.CODE),
jit.emit ctx code_S = some code_T →
∃ (σ_T' : target.STATE),
target.star oracle code_T (jit.init_target_state ctx i) σ_T' tr ∧
target.result_of σ_T' = some res :=
begin
intros _ _ _ _ _ _ H1 H2 H3 _ _ H4,
-- Construct the prologue star
have hprologue : ∃ t2, target.star oracle (jit.emit_prologue ctx) (jit.init_target_state ctx i) t2 [] ∧
(source.init_state i) ~[ctx] t2,
{
apply prologue_correct,
},
cases hprologue with t2 hprologue,
cases hprologue,
-- construct the regular instr star using the lemma defined above
have hstar : ∃ t3, target.star oracle code_T t2 t3 tr ∧ σ_S' ~[ctx] t3,
{
apply star_src_correct; try{assumption},
apply source.wf_safe; assumption,
},
cases hstar with t3 hstar,
cases hstar with hstar_left hstar_right,
-- construct the epilogue star
have hepilogue : ∃ t4, target.star oracle (jit.emit_epilogue ctx) t3 t4 [] ∧ source.result_of σ_S' = target.result_of t4,
{
apply epilogue_correct, from hstar_right,
existsi res, from H3,
},
cases hepilogue with t4 hepilogue,
cases hepilogue,
-- Now we can glue all the steps together
existsi t4,
split, tactic.swap,
{
-- Handle the easy case first: prove the results match
rewrite ← hepilogue_right,
rewrite H3,
},
-- Get the code to run in the target and show code_T is a superset of each component
let ec := jit.emit_correct,
specialize ec ctx code_S code_T (by assumption) (by assumption),
cases ec with ec_insn ec,
cases ec with ec_prologue ec_epilogue,
-- Run the prologue
change tr with (list.nil ++ tr),
apply machine.star_trans,
{
apply machine.star_subset, tactic.swap, from ec_prologue,
assumption,
},
-- Run the middle
rewrite ← list.append_nil tr,
apply machine.star_trans,
{
assumption,
},
-- Run the epilogue
apply machine.star_subset, tactic.swap, from ec_epilogue,
assumption,
end
lemma target_deterministic :
∀ (oracle : NONDET) (code : target.CODE) (s1 s2 : target.STATE)
(tr : TRACE) (res : RESULT),
target.star oracle code s1 s2 tr →
target.result_of s2 = some res →
∀ (s2' : target.STATE) (tr' : TRACE) (res' : RESULT),
target.star oracle code s1 s2' tr' →
target.result_of s2' = some res' →
(tr = tr' ∧ s2 = s2') :=
begin
intros _ _ _ _ _ _ h1 h2,
induction h1 with s' s' s'' s''' tr1 tr2 h1 h3 IH,
{ intros _ _ _ h4 h5,
have : tr' = [] ∧ s2' = s',
by {apply machine.final_star, from h2, all_goals{assumption}},
cc,
},
{ intros _ _ _ h4 h5,
cases h4 with _ _ _ h4_b h4_tr₁ h4_tr₂,
{ have : tr1 = [] ∧ s'' = s',
by { apply machine.final_step, from h5, all_goals{assumption}},
cases this, subst this_left, subst this_right,
simp,
apply IH; tauto,
},
{ have : (tr1 = h4_tr₁), by cc, subst this,
have : (s'' = h4_b), by cc, subst this,
suffices : tr2 = h4_tr₂ ∧ s''' = s2', by tauto,
apply IH; tauto,
} }
end
lemma source_target_deterministic :
∀ (oracle : NONDET) (code_S : source.CODE) (σ_S' : source.STATE) (tr : TRACE)
(i : INPUT) (res : RESULT),
source.wf code_S →
source.star oracle code_S (source.init_state i) σ_S' tr →
source.result_of σ_S' = some res →
∀ (ctx : jit.CONTEXT) (code_T : target.CODE) (σ_T' : target.STATE)
(tr' : TRACE) (res' : RESULT),
jit.emit ctx code_S = some code_T →
target.star oracle code_T (jit.init_target_state ctx i) σ_T' tr' →
target.result_of σ_T' = some res' →
(tr = tr' ∧ res = res') :=
begin
intros _ _ _ _ _ _ WF h1 h2 _ _ _ _ _ h3 h4 h5,
let x := forward_simulation,
specialize x oracle code_S σ_S' tr i res (by assumption)
(by assumption) (by assumption) ctx code_T (by assumption),
cases x with T H,
cases H,
suffices : tr = tr' ∧ T = σ_T', by { split; cc },
apply target_deterministic; assumption,
end
-- The behavior of the jited target code is allowed by the source program.
theorem backward_simulation :
∀ (ctx : jit.CONTEXT) (code_S : source.CODE) (code_T : target.CODE)
(oracle : NONDET) (σ_T' : target.STATE) (tr : TRACE) (i : INPUT) (res : RESULT),
source.wf code_S →
jit.emit ctx code_S = some code_T →
target.star oracle code_T (jit.init_target_state ctx i) σ_T' tr →
target.result_of σ_T' = some res →
∃ (σ_S' : source.STATE),
source.star oracle code_S (source.init_state i) σ_S' tr ∧
source.result_of σ_S' = some res :=
begin
intros,
let x := source.wf_terminates,
specialize x oracle i code_S (by assumption),
cases x with s' x,
cases x with tr' x,
cases x with res' H,
existsi s',
cases H,
suffices : tr' = tr ∧ res' = res, by cc,
apply source_target_deterministic; assumption,
end
theorem bisimulation :
∀ (ctx : jit.CONTEXT) (code_S : source.CODE) (code_T : target.CODE)
(oracle : NONDET) (σ_T' : target.STATE) (tr : TRACE) (i : INPUT) (res : RESULT),
source.wf code_S →
jit.emit ctx code_S = some code_T →
((∃ (σ_T' : target.STATE),
target.star oracle code_T (jit.init_target_state ctx i) σ_T' tr ∧
target.result_of σ_T' = some res)
↔
(∃ (σ_S' : source.STATE),
source.star oracle code_S (source.init_state i) σ_S' tr ∧
source.result_of σ_S' = some res)) :=
begin
intros,
split; intros,
{ cases a_2,
cases a_2_h,
apply backward_simulation; assumption,
},
{ cases a_2,
cases a_2_h,
apply forward_simulation; assumption,
},
end
|
077267e10755d35707a3746c402e7e2bd0676c2e | 9dd3f3912f7321eb58ee9aa8f21778ad6221f87c | /library/init/meta/name.lean | 79edef84134d5e8244c26033f9360356dd714626 | [
"Apache-2.0"
] | permissive | bre7k30/lean | de893411bcfa7b3c5572e61b9e1c52951b310aa4 | 5a924699d076dab1bd5af23a8f910b433e598d7a | refs/heads/master | 1,610,900,145,817 | 1,488,006,845,000 | 1,488,006,845,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,073 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.data.ordering init.coe
/- Reflect a C++ name object. The VM replaces it with the C++ implementation. -/
inductive name
| anonymous : name
| mk_string : string → name → name
| mk_numeral : unsigned → name → name
/-- Gadget for automatic parameter support. This is similar to the opt_param gadget, but it uses
the tactic declaration names tac_name to synthesize the argument.
Like opt_param, this gadget only affects elaboration.
For example, the tactic will *not* be invoked during type class resolution. -/
@[reducible] def {u} auto_param (α : Sort u) (tac_name : name) : Sort u :=
α
instance : inhabited name :=
⟨name.anonymous⟩
def mk_str_name (n : name) (s : string) : name :=
name.mk_string s n
def mk_num_name (n : name) (v : nat) : name :=
name.mk_numeral (unsigned.of_nat v) n
def mk_simple_name (s : string) : name :=
mk_str_name name.anonymous s
instance string_to_name : has_coe string name :=
⟨mk_simple_name⟩
infix ` <.> `:65 := mk_str_name
open name
def name.get_prefix : name → name
| anonymous := anonymous
| (mk_string s p) := p
| (mk_numeral s p) := p
def name.update_prefix : name → name → name
| anonymous new_p := anonymous
| (mk_string s p) new_p := mk_string s new_p
| (mk_numeral s p) new_p := mk_numeral s new_p
def name.to_string_with_sep (sep : string) : name → string
| anonymous := "[anonymous]"
| (mk_string s anonymous) := s
| (mk_numeral v anonymous) := to_string v
| (mk_string s n) := name.to_string_with_sep n ++ sep ++ s
| (mk_numeral v n) := name.to_string_with_sep n ++ sep ++ to_string v
private def name.components' : name -> list name
| anonymous := []
| (mk_string s n) := mk_string s anonymous :: name.components' n
| (mk_numeral v n) := mk_numeral v anonymous :: name.components' n
def name.components (n : name) : list name :=
(name.components' n)^.reverse
def name.to_string : name → string :=
name.to_string_with_sep "."
instance : has_to_string name :=
⟨name.to_string⟩
/- TODO(Leo): provide a definition in Lean. -/
meta constant name.has_decidable_eq : decidable_eq name
/- Both cmp and lex_cmp are total orders, but lex_cmp implements a lexicographical order. -/
meta constant name.cmp : name → name → ordering
meta constant name.lex_cmp : name → name → ordering
meta constant name.append : name → name → name
meta constant name.is_internal : name → bool
attribute [instance] name.has_decidable_eq
meta instance : has_ordering name :=
⟨name.cmp⟩
meta instance : has_append name :=
⟨name.append⟩
/- (name.append_after n i) return a name of the form n_i -/
meta constant name.append_after : name → nat → name
meta def name.is_prefix_of : name → name → bool
| p name.anonymous := ff
| p n :=
if p = n then tt else name.is_prefix_of p n^.get_prefix
|
ea0e9868ddcf57dd9a8f8c956b87168670ec6085 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/category_theory/endomorphism.lean | 11e45c9289095be4ae4b85131b21f7b7374a96ad | [
"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 | 3,861 | lean | /-
Copyright (c) 2019 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, Scott Morrison, Simon Hudon
Definition and basic properties of endomorphisms and automorphisms of an object in a category.
-/
import category_theory.groupoid
import data.equiv.mul_add
universes v v' u u'
namespace category_theory
/-- Endomorphisms of an object in a category. Arguments order in multiplication agrees with
`function.comp`, not with `category.comp`. -/
def End {C : Type u} [category_struct.{v} C] (X : C) := X ⟶ X
namespace End
section struct
variables {C : Type u} [category_struct.{v} C] (X : C)
instance has_one : has_one (End X) := ⟨𝟙 X⟩
instance inhabited : inhabited (End X) := ⟨𝟙 X⟩
/-- Multiplication of endomorphisms agrees with `function.comp`, not `category_struct.comp`. -/
instance has_mul : has_mul (End X) := ⟨λ x y, y ≫ x⟩
variable {X}
/-- Assist the typechecker by expressing a morphism `X ⟶ X` as a term of `End X`. -/
def of (f : X ⟶ X) : End X := f
/-- Assist the typechecker by expressing an endomorphism `f : End X` as a term of `X ⟶ X`. -/
def as_hom (f : End X) : X ⟶ X := f
@[simp] lemma one_def : (1 : End X) = 𝟙 X := rfl
@[simp] lemma mul_def (xs ys : End X) : xs * ys = ys ≫ xs := rfl
end struct
/-- Endomorphisms of an object form a monoid -/
instance monoid {C : Type u} [category.{v} C] {X : C} : monoid (End X) :=
{ mul_one := category.id_comp,
one_mul := category.comp_id,
mul_assoc := λ x y z, (category.assoc z y x).symm,
..End.has_mul X, ..End.has_one X }
/-- In a groupoid, endomorphisms form a group -/
instance group {C : Type u} [groupoid.{v} C] (X : C) : group (End X) :=
{ mul_left_inv := groupoid.comp_inv, inv := groupoid.inv, ..End.monoid }
end End
lemma is_unit_iff_is_iso {C : Type u} [category.{v} C] {X : C} (f : End X) :
is_unit (f : End X) ↔ is_iso f :=
⟨λ h, { out := ⟨h.unit.inv,
⟨by { convert h.unit.inv_val, exact h.unit_spec.symm, },
by { convert h.unit.val_inv, exact h.unit_spec.symm, }⟩⟩ },
λ h, by exactI ⟨⟨f, inv f, by simp, by simp⟩, rfl⟩⟩
variables {C : Type u} [category.{v} C] (X : C)
/--
Automorphisms of an object in a category.
The order of arguments in multiplication agrees with
`function.comp`, not with `category.comp`.
-/
def Aut (X : C) := X ≅ X
attribute [ext Aut] iso.ext
namespace Aut
instance inhabited : inhabited (Aut X) := ⟨iso.refl X⟩
instance : group (Aut X) :=
by refine_struct
{ one := iso.refl X,
inv := iso.symm,
mul := flip iso.trans,
div := _,
npow := @npow_rec (Aut X) ⟨iso.refl X⟩ ⟨flip iso.trans⟩,
gpow := @gpow_rec (Aut X) ⟨iso.refl X⟩ ⟨flip iso.trans⟩ ⟨iso.symm⟩ };
intros; try { refl }; ext;
simp [flip, (*), monoid.mul, mul_one_class.mul, mul_one_class.one, has_one.one, monoid.one,
has_inv.inv]
/--
Units in the monoid of endomorphisms of an object
are (multiplicatively) equivalent to automorphisms of that object.
-/
def units_End_equiv_Aut : units (End X) ≃* Aut X :=
{ to_fun := λ f, ⟨f.1, f.2, f.4, f.3⟩,
inv_fun := λ f, ⟨f.1, f.2, f.4, f.3⟩,
left_inv := λ ⟨f₁, f₂, f₃, f₄⟩, rfl,
right_inv := λ ⟨f₁, f₂, f₃, f₄⟩, rfl,
map_mul' := λ f g, by rcases f; rcases g; refl }
end Aut
namespace functor
variables {D : Type u'} [category.{v'} D] (f : C ⥤ D) (X)
/-- `f.map` as a monoid hom between endomorphism monoids. -/
@[simps] def map_End : End X →* End (f.obj X) :=
{ to_fun := functor.map f,
map_mul' := λ x y, f.map_comp y x,
map_one' := f.map_id X }
/-- `f.map_iso` as a group hom between automorphism groups. -/
def map_Aut : Aut X →* Aut (f.obj X) :=
{ to_fun := f.map_iso,
map_mul' := λ x y, f.map_iso_trans y x,
map_one' := f.map_iso_refl X }
end functor
end category_theory
|
c51c8f531309716e1619b5976a4a428eac038b50 | efa51dd2edbbbbd6c34bd0ce436415eb405832e7 | /20150803_CADE/examples/ex7.lean | 5403a247422aa06bf39eaecb6d0978b4689d2888 | [
"Apache-2.0"
] | permissive | leanprover/presentations | dd031a05bcb12c8855676c77e52ed84246bd889a | 3ce2d132d299409f1de269fa8e95afa1333d644e | refs/heads/master | 1,688,703,388,796 | 1,686,838,383,000 | 1,687,465,742,000 | 29,750,158 | 12 | 9 | Apache-2.0 | 1,540,211,670,000 | 1,422,042,683,000 | Lean | UTF-8 | Lean | false | false | 291 | lean | import data.nat
import theories.number_theory.primes
open nat
eval if (∀ x, x < 10 → x ≠ 5) then 1 else 2
eval is_true (prime 5)
eval is_true (prime 6)
definition f (a : nat) (b : nat) :=
if (∀ x, x < a → x ≠ b ∧ x < 10) then 1 else 2
set_option pp.implicit true
print f
|
d77d030a4e4f7f4f05719ae1b1d44d89466f5c47 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/group_theory/subgroup/mul_opposite.lean | acc7c3d591f76945db1429f5dd66d5d9f9ba2ea3 | [
"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,952 | lean | /-
Copyright (c) 2022 Alex Kontorovich. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alex Kontorovich
-/
import group_theory.subgroup.actions
/-!
# Mul-opposite subgroups
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
## Tags
subgroup, subgroups
-/
variables {G : Type*} [group G]
namespace subgroup
/-- A subgroup `H` of `G` determines a subgroup `H.opposite` of the opposite group `Gᵐᵒᵖ`. -/
@[to_additive "An additive subgroup `H` of `G` determines an additive subgroup `H.opposite` of the
opposite additive group `Gᵃᵒᵖ`."]
def opposite : subgroup G ≃ subgroup Gᵐᵒᵖ :=
{ to_fun := λ H, { carrier := mul_opposite.unop ⁻¹' (H : set G),
one_mem' := H.one_mem,
mul_mem' := λ a b ha hb, H.mul_mem hb ha,
inv_mem' := λ a, H.inv_mem },
inv_fun := λ H, { carrier := mul_opposite.op ⁻¹' (H : set Gᵐᵒᵖ),
one_mem' := H.one_mem,
mul_mem' := λ a b ha hb, H.mul_mem hb ha,
inv_mem' := λ a, H.inv_mem },
left_inv := λ H, set_like.coe_injective rfl,
right_inv := λ H, set_like.coe_injective rfl }
/-- Bijection between a subgroup `H` and its opposite. -/
@[to_additive "Bijection between an additive subgroup `H` and its opposite.", simps]
def opposite_equiv (H : subgroup G) : H ≃ H.opposite :=
mul_opposite.op_equiv.subtype_equiv $ λ _, iff.rfl
@[to_additive] instance (H : subgroup G) [encodable H] : encodable H.opposite :=
encodable.of_equiv H H.opposite_equiv.symm
@[to_additive] instance (H : subgroup G) [countable H] : countable H.opposite :=
countable.of_equiv H H.opposite_equiv
@[to_additive] lemma smul_opposite_mul {H : subgroup G} (x g : G) (h : H.opposite) :
h • (g * x) = g * (h • x) :=
begin
cases h,
simp [(•), mul_assoc],
end
end subgroup
|
59d8895463d51a52a43a2f5e8c35de460db0c134 | 5df84495ec6c281df6d26411cc20aac5c941e745 | /src/formal_ml/vc_pac_bounds.lean | f0dd4f65a4cdc653e84ca6af6fe8cadfc7181e8c | [
"Apache-2.0"
] | permissive | eric-wieser/formal-ml | e278df5a8df78aa3947bc8376650419e1b2b0a14 | 630011d19fdd9539c8d6493a69fe70af5d193590 | refs/heads/master | 1,681,491,589,256 | 1,612,642,743,000 | 1,612,642,743,000 | 360,114,136 | 0 | 0 | Apache-2.0 | 1,618,998,189,000 | 1,618,998,188,000 | null | UTF-8 | Lean | false | false | 38,497 | lean | /-
Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-/
import measure_theory.measurable_space
import measure_theory.measure_space
import measure_theory.outer_measure
import measure_theory.lebesgue_measure
import measure_theory.integration
import measure_theory.borel_space
import data.set.countable
import formal_ml.measurable_space
import formal_ml.probability_space
import formal_ml.real_random_variable
import data.complex.exponential
import formal_ml.ennreal
import formal_ml.nnreal
import formal_ml.sum
import formal_ml.exp_bound
/-
The Vapnik-Chevronenkis Dimension and its connection to learning is one of the most
remarkable and fundamental results in machine learning. In particular, it allows us
to understand simple, infinite hypothesis spaces, like the separating hyperplane,
and begin to understand the complexity of neural networks. This analysis is also a
precursor to understanding support vector machines and structural risk.
-/
lemma finset.subset_of_not_mem_of_subset_insert {α:Type*} [decidable_eq α] {x:α} {S T:finset α}:x∉ S →
S ⊆ insert x T → S ⊆ T :=
begin
intros A1 A2,
rw finset.subset_iff,
rw finset.subset_iff at A2,
intros a B1,
have B2 := A2 B1,
rw finset.mem_insert at B2,
cases B2,
subst a,
exfalso,
apply A1,
apply B1,
apply B2,
end
/-
A type is of class inhabited if it has at least one element.
Thus, its cardinality is not zero.
--Not sure where to put this. Here is fine for now.
--Note: this is the kind of trivial thing that takes ten minutes to prove.
-/
/--
Normally, we would not assume that the representation type was encodable (i.e. countable).
Specifically, one could imagine real numbers as part of the representation type.
However, that creates some issues with measurability.
-/
structure VC_PAC_problem :=
(Ω:Type*) -- Underlying outcome type
(p:probability_space Ω) -- Underlying probability space
(X:Type*) -- instance type
(MX:measurable_space X) -- Measurable space for the instances
(H:Type*) -- Representation type
(ER:encodable H) -- The representation type is encodable.
(R:H → (set X)) -- Representation scheme
(MC:∀ h:H, is_measurable (R(h))) -- Concepts are measurable.
(Di:Type*) -- number of examples
(FDi:fintype Di) -- number of examples are finite
(EDi:encodable Di) -- example index is encodable
(D:Di → (p →ᵣ MX)) -- example distribution
(IID:random_variables_IID D) -- examples are IID
(has_example:inhabited Di) -- there exists an example
(c:H) -- the correct hypothesis
namespace VC_PAC_problem
variable (P:VC_PAC_problem)
--The measurable space for the hypotheses is ⊤.
--Everything is measurable.
def MH:measurable_space (P.H) := ⊤
--The space of training datasets.
def data_space:measurable_space (P.Di → P.X) := @measurable_space.pi P.Di (λ i, P.X) (λ i, P.MX)
--The learning algorithm is a function of the training dataset.
def algorithm:Type* := measurable_fun (P.data_space) P.MH
def concept (h:P.H):measurable_set P.MX := measurable_set.mk (P.MC h)
def target_concept:measurable_set P.MX := (P.concept P.c)
def in_concept (h:P.H) (i:P.Di):event (P.p) := @rv_event P.Ω P.p P.X P.MX (P.D i) (P.concept h)
def label_positive (i:P.Di):event (P.p) := P.in_concept P.c i
def example_correct (h:P.H) (i:P.Di):event (P.p) :=
(P.in_concept h i) =ₑ (P.label_positive i)
def example_error (h:P.H) (i:P.Di):event (P.p) :=
¬ₑ (P.example_correct h i)
/-
num_examples P is the number of examples in the problem.
This is defined as the cardinality of the index type of the examples.
-/
def num_examples:nat
:= @fintype.card P.Di P.FDi
--the measurable space on hypotheses and instances.
def MHX:measurable_space (P.H × P.X) := P.MH ×ₘ P.MX
noncomputable def training_error (h:P.H):P.p →ᵣ (borel nnreal) :=
average_identifier (P.example_error h) (P.FDi)
/-
The number of examples is the number of elements of type P.Di.
P.FDi.elems is the set of all elements in P.Di, and P.FDi.elems.card is the cardinality of
P.FDi.elems.
-/
lemma num_examples_eq_finset_card:
P.num_examples = P.FDi.elems.card :=
begin
refl,
end
/-
The number of examples do not equal zero.
-/
lemma num_examples_ne_zero:
P.num_examples ≠ 0 :=
begin
unfold VC_PAC_problem.num_examples,
apply @card_ne_zero_of_inhabited P.Di P.has_example P.FDi,
end
/-
The expected test error.
The test error is equal to the expected training error. Because we have not defined a generating
process for examples, we use this as the definition.
-/
noncomputable def test_error'
(h:P.H):ennreal := E[P.training_error h]
lemma example_error_IID (P:VC_PAC_problem) (i:P.H):
@events_IID P.Ω P.Di P.p P.FDi (P.example_error i) :=
begin
/-
To prove that the errors of a particular hypothesis are IID, we must use an alternate
formulation of the example_error events. Specifically, instead of constructing a hierarchy
of random variables, we must make a leap from the established IID random variable
(the data), construct another IID random variable (the product of
the classification and the label), and show that the set of all label/classification pairs
that aren't equal are a measurable set (because has_measurable_eq Mγ).
The indexed set of events of each IID random variable being in a measurable set is IID,
so the result holds.
Note that while this proof looks a little long, most of the proof is just unwrapping
the traditional and internal definitions of example error, and then using simp to show that
they are equal on all outcomes.
-/
let S:measurable_set P.MX := (P.concept i ∩ (P.target_concept)ᶜ) ∪ ((P.concept i)ᶜ ∩ (P.target_concept)),
begin
have B1:S = (P.concept i ∩ P.target_conceptᶜ) ∪ (((P.concept i)ᶜ) ∩ ((P.target_concept))) := rfl,
have A1:@random_variables_IID P.Ω P.p P.Di P.FDi P.X P.MX P.D,
{
apply P.IID,
},
have A2:@events_IID P.Ω P.Di P.p P.FDi (λ j:P.Di, @rv_event P.Ω P.p P.X P.MX (P.D j) S),
{
apply rv_event_IID,
apply A1,
},
have A3: (λ j:P.Di, @rv_event P.Ω P.p P.X P.MX (P.D j) S) = P.example_error i,
{
apply funext,
intro j,
apply event.eq,
rw B1,
unfold VC_PAC_problem.example_error VC_PAC_problem.example_correct VC_PAC_problem.target_concept
VC_PAC_problem.label_positive VC_PAC_problem.in_concept,
rw enot_val_def,
rw event_eqv_def,
rw rv_event_val_def,
rw eor_val_def,
repeat {rw eand_val_def},
rw measurable_union_val_def2,
repeat {rw measurable_inter_val_def2},
repeat {rw measurable_set_compl_val_def},
repeat {rw enot_val_def},
repeat {rw rv_event_val_def},
ext ω,
split;intros A3B;simp;simp at A3B,
{
cases A3B with A3B A3B,
{
split,
{
intros A3BA,
apply A3B.right,
},
{
intro A3BA,
exfalso,
apply A3BA,
apply A3B.left,
},
},
{
split;intros A3BA,
{
intros A3BB,
apply A3B.left A3BA,
},
{
apply A3B.right,
},
},
},
{
cases (classical.em ((P.D j).val ω ∈ (P.concept i).val)) with A3C A3C,
{
apply or.inl (and.intro A3C (A3B.left A3C)),
},
{
apply or.inr (and.intro A3C (A3B.right A3C)),
},
},
},
rw ← A3,
exact A2,
end
end
/-
The expected test error.
The test error is equal to the expected training error. Because we have not defined a generating
process for examples, we use this as the definition.
-/
lemma test_error_def
(h:P.H) (i:P.Di):P.test_error' h = Pr[P.example_error h i] :=
begin
unfold VC_PAC_problem.test_error' VC_PAC_problem.training_error,
rw average_identifier_eq_pr_elem,
apply VC_PAC_problem.example_error_IID,
end
--This is probably true, but just very hard to prove.
def test_error_measurable:Prop :=
@measurable P.H ennreal P.MH (borel ennreal) P.test_error'
noncomputable def test_error (TEM:P.test_error_measurable):P.MH →ₘ (borel ennreal) := {
val := P.test_error',
property := TEM,
}
def C:set (set P.X) := set.range P.R
def Φ:ℕ → ℕ → ℕ
| 0 m := 1
| d 0 := 1
| (nat.succ d) (nat.succ m) := Φ (d.succ) m + Φ d m
@[simp]
lemma phi_d_zero_eq_one {d:ℕ}:Φ d 0 = 1 :=
begin
cases d;unfold Φ,
end
@[simp]
lemma phi_zero_m_eq_one {m:ℕ}:Φ 0 m = 1 :=
begin
cases m;unfold Φ,
end
lemma phi_succ_succ {d m:ℕ}:Φ d.succ m.succ = Φ d.succ m + Φ d m := rfl
end VC_PAC_problem
def finset.to_set_of_sets {α:Type*} (C:finset (finset α)):set (set α) :=
(λ c:finset α, (↑c:set α)) '' (↑C:set (finset α))
lemma finset.mem_to_set_of_sets {α:Type*} {C:finset (finset α)} {c:finset α}:
(↑c ∈ (C.to_set_of_sets)) ↔ c ∈ C :=
begin
unfold finset.to_set_of_sets,
simp,
end
lemma finset.mem_to_set_of_sets' {α:Type*} {C:finset (finset α)} {c:set α}:
c∈ C.to_set_of_sets ↔ ∃ c' ∈ C, c=(↑c') :=
begin
unfold finset.to_set_of_sets,
split;intro A1,
{
simp at A1,
cases A1 with c' A1,
apply exists.intro c',
apply exists.intro A1.left,
rw A1.right,
},
{
simp,
cases A1 with c' A1,
apply exists.intro c',
cases A1 with A1 A2,
simp [A1, A2],
},
end
/-
It is important to be able to talk about the VC dimension of a set of sets without
referring to a particular problem. For that reason, I have placed it outside of the
VC_PAC_problem.
-/
namespace VC_PAC_problem
section VC_PAC_problem
universe u
variable {α:Type u}
open_locale classical
--The set of restrictions of concepts onto S, conventionally written as Πc(S) and represented as vectors.
noncomputable def restrict_set (C:set (set α)) (S:finset α):finset (finset α) :=
S.powerset.filter (λ x, ∃ c∈ C, c ∩ (↑S) = (↑x))
--Does there exist a concept that agrees with any subset of S on S?
def shatters (C:set (set α)) (S:finset α):Prop :=
(restrict_set C S) = S.powerset
--What is the largest extended natural number n such that all finite sets of size ≤ n can be shattered?
--Note that if the VC dimension is infinity, then that means that any finite set can be shattered,
--but it does not say anything about infinite sets. See Kearns and Vazirani, page 51.
--For example, the Borel algebra on the reals shatters every finite set, but does not shatter
--all infinite sets (e.g. it does not shatter the reals themselves), so it has a VC dimension of
--infinity.
--Note: an empty hypothesis space, by this definition, has a VCD of infinity. This may cause problems.
/-noncomputable def VCD (C:set (set α)):enat := Sup {n:enat|∃ (X':finset α), ((X'.card:enat) = n) ∧
shatters C (X')}-/
/-
Consider all sets that can be shattered. What is the supremum of their sizes (in enat)?
-/
noncomputable def VCD (C:set (set α)):enat := Sup
((λ X':finset α, (↑(X'.card):enat)) '' {X':finset α|shatters C (X')})
/-
Normally, this restriction is defined for sets of exactly size m. However, this
runs into problems if there do not exist sets of a certain size.
-/
noncomputable def restrict_set_bound (C:set (set α)) (m:ℕ):nat := Sup ((λ X', (restrict_set C X').card) ''
{X':finset α|X'.card ≤ m})
lemma restrict_set_subset {C:set (set α)} (S:finset α):restrict_set C S⊆ S.powerset :=
begin
unfold restrict_set,
simp,
end
lemma mem_restrict_set_subset {C:set (set α)} {S:finset α} {c:finset α}:c ∈ restrict_set C S →
c⊆ S :=
begin
intros A1,
rw ← finset.mem_powerset,
have A2:= @restrict_set_subset α C S,
apply A2,
apply A1,
end
-- filter (λ x, true)
--{S':set P.X|∃ c ∈ P.C, (S')= c ∩ (S)}
lemma mem_restrict_set {C:set (set α)} (S:finset α) (T:finset α):
T ∈ restrict_set C S ↔ (∃ c∈ C, c ∩ (↑S) = (↑T)) :=
begin
unfold restrict_set,
rw finset.mem_filter,
split;intros B1,
{
apply B1.right,
},
{
split,
rw finset.mem_powerset,
cases B1 with c B1,
cases B1 with B1 B2,
rw finset.subset_iff,
intros x A1,
have B3:= set.inter_subset_right c (↑S),
rw B2 at B3,
apply B3,
simp,
apply A1,
apply B1,
},
end
lemma shatters_iff {C:set (set α)} (S:finset α):
(shatters C S) ↔ (∀ S'⊆ S, ∃ c∈ C, c ∩(↑S) = (↑S')) :=
begin
unfold shatters,
split;intros A1,
{
intros S' B1,
rw finset.ext_iff at A1,
have B2 := A1 S',
rw finset.mem_powerset at B2,
rw ← B2 at B1,
rw mem_restrict_set at B1,
apply B1,
},
{
apply finset.subset.antisymm,
apply restrict_set_subset,
rw finset.subset_iff,
intros S' C1,
rw finset.mem_powerset at C1,
have C2 := A1 S' C1,
rw mem_restrict_set,
apply C2,
},
end
lemma shatters_def (C:set (set α)) (S:finset α):
shatters C S = ((restrict_set C S) = S.powerset) := rfl
/-Introducing a trivial upper bound establishes that Sup exists meaningfully (instead
of a default value of zero).-/
lemma restrict_set_trivial_upper_bound {C:set (set α)} (X':finset α):
(restrict_set C X').card ≤ 2^(X'.card) :=
begin
have B1:(restrict_set C X').card ≤ X'.powerset.card,
{
apply finset.card_le_of_subset,
apply restrict_set_subset,
},
apply le_trans B1,
rw finset.card_powerset,
end
lemma restrict_set_le_upper_bound {C:set (set α)} (X':finset α):
(restrict_set C X').card ≤ restrict_set_bound C (X'.card) :=
begin
apply le_cSup,
rw bdd_above_def,
unfold upper_bounds,
apply exists.intro (2^(X'.card)),
simp,
intros a X'',
intros A1 A2,
subst A2,
have A3:2^(X''.card) ≤ 2^(X'.card),
{
apply linear_ordered_semiring.pow_monotone one_le_two A1,
},
apply le_trans _ A3,
apply restrict_set_trivial_upper_bound,
simp,
apply exists.intro X',
split,
refl,
refl,
end
lemma shatters_card_le_VCD {C:set (set α)} {S:finset α}:shatters C S → (S.card:enat) ≤ VCD C :=
begin
unfold VCD,
intros A1,
apply le_Sup,
simp,
apply exists.intro S,
simp [A1],
end
lemma VCD_le {C:set (set α)} {d:enat}:(∀ S:finset α, shatters C S → (↑S.card) ≤ d) → VCD C ≤ d :=
begin
intros A1,
unfold VCD,
apply Sup_le,
intros b B1,
simp at B1,
cases B1 with X' B1,
cases B1 with B1 B2,
subst b,
apply A1 X' B1,
end
lemma restrict_set_elements_subset_of_VCD_zero {C:set (set α)} {S T U:finset α}:(VCD C = 0) →
T ∈ (restrict_set C S) → U ∈ (restrict_set C S) → T ⊆ U :=
begin
intros A1 A2 A3,
rw finset.subset_iff,
intros x B1,
apply by_contradiction,
intros B2,
have B3 := (mem_restrict_set _ _).mp A2,
have B4 := (mem_restrict_set _ _).mp A3,
cases B3 with c_yes B3,
cases B4 with c_no B4,
cases B3 with B3 B5,
cases B4 with B4 B6,
have C1:↑T ⊆ c_yes, {rw ← B5,apply set.inter_subset_left},
have C2:x∈ c_yes,{apply C1,simp,apply B1},
have C3:c_yes ∩ {x} = {x},
{ext,split;intros B8A;simp;simp at B8A,apply B8A.right,subst x_1,simp [C2]},
have C4:↑U ⊆ c_no, {rw ← B6,apply set.inter_subset_left},
have C5:T ⊆ S,
{
rw ← finset.coe_subset,rw ← B5, apply set.inter_subset_right,
},
have C6:x ∈ S,
{
apply C5, apply B1,
},
have C7:x∉ c_no,
{
intros C5A,apply B2,rw ← finset.mem_coe,rw ← B6, simp,
apply and.intro C5A C6,
},
have C8:c_no ∩ ↑({x}:finset α) = ↑(∅:finset α),
{
simp,
ext,split;intros C8A,
simp at C8A,cases C8A with C8A C8B,subst x_1,exfalso,apply C7 C8A,
exfalso, apply C8A,
},
have C9:shatters C {x},
{
unfold shatters,
rw finset.powerset_singleton,
apply finset.subset.antisymm,
apply restrict_set_subset,
rw finset.subset_iff,
intros X' C9A,
simp at C9A,cases C9A;subst X';rw mem_restrict_set,
{apply exists.intro c_no, apply exists.intro B4, exact C8},
{apply exists.intro c_yes, apply exists.intro B3,simp,apply C3},
},
have C10:1 ≤ VCD C,
{
apply shatters_card_le_VCD C9,
},
rw A1 at C10,
have C11:(0:enat) < (1:enat) := enat.zero_lt_one,
rw lt_iff_not_ge at C11,
apply C11,
apply C10,
end
lemma restrict_set_elements_eq_of_VCD_zero {C:set (set α)} {S T U:finset α}:(VCD C = 0) →
T ∈ (restrict_set C S) → U ∈ (restrict_set C S) → T = U :=
begin
intros A1 A2 A3,
apply finset.subset.antisymm,
apply restrict_set_elements_subset_of_VCD_zero A1 A2 A3,
apply restrict_set_elements_subset_of_VCD_zero A1 A3 A2,
end
--Note: S could be either empty or have a unique element.
lemma finset.card_identical_elements {α:Type*} [decidable_eq α] {S:finset α}:
(∀ a b:α, a ∈ S → b ∈ S → a=b ) → S.card ≤ 1 :=
begin
--intros A1,
apply finset.induction_on S,
{
simp,
},
{
intros a s B1 B2 B3,
have C1:s = ∅,
{
rw ← finset.subset_empty,
rw finset.subset_iff,
intros b C1A,
exfalso,
apply B1,
have C1B:a = b,
{
apply B3;simp [C1A],
},
rw C1B,
apply C1A,
},
rw C1,
simp,
},
end
lemma mem_restrict_set_of_mem_restrict_set {C:set (set α)} {S₁ S₂ T:finset α}:
T ∈ restrict_set C S₂ →
S₁ ⊆ S₂ →
(T ∩ S₁) ∈ restrict_set C S₁ :=
begin
repeat {rw mem_restrict_set},
intros A1 A2,
cases A1 with c A1,
apply exists.intro c,
cases A1 with A1 A3,
apply exists.intro A1,
simp,
rw ← A3,
rw set.inter_assoc,
rw ← finset.coe_subset at A2,
rw set.inter_eq_self_of_subset_right A2,
end
lemma set.insert_inter_of_not_mem {α:Type*} {A B:set α} {x:α}:(x∉ B) → ((insert x A) ∩ B = A ∩ B) :=
begin
intros A1,
ext a,
split;intros A2;simp at A2;simp,
{
cases A2 with A2 A3,
cases A2 with A2 A4,
{
subst A2,
exfalso,
apply A1 A3,
},
{
apply and.intro A4 A3,
},
},
{
apply and.intro (or.inr A2.left) A2.right,
},
end
lemma set.inter_insert_of_not_mem {α:Type*} {A B:set α} {x:α}:(x∉ A) → (A ∩ (insert x B) = A ∩ B) :=
begin
intros A1,
rw set.inter_comm,
rw set.insert_inter_of_not_mem A1,
rw set.inter_comm,
end
lemma set.not_mem_of_inter_insert {α:Type*} {A B:set α} {x:α}:(x∉ A) → (A ∩ (insert x B) = A ∩ B) :=
begin
intros A1,
rw set.inter_comm,
rw set.insert_inter_of_not_mem A1,
rw set.inter_comm,
end
lemma set.inter_insert_of_mem {α:Type*} {A B:set α} {x:α}:(x∈ A) → (A ∩ (insert x B) = insert x (A ∩ B)) :=
begin
intros A1,
rw set.insert_inter,
rw set.insert_eq_of_mem A1,
end
lemma set.mem_of_inter_insert {α:Type*} {A B C:set α} {x:α}:
(A ∩ (insert x B) = insert x (C)) → (x ∈ A) :=
begin
intros A1,
have B1 := set.mem_insert x (C),
rw ← A1 at B1,
simp at B1,
apply B1,
end
lemma set.eq_of_insert_of_not_mem {α:Type*} {A B:set α} {x:α}:(x∉ A) → (x∉ B) → (insert x A = insert x B)
→ A = B :=
begin
intros A1 A3 A2,
ext a;split;intros B1;have C1 := set.mem_insert_of_mem x B1,
{
rw A2 at C1,
apply set.mem_of_mem_insert_of_ne C1,
intros C2,
subst a,
apply A1 B1,
},
{
rw ← A2 at C1,
apply set.mem_of_mem_insert_of_ne C1,
intros C2,
subst a,
apply A3 B1,
},
end
lemma set.insert_subset_insert {α:Type*} {A B:set α} {x:α}:A ⊆ B → (insert x A) ⊆ (insert x B) :=
begin
intros A1,
rw set.subset_def,
intros a B1,
simp at B1,
simp,
cases B1 with B1 B1,
apply or.inl B1,
apply or.inr (A1 B1),
end
lemma finset.eq_of_insert_of_not_mem {α:Type*} {A B:finset α} {x:α}:(x∉ A) → (x∉ B) → (insert x A = insert x B)
→ A = B :=
begin
intros A1 A3 A2,
ext a;split;intros B1;have C1 := finset.mem_insert_of_mem B1,
{
rw A2 at C1,
apply finset.mem_of_mem_insert_of_ne C1,
intros C2,
subst a,
apply A1 B1,
},
{
rw ← A2 at C1,
apply finset.mem_of_mem_insert_of_ne C1,
intros C2,
subst a,
apply A3 B1,
},
end
lemma mem_restrict_set_insert {C:set (set α)} {S c:finset α} {x:α}:x∉ S → (x∉ c) →
((c ∈ restrict_set C S) ↔ (insert x c ∈ restrict_set C (insert x S)) ∨ c∈ restrict_set C (insert x S))
:=
begin
repeat {rw mem_restrict_set},
intros A1 AX,split;intros A2,
{
cases A2 with c' A2,
cases A2 with A2 A3,
cases (em (x∈ c')) with B1 B1,
{
left,
apply exists.intro c',
apply exists.intro A2,
simp,
have B2:insert x c' = c' := set.insert_eq_of_mem B1,
rw ← B2,
rw ← set.insert_inter,
rw A3,
},
{
right,
apply exists.intro c',
apply exists.intro A2,
simp,
rw set.inter_insert_of_not_mem B1,
apply A3,
},
},
{
cases A2 with A2 A2;cases A2 with c' A2;cases A2 with A2 A3;
apply exists.intro c';apply exists.intro A2,
{
simp at A3,
have C1:=set.mem_of_inter_insert A3,
rw set.inter_insert_of_mem C1 at A3,
apply set.eq_of_insert_of_not_mem _ _ A3,
simp,
intro C2,
apply A1,
apply AX,
},
{
ext a;split;intros D1,
{
rw ← A3,
simp at D1,
simp [D1],
},
{
have D2:a ≠ x,
{
intros D2A,
subst a,
apply AX D1,
},
rw ← A3 at D1,
simp [D2] at D1,
simp [D1],
},
},
},
end
lemma finset.insert_inter_eq_insert_inter_insert {α:Type*} [decidable_eq α]
{S T:finset α} {a:α}:(insert a S) ∩ (insert a T) = insert a (S ∩ T) :=
begin
ext b,
split;intros A1,
{
rw finset.mem_insert,
simp at A1,
cases A1,
subst a,
simp,
cases A1 with A1 A2,
cases A1 with A1 A1,
apply or.inl A1,
simp [A1,A2],
},
{
simp,
simp at A1,
cases A1 with A1 A1,
apply or.inl A1,
simp [A1],
},
end
lemma mem_restrict_set_erase {C:set (set α)} {S c:finset α} {x:α}:x∉ S → (x∈ c) →
(c ∈ restrict_set C (insert x S)) → (c.erase x ∈ restrict_set C S)
:=
begin
intros A1 A2 A3,
rw mem_restrict_set_insert A1,
left,
rw finset.insert_erase,
apply A3,
apply A2,
apply finset.not_mem_erase,
end
lemma restrict_card_le_one_of_VCD_zero {C:set (set α)} {S:finset α}:(VCD C = 0) →
(restrict_set C S).card ≤ 1 :=
begin
intros A1,
apply finset.card_identical_elements,
intros T U B1 B2,
apply restrict_set_elements_eq_of_VCD_zero A1 B1 B2,
end
lemma restrict_set_empty_of_empty {S:finset α}:restrict_set ∅ S = ∅ :=
begin
ext c,
rw mem_restrict_set,
split;intros B1,
{
cases B1 with c2 B1,
cases B1 with B1 B2,
simp at B1,
exfalso,
apply B1,
},
{
exfalso,
simp at B1,
apply B1,
},
end
lemma restrict_set_nonempty_empty {C:set (set α)}:
set.nonempty C → restrict_set C ∅ = {∅} :=
begin
intros A1,
ext c,
rw mem_restrict_set,split;intros B1,
{
simp,
cases B1 with c' B1,
cases B1 with B1 B2,
rw ← finset.coe_inj,
rw ← B2,
simp,
},
{
simp at B1,
subst c,
rw set.nonempty_def at A1,
cases A1 with c' A1,
apply exists.intro c',
apply exists.intro A1,
simp,
},
end
lemma restrict_set_empty_card_le_1 {C:set (set α)}:
(restrict_set C ∅).card ≤ 1 :=
begin
cases (set.eq_empty_or_nonempty C) with B1 B1,
{
subst C,
rw restrict_set_empty_of_empty,
simp,
},
{
rw restrict_set_nonempty_empty B1,
simp,
},
end
lemma filter_union {S:finset α} {P:α → Prop}:
finset.filter P S ∪ finset.filter (λ a, ¬P a) S = S :=
begin
ext a;split;intro A1,
{
simp at A1,
cases A1 with A1 A1;apply A1.left,
},
{
simp,
simp [A1],
apply em,
},
end
lemma filter_disjoint {S T:finset α} {P:α → Prop}:
disjoint (finset.filter P S) (finset.filter (λ a, ¬P a) T) :=
begin
rw finset.disjoint_left,
intros a B1 B2,
simp at B1,
simp at B2,
apply B2.right,
apply B1.right,
end
lemma filter_disjoint' {S:finset α} {P:α → Prop}:
disjoint (finset.filter P S) (finset.filter (λ a, ¬P a) S) :=
@filter_disjoint α S S P
lemma filter_card {S:finset α} {P:α → Prop}:
(finset.filter P S).card + (finset.filter (λ a, ¬P a) S).card = S.card :=
begin
have A1:(finset.filter P S ∪ finset.filter (λ a, ¬P a) S).card = S.card,
{
rw filter_union,
},
rw ← A1,
rw finset.card_union_eq,
apply filter_disjoint,
end
lemma recursive_restrict_set_card {C:set (set α)} {x:α} {S:finset α}:x∉ S →
((restrict_set C (insert x S)).filter (λ c,(x∉c ∧ (insert x c) ∈ (restrict_set
C (insert x S))))).card + (restrict_set C S).card = (restrict_set C (insert x S)).card :=
begin
intro A1,
let Ex := restrict_set C (insert x S),
let E := restrict_set C S,
begin
have B1:Ex = restrict_set C (insert x S) := rfl,
have B2:E = restrict_set C S := rfl,
repeat {rw ← B1},
repeat {rw ← B2},
rw add_comm,
rw ← @filter_card _ Ex (λ c, x ∈ c),
simp,
simp,
rw ← @filter_card _ (finset.filter (λ c, x∉ c) Ex)
(λ c, (insert x c) ∈ Ex),
simp,
repeat {rw finset.filter_filter},
rw add_comm _ (finset.filter (λ (a : finset α), x ∉ a ∧ insert x a ∉ Ex) Ex).card,
rw ← add_assoc,
simp,
have C1:(finset.filter (λ (a : finset α), x ∉ a ∧ insert x a ∉ Ex) Ex) =
(finset.filter (λ (a : finset α), insert x a ∉ Ex) E),
{
ext c,split;repeat {rw B1};repeat {rw B2};intros C1A;simp at C1A;simp [C1A],
{ rw mem_restrict_set_insert A1 C1A.right.left, apply or.inr C1A.left},
{
have C1B:x ∉ c,
{
have C1B1:c ⊆ S := mem_restrict_set_subset C1A.left,
intro C1B2,
apply A1,
apply C1B1,
apply C1B2,
},
have C1C := (mem_restrict_set_insert A1 C1B).mp C1A.left,
simp [C1A.right] at C1C,
apply and.intro C1C C1B,
},
},
rw C1,
clear C1,
have C2:(finset.filter (has_mem.mem x) Ex).card =
(finset.filter (λ a, insert x a ∈ Ex) E).card ,
{
have C2A:(finset.filter (has_mem.mem x) Ex) =
(finset.filter (λ a, insert x a ∈ Ex) E).image (insert x),
{
ext a,split;repeat {rw B1};repeat {rw B2};intros C2A1;simp at C2A1;simp,
{
apply exists.intro (a.erase x),
cases C2A1 with C2A1 C2A2,
have C2A3:insert x (a.erase x) = a := finset.insert_erase C2A2,
have C2A4:x ∉ a.erase x := finset.not_mem_erase x a,
split,
split,
apply mem_restrict_set_erase A1 C2A2 C2A1,
rw C2A3,
apply C2A1,
apply C2A3,
},
{
cases C2A1 with c C2A1,
cases C2A1 with C2A1 C2A2,
cases C2A1 with C2A1 C2A3,
subst a,
simp [C2A3],
},
},
rw C2A,
clear C2A,
repeat {rw B1},
repeat {rw B2},
apply finset.card_image_of_inj_on,
intros c C2B c' C2C,
simp at C2B,
simp at C2C,
have C2D:∀ {c'':finset α}, c'' ∈ restrict_set C S → x ∉ c'',
{
intros c'' C2D1 C2D3,
apply A1,
have C2D2 := mem_restrict_set_subset C2D1,
apply C2D2,
apply C2D3,
},
apply finset.eq_of_insert_of_not_mem,
apply C2D C2B.left,
apply C2D C2C.left,
},
rw C2,
rw ← @filter_card _ E (λ a, insert x a ∈ Ex),
simp,
end
end
lemma enat.le_coe_eq_coe {v:enat} {d:nat}:v ≤ d → ∃ d':ℕ, v = d' ∧ d' ≤ d :=
begin
--intros A1,
apply enat.cases_on v,
{
intros A1,
simp at A1,
exfalso,
apply A1,
},
{
intros n A1,
apply exists.intro n,
simp at A1,
simp [A1],
},
end
lemma phi_monotone_m {d m₁ m₂:ℕ}:m₁ ≤ m₂ → Φ d m₁ ≤ Φ d m₂ :=
begin
intros A1,
rw le_iff_exists_add at A1,
cases A1 with c A1,
subst m₂,
induction c,
simp,
have A2:(m₁ + c_n.succ) = (m₁ + c_n).succ := rfl,
rw A2,
cases d,
simp,
rw phi_succ_succ,
apply le_trans c_ih,
simp,
end
lemma phi_le_d_succ {d m:ℕ}:Φ d m ≤ Φ d.succ m :=
begin
revert d,
induction m,
intro d,
simp,
intro d,
rw phi_succ_succ,
cases d,
simp,
rw phi_succ_succ,
rw add_comm,
simp,
apply le_trans m_ih,
apply m_ih,
end
lemma phi_monotone_d {d₁ d₂ m:ℕ}:d₁ ≤ d₂ → Φ d₁ m ≤ Φ d₂ m :=
begin
intros A1,
rw le_iff_exists_add at A1,
cases A1 with c A1,
subst d₂,
induction c,
simp,
have A2:(d₁ + c_n.succ) = (d₁ + c_n).succ := rfl,
rw A2,
apply le_trans c_ih,
apply phi_le_d_succ,
end
lemma eq_restrict_set {C:finset (finset α)} {S:finset α}:(∀ c∈ C , c⊆ S)→
C = restrict_set (C.to_set_of_sets) S :=
begin
intros A1,
ext c,split;intros B1,
{
rw mem_restrict_set,
apply exists.intro (↑c),
split,
rw finset.mem_to_set_of_sets,
apply B1,
have B2 := A1 c B1,
apply set.inter_eq_self_of_subset_left,
simp,
apply B2,
},
{
rw mem_restrict_set at B1,
cases B1 with c' B1,
cases B1 with B1 B2,
rw finset.mem_to_set_of_sets' at B1,
cases B1 with c'' B1,
cases B1 with B1 B2,
subst c',
rw set.inter_eq_self_of_subset_left at B2,
simp at B2,
subst c'',
apply B1,
simp,
apply A1 c'' B1,
},
end
lemma finite_restrict_set_eq_image {C:finset (finset α)} {S:finset α}:
(restrict_set C.to_set_of_sets S) = C.image (λ S', S'∩ S) :=
begin
ext,split;intros A1A,
{
simp,
rw mem_restrict_set at A1A,
cases A1A with c A1A,
cases A1A with A1A A1B,
rw finset.mem_to_set_of_sets' at A1A,
cases A1A with c' A1A,
apply exists.intro c',
cases A1A with A1A A1C,
rw A1C at A1B,
rw ← finset.coe_inter at A1B,
rw finset.coe_inj at A1B,
apply and.intro A1A A1B,
},
{
simp at A1A,
cases A1A with c A1A,
cases A1A with A1A A1B,
subst a,
rw mem_restrict_set,
apply exists.intro (↑c),
split,
rw finset.mem_to_set_of_sets,
apply A1A,
rw finset.coe_inter,
},
end
lemma finite_restrict_set_le {C:finset (finset α)} {S:finset α}:
(restrict_set C.to_set_of_sets S).card ≤ C.card :=
begin
rw finite_restrict_set_eq_image,
apply finset.card_image_le,
end
lemma shatters_subset {S:finset α} {x:α} {C:set (set α)} {S':finset α}:x∉S →
shatters (
(
(restrict_set C (insert x S)).filter
(λ (c:finset α),(x∉c ∧ ((insert x c) ∈ (restrict_set C (insert x S)))))
).to_set_of_sets
) S' → S' ⊆ S :=
begin
intros A1 A2,
rw shatters_iff at A2,
have D1A:S' ⊆ S' := finset.subset.refl S',
have D1B := A2 S' D1A,
cases D1B with c D1B,
cases D1B with D1B D1C,
rw finset.mem_to_set_of_sets' at D1B,
cases D1B with c' D1B,
cases D1B with D1B D1D,
subst c,
simp at D1B,
cases D1B with D1B D1E,
cases D1E with D1E D1F,
have D1G:= mem_restrict_set_subset D1B,
rw ← finset.coe_inter at D1C,
rw finset.coe_inj at D1C,
have D1H:S'⊆ c',
{
rw ← D1C,
apply finset.inter_subset_left,
},
apply finset.subset.trans D1H,
apply finset.subset_of_not_mem_of_subset_insert D1E D1G,
end
lemma shatters_succ {S:finset α} {x:α} {C:set (set α)} {S':finset α}:x∉S →
shatters (
(
(restrict_set C (insert x S)).filter
(λ (c:finset α),(x∉c ∧ ((insert x c) ∈ (restrict_set C (insert x S)))))
).to_set_of_sets
) S' → shatters C (insert x S') :=
begin
intros A1 A2,
rw shatters_iff,
intros c B1,
have D1:S' ⊆ S := shatters_subset A1 A2,
have D2:(insert x (↑S':set α)) ⊆ (insert x ↑S),
{
apply set.insert_subset_insert,
simp,
apply D1,
},
rw shatters_iff at A2,
cases (em (x ∈ c)) with A3 A3,
{
have C1:c.erase x ⊆ S',
{
rw ← finset.subset_insert_iff,
apply B1,
},
have B2 := A2 (c.erase x) C1,
cases B2 with c' B2,
cases B2 with B2 B3,
simp,
rw finset.mem_to_set_of_sets' at B2,
cases B2 with c'' B2,
cases B2 with B2 B4,
simp at B2,
cases B2 with B2 B5,
cases B5 with B5 B6,
rw mem_restrict_set at B6,
cases B6 with c''' B6,
cases B6 with B6 B7,
subst c',
apply exists.intro c''',
apply and.intro B6,
simp at B7,
rw ← finset.coe_inter at B3,
rw finset.coe_inj at B3,
have B8:insert x (c'' ∩ S') = insert x (c.erase x),
{
rw B3,
},
rw finset.insert_erase A3 at B8,
have B9 := set.mem_of_inter_insert B7,
rw ← finset.insert_inter_eq_insert_inter_insert at B8,
rw ← B8,
rw finset.coe_inter,
repeat {rw finset.coe_insert},
rw ← B7,
rw set.inter_assoc,
rw set.inter_comm (insert x ↑S),
rw ← set.inter_assoc,
symmetry,
apply set.inter_eq_self_of_subset_left,
have B10:=set.inter_subset_right c''' (insert x ↑S'),
apply set.subset.trans B10 D2,
},
{
have E1:c ⊆ S',
{
rw finset.subset_iff,
intros a E1A,
have E1B := B1 E1A,
rw finset.mem_insert at E1B,
cases E1B with E1B E1B,
{
subst a,
exfalso,
apply A3 E1A,
},
apply E1B,
},
have E2 := A2 c E1,
cases E2 with c' E2,
cases E2 with E2 E3,
rw finset.mem_to_set_of_sets' at E2,
cases E2 with c'' E2,
cases E2 with E2 E3,
simp at E2,
subst c',
cases E2 with E2 E4,
cases E4 with E4 E5,
rw mem_restrict_set at E2,
cases E2 with c''' E2,
cases E2 with E2 E6,
apply exists.intro c''',
apply exists.intro E2,
have E7:x ∉ (↑c'':set α),
{simp [E4]},
rw ← set.inter_insert_of_not_mem E7 at E3,
simp at E6,
rw ← E3,
simp,
rw ← E6,
rw set.inter_assoc,
rw set.inter_comm (insert x ↑S),
rw ← set.inter_assoc,
symmetry,
apply set.inter_eq_self_of_subset_left,
have E8:=set.inter_subset_right c''' (insert x ↑S'),
apply set.subset.trans E8 D2,
},
end
lemma VCD_succ {S:finset α} {x:α} {C:set (set α)} {d:ℕ}:x∉S → VCD C = d.succ →
VCD (
(
(restrict_set C (insert x S)).filter
(λ (c:finset α),(x∉c ∧ ((insert x c) ∈ (restrict_set C (insert x S)))))
).to_set_of_sets
) ≤ d :=
begin
intros A1 A2,
apply VCD_le,
intros T B1,
have B2:T ⊆ S := shatters_subset A1 B1,
have B3:x ∉ T,
{
intro B3A,
apply A1,
apply B2,
apply B3A,
},
have B4:shatters C (insert x T),
{
apply shatters_succ,
apply A1,
apply B1,
},
have B5:((insert x T).card:enat) ≤ VCD C,
{
apply shatters_card_le_VCD B4,
},
rw A2 at B5,
simp at B5,
rw finset.card_insert_of_not_mem B3 at B5,
have B6:T.card + 1 = (T.card).succ := rfl,
rw B6 at B5,
rw nat.succ_le_succ_iff at B5,
simp,
apply B5
end
--This is known as Sauer's Lemma, or Sauer-Saleh Lemma.
--This connects VC-dimension to the complexity of the hypothesis space restricted to a finite set
--of certain size.
lemma restrict_set_le_phi {C:set (set α)} {S:finset α} (d:ℕ):
(VCD C = d) →
(restrict_set C S).card ≤ Φ d S.card :=
begin
revert d,
revert C,
apply finset.induction_on S,
{
intros C d A1,
simp,
apply restrict_set_empty_card_le_1,
},
{
intros x S B1 B2 C d B3,
cases d,
{
rw phi_zero_m_eq_one,
apply restrict_card_le_one_of_VCD_zero,
simp at B3,
apply B3,
},
let C':finset (finset α) := (restrict_set C (insert x S)).filter (λ c,(x∉c ∧ (insert x c) ∈ (restrict_set C (insert x S)))),
begin
have C0:C' = (restrict_set C (insert x S)).filter (λ c,(x∉c ∧ (insert x c) ∈ (restrict_set C (insert x S)))) := rfl,
rw ← recursive_restrict_set_card B1,
rw ← C0,
have D1:C'.card + (restrict_set C S).card ≤ C'.card + Φ d.succ S.card,
{
simp [B2,B3],
},
apply le_trans D1,
have C5:C' = restrict_set (C'.to_set_of_sets) S,
{
apply eq_restrict_set,
intros c C3A,
rw C0 at C3A,
simp at C3A,
have C3C := mem_restrict_set_subset C3A.left,
apply finset.subset_of_not_mem_of_subset_insert C3A.right.left C3C,
},
rw C5,
have C6:VCD (C'.to_set_of_sets) ≤ (d:enat),
{
rw C0,
apply VCD_succ,
apply B1,
apply B3
},
have C7:∃d':ℕ, VCD (C'.to_set_of_sets) = d' ∧ d' ≤ d,
{
apply enat.le_coe_eq_coe C6,
},
cases C7 with d' C7,
have C8:(restrict_set C'.to_set_of_sets S).card + Φ d.succ S.card ≤ Φ d S.card + Φ d.succ S.card,
{
simp,
have C8A:(restrict_set C'.to_set_of_sets S).card ≤ Φ d' S.card,
{
apply B2,
apply C7.left,
},
apply le_trans C8A,
apply phi_monotone_d,
apply C7.right,
},
apply le_trans C8,
rw finset.card_insert_of_not_mem B1,
rw phi_succ_succ,
rw add_comm,
end,
},
end
-- TODO: prove Φ d m = (finset.range (d.succ)).sum (λ i, nat.choose m i)
-- See mathlib/src/data/nat/choose/basic.lean
-- TODO: introduce ε-nets, and show that the VC dimension of C is a bound on
-- the VC-dimension of the ε-net.
-- TODO: show that if the training examples cover the ε-net, then any consistent
-- algorithm will get a hypothesis with low error.
-- TODO: Introduce the proof from 3.5.2 proving a bound on the probability of
-- hitting the ε-net.
end VC_PAC_problem
end VC_PAC_problem
|
de3df59e7ed24308207f252a8812048bf9b3b0ef | 90bd8c2a52dbaaba588bdab57b155a7ec1532de0 | /src/homotopy_group/basic.lean | e1ceb1b0926d219ee7cfca022e2b80f7040b7965 | [
"Apache-2.0"
] | permissive | shingtaklam1324/alg-top | fd434f1478925a232af45f18f370ee3a22811c54 | 4c88e28df6f0a329f26eab32bae023789193990e | refs/heads/master | 1,689,447,024,947 | 1,630,073,400,000 | 1,630,073,400,000 | 381,528,689 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,268 | lean | import homotopy.loop
import homotopy.tactic
/-!
# The Fundamental Group of a Topological Space
In this file, we define the fundamental group `π₁ x₀` of a topological space `X` based at `x₀`.
-/
noncomputable theory
variables {X : Type _} [topological_space X]
/--
For `x₀ : X`, `π₁ x₀` is the fundamental group of `X` based at `x₀`.
-/
@[nolint has_inhabited_instance] -- I think it might be always inhabited? But I'm not sure.
def π₁ (x₀ : X) := quotient (@loop.setoid _ _ x₀)
namespace π₁
variables {x₀ : X}
/--
Multiplication of elements in `π₁ x₀` is defined by joining the paths of an element of the
homotopy class.
-/
def mul (l₀ l₁ : π₁ x₀) : π₁ x₀ := quotient.lift₂ (λ l l' : loop x₀, quotient.mk (l.trans l'))
begin
rintros p₁ p₂ q₁ q₂ ⟨h₁⟩ ⟨h₂⟩,
simp only [quotient.eq],
exact ⟨path_homotopy.trans₂ h₁ h₂⟩,
end l₀ l₁
/--
The identity in `π₁ x₀` is the homotopy class of the coonstant path.
-/
def one : π₁ x₀ := quotient.mk (path'.const x₀)
/--
The inverse of an element `l` of `π₁ x₀` is defined by taking the inverse of an element of the
equivalence class.
-/
def inv (l : π₁ x₀) : π₁ x₀ := quotient.lift (λ l', quotient.mk (path'.inv l'))
begin
rintros p₁ p₂ ⟨h₁⟩,
simp only [quotient.eq],
exact ⟨h₁.inv⟩,
end l
instance : has_mul (π₁ x₀) := ⟨mul⟩
instance : has_one (π₁ x₀) := ⟨one⟩
instance : has_inv (π₁ x₀) := ⟨inv⟩
lemma mul_def (l₀ l₁ : loop x₀) : @has_mul.mul (π₁ x₀) _ (⟦l₀⟧ : π₁ x₀) ⟦l₁⟧ = ⟦l₀.trans l₁⟧ := rfl
lemma one_def : (1 : π₁ x₀) = ⟦path'.const x₀⟧ := rfl
lemma inv_def (l : loop x₀) : @has_inv.inv (π₁ x₀) _ ⟦l⟧ = ⟦path'.inv l⟧ := rfl
lemma mul_assoc (l₀ l₁ l₂ : π₁ x₀) : l₀ * l₁ * l₂ = l₀ * (l₁ * l₂) :=
quotient.induction_on₃ l₀ l₁ l₂ (λ p₀ p₁ p₂, begin
simp only [mul_def, quotient.eq],
exact ⟨path_homotopy.assoc⟩,
end)
lemma one_mul (l : π₁ x₀) : 1 * l = l :=
quotient.induction_on l (λ p, begin
simp only [one_def, mul_def, quotient.eq],
exact ⟨(path_homotopy.const_trans p).symm⟩,
end)
lemma mul_one (l : π₁ x₀) : l * 1 = l :=
quotient.induction_on l (λ p, begin
simp only [one_def, mul_def, quotient.eq],
exact ⟨(path_homotopy.trans_const p).symm⟩,
end)
lemma mul_left_inv (l : π₁ x₀) : l⁻¹ * l = 1 :=
quotient.induction_on l (λ p, begin
simp [one_def, mul_def, inv_def],
refine ⟨path_homotopy.trans_left_inv⟩,
end)
/--
The `group` instance for `π₁ x₀`.
-/
instance : group (π₁ x₀) :=
{ mul_assoc := mul_assoc,
one_mul := one_mul,
mul_one := mul_one,
mul_left_inv := mul_left_inv,
..π₁.has_mul, ..π₁.has_inv, ..π₁.has_one }
section defs
open path_homotopy.tactic
/--
Given a path `α` from `x₀` to `x₁`, we can define a group isomorphism from `π₁ x₀` to `π₁ x₁`.
-/
def change_of_basepoint {x₀ x₁ : X} (α : path' x₀ x₁) : π₁ x₀ ≃* π₁ x₁ :=
{ to_fun := quotient.lift (λ l, ⟦(α.inv.trans l).trans α⟧) begin
rintros a b ⟨h⟩,
rw quotient.eq,
exact ⟨path_homotopy.trans₂
(path_homotopy.trans₂ (path_homotopy.refl _) h) (path_homotopy.refl _)⟩,
end,
inv_fun := quotient.lift (λ l, ⟦(α.trans l).trans α.inv⟧) begin
rintros a b ⟨h⟩,
rw quotient.eq,
refine
⟨path_homotopy.trans₂ (path_homotopy.trans₂ (path_homotopy.refl _) h) (path_homotopy.refl _)⟩,
end,
left_inv := begin
intro l,
apply quotient.induction_on l,
intro p,
rw [quotient.lift_mk, quotient.lift_mk, quotient.eq],
refine ⟨homotopy_with.trans
(homotopy_with.trans _ (path_homotopy.trans₂ (@path_homotopy.trans_right_inv _ _ _ _ α)
(path_homotopy.trans₂ (path_homotopy.refl _) (@path_homotopy.trans_right_inv _ _ _ _ α))))
(homotopy_with.trans (path_homotopy.trans_const _) (path_homotopy.const_trans _)).symm⟩,
assocl, assocr',
refine path_homotopy.trans₂ (path_homotopy.refl _) _,
assocl, assocl,
exact path_homotopy.refl _,
end,
right_inv := begin
intro l,
apply quotient.induction_on l,
intro p,
rw [quotient.lift_mk, quotient.lift_mk, quotient.eq],
refine ⟨homotopy_with.trans
(homotopy_with.trans _ (path_homotopy.trans₂ (@path_homotopy.trans_left_inv _ _ _ _ α)
(path_homotopy.trans₂ (path_homotopy.refl _) (@path_homotopy.trans_left_inv _ _ _ _ α))))
(homotopy_with.trans (path_homotopy.trans_const _) (path_homotopy.const_trans _)).symm⟩,
assocl, assocr',
refine path_homotopy.trans₂ (path_homotopy.refl _) _,
assocl, assocl,
refine path_homotopy.trans₂ (path_homotopy.refl _) _,
exact path_homotopy.refl _,
end,
map_mul' := begin
intros x y,
apply quotient.induction_on₂ x y,
intros p q,
rw [mul_def, quotient.lift_mk, quotient.lift_mk, quotient.lift_mk, mul_def, quotient.eq],
exact ⟨homotopy_with.trans (path_homotopy.trans₂ (homotopy_with.trans
(homotopy_with.trans path_homotopy.assoc.symm (path_homotopy.trans₂ (homotopy_with.trans
(homotopy_with.trans (path_homotopy.trans_const _)
(path_homotopy.trans₂
(path_homotopy.refl _) path_homotopy.trans_right_inv.symm)) path_homotopy.assoc.symm)
(path_homotopy.refl _)))
path_homotopy.assoc)
(path_homotopy.refl _)) path_homotopy.assoc⟩,
end }
/--
Given a continuous function `f : C(X, Y)`, we have a group homomorphism from `π₁ x₀` to `π₁ (f x₀)`.
-/
def map {Y : Type _} [topological_space Y] (f : C(X, Y)) : π₁ x₀ →* π₁ (f x₀) :=
{ to_fun := quotient.lift (λ l, ⟦path'.map l f⟧) begin
rintros a b ⟨h⟩,
rw [quotient.eq],
exact ⟨h.map _⟩,
end,
map_one' := begin
rw [one_def, one_def, quotient.lift_mk, quotient.eq],
exact ⟨path_homotopy.of_refl (path'.const_map _ _)⟩,
end,
map_mul' := begin
intros x y,
apply quotient.induction_on₂ x y,
intros p q,
rw [mul_def, quotient.lift_mk, quotient.lift_mk, quotient.lift_mk, mul_def, quotient.eq],
refine ⟨path_homotopy.of_refl (path'.map_trans _ _ _)⟩,
end } .
lemma map_comp {Y Z : Type _} [topological_space Y] [topological_space Z] (h : C(X, Y)) (k : C(Y, Z)) :
@map _ _ x₀ _ _ (k.comp h) = (map k).comp (map h) :=
begin
ext t,
apply quotient.induction_on t,
intro a,
simp [map],
end
@[simp] lemma map_id :
@map _ _ x₀ _ _ continuous_map.id = monoid_hom.id _ :=
begin
ext t,
apply quotient.induction_on t,
intro a,
simp only [map, path'.map, quotient.lift_mk, monoid_hom.id_apply, monoid_hom.coe_mk, quotient.eq],
refine ⟨path_homotopy.of_refl _⟩,
ext u,
refl,
end
end defs
section path_connected
variable [path_connected_space X]
/--
In a path connected space `X`, for `x₀ x₁ : X`, `π₁ x₀` and `π₁ x₁` are isomorphic.
-/
noncomputable def mul_equiv_of_path_connected (x₀ x₁ : X) :
π₁ x₀ ≃* π₁ x₁ :=
change_of_basepoint (path'.of_path (path_connected_space.some_path x₀ x₁))
end path_connected
end π₁
|
a0c739d32bdd480b3646f6be3f99bcb9b8e1646d | 4fa161becb8ce7378a709f5992a594764699e268 | /src/data/list/range.lean | b4d8704aa7f58dcde48452ff90d503ea8f92949f | [
"Apache-2.0"
] | permissive | laughinggas/mathlib | e4aa4565ae34e46e834434284cb26bd9d67bc373 | 86dcd5cda7a5017c8b3c8876c89a510a19d49aad | refs/heads/master | 1,669,496,232,688 | 1,592,831,995,000 | 1,592,831,995,000 | 274,155,979 | 0 | 0 | Apache-2.0 | 1,592,835,190,000 | 1,592,835,189,000 | null | UTF-8 | Lean | false | false | 8,391 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Kenny Lau, Scott Morrison
-/
import data.list.chain
import data.list.nodup
import data.list.of_fn
open nat
namespace list
/- iota and range(') -/
universe u
variables {α : Type u}
@[simp] theorem length_range' : ∀ (s n : ℕ), length (range' s n) = n
| s 0 := rfl
| s (n+1) := congr_arg succ (length_range' _ _)
@[simp] theorem mem_range' {m : ℕ} : ∀ {s n : ℕ}, m ∈ range' s n ↔ s ≤ m ∧ m < s + n
| s 0 := (false_iff _).2 $ λ ⟨H1, H2⟩, not_le_of_lt H2 H1
| s (succ n) :=
have m = s → m < s + n + 1,
from λ e, e ▸ lt_succ_of_le (le_add_right _ _),
have l : m = s ∨ s + 1 ≤ m ↔ s ≤ m,
by simpa only [eq_comm] using (@le_iff_eq_or_lt _ _ s m).symm,
(mem_cons_iff _ _ _).trans $ by simp only [mem_range',
or_and_distrib_left, or_iff_right_of_imp this, l, add_right_comm]; refl
theorem map_add_range' (a) : ∀ s n : ℕ, map ((+) a) (range' s n) = range' (a + s) n
| s 0 := rfl
| s (n+1) := congr_arg (cons _) (map_add_range' (s+1) n)
theorem map_sub_range' (a) :
∀ (s n : ℕ) (h : a ≤ s), map (λ x, x - a) (range' s n) = range' (s - a) n
| s 0 _ := rfl
| s (n+1) h :=
begin
convert congr_arg (cons (s-a)) (map_sub_range' (s+1) n (nat.le_succ_of_le h)),
rw nat.succ_sub h,
refl,
end
theorem chain_succ_range' : ∀ s n : ℕ, chain (λ a b, b = succ a) s (range' (s+1) n)
| s 0 := chain.nil
| s (n+1) := (chain_succ_range' (s+1) n).cons rfl
theorem chain_lt_range' (s n : ℕ) : chain (<) s (range' (s+1) n) :=
(chain_succ_range' s n).imp (λ a b e, e.symm ▸ lt_succ_self _)
theorem pairwise_lt_range' : ∀ s n : ℕ, pairwise (<) (range' s n)
| s 0 := pairwise.nil
| s (n+1) := (chain_iff_pairwise (by exact λ a b c, lt_trans)).1 (chain_lt_range' s n)
theorem nodup_range' (s n : ℕ) : nodup (range' s n) :=
(pairwise_lt_range' s n).imp (λ a b, ne_of_lt)
@[simp] theorem range'_append : ∀ s m n : ℕ, range' s m ++ range' (s+m) n = range' s (n+m)
| s 0 n := rfl
| s (m+1) n := show s :: (range' (s+1) m ++ range' (s+m+1) n) = s :: range' (s+1) (n+m),
by rw [add_right_comm, range'_append]
theorem range'_sublist_right {s m n : ℕ} : range' s m <+ range' s n ↔ m ≤ n :=
⟨λ h, by simpa only [length_range'] using length_le_of_sublist h,
λ h, by rw [← nat.sub_add_cancel h, ← range'_append]; apply sublist_append_left⟩
theorem range'_subset_right {s m n : ℕ} : range' s m ⊆ range' s n ↔ m ≤ n :=
⟨λ h, le_of_not_lt $ λ hn, lt_irrefl (s+n) $
(mem_range'.1 $ h $ mem_range'.2 ⟨le_add_right _ _, nat.add_lt_add_left hn s⟩).2,
λ h, (range'_sublist_right.2 h).subset⟩
theorem nth_range' : ∀ s {m n : ℕ}, m < n → nth (range' s n) m = some (s + m)
| s 0 (n+1) _ := rfl
| s (m+1) (n+1) h := (nth_range' (s+1) (lt_of_add_lt_add_right h)).trans $
by rw add_right_comm; refl
theorem range'_concat (s n : ℕ) : range' s (n + 1) = range' s n ++ [s+n] :=
by rw add_comm n 1; exact (range'_append s n 1).symm
theorem range_core_range' : ∀ s n : ℕ, range_core s (range' s n) = range' 0 (n + s)
| 0 n := rfl
| (s+1) n := by rw [show n+(s+1) = n+1+s, from add_right_comm n s 1];
exact range_core_range' s (n+1)
theorem range_eq_range' (n : ℕ) : range n = range' 0 n :=
(range_core_range' n 0).trans $ by rw zero_add
theorem range_succ_eq_map (n : ℕ) : range (n + 1) = 0 :: map succ (range n) :=
by rw [range_eq_range', range_eq_range', range',
add_comm, ← map_add_range'];
congr; exact funext one_add
theorem range'_eq_map_range (s n : ℕ) : range' s n = map ((+) s) (range n) :=
by rw [range_eq_range', map_add_range']; refl
@[simp] theorem length_range (n : ℕ) : length (range n) = n :=
by simp only [range_eq_range', length_range']
theorem pairwise_lt_range (n : ℕ) : pairwise (<) (range n) :=
by simp only [range_eq_range', pairwise_lt_range']
theorem nodup_range (n : ℕ) : nodup (range n) :=
by simp only [range_eq_range', nodup_range']
theorem range_sublist {m n : ℕ} : range m <+ range n ↔ m ≤ n :=
by simp only [range_eq_range', range'_sublist_right]
theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n :=
by simp only [range_eq_range', range'_subset_right]
@[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n :=
by simp only [range_eq_range', mem_range', nat.zero_le, true_and, zero_add]
@[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n :=
mt mem_range.1 $ lt_irrefl _
@[simp] theorem self_mem_range_succ (n : ℕ) : n ∈ range (n + 1) :=
by simp only [succ_pos', lt_add_iff_pos_right, mem_range]
theorem nth_range {m n : ℕ} (h : m < n) : nth (range n) m = some m :=
by simp only [range_eq_range', nth_range' _ h, zero_add]
theorem range_concat (n : ℕ) : range (succ n) = range n ++ [n] :=
by simp only [range_eq_range', range'_concat, zero_add]
theorem iota_eq_reverse_range' : ∀ n : ℕ, iota n = reverse (range' 1 n)
| 0 := rfl
| (n+1) := by simp only [iota, range'_concat, iota_eq_reverse_range' n, reverse_append, add_comm]; refl
@[simp] theorem length_iota (n : ℕ) : length (iota n) = n :=
by simp only [iota_eq_reverse_range', length_reverse, length_range']
theorem pairwise_gt_iota (n : ℕ) : pairwise (>) (iota n) :=
by simp only [iota_eq_reverse_range', pairwise_reverse, pairwise_lt_range']
theorem nodup_iota (n : ℕ) : nodup (iota n) :=
by simp only [iota_eq_reverse_range', nodup_reverse, nodup_range']
theorem mem_iota {m n : ℕ} : m ∈ iota n ↔ 1 ≤ m ∧ m ≤ n :=
by simp only [iota_eq_reverse_range', mem_reverse, mem_range', add_comm, lt_succ_iff]
theorem reverse_range' : ∀ s n : ℕ,
reverse (range' s n) = map (λ i, s + n - 1 - i) (range n)
| s 0 := rfl
| s (n+1) := by rw [range'_concat, reverse_append, range_succ_eq_map];
simpa only [show s + (n + 1) - 1 = s + n, from rfl, (∘),
λ a i, show a - 1 - i = a - succ i, from pred_sub _ _,
reverse_singleton, map_cons, nat.sub_zero, cons_append,
nil_append, eq_self_iff_true, true_and, map_map]
using reverse_range' s n
/-- All elements of `fin n`, from `0` to `n-1`. -/
def fin_range (n : ℕ) : list (fin n) :=
(range n).pmap fin.mk (λ _, list.mem_range.1)
@[simp] lemma mem_fin_range {n : ℕ} (a : fin n) : a ∈ fin_range n :=
mem_pmap.2 ⟨a.1, mem_range.2 a.2, fin.eta _ _⟩
lemma nodup_fin_range (n : ℕ) : (fin_range n).nodup :=
nodup_pmap (λ _ _ _ _, fin.veq_of_eq) (nodup_range _)
@[simp] lemma length_fin_range (n : ℕ) : (fin_range n).length = n :=
by rw [fin_range, length_pmap, length_range]
@[to_additive]
theorem prod_range_succ {α : Type u} [monoid α] (f : ℕ → α) (n : ℕ) :
((range n.succ).map f).prod = ((range n).map f).prod * f n :=
by rw [range_concat, map_append, map_singleton,
prod_append, prod_cons, prod_nil, mul_one]
/-- A variant of `prod_range_succ` which pulls off the first
term in the product rather than the last.-/
@[to_additive "A variant of `sum_range_succ` which pulls off the first term in the sum
rather than the last."]
theorem prod_range_succ' {α : Type u} [monoid α] (f : ℕ → α) (n : ℕ) :
((range n.succ).map f).prod = f 0 * ((range n).map (λ i, f (succ i))).prod :=
nat.rec_on n
(show 1 * f 0 = f 0 * 1, by rw [one_mul, mul_one])
(λ _ hd, by rw [list.prod_range_succ, hd, mul_assoc, ←list.prod_range_succ])
@[simp] theorem enum_from_map_fst : ∀ n (l : list α),
map prod.fst (enum_from n l) = range' n l.length
| n [] := rfl
| n (a :: l) := congr_arg (cons _) (enum_from_map_fst _ _)
@[simp] theorem enum_map_fst (l : list α) :
map prod.fst (enum l) = range l.length :=
by simp only [enum, enum_from_map_fst, range_eq_range']
@[simp] lemma nth_le_range {n} (i) (H : i < (range n).length) :
nth_le (range n) i H = i :=
option.some.inj $ by rw [← nth_le_nth _, nth_range (by simpa using H)]
theorem of_fn_eq_pmap {α n} {f : fin n → α} :
of_fn f = pmap (λ i hi, f ⟨i, hi⟩) (range n) (λ _, mem_range.1) :=
by rw [pmap_eq_map_attach]; from ext_le (by simp)
(λ i hi1 hi2, by simp at hi1; simp [nth_le_of_fn f ⟨i, hi1⟩])
theorem nodup_of_fn {α n} {f : fin n → α} (hf : function.injective f) :
nodup (of_fn f) :=
by rw of_fn_eq_pmap; from nodup_pmap
(λ _ _ _ _ H, fin.veq_of_eq $ hf H) (nodup_range n)
end list
|
08d8593be998ac9c202eb701c50c42f4df2f80ee | 7b66d83f3b69dae0a3dfb684d7ebe5e9e3f3c913 | /src/exercises_sources/thursday/afternoon/category_theory/exercise2.lean | aa7424e921f4d8cffd9c9e9c8fd3c5537da562b6 | [] | permissive | dpochekutov/lftcm2020 | 58a09e10f0e638075b97884d3c2612eb90296adb | cdfbf1ac089f21058e523db73f2476c9c98ed16a | refs/heads/master | 1,669,226,265,076 | 1,594,629,725,000 | 1,594,629,725,000 | 279,213,346 | 1 | 0 | MIT | 1,594,622,757,000 | 1,594,615,843,000 | null | UTF-8 | Lean | false | false | 1,605 | lean | import category_theory.preadditive
import category_theory.limits.shapes.biproducts
/-!
We prove that biproducts (direct sums) are preserved by any preadditive functor.
This result is not in mathlib, so full marks for the exercise are only achievable if you
contribute to a pull request! :-)
-/
universes v₁ v₂ u₁ u₂
open category_theory
open category_theory.limits
namespace category_theory
variables {C : Type u₁} [category.{v₁} C] [preadditive C]
variables {D : Type u₂} [category.{v₂} D] [preadditive D]
/-!
In fact, no one has gotten around to defining preadditive functors,
so I'll help you out by doing that first.
-/
structure functor.preadditive (F : C ⥤ D) : Prop :=
(map_zero' : ∀ X Y, F.map (0 : X ⟶ Y) = 0)
(map_add' : ∀ {X Y} (f g : X ⟶ Y), F.map (f + g) = F.map f + F.map g)
variables [has_binary_biproducts C] [has_binary_biproducts D]
-- In fact one could prove a better result,
-- not requiring chosen biproducts in D,
-- just asserting that `F.obj (X ⊞ Y)` is a biproduct of `F.obj X` and `F.obj Y`.
def functor.preadditive.preserves_biproducts (F : C ⥤ D) (P : F.preadditive) (X Y : C) :
F.obj (X ⊞ Y) ≅ F.obj X ⊞ F.obj Y :=
{ hom := biprod.lift (F.map biprod.fst) (F.map biprod.snd),
inv := biprod.desc (F.map biprod.inl) (F.map biprod.inr),
hom_inv_id' := begin simp, simp_rw [←F.map_comp, ←P.map_add'], simp, end,
inv_hom_id' := begin ext; simp; simp_rw [←F.map_comp]; simp [P.map_zero'], end, }
-- This proof is not okay as a mathlib proof, because it uses "nonterminal" `simp`s.
-- Can you fix it?
end category_theory
|
74ca9c381172fa761f3de72aeee694c059ff4b2d | f4bff2062c030df03d65e8b69c88f79b63a359d8 | /src/old_defs.lean | 32a54ed18af36bcebafbc5623b9e6f8d037b686e | [
"Apache-2.0"
] | permissive | adastra7470/real-number-game | 776606961f52db0eb824555ed2f8e16f92216ea3 | f9dcb7d9255a79b57e62038228a23346c2dc301b | refs/heads/master | 1,669,221,575,893 | 1,594,669,800,000 | 1,594,669,800,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,963 | lean | import data.real.basic
import data.set.intervals
import tactic.norm_num
-- nonempty is a class but let's have it working on set ℝ
namespace real_number_game
-- hide (need to choose this or P)
class nonemptyT (S : set ℝ) : Type :=
(x : ℝ)
(thm : x ∈ S)
-- hide (need to choose this or T)
class nonemptyP (S : set ℝ) : Prop :=
(thm' : ∃ x : ℝ, x ∈ S)
def nonemptyP.thm (S : set ℝ) [nonemptyP S] :
∃ x : ℝ, x ∈ S :=
nonemptyP.thm'
-- irrelevant example
example : ∃ x: ℝ, x < 1 := ⟨0.5, by norm_num⟩
example : (0.5 : ℝ) < 1 := by norm_num
-- irrelevant example
noncomputable example : nonemptyT (set.Icc 0 1) :=
{ x := 0.5,
thm := by {simp,split;norm_num}
}
-- show
def is_upper_bound (S : set ℝ) (b : ℝ) : Prop := ∀ s ∈ S, s ≤ b
-- hide this def
class bounded_aboveT (S : set ℝ) : Type :=
(b : ℝ)
(thm : is_upper_bound S b)
-- hide this def
class bounded_aboveP (S : set ℝ) : Prop :=
(thm' : ∃ b : ℝ, is_upper_bound S b)
def bounded_aboveP.thm (S : set ℝ) [bounded_aboveP S] :
∃ b : ℝ, is_upper_bound S b :=
bounded_aboveP.thm'
-- example (for me only)
instance : bounded_aboveT (set.Icc 0 1) :=
{ b := 2,
thm := λ r ⟨h1, h2⟩, le_trans h2 (by norm_num)
}
-- hide
noncomputable def Sup (S : set ℝ) [nonemptyP S] [bounded_aboveP S] := Sup S
-- state as axiom; hide proof
theorem le_Sup {S : set ℝ} [nonemptyP S] [bounded_aboveP S] : ∀ x ∈ S, x ≤ Sup S :=
begin
apply real.le_Sup,
cases bounded_aboveP.thm S with b hb,
use b,
exact hb,
end
-- state as axiom; hide proof
theorem Sup_le {S : set ℝ} [nonemptyP S] [bounded_aboveP S] :
∀ b : ℝ, is_upper_bound S b → Sup S ≤ b :=
begin
intros b hb,
show has_Sup.Sup S ≤ b,
rw real.Sup_le,
{ exact hb},
{ cases nonemptyP.thm S with c hc, use c, exact hc},
{ use b, exact hb}
end
-- other axioms: ℤ unbounded, linearly ordered field.
-- Might need to introduce later.
end real_number_game |
87d82b8b8bf2d3b78d703e61f03ebc1999f6badf | 94e33a31faa76775069b071adea97e86e218a8ee | /src/algebra/char_p/char_and_card.lean | 9581ba6c4602f09359304da464c60fb67de1d351 | [
"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 | 2,969 | lean | /-
Copyright (c) 2022 Michael Stoll. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Michael Stoll
-/
import algebra.char_p.basic
import group_theory.perm.cycle.type
/-!
# Characteristic and cardinality
We prove some results relating characteristic and cardinality of finite rings
## Tags
characterstic, cardinality, ring
-/
/-- A prime `p` is a unit in a finite commutative ring `R`
iff it does not divide the characteristic. -/
lemma is_unit_iff_not_dvd_char (R : Type*) [comm_ring R] [fintype R] (p : ℕ) [fact p.prime] :
is_unit (p : R) ↔ ¬ p ∣ ring_char R :=
begin
have hch := char_p.cast_eq_zero R (ring_char R),
split,
{ rintros h₁ ⟨q, hq⟩,
rcases is_unit.exists_left_inv h₁ with ⟨a, ha⟩,
have h₃ : ¬ ring_char R ∣ q :=
begin
rintro ⟨r, hr⟩,
rw [hr, ← mul_assoc, mul_comm p, mul_assoc] at hq,
nth_rewrite 0 ← mul_one (ring_char R) at hq,
exact nat.prime.not_dvd_one (fact.out p.prime)
⟨r, mul_left_cancel₀ (char_p.char_ne_zero_of_fintype R (ring_char R)) hq⟩,
end,
have h₄ := mt (char_p.int_cast_eq_zero_iff R (ring_char R) q).mp,
apply_fun (coe : ℕ → R) at hq,
apply_fun ((*) a) at hq,
rw [nat.cast_mul, hch, mul_zero, ← mul_assoc, ha, one_mul] at hq,
norm_cast at h₄,
exact h₄ h₃ hq.symm, },
{ intro h,
rcases nat.is_coprime_iff_coprime.mpr ((nat.prime.coprime_iff_not_dvd (fact.out _)).mpr h)
with ⟨a, b, hab⟩,
apply_fun (coe : ℤ → R) at hab,
push_cast at hab,
rw [hch, mul_zero, add_zero, mul_comm] at hab,
exact is_unit_of_mul_eq_one (p : R) a hab, },
end
/-- The prime divisors of the characteristic of a finite commutative ring are exactly
the prime divisors of its cardinality. -/
lemma prime_dvd_char_iff_dvd_card {R : Type*} [comm_ring R] [fintype R] (p : ℕ) [fact p.prime] :
p ∣ ring_char R ↔ p ∣ fintype.card R :=
begin
refine ⟨λ h, h.trans $ int.coe_nat_dvd.mp $ (char_p.int_cast_eq_zero_iff R (ring_char R)
(fintype.card R)).mp $ by exact_mod_cast char_p.cast_card_eq_zero R, λ h, _⟩,
by_contra h₀,
rcases exists_prime_add_order_of_dvd_card p h with ⟨r, hr⟩,
have hr₁ := add_order_of_nsmul_eq_zero r,
rw [hr, nsmul_eq_mul] at hr₁,
rcases is_unit.exists_left_inv ((is_unit_iff_not_dvd_char R p).mpr h₀) with ⟨u, hu⟩,
apply_fun ((*) u) at hr₁,
rw [mul_zero, ← mul_assoc, hu, one_mul] at hr₁,
exact mt add_monoid.order_of_eq_one_iff.mpr
(ne_of_eq_of_ne hr (nat.prime.ne_one (fact.out p.prime))) hr₁,
end
/-- A prime that does not divide the cardinality of a finite commutative ring `R`
is a unit in `R`. -/
lemma not_is_unit_prime_of_dvd_card {R : Type*} [comm_ring R] [fintype R] (p : ℕ) [fact p.prime]
(hp : p ∣ fintype.card R) : ¬ is_unit (p : R) :=
mt (is_unit_iff_not_dvd_char R p).mp (not_not.mpr ((prime_dvd_char_iff_dvd_card p).mpr hp))
|
3ea922f1e30113eb8885612e68dc51f44594d7d8 | 491068d2ad28831e7dade8d6dff871c3e49d9431 | /hott/init/function.hlean | cb6e9075fa990f22509f7915eb444861009d35b2 | [
"Apache-2.0"
] | permissive | davidmueller13/lean | 65a3ed141b4088cd0a268e4de80eb6778b21a0e9 | c626e2e3c6f3771e07c32e82ee5b9e030de5b050 | refs/heads/master | 1,611,278,313,401 | 1,444,021,177,000 | 1,444,021,177,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,971 | hlean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
General operations on functions.
-/
prelude
import init.reserved_notation .types
open prod
namespace function
variables {A B C D E : Type}
definition compose [reducible] [unfold-full] (f : B → C) (g : A → B) : A → C :=
λx, f (g x)
definition compose_right [reducible] [unfold-full] (f : B → B → B) (g : A → B) : B → A → B :=
λ b a, f b (g a)
definition compose_left [reducible] [unfold-full] (f : B → B → B) (g : A → B) : A → B → B :=
λ a b, f (g a) b
definition id [reducible] [unfold-full] (a : A) : A :=
a
definition on_fun [reducible] [unfold-full] (f : B → B → C) (g : A → B) : A → A → C :=
λx y, f (g x) (g y)
definition combine [reducible] [unfold-full] (f : A → B → C) (op : C → D → E) (g : A → B → D)
: A → B → E :=
λx y, op (f x y) (g x y)
definition const [reducible] [unfold-full] (B : Type) (a : A) : B → A :=
λx, a
definition dcompose [reducible] [unfold-full] {B : A → Type} {C : Π {x : A}, B x → Type}
(f : Π {x : A} (y : B x), C y) (g : Πx, B x) : Πx, C (g x) :=
λx, f (g x)
definition flip [reducible] [unfold-full] {C : A → B → Type} (f : Πx y, C x y) : Πy x, C x y :=
λy x, f x y
definition app [reducible] [unfold-full] {B : A → Type} (f : Πx, B x) (x : A) : B x :=
f x
definition curry [reducible] [unfold-full] : (A × B → C) → A → B → C :=
λ f a b, f (a, b)
definition uncurry [reducible] [unfold 5] : (A → B → C) → (A × B → C) :=
λ f p, match p with (a, b) := f a b end
infixr ` ∘ ` := compose
infixr ` ∘' `:60 := dcompose
infixl ` on `:1 := on_fun
infixr ` $ `:1 := app
notation f ` -[` op `]- ` g := combine f op g
end function
-- copy reducible annotations to top-level
export [reduce-hints] [unfold-hints] function
|
425925948be67669e0a805e0e47b2f177c8fc989 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/category_theory/limits/types.lean | adf4696e1c695c09e790ed458f4d3179ca442825 | [
"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 | 17,955 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Reid Barton
-/
import category_theory.limits.shapes.images
import category_theory.filtered
import tactic.equiv_rw
/-!
# Limits in the category of types.
We show that the category of types has all (co)limits, by providing the usual concrete models.
We also give a characterisation of filtered colimits in `Type`, via
`colimit.ι F i xi = colimit.ι F j xj ↔ ∃ k (f : i ⟶ k) (g : j ⟶ k), F.map f xi = F.map g xj`.
Finally, we prove the category of types has categorical images,
and that these agree with the range of a function.
-/
universes v u
open category_theory
open category_theory.limits
namespace category_theory.limits.types
variables {J : Type v} [small_category J]
/--
(internal implementation) the limit cone of a functor,
implemented as flat sections of a pi type
-/
def limit_cone (F : J ⥤ Type (max v u)) : cone F :=
{ X := F.sections,
π := { app := λ j u, u.val j } }
local attribute [elab_simple] congr_fun
/-- (internal implementation) the fact that the proposed limit cone is the limit -/
def limit_cone_is_limit (F : J ⥤ Type (max v u)) : is_limit (limit_cone F) :=
{ lift := λ s v, ⟨λ j, s.π.app j v, λ j j' f, congr_fun (cone.w s f) _⟩,
uniq' := by { intros, ext x j, exact congr_fun (w j) x } }
/--
The category of types has all limits.
See <https://stacks.math.columbia.edu/tag/002U>.
-/
instance has_limits_of_size : has_limits_of_size.{v} (Type (max v u)) :=
{ has_limits_of_shape := λ J 𝒥, by exactI
{ has_limit := λ F, has_limit.mk
{ cone := limit_cone F, is_limit := limit_cone_is_limit F } } }
instance : has_limits (Type u) := types.has_limits_of_size.{u u}
/--
The equivalence between a limiting cone of `F` in `Type u` and the "concrete" definition as the
sections of `F`.
-/
def is_limit_equiv_sections {F : J ⥤ Type (max v u)} {c : cone F} (t : is_limit c) :
c.X ≃ F.sections :=
(is_limit.cone_point_unique_up_to_iso t (limit_cone_is_limit F)).to_equiv
@[simp]
lemma is_limit_equiv_sections_apply
{F : J ⥤ Type (max v u)} {c : cone F} (t : is_limit c) (j : J) (x : c.X) :
(((is_limit_equiv_sections t) x) : Π j, F.obj j) j = c.π.app j x :=
rfl
@[simp]
lemma is_limit_equiv_sections_symm_apply
{F : J ⥤ Type (max v u)} {c : cone F} (t : is_limit c) (x : F.sections) (j : J) :
c.π.app j ((is_limit_equiv_sections t).symm x) = (x : Π j, F.obj j) j :=
begin
equiv_rw (is_limit_equiv_sections t).symm at x,
simp,
end
/--
The equivalence between the abstract limit of `F` in `Type u`
and the "concrete" definition as the sections of `F`.
-/
noncomputable
def limit_equiv_sections (F : J ⥤ Type (max v u)) : (limit F : Type (max v u)) ≃ F.sections :=
is_limit_equiv_sections (limit.is_limit _)
@[simp]
lemma limit_equiv_sections_apply (F : J ⥤ Type (max v u)) (x : limit F) (j : J) :
(((limit_equiv_sections F) x) : Π j, F.obj j) j = limit.π F j x :=
rfl
@[simp]
lemma limit_equiv_sections_symm_apply (F : J ⥤ Type (max v u)) (x : F.sections) (j : J) :
limit.π F j ((limit_equiv_sections F).symm x) = (x : Π j, F.obj j) j :=
is_limit_equiv_sections_symm_apply _ _ _
@[simp]
lemma limit_equiv_sections_symm_apply' (F : J ⥤ Type v) (x : F.sections) (j : J) :
limit.π F j ((limit_equiv_sections.{v v} F).symm x) = (x : Π j, F.obj j) j :=
is_limit_equiv_sections_symm_apply _ _ _
/--
Construct a term of `limit F : Type u` from a family of terms `x : Π j, F.obj j`
which are "coherent": `∀ (j j') (f : j ⟶ j'), F.map f (x j) = x j'`.
-/
@[ext]
noncomputable
def limit.mk (F : J ⥤ Type (max v u)) (x : Π j, F.obj j)
(h : ∀ (j j') (f : j ⟶ j'), F.map f (x j) = x j') : (limit F : Type (max v u)) :=
(limit_equiv_sections F).symm ⟨x, h⟩
@[simp]
lemma limit.π_mk (F : J ⥤ Type (max v u)) (x : Π j, F.obj j)
(h : ∀ (j j') (f : j ⟶ j'), F.map f (x j) = x j') (j) : limit.π F j (limit.mk F x h) = x j :=
by { dsimp [limit.mk], simp, }
@[simp]
lemma limit.π_mk' (F : J ⥤ Type v) (x : Π j, F.obj j)
(h : ∀ (j j') (f : j ⟶ j'), F.map f (x j) = x j') (j) :
limit.π F j (limit.mk.{v v} F x h) = x j :=
by { dsimp [limit.mk], simp, }
-- PROJECT: prove this for concrete categories where the forgetful functor preserves limits
@[ext]
lemma limit_ext (F : J ⥤ Type (max v u)) (x y : limit F) (w : ∀ j, limit.π F j x = limit.π F j y) :
x = y :=
begin
apply (limit_equiv_sections F).injective,
ext j,
simp [w j],
end
@[ext]
lemma limit_ext' (F : J ⥤ Type v) (x y : limit F) (w : ∀ j, limit.π F j x = limit.π F j y) :
x = y :=
begin
apply (limit_equiv_sections.{v v} F).injective,
ext j,
simp [w j],
end
lemma limit_ext_iff (F : J ⥤ Type (max v u)) (x y : limit F) :
x = y ↔ (∀ j, limit.π F j x = limit.π F j y) :=
⟨λ t _, t ▸ rfl, limit_ext _ _ _⟩
lemma limit_ext_iff' (F : J ⥤ Type v) (x y : limit F) :
x = y ↔ (∀ j, limit.π F j x = limit.π F j y) :=
⟨λ t _, t ▸ rfl, limit_ext _ _ _⟩
-- TODO: are there other limits lemmas that should have `_apply` versions?
-- Can we generate these like with `@[reassoc]`?
-- PROJECT: prove these for any concrete category where the forgetful functor preserves limits?
@[simp]
lemma limit.w_apply {F : J ⥤ Type (max v u)} {j j' : J} {x : limit F} (f : j ⟶ j') :
F.map f (limit.π F j x) = limit.π F j' x :=
congr_fun (limit.w F f) x
@[simp]
lemma limit.lift_π_apply (F : J ⥤ Type (max v u)) (s : cone F) (j : J) (x : s.X) :
limit.π F j (limit.lift F s x) = s.π.app j x :=
congr_fun (limit.lift_π s j) x
@[simp]
lemma limit.map_π_apply {F G : J ⥤ Type (max v u)} (α : F ⟶ G) (j : J) (x) :
limit.π G j (lim_map α x) = α.app j (limit.π F j x) :=
congr_fun (lim_map_π α j) x
@[simp]
lemma limit.w_apply' {F : J ⥤ Type v} {j j' : J} {x : limit F} (f : j ⟶ j') :
F.map f (limit.π F j x) = limit.π F j' x :=
congr_fun (limit.w F f) x
@[simp]
lemma limit.lift_π_apply' (F : J ⥤ Type v) (s : cone F) (j : J) (x : s.X) :
limit.π F j (limit.lift F s x) = s.π.app j x :=
congr_fun (limit.lift_π s j) x
@[simp]
lemma limit.map_π_apply' {F G : J ⥤ Type v} (α : F ⟶ G) (j : J) (x) :
limit.π G j (lim_map α x) = α.app j (limit.π F j x) :=
congr_fun (lim_map_π α j) x
/--
The relation defining the quotient type which implements the colimit of a functor `F : J ⥤ Type u`.
See `category_theory.limits.types.quot`.
-/
def quot.rel (F : J ⥤ Type (max v u)) : (Σ j, F.obj j) → (Σ j, F.obj j) → Prop :=
(λ p p', ∃ f : p.1 ⟶ p'.1, p'.2 = F.map f p.2)
/--
A quotient type implementing the colimit of a functor `F : J ⥤ Type u`,
as pairs `⟨j, x⟩` where `x : F.obj j`, modulo the equivalence relation generated by
`⟨j, x⟩ ~ ⟨j', x'⟩` whenever there is a morphism `f : j ⟶ j'` so `F.map f x = x'`.
-/
@[nolint has_inhabited_instance]
def quot (F : J ⥤ Type (max v u)) : Type (max v u) :=
@quot (Σ j, F.obj j) (quot.rel F)
/--
(internal implementation) the colimit cocone of a functor,
implemented as a quotient of a sigma type
-/
def colimit_cocone (F : J ⥤ Type (max v u)) : cocone F :=
{ X := quot F,
ι :=
{ app := λ j x, quot.mk _ ⟨j, x⟩,
naturality' := λ j j' f, funext $ λ x, eq.symm (quot.sound ⟨f, rfl⟩) } }
local attribute [elab_with_expected_type] quot.lift
/-- (internal implementation) the fact that the proposed colimit cocone is the colimit -/
def colimit_cocone_is_colimit (F : J ⥤ Type (max v u)) : is_colimit (colimit_cocone F) :=
{ desc := λ s, quot.lift (λ (p : Σ j, F.obj j), s.ι.app p.1 p.2)
(assume ⟨j, x⟩ ⟨j', x'⟩ ⟨f, hf⟩, by rw hf; exact (congr_fun (cocone.w s f) x).symm) }
/--
The category of types has all colimits.
See <https://stacks.math.columbia.edu/tag/002U>.
-/
instance has_colimits_of_size : has_colimits_of_size.{v} (Type (max v u)) :=
{ has_colimits_of_shape := λ J 𝒥, by exactI
{ has_colimit := λ F, has_colimit.mk
{ cocone := colimit_cocone F, is_colimit := colimit_cocone_is_colimit F } } }
instance : has_colimits (Type u) := types.has_colimits_of_size.{u u}
/--
The equivalence between the abstract colimit of `F` in `Type u`
and the "concrete" definition as a quotient.
-/
noncomputable
def colimit_equiv_quot (F : J ⥤ Type (max v u)) : (colimit F : Type (max v u)) ≃ quot F :=
(is_colimit.cocone_point_unique_up_to_iso
(colimit.is_colimit F)
(colimit_cocone_is_colimit F)).to_equiv
@[simp]
lemma colimit_equiv_quot_symm_apply (F : J ⥤ Type (max v u)) (j : J) (x : F.obj j) :
(colimit_equiv_quot F).symm (quot.mk _ ⟨j, x⟩) = colimit.ι F j x :=
rfl
@[simp]
lemma colimit_equiv_quot_apply (F : J ⥤ Type (max v u)) (j : J) (x : F.obj j) :
(colimit_equiv_quot F) (colimit.ι F j x) = quot.mk _ ⟨j, x⟩ :=
begin
apply (colimit_equiv_quot F).symm.injective,
simp,
end
@[simp]
lemma colimit.w_apply {F : J ⥤ Type (max v u)} {j j' : J} {x : F.obj j} (f : j ⟶ j') :
colimit.ι F j' (F.map f x) = colimit.ι F j x :=
congr_fun (colimit.w F f) x
@[simp]
lemma colimit.ι_desc_apply (F : J ⥤ Type (max v u)) (s : cocone F) (j : J) (x : F.obj j) :
colimit.desc F s (colimit.ι F j x) = s.ι.app j x :=
congr_fun (colimit.ι_desc s j) x
@[simp]
lemma colimit.ι_map_apply {F G : J ⥤ Type (max v u)} (α : F ⟶ G) (j : J) (x) :
colim.map α (colimit.ι F j x) = colimit.ι G j (α.app j x) :=
congr_fun (colimit.ι_map α j) x
@[simp]
lemma colimit.w_apply' {F : J ⥤ Type v} {j j' : J} {x : F.obj j} (f : j ⟶ j') :
colimit.ι F j' (F.map f x) = colimit.ι F j x :=
congr_fun (colimit.w F f) x
@[simp]
lemma colimit.ι_desc_apply' (F : J ⥤ Type v) (s : cocone F) (j : J) (x : F.obj j) :
colimit.desc F s (colimit.ι F j x) = s.ι.app j x :=
congr_fun (colimit.ι_desc s j) x
@[simp]
lemma colimit.ι_map_apply' {F G : J ⥤ Type v} (α : F ⟶ G) (j : J) (x) :
colim.map α (colimit.ι F j x) = colimit.ι G j (α.app j x) :=
congr_fun (colimit.ι_map α j) x
lemma colimit_sound
{F : J ⥤ Type (max v u)} {j j' : J} {x : F.obj j} {x' : F.obj j'}
(f : j ⟶ j') (w : F.map f x = x') : colimit.ι F j x = colimit.ι F j' x' :=
begin
rw [←w],
simp,
end
lemma colimit_sound'
{F : J ⥤ Type (max v u)} {j j' : J} {x : F.obj j} {x' : F.obj j'} {j'' : J}
(f : j ⟶ j'') (f' : j' ⟶ j'') (w : F.map f x = F.map f' x') :
colimit.ι F j x = colimit.ι F j' x' :=
begin
rw [←colimit.w _ f, ←colimit.w _ f'],
rw [types_comp_apply, types_comp_apply, w],
end
lemma colimit_eq {F : J ⥤ Type (max v u)} {j j' : J} {x : F.obj j} {x' : F.obj j'}
(w : colimit.ι F j x = colimit.ι F j' x') : eqv_gen (quot.rel F) ⟨j, x⟩ ⟨j', x'⟩ :=
begin
apply quot.eq.1,
simpa using congr_arg (colimit_equiv_quot F) w,
end
lemma jointly_surjective (F : J ⥤ Type (max v u)) {t : cocone F} (h : is_colimit t)
(x : t.X) : ∃ j y, t.ι.app j y = x :=
begin
suffices : (λ (x : t.X), ulift.up (∃ j y, t.ι.app j y = x)) = (λ _, ulift.up true),
{ have := congr_fun this x,
have H := congr_arg ulift.down this,
dsimp at H,
rwa eq_true at H },
refine h.hom_ext _,
intro j, ext y,
erw iff_true,
exact ⟨j, y, rfl⟩
end
/-- A variant of `jointly_surjective` for `x : colimit F`. -/
lemma jointly_surjective' {F : J ⥤ Type (max v u)}
(x : colimit F) : ∃ j y, colimit.ι F j y = x :=
jointly_surjective F (colimit.is_colimit _) x
namespace filtered_colimit
/- For filtered colimits of types, we can give an explicit description
of the equivalence relation generated by the relation used to form
the colimit. -/
variables (F : J ⥤ Type (max v u))
/--
An alternative relation on `Σ j, F.obj j`,
which generates the same equivalence relation as we use to define the colimit in `Type` above,
but that is more convenient when working with filtered colimits.
Elements in `F.obj j` and `F.obj j'` are equivalent if there is some `k : J` to the right
where their images are equal.
-/
protected def rel (x y : Σ j, F.obj j) : Prop :=
∃ k (f : x.1 ⟶ k) (g : y.1 ⟶ k), F.map f x.2 = F.map g y.2
lemma rel_of_quot_rel (x y : Σ j, F.obj j) : quot.rel F x y → filtered_colimit.rel F x y :=
λ ⟨f, h⟩, ⟨y.1, f, 𝟙 y.1, by rw [← h, functor_to_types.map_id_apply]⟩
lemma eqv_gen_quot_rel_of_rel (x y : Σ j, F.obj j) :
filtered_colimit.rel F x y → eqv_gen (quot.rel F) x y :=
λ ⟨k, f, g, h⟩, eqv_gen.trans _ ⟨k, F.map f x.2⟩ _ (eqv_gen.rel _ _ ⟨f, rfl⟩)
(eqv_gen.symm _ _ (eqv_gen.rel _ _ ⟨g, h⟩))
local attribute [elab_simple] nat_trans.app
/-- Recognizing filtered colimits of types. -/
noncomputable def is_colimit_of (t : cocone F) (hsurj : ∀ (x : t.X), ∃ i xi, x = t.ι.app i xi)
(hinj : ∀ i j xi xj, t.ι.app i xi = t.ι.app j xj →
∃ k (f : i ⟶ k) (g : j ⟶ k), F.map f xi = F.map g xj) : is_colimit t :=
-- Strategy: Prove that the map from "the" colimit of F (defined above) to t.X
-- is a bijection.
begin
apply is_colimit.of_iso_colimit (colimit.is_colimit F),
refine cocones.ext (equiv.to_iso (equiv.of_bijective _ _)) _,
{ exact colimit.desc F t },
{ split,
{ show function.injective _,
intros a b h,
rcases jointly_surjective F (colimit.is_colimit F) a with ⟨i, xi, rfl⟩,
rcases jointly_surjective F (colimit.is_colimit F) b with ⟨j, xj, rfl⟩,
change (colimit.ι F i ≫ colimit.desc F t) xi = (colimit.ι F j ≫ colimit.desc F t) xj at h,
rw [colimit.ι_desc, colimit.ι_desc] at h,
rcases hinj i j xi xj h with ⟨k, f, g, h'⟩,
change colimit.ι F i xi = colimit.ι F j xj,
rw [←colimit.w F f, ←colimit.w F g],
change colimit.ι F k (F.map f xi) = colimit.ι F k (F.map g xj),
rw h' },
{ show function.surjective _,
intro x,
rcases hsurj x with ⟨i, xi, rfl⟩,
use colimit.ι F i xi,
simp } },
{ intro j, apply colimit.ι_desc }
end
variables [is_filtered_or_empty J]
protected lemma rel_equiv : equivalence (filtered_colimit.rel F) :=
⟨λ x, ⟨x.1, 𝟙 x.1, 𝟙 x.1, rfl⟩,
λ x y ⟨k, f, g, h⟩, ⟨k, g, f, h.symm⟩,
λ x y z ⟨k, f, g, h⟩ ⟨k', f', g', h'⟩,
let ⟨l, fl, gl, _⟩ := is_filtered_or_empty.cocone_objs k k',
⟨m, n, hn⟩ := is_filtered_or_empty.cocone_maps (g ≫ fl) (f' ≫ gl) in
⟨m, f ≫ fl ≫ n, g' ≫ gl ≫ n, calc
F.map (f ≫ fl ≫ n) x.2
= F.map (fl ≫ n) (F.map f x.2) : by simp
... = F.map (fl ≫ n) (F.map g y.2) : by rw h
... = F.map ((g ≫ fl) ≫ n) y.2 : by simp
... = F.map ((f' ≫ gl) ≫ n) y.2 : by rw hn
... = F.map (gl ≫ n) (F.map f' y.2) : by simp
... = F.map (gl ≫ n) (F.map g' z.2) : by rw h'
... = F.map (g' ≫ gl ≫ n) z.2 : by simp⟩⟩
protected lemma rel_eq_eqv_gen_quot_rel :
filtered_colimit.rel F = eqv_gen (quot.rel F) :=
begin
ext ⟨j, x⟩ ⟨j', y⟩,
split,
{ apply eqv_gen_quot_rel_of_rel },
{ rw ←(filtered_colimit.rel_equiv F).eqv_gen_iff,
exact eqv_gen.mono (rel_of_quot_rel F) }
end
lemma colimit_eq_iff_aux {i j : J} {xi : F.obj i} {xj : F.obj j} :
(colimit_cocone F).ι.app i xi = (colimit_cocone F).ι.app j xj ↔
filtered_colimit.rel F ⟨i, xi⟩ ⟨j, xj⟩ :=
begin
change quot.mk _ _ = quot.mk _ _ ↔ _,
rw [quot.eq, filtered_colimit.rel_eq_eqv_gen_quot_rel],
end
lemma is_colimit_eq_iff {t : cocone F} (ht : is_colimit t) {i j : J} {xi : F.obj i} {xj : F.obj j} :
t.ι.app i xi = t.ι.app j xj ↔ ∃ k (f : i ⟶ k) (g : j ⟶ k), F.map f xi = F.map g xj :=
let t' := colimit_cocone F,
e : t' ≅ t := is_colimit.unique_up_to_iso (colimit_cocone_is_colimit F) ht,
e' : t'.X ≅ t.X := (cocones.forget _).map_iso e in
begin
refine iff.trans _ (colimit_eq_iff_aux F),
convert e'.to_equiv.apply_eq_iff_eq; rw ←e.hom.w; refl
end
lemma colimit_eq_iff {i j : J} {xi : F.obj i} {xj : F.obj j} :
colimit.ι F i xi = colimit.ι F j xj ↔ ∃ k (f : i ⟶ k) (g : j ⟶ k), F.map f xi = F.map g xj :=
is_colimit_eq_iff _ (colimit.is_colimit F)
end filtered_colimit
variables {α β : Type u} (f : α ⟶ β)
section -- implementation of `has_image`
/-- the image of a morphism in Type is just `set.range f` -/
def image : Type u := set.range f
instance [inhabited α] : inhabited (image f) :=
{ default := ⟨f default, ⟨_, rfl⟩⟩ }
/-- the inclusion of `image f` into the target -/
def image.ι : image f ⟶ β := subtype.val
instance : mono (image.ι f) :=
(mono_iff_injective _).2 subtype.val_injective
variables {f}
/-- the universal property for the image factorisation -/
noncomputable def image.lift (F' : mono_factorisation f) : image f ⟶ F'.I :=
(λ x, F'.e (classical.indefinite_description _ x.2).1 : image f → F'.I)
lemma image.lift_fac (F' : mono_factorisation f) : image.lift F' ≫ F'.m = image.ι f :=
begin
ext x,
change (F'.e ≫ F'.m) _ = _,
rw [F'.fac, (classical.indefinite_description _ x.2).2],
refl,
end
end
/-- the factorisation of any morphism in Type through a mono. -/
def mono_factorisation : mono_factorisation f :=
{ I := image f,
m := image.ι f,
e := set.range_factorization f }
/-- the facorisation through a mono has the universal property of the image. -/
noncomputable def is_image : is_image (mono_factorisation f) :=
{ lift := image.lift,
lift_fac' := image.lift_fac }
instance : has_image f :=
has_image.mk ⟨_, is_image f⟩
instance : has_images (Type u) :=
{ has_image := by apply_instance }
instance : has_image_maps (Type u) :=
{ has_image_map := λ f g st, has_image_map.transport st (mono_factorisation f.hom) (is_image g.hom)
(λ x, ⟨st.right x.1, ⟨st.left (classical.some x.2),
begin
have p := st.w,
replace p := congr_fun p (classical.some x.2),
simp only [functor.id_map, types_comp_apply, subtype.val_eq_coe] at p,
erw [p, classical.some_spec x.2],
end⟩⟩) rfl }
end category_theory.limits.types
|
ae546ba800233e11fb8038fe927c70f6d1101abe | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/control/fold.lean | 8ee369cf3898e54f039d4f01a15c709265a4b9e6 | [
"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 | 14,930 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Sean Leather
-/
import algebra.free_monoid
import algebra.opposites
import control.traversable.instances
import control.traversable.lemmas
import category_theory.endomorphism
import category_theory.types
import category_theory.category.Kleisli
import deprecated.group
/-!
# List folds generalized to `traversable`
Informally, we can think of `foldl` as a special case of `traverse` where we do not care about the
reconstructed data structure and, in a state monad, we care about the final state.
The obvious way to define `foldl` would be to use the state monad but it
is nicer to reason about a more abstract interface with `fold_map` as a
primitive and `fold_map_hom` as a defining property.
```
def fold_map {α ω} [has_one ω] [has_mul ω] (f : α → ω) : t α → ω := ...
lemma fold_map_hom (α β)
[monoid α] [monoid β] (f : α → β) [is_monoid_hom f]
(g : γ → α) (x : t γ) :
f (fold_map g x) = fold_map (f ∘ g) x :=
...
```
`fold_map` uses a monoid ω to accumulate a value for every element of
a data structure and `fold_map_hom` uses a monoid homomorphism to
substitute the monoid used by `fold_map`. The two are sufficient to
define `foldl`, `foldr` and `to_list`. `to_list` permits the
formulation of specifications in terms of operations on lists.
Each fold function can be defined using a specialized
monoid. `to_list` uses a free monoid represented as a list with
concatenation while `foldl` uses endofunctions together with function
composition.
The definition through monoids uses `traverse` together with the
applicative functor `const m` (where `m` is the monoid). As an
implementation, `const` guarantees that no resource is spent on
reconstructing the structure during traversal.
A special class could be defined for `foldable`, similarly to Haskell,
but the author cannot think of instances of `foldable` that are not also
`traversable`.
-/
universes u v
open ulift category_theory opposite
namespace monoid
variables {m : Type u → Type u} [monad m]
variables {α β : Type u}
/--
For a list, foldl f x [y₀,y₁] reduces as follows:
```
calc foldl f x [y₀,y₁]
= foldl f (f x y₀) [y₁] : rfl
... = foldl f (f (f x y₀) y₁) [] : rfl
... = f (f x y₀) y₁ : rfl
```
with
```
f : α → β → α
x : α
[y₀,y₁] : list β
```
We can view the above as a composition of functions:
```
... = f (f x y₀) y₁ : rfl
... = flip f y₁ (flip f y₀ x) : rfl
... = (flip f y₁ ∘ flip f y₀) x : rfl
```
We can use traverse and const to construct this composition:
```
calc const.run (traverse (λ y, const.mk' (flip f y)) [y₀,y₁]) x
= const.run ((::) <$> const.mk' (flip f y₀) <*> traverse (λ y, const.mk' (flip f y)) [y₁]) x
... = const.run ((::) <$> const.mk' (flip f y₀) <*>
( (::) <$> const.mk' (flip f y₁) <*> traverse (λ y, const.mk' (flip f y)) [] )) x
... = const.run ((::) <$> const.mk' (flip f y₀) <*>
( (::) <$> const.mk' (flip f y₁) <*> pure [] )) x
... = const.run ( ((::) <$> const.mk' (flip f y₁) <*> pure []) ∘
((::) <$> const.mk' (flip f y₀)) ) x
... = const.run ( const.mk' (flip f y₁) ∘ const.mk' (flip f y₀) ) x
... = const.run ( flip f y₁ ∘ flip f y₀ ) x
... = f (f x y₀) y₁
```
And this is how `const` turns a monoid into an applicative functor and
how the monoid of endofunctions define `foldl`.
-/
@[reducible] def foldl (α : Type u) : Type u := (End α)ᵒᵖ
def foldl.mk (f : α → α) : foldl α := op f
def foldl.get (x : foldl α) : α → α := unop x
def foldl.of_free_monoid (f : β → α → β) (xs : free_monoid α) : monoid.foldl β :=
op $ flip (list.foldl f) xs
@[reducible] def foldr (α : Type u) : Type u := End α
def foldr.mk (f : α → α) : foldr α := f
def foldr.get (x : foldr α) : α → α := x
def foldr.of_free_monoid (f : α → β → β) (xs : free_monoid α) : monoid.foldr β :=
flip (list.foldr f) xs
@[reducible] def mfoldl (m : Type u → Type u) [monad m] (α : Type u) : Type u :=
opposite $ End $ Kleisli.mk m α
def mfoldl.mk (f : α → m α) : mfoldl m α := op f
def mfoldl.get (x : mfoldl m α) : α → m α := unop x
def mfoldl.of_free_monoid (f : β → α → m β) (xs : free_monoid α) : monoid.mfoldl m β :=
op $ flip (list.mfoldl f) xs
@[reducible] def mfoldr (m : Type u → Type u) [monad m] (α : Type u) : Type u :=
End $ Kleisli.mk m α
def mfoldr.mk (f : α → m α) : mfoldr m α := f
def mfoldr.get (x : mfoldr m α) : α → m α := x
def mfoldr.of_free_monoid (f : α → β → m β) (xs : free_monoid α) : monoid.mfoldr m β :=
flip (list.mfoldr f) xs
end monoid
namespace traversable
open monoid functor
section defs
variables {α β : Type u} {t : Type u → Type u} [traversable t]
def fold_map {α ω} [has_one ω] [has_mul ω] (f : α → ω) : t α → ω :=
traverse (const.mk' ∘ f)
def foldl (f : α → β → α) (x : α) (xs : t β) : α :=
(fold_map (foldl.mk ∘ flip f) xs).get x
def foldr (f : α → β → β) (x : β) (xs : t α) : β :=
(fold_map (foldr.mk ∘ f) xs).get x
/--
Conceptually, `to_list` collects all the elements of a collection
in a list. This idea is formalized by
`lemma to_list_spec (x : t α) : to_list x = fold_map free_monoid.mk x`.
The definition of `to_list` is based on `foldl` and `list.cons` for
speed. It is faster than using `fold_map free_monoid.mk` because, by
using `foldl` and `list.cons`, each insertion is done in constant
time. As a consequence, `to_list` performs in linear.
On the other hand, `fold_map free_monoid.mk` creates a singleton list
around each element and concatenates all the resulting lists. In
`xs ++ ys`, concatenation takes a time proportional to `length xs`. Since
the order in which concatenation is evaluated is unspecified, nothing
prevents each element of the traversable to be appended at the end
`xs ++ [x]` which would yield a `O(n²)` run time. -/
def to_list : t α → list α :=
list.reverse ∘ foldl (flip list.cons) []
def length (xs : t α) : ℕ :=
down $ foldl (λ l _, up $ l.down + 1) (up 0) xs
variables {m : Type u → Type u} [monad m]
def mfoldl (f : α → β → m α) (x : α) (xs : t β) : m α :=
(fold_map (mfoldl.mk ∘ flip f) xs).get x
def mfoldr (f : α → β → m β) (x : β) (xs : t α) : m β :=
(fold_map (mfoldr.mk ∘ f) xs).get x
end defs
section applicative_transformation
variables {α β γ : Type u}
open function (hiding const) is_monoid_hom
def map_fold [monoid α] [monoid β] {f : α → β} (hf : is_monoid_hom f) :
applicative_transformation (const α) (const β) :=
{ app := λ x, f,
preserves_seq' := by { intros, simp only [map_mul hf, (<*>)], },
preserves_pure' := by { intros, simp only [map_one hf, pure] } }
def free.mk : α → free_monoid α := list.ret
def free.map (f : α → β) : free_monoid α → free_monoid β := list.map f
lemma free.map_eq_map (f : α → β) (xs : list α) :
f <$> xs = free.map f xs := rfl
lemma free.map.is_monoid_hom (f : α → β) : is_monoid_hom (free.map f) :=
{ map_mul := λ x y,
by simp only [free.map, free_monoid.mul_def, list.map_append, free_add_monoid.add_def],
map_one := by simp only [free.map, free_monoid.one_def, list.map, free_add_monoid.zero_def] }
lemma fold_foldl (f : β → α → β) :
is_monoid_hom (foldl.of_free_monoid f) :=
{ map_one := rfl,
map_mul := by intros; simp only [free_monoid.mul_def, foldl.of_free_monoid, flip, unop_op,
list.foldl_append, op_inj_iff]; refl }
lemma foldl.unop_of_free_monoid (f : β → α → β) (xs : free_monoid α) (a : β) :
unop (foldl.of_free_monoid f xs) a = list.foldl f a xs := rfl
lemma fold_foldr (f : α → β → β) :
is_monoid_hom (foldr.of_free_monoid f) :=
{ map_one := rfl,
map_mul :=
begin
intros,
simp only [free_monoid.mul_def, foldr.of_free_monoid, list.foldr_append, flip],
refl
end }
variables (m : Type u → Type u) [monad m] [is_lawful_monad m]
@[simp]
lemma mfoldl.unop_of_free_monoid (f : β → α → m β) (xs : free_monoid α) (a : β) :
unop (mfoldl.of_free_monoid f xs) a = list.mfoldl f a xs := rfl
lemma fold_mfoldl (f : β → α → m β) :
is_monoid_hom (mfoldl.of_free_monoid f) :=
{ map_one := rfl,
map_mul := by intros; apply unop_injective; ext; apply list.mfoldl_append }
lemma fold_mfoldr (f : α → β → m β) :
is_monoid_hom (mfoldr.of_free_monoid f) :=
{ map_one := rfl,
map_mul := by intros; ext; apply list.mfoldr_append }
variables {t : Type u → Type u} [traversable t] [is_lawful_traversable t]
open is_lawful_traversable
lemma fold_map_hom
[monoid α] [monoid β] {f : α → β} (hf : is_monoid_hom f)
(g : γ → α) (x : t γ) :
f (fold_map g x) = fold_map (f ∘ g) x :=
calc f (fold_map g x)
= f (traverse (const.mk' ∘ g) x) : rfl
... = (map_fold hf).app _ (traverse (const.mk' ∘ g) x) : rfl
... = traverse ((map_fold hf).app _ ∘ (const.mk' ∘ g)) x : naturality (map_fold hf) _ _
... = fold_map (f ∘ g) x : rfl
lemma fold_map_hom_free
[monoid β] {f : free_monoid α → β} (hf : is_monoid_hom f) (x : t α) :
f (fold_map free.mk x) = fold_map (f ∘ free.mk) x :=
fold_map_hom hf _ x
variable {m}
lemma fold_mfoldl_cons (f : α → β → m α) (x : β) (y : α) :
list.mfoldl f y (free.mk x) = f y x :=
by simp only [free.mk, list.ret, list.mfoldl, bind_pure]
lemma fold_mfoldr_cons (f : β → α → m α) (x : β) (y : α) :
list.mfoldr f y (free.mk x) = f x y :=
by simp only [free.mk, list.ret, list.mfoldr, pure_bind]
end applicative_transformation
section equalities
open is_lawful_traversable list (cons)
variables {α β γ : Type u}
variables {t : Type u → Type u} [traversable t] [is_lawful_traversable t]
@[simp]
lemma foldl.of_free_monoid_comp_free_mk (f : α → β → α) :
foldl.of_free_monoid f ∘ free.mk = foldl.mk ∘ flip f := rfl
@[simp]
lemma foldr.of_free_monoid_comp_free_mk (f : β → α → α) :
foldr.of_free_monoid f ∘ free.mk = foldr.mk ∘ f := rfl
@[simp]
lemma mfoldl.of_free_monoid_comp_free_mk {m} [monad m] [is_lawful_monad m] (f : α → β → m α) :
mfoldl.of_free_monoid f ∘ free.mk = mfoldl.mk ∘ flip f :=
by ext; simp only [(∘), mfoldl.of_free_monoid, mfoldl.mk, flip, fold_mfoldl_cons]; refl
@[simp]
lemma mfoldr.of_free_monoid_comp_free_mk {m} [monad m] [is_lawful_monad m] (f : β → α → m α) :
mfoldr.of_free_monoid f ∘ free.mk = mfoldr.mk ∘ f :=
by { ext, simp only [(∘), mfoldr.of_free_monoid, mfoldr.mk, flip, fold_mfoldr_cons] }
lemma to_list_spec (xs : t α) :
to_list xs = (fold_map free.mk xs : free_monoid _) :=
eq.symm $
calc fold_map free.mk xs
= (fold_map free.mk xs).reverse.reverse : by simp only [list.reverse_reverse]
... = (list.foldr cons [] (fold_map free.mk xs).reverse).reverse
: by simp only [list.foldr_eta]
... = (unop (foldl.of_free_monoid (flip cons) (fold_map free.mk xs)) []).reverse
: by simp only [flip,list.foldr_reverse,foldl.of_free_monoid, unop_op]
... = to_list xs : begin
have : is_monoid_hom (foldl.of_free_monoid (flip $ @cons α)),
{ apply fold_foldl },
rw fold_map_hom_free this,
simp only [to_list, foldl, list.reverse_inj, foldl.get,
foldl.of_free_monoid_comp_free_mk],
all_goals { apply_instance }
end
lemma fold_map_map [monoid γ] (f : α → β) (g : β → γ) (xs : t α) :
fold_map g (f <$> xs) = fold_map (g ∘ f) xs :=
by simp only [fold_map,traverse_map]
lemma foldl_to_list (f : α → β → α) (xs : t β) (x : α) :
foldl f x xs = list.foldl f x (to_list xs) :=
begin
rw ← foldl.unop_of_free_monoid,
simp only [foldl, to_list_spec, fold_map_hom_free (fold_foldl f),
foldl.of_free_monoid_comp_free_mk, foldl.get]
end
lemma foldr_to_list (f : α → β → β) (xs : t α) (x : β) :
foldr f x xs = list.foldr f x (to_list xs) :=
begin
change _ = foldr.of_free_monoid _ _ _,
simp only [foldr, to_list_spec, fold_map_hom_free (fold_foldr f),
foldr.of_free_monoid_comp_free_mk, foldr.get]
end
lemma to_list_map (f : α → β) (xs : t α) :
to_list (f <$> xs) = f <$> to_list xs := by
{ simp only [to_list_spec,free.map_eq_map,fold_map_hom (free.map.is_monoid_hom f), fold_map_map];
refl }
@[simp] theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : t β) :
foldl f a (g <$> l) = foldl (λ x y, f x (g y)) a l :=
by simp only [foldl, fold_map_map, (∘), flip]
@[simp] theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : t β) :
foldr f a (g <$> l) = foldr (f ∘ g) a l :=
by simp only [foldr, fold_map_map, (∘), flip]
@[simp] theorem to_list_eq_self {xs : list α} : to_list xs = xs :=
begin
simp only [to_list_spec, fold_map, traverse],
induction xs,
case list.nil { refl },
case list.cons : _ _ ih { unfold list.traverse list.ret, rw ih, refl }
end
theorem length_to_list {xs : t α} : length xs = list.length (to_list xs) :=
begin
unfold length,
rw foldl_to_list,
generalize : to_list xs = ys,
let f := λ (n : ℕ) (a : α), n + 1,
transitivity list.foldl f 0 ys,
{ generalize : 0 = n,
induction ys with _ _ ih generalizing n,
{ simp only [list.foldl_nil] },
{ simp only [list.foldl, ih (n+1)] } },
{ induction ys with _ tl ih,
{ simp only [list.length, list.foldl_nil] },
{ simp only [list.foldl, list.length],
rw [← ih],
exact tl.foldl_hom (λx, x+1) f f 0 (λ n x, rfl) } }
end
variables {m : Type u → Type u} [monad m] [is_lawful_monad m]
section
local attribute [semireducible] opposite
lemma mfoldl_to_list {f : α → β → m α} {x : α} {xs : t β} :
mfoldl f x xs = list.mfoldl f x (to_list xs) :=
begin
change _ = unop (mfoldl.of_free_monoid f (to_list xs)) x,
simp only [mfoldl, to_list_spec, fold_map_hom_free (fold_mfoldl (λ (β : Type u), m β) f),
mfoldl.of_free_monoid_comp_free_mk, mfoldl.get]
end
end
lemma mfoldr_to_list (f : α → β → m β) (x : β) (xs : t α) :
mfoldr f x xs = list.mfoldr f x (to_list xs) :=
begin
change _ = mfoldr.of_free_monoid f (to_list xs) x,
simp only [mfoldr, to_list_spec, fold_map_hom_free (fold_mfoldr (λ (β : Type u), m β) f),
mfoldr.of_free_monoid_comp_free_mk, mfoldr.get]
end
@[simp] theorem mfoldl_map (g : β → γ) (f : α → γ → m α) (a : α) (l : t β) :
mfoldl f a (g <$> l) = mfoldl (λ x y, f x (g y)) a l :=
by simp only [mfoldl, fold_map_map, (∘), flip]
@[simp] theorem mfoldr_map (g : β → γ) (f : γ → α → m α) (a : α) (l : t β) :
mfoldr f a (g <$> l) = mfoldr (f ∘ g) a l :=
by simp only [mfoldr, fold_map_map, (∘), flip]
end equalities
end traversable
|
2ecb09d2891d7e5b955ca3093cc312aed66c69e1 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/category_theory/action.lean | 532cc9eb637638879e2da300a333125a3b192e32 | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 3,142 | lean | /-
Copyright (c) 2020 David Wärn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: David Wärn
-/
import category_theory.elements
import category_theory.single_obj
/-!
# Actions as functors and as categories
From a multiplicative action M ↻ X, we can construct a functor from M to the category of
types, mapping the single object of M to X and an element `m : M` to map `X → X` given by
multiplication by `m`.
This functor induces a category structure on X -- a special case of the category of elements.
A morphism `x ⟶ y` in this category is simply a scalar `m : M` such that `m • x = y`. In the case
where M is a group, this category is a groupoid -- the `action groupoid'.
-/
open mul_action
namespace category_theory
universes u
variables (M : Type*) [monoid M] (X : Type u) [mul_action M X]
/-- A multiplicative action M ↻ X viewed as a functor mapping the single object of M to X
and an element `m : M` to the map `X → X` given by multiplication by `m`. -/
@[simps]
def action_as_functor : single_obj M ⥤ Type u :=
{ obj := λ _, X,
map := λ _ _, (•),
map_id' := λ _, funext $ mul_action.one_smul,
map_comp' := λ _ _ _ f g, funext $ λ x, (smul_smul g f x).symm }
/-- A multiplicative action M ↻ X induces a category strucure on X, where a morphism
from x to y is a scalar taking x to y. Due to implementation details, the object type
of this category is not equal to X, but is in bijection with X. -/
@[derive category]
def action_category := (action_as_functor M X).elements
namespace action_category
instance (G : Type*) [group G] [mul_action G X] : groupoid (action_category G X) :=
category_theory.groupoid_of_elements _
/-- The projection from the action category to the monoid, mapping a morphism to its
label. -/
def π : action_category M X ⥤ single_obj M :=
category_of_elements.π _
@[simp]
lemma π_map (p q : action_category M X) (f : p ⟶ q) : (π M X).map f = f.val := rfl
@[simp]
lemma π_obj (p : action_category M X) : (π M X).obj p = single_obj.star M :=
@subsingleton.elim unit _ _ _
/-- An object of the action category given by M ↻ X corresponds to an element of X. -/
def obj_equiv : X ≃ action_category M X :=
{ to_fun := λ x, ⟨single_obj.star M, x⟩,
inv_fun := λ p, p.2,
left_inv := by tidy,
right_inv := by tidy }
lemma hom_as_subtype (p q : action_category M X) :
(p ⟶ q) = { m : M // m • (obj_equiv M X).symm p = (obj_equiv M X).symm q } := rfl
instance [inhabited X] : inhabited (action_category M X) :=
{ default := obj_equiv M X (default X) }
variables {X} (x : X)
/-- The stabilizer of a point is isomorphic to the endomorphism monoid at the
corresponding point. In fact they are definitionally equivalent. -/
def stabilizer_iso_End : stabilizer.submonoid M x ≃* End (obj_equiv M X x) :=
mul_equiv.refl _
@[simp]
lemma stabilizer_iso_End_apply (f : stabilizer.submonoid M x) :
(stabilizer_iso_End M x).to_fun f = f := rfl
@[simp]
lemma stabilizer_iso_End_symm_apply (f : End _) :
(stabilizer_iso_End M x).inv_fun f = f := rfl
end action_category
end category_theory
|
842cf5dd2b31724332870b59c9f89f032a5ca3a2 | 31f556cdeb9239ffc2fad8f905e33987ff4feab9 | /stage0/src/Lean/Meta/Tactic/Apply.lean | a42de3520bcf2d467032058afa52a01dfce4ce18 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | tobiasgrosser/lean4 | ce0fd9cca0feba1100656679bf41f0bffdbabb71 | ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f | refs/heads/master | 1,673,103,412,948 | 1,664,930,501,000 | 1,664,930,501,000 | 186,870,185 | 0 | 0 | Apache-2.0 | 1,665,129,237,000 | 1,557,939,901,000 | Lean | UTF-8 | Lean | false | false | 6,890 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Util.FindMVar
import Lean.Meta.SynthInstance
import Lean.Meta.CollectMVars
import Lean.Meta.Tactic.Util
namespace Lean.Meta
/--
Compute the number of expected arguments and whether the result type is of the form
(?m ...) where ?m is an unassigned metavariable.
-/
def getExpectedNumArgsAux (e : Expr) : MetaM (Nat × Bool) :=
withDefault <| forallTelescopeReducing e fun xs body =>
pure (xs.size, body.getAppFn.isMVar)
def getExpectedNumArgs (e : Expr) : MetaM Nat := do
let (numArgs, _) ← getExpectedNumArgsAux e
pure numArgs
private def throwApplyError {α} (mvarId : MVarId) (eType : Expr) (targetType : Expr) : MetaM α :=
throwTacticEx `apply mvarId m!"failed to unify{indentExpr eType}\nwith{indentExpr targetType}"
def synthAppInstances (tacticName : Name) (mvarId : MVarId) (newMVars : Array Expr) (binderInfos : Array BinderInfo) : MetaM Unit :=
newMVars.size.forM fun i => do
if binderInfos[i]!.isInstImplicit then
let mvar := newMVars[i]!
let mvarType ← inferType mvar
let mvarVal ← synthInstance mvarType
unless (← isDefEq mvar mvarVal) do
throwTacticEx tacticName mvarId "failed to assign synthesized instance"
def appendParentTag (mvarId : MVarId) (newMVars : Array Expr) (binderInfos : Array BinderInfo) : MetaM Unit := do
let parentTag ← mvarId.getTag
if newMVars.size == 1 then
-- if there is only one subgoal, we inherit the parent tag
newMVars[0]!.mvarId!.setTag parentTag
else
unless parentTag.isAnonymous do
newMVars.size.forM fun i => do
let mvarIdNew := newMVars[i]!.mvarId!
unless (← mvarIdNew.isAssigned) do
unless binderInfos[i]!.isInstImplicit do
let currTag ← mvarIdNew.getTag
mvarIdNew.setTag (appendTag parentTag currTag)
def postprocessAppMVars (tacticName : Name) (mvarId : MVarId) (newMVars : Array Expr) (binderInfos : Array BinderInfo) : MetaM Unit := do
synthAppInstances tacticName mvarId newMVars binderInfos
-- TODO: default and auto params
appendParentTag mvarId newMVars binderInfos
private def dependsOnOthers (mvar : Expr) (otherMVars : Array Expr) : MetaM Bool :=
otherMVars.anyM fun otherMVar => do
if mvar == otherMVar then
return false
else
let otherMVarType ← inferType otherMVar
return (otherMVarType.findMVar? fun mvarId => mvarId == mvar.mvarId!).isSome
/-- Partitions the given mvars in to two arrays (non-deps, deps)
according to whether the given mvar depends on other mvars in the array.-/
private def partitionDependentMVars (mvars : Array Expr) : MetaM (Array MVarId × Array MVarId) :=
mvars.foldlM (init := (#[], #[])) fun (nonDeps, deps) mvar => do
let currMVarId := mvar.mvarId!
if (← dependsOnOthers mvar mvars) then
return (nonDeps, deps.push currMVarId)
else
return (nonDeps.push currMVarId, deps)
/-- Controls which new mvars are turned in to goals by the `apply` tactic.
- `nonDependentFirst` mvars that don't depend on other goals appear first in the goal list.
- `nonDependentOnly` only mvars that don't depend on other goals are added to goal list.
- `all` all unassigned mvars are added to the goal list.
-/
inductive ApplyNewGoals where
| nonDependentFirst | nonDependentOnly | all
private def reorderGoals (mvars : Array Expr) : ApplyNewGoals → MetaM (List MVarId)
| ApplyNewGoals.nonDependentFirst => do
let (nonDeps, deps) ← partitionDependentMVars mvars
return nonDeps.toList ++ deps.toList
| ApplyNewGoals.nonDependentOnly => do
let (nonDeps, _) ← partitionDependentMVars mvars
return nonDeps.toList
| ApplyNewGoals.all => return mvars.toList.map Lean.Expr.mvarId!
/-- Configures the behaviour of the `apply` tactic. -/
structure ApplyConfig where
newGoals := ApplyNewGoals.nonDependentFirst
/--
Close the given goal using `apply e`.
-/
def _root_.Lean.MVarId.apply (mvarId : MVarId) (e : Expr) (cfg : ApplyConfig := {}) : MetaM (List MVarId) :=
mvarId.withContext do
mvarId.checkNotAssigned `apply
let targetType ← mvarId.getType
let eType ← inferType e
let mut (numArgs, hasMVarHead) ← getExpectedNumArgsAux eType
unless hasMVarHead do
let targetTypeNumArgs ← getExpectedNumArgs targetType
numArgs := numArgs - targetTypeNumArgs
let (newMVars, binderInfos, eType) ← forallMetaTelescopeReducing eType (some numArgs)
unless (← isDefEq eType targetType) do throwApplyError mvarId eType targetType
postprocessAppMVars `apply mvarId newMVars binderInfos
let e ← instantiateMVars e
mvarId.assign (mkAppN e newMVars)
let newMVars ← newMVars.filterM fun mvar => not <$> mvar.mvarId!.isAssigned
let otherMVarIds ← getMVarsNoDelayed e
let newMVarIds ← reorderGoals newMVars cfg.newGoals
let otherMVarIds := otherMVarIds.filter fun mvarId => !newMVarIds.contains mvarId
let result := newMVarIds ++ otherMVarIds.toList
result.forM (·.headBetaType)
return result
@[deprecated MVarId.apply]
def apply (mvarId : MVarId) (e : Expr) (cfg : ApplyConfig := {}) : MetaM (List MVarId) :=
mvarId.apply e cfg
partial def splitAndCore (mvarId : MVarId) : MetaM (List MVarId) :=
mvarId.withContext do
mvarId.checkNotAssigned `splitAnd
let type ← mvarId.getType'
if !type.isAppOfArity ``And 2 then
return [mvarId]
else
let tag ← mvarId.getTag
let rec go (type : Expr) : StateRefT (Array MVarId) MetaM Expr := do
let type ← whnf type
if type.isAppOfArity ``And 2 then
let p₁ := type.appFn!.appArg!
let p₂ := type.appArg!
return mkApp4 (mkConst ``And.intro) p₁ p₂ (← go p₁) (← go p₂)
else
let idx := (← get).size + 1
let mvar ← mkFreshExprSyntheticOpaqueMVar type (tag ++ (`h).appendIndexAfter idx)
modify fun s => s.push mvar.mvarId!
return mvar
let (val, s) ← go type |>.run #[]
mvarId.assign val
return s.toList
/--
Apply `And.intro` as much as possible to goal `mvarId`.
-/
abbrev _root_.Lean.MVarId.splitAnd (mvarId : MVarId) : MetaM (List MVarId) :=
splitAndCore mvarId
@[deprecated MVarId.splitAnd]
def splitAnd (mvarId : MVarId) : MetaM (List MVarId) :=
mvarId.splitAnd
def _root_.Lean.MVarId.exfalso (mvarId : MVarId) : MetaM MVarId :=
mvarId.withContext do
mvarId.checkNotAssigned `exfalso
let target ← instantiateMVars (← mvarId.getType)
let u ← getLevel target
let mvarIdNew ← mkFreshExprSyntheticOpaqueMVar (mkConst ``False) (tag := (← mvarId.getTag))
mvarId.assign (mkApp2 (mkConst ``False.elim [u]) target mvarIdNew)
return mvarIdNew.mvarId!
end Lean.Meta
|
07341002f18e8f5c4aa48a9746273fc6e818c68f | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/ring_theory/tensor_product_auto.lean | 96dbd0e78b5a0d089587c3d25aee64ee9f81df80 | [] | 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 | 20,377 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.linear_algebra.tensor_product
import Mathlib.algebra.algebra.basic
import Mathlib.PostPort
universes u v₁ v₂ v₃ v₄
namespace Mathlib
/-!
# The tensor product of R-algebras
We construct the R-algebra structure on `A ⊗[R] B`, when `A` and `B` are both `R`-algebras,
and provide the structure isomorphisms
* `R ⊗[R] A ≃ₐ[R] A`
* `A ⊗[R] R ≃ₐ[R] A`
* `A ⊗[R] B ≃ₐ[R] B ⊗[R] A`
The code for
* `((A ⊗[R] B) ⊗[R] C) ≃ₐ[R] (A ⊗[R] (B ⊗[R] C))`
is written and compiles, but takes longer than the `-T100000` time limit,
so is currently commented out.
-/
namespace algebra
namespace tensor_product
/--
(Implementation detail)
The multiplication map on `A ⊗[R] B`,
for a fixed pure tensor in the first argument,
as an `R`-linear map.
-/
def mul_aux {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂}
[semiring B] [algebra R B] (a₁ : A) (b₁ : B) :
linear_map R (tensor_product R A B) (tensor_product R A B) :=
tensor_product.lift
(linear_map.mk
(fun (a₂ : A) =>
linear_map.mk (fun (b₂ : B) => tensor_product.tmul R (a₁ * a₂) (b₁ * b₂)) sorry sorry)
sorry sorry)
@[simp] theorem mul_aux_apply {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A]
[algebra R A] {B : Type v₂} [semiring B] [algebra R B] (a₁ : A) (a₂ : A) (b₁ : B) (b₂ : B) :
coe_fn (mul_aux a₁ b₁) (tensor_product.tmul R a₂ b₂) =
tensor_product.tmul R (a₁ * a₂) (b₁ * b₂) :=
rfl
/--
(Implementation detail)
The multiplication map on `A ⊗[R] B`,
as an `R`-bilinear map.
-/
def mul {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂}
[semiring B] [algebra R B] :
linear_map R (tensor_product R A B)
(linear_map R (tensor_product R A B) (tensor_product R A B)) :=
tensor_product.lift
(linear_map.mk (fun (a₁ : A) => linear_map.mk (fun (b₁ : B) => mul_aux a₁ b₁) sorry sorry) sorry
sorry)
@[simp] theorem mul_apply {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A]
{B : Type v₂} [semiring B] [algebra R B] (a₁ : A) (a₂ : A) (b₁ : B) (b₂ : B) :
coe_fn (coe_fn mul (tensor_product.tmul R a₁ b₁)) (tensor_product.tmul R a₂ b₂) =
tensor_product.tmul R (a₁ * a₂) (b₁ * b₂) :=
rfl
theorem mul_assoc' {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A]
{B : Type v₂} [semiring B] [algebra R B]
(mul :
linear_map R (tensor_product R A B)
(linear_map R (tensor_product R A B) (tensor_product R A B)))
(h :
∀ (a₁ a₂ a₃ : A) (b₁ b₂ b₃ : B),
coe_fn
(coe_fn mul
(coe_fn (coe_fn mul (tensor_product.tmul R a₁ b₁)) (tensor_product.tmul R a₂ b₂)))
(tensor_product.tmul R a₃ b₃) =
coe_fn (coe_fn mul (tensor_product.tmul R a₁ b₁))
(coe_fn (coe_fn mul (tensor_product.tmul R a₂ b₂)) (tensor_product.tmul R a₃ b₃)))
(x : tensor_product R A B) (y : tensor_product R A B) (z : tensor_product R A B) :
coe_fn (coe_fn mul (coe_fn (coe_fn mul x) y)) z =
coe_fn (coe_fn mul x) (coe_fn (coe_fn mul y) z) :=
sorry
theorem mul_assoc {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A]
{B : Type v₂} [semiring B] [algebra R B] (x : tensor_product R A B) (y : tensor_product R A B)
(z : tensor_product R A B) :
coe_fn (coe_fn mul (coe_fn (coe_fn mul x) y)) z =
coe_fn (coe_fn mul x) (coe_fn (coe_fn mul y) z) :=
sorry
theorem one_mul {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A]
{B : Type v₂} [semiring B] [algebra R B] (x : tensor_product R A B) :
coe_fn (coe_fn mul (tensor_product.tmul R 1 1)) x = x :=
sorry
theorem mul_one {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A]
{B : Type v₂} [semiring B] [algebra R B] (x : tensor_product R A B) :
coe_fn (coe_fn mul x) (tensor_product.tmul R 1 1) = x :=
sorry
protected instance tensor_product.semiring {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A]
[algebra R A] {B : Type v₂} [semiring B] [algebra R B] : semiring (tensor_product R A B) :=
semiring.mk Add.add sorry 0 sorry sorry sorry
(fun (a b : tensor_product R A B) => coe_fn (coe_fn mul a) b) mul_assoc
(tensor_product.tmul R 1 1) one_mul mul_one sorry sorry sorry sorry
theorem one_def {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A]
{B : Type v₂} [semiring B] [algebra R B] : 1 = tensor_product.tmul R 1 1 :=
rfl
@[simp] theorem tmul_mul_tmul {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A]
[algebra R A] {B : Type v₂} [semiring B] [algebra R B] (a₁ : A) (a₂ : A) (b₁ : B) (b₂ : B) :
tensor_product.tmul R a₁ b₁ * tensor_product.tmul R a₂ b₂ =
tensor_product.tmul R (a₁ * a₂) (b₁ * b₂) :=
rfl
@[simp] theorem tmul_pow {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A]
{B : Type v₂} [semiring B] [algebra R B] (a : A) (b : B) (k : ℕ) :
tensor_product.tmul R a b ^ k = tensor_product.tmul R (a ^ k) (b ^ k) :=
sorry
/--
The algebra map `R →+* (A ⊗[R] B)` giving `A ⊗[R] B` the structure of an `R`-algebra.
-/
def tensor_algebra_map {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A]
{B : Type v₂} [semiring B] [algebra R B] : R →+* tensor_product R A B :=
ring_hom.mk (fun (r : R) => tensor_product.tmul R (coe_fn (algebra_map R A) r) 1) sorry sorry
sorry sorry
protected instance tensor_product.algebra {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A]
[algebra R A] {B : Type v₂} [semiring B] [algebra R B] : algebra R (tensor_product R A B) :=
mk (ring_hom.mk (ring_hom.to_fun tensor_algebra_map) sorry sorry sorry sorry) sorry sorry
@[simp] theorem algebra_map_apply {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A]
[algebra R A] {B : Type v₂} [semiring B] [algebra R B] (r : R) :
coe_fn (algebra_map R (tensor_product R A B)) r =
tensor_product.tmul R (coe_fn (algebra_map R A) r) 1 :=
rfl
theorem ext {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂}
[semiring B] [algebra R B] {C : Type v₃} [semiring C] [algebra R C]
{g : alg_hom R (tensor_product R A B) C} {h : alg_hom R (tensor_product R A B) C}
(H :
∀ (a : A) (b : B),
coe_fn g (tensor_product.tmul R a b) = coe_fn h (tensor_product.tmul R a b)) :
g = h :=
sorry
/-- The algebra morphism `A →ₐ[R] A ⊗[R] B` sending `a` to `a ⊗ₜ 1`. -/
def include_left {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A]
{B : Type v₂} [semiring B] [algebra R B] : alg_hom R A (tensor_product R A B) :=
alg_hom.mk (fun (a : A) => tensor_product.tmul R a 1) sorry sorry sorry sorry sorry
@[simp] theorem include_left_apply {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A]
[algebra R A] {B : Type v₂} [semiring B] [algebra R B] (a : A) :
coe_fn include_left a = tensor_product.tmul R a 1 :=
rfl
/-- The algebra morphism `B →ₐ[R] A ⊗[R] B` sending `b` to `1 ⊗ₜ b`. -/
def include_right {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A]
{B : Type v₂} [semiring B] [algebra R B] : alg_hom R B (tensor_product R A B) :=
alg_hom.mk (fun (b : B) => tensor_product.tmul R 1 b) sorry sorry sorry sorry sorry
@[simp] theorem include_right_apply {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A]
[algebra R A] {B : Type v₂} [semiring B] [algebra R B] (b : B) :
coe_fn include_right b = tensor_product.tmul R 1 b :=
rfl
protected instance tensor_product.ring {R : Type u} [comm_ring R] {A : Type v₁} [ring A]
[algebra R A] {B : Type v₂} [ring B] [algebra R B] : ring (tensor_product R A B) :=
ring.mk add_comm_group.add sorry add_comm_group.zero sorry sorry add_comm_group.neg
add_comm_group.sub sorry sorry semiring.mul sorry semiring.one sorry sorry sorry sorry
protected instance tensor_product.comm_ring {R : Type u} [comm_ring R] {A : Type v₁} [comm_ring A]
[algebra R A] {B : Type v₂} [comm_ring B] [algebra R B] : comm_ring (tensor_product R A B) :=
comm_ring.mk ring.add sorry ring.zero sorry sorry ring.neg ring.sub sorry sorry ring.mul sorry
ring.one sorry sorry sorry sorry sorry
/--
Verify that typeclass search finds the ring structure on `A ⊗[ℤ] B`
when `A` and `B` are merely rings, by treating both as `ℤ`-algebras.
-/
/--
Verify that typeclass search finds the comm_ring structure on `A ⊗[ℤ] B`
when `A` and `B` are merely comm_rings, by treating both as `ℤ`-algebras.
-/
/-!
We now build the structure maps for the symmetric monoidal category of `R`-algebras.
-/
/--
Build an algebra morphism from a linear map out of a tensor product,
and evidence of multiplicativity on pure tensors.
-/
def alg_hom_of_linear_map_tensor_product {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A]
[algebra R A] {B : Type v₂} [semiring B] [algebra R B] {C : Type v₃} [semiring C] [algebra R C]
(f : linear_map R (tensor_product R A B) C)
(w₁ :
∀ (a₁ a₂ : A) (b₁ b₂ : B),
coe_fn f (tensor_product.tmul R (a₁ * a₂) (b₁ * b₂)) =
coe_fn f (tensor_product.tmul R a₁ b₁) * coe_fn f (tensor_product.tmul R a₂ b₂))
(w₂ :
∀ (r : R),
coe_fn f (tensor_product.tmul R (coe_fn (algebra_map R A) r) 1) =
coe_fn (algebra_map R C) r) :
alg_hom R (tensor_product R A B) C :=
alg_hom.mk (linear_map.to_fun f) sorry sorry sorry sorry sorry
@[simp] theorem alg_hom_of_linear_map_tensor_product_apply {R : Type u} [comm_semiring R]
{A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] {C : Type v₃}
[semiring C] [algebra R C] (f : linear_map R (tensor_product R A B) C)
(w₁ :
∀ (a₁ a₂ : A) (b₁ b₂ : B),
coe_fn f (tensor_product.tmul R (a₁ * a₂) (b₁ * b₂)) =
coe_fn f (tensor_product.tmul R a₁ b₁) * coe_fn f (tensor_product.tmul R a₂ b₂))
(w₂ :
∀ (r : R),
coe_fn f (tensor_product.tmul R (coe_fn (algebra_map R A) r) 1) =
coe_fn (algebra_map R C) r)
(x : tensor_product R A B) :
coe_fn (alg_hom_of_linear_map_tensor_product f w₁ w₂) x = coe_fn f x :=
rfl
/--
Build an algebra equivalence from a linear equivalence out of a tensor product,
and evidence of multiplicativity on pure tensors.
-/
def alg_equiv_of_linear_equiv_tensor_product {R : Type u} [comm_semiring R] {A : Type v₁}
[semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] {C : Type v₃} [semiring C]
[algebra R C] (f : linear_equiv R (tensor_product R A B) C)
(w₁ :
∀ (a₁ a₂ : A) (b₁ b₂ : B),
coe_fn f (tensor_product.tmul R (a₁ * a₂) (b₁ * b₂)) =
coe_fn f (tensor_product.tmul R a₁ b₁) * coe_fn f (tensor_product.tmul R a₂ b₂))
(w₂ :
∀ (r : R),
coe_fn f (tensor_product.tmul R (coe_fn (algebra_map R A) r) 1) =
coe_fn (algebra_map R C) r) :
alg_equiv R (tensor_product R A B) C :=
alg_equiv.mk (alg_hom.to_fun (alg_hom_of_linear_map_tensor_product (↑f) w₁ w₂))
(linear_equiv.inv_fun f) sorry sorry sorry sorry sorry
@[simp] theorem alg_equiv_of_linear_equiv_tensor_product_apply {R : Type u} [comm_semiring R]
{A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] {C : Type v₃}
[semiring C] [algebra R C] (f : linear_equiv R (tensor_product R A B) C)
(w₁ :
∀ (a₁ a₂ : A) (b₁ b₂ : B),
coe_fn f (tensor_product.tmul R (a₁ * a₂) (b₁ * b₂)) =
coe_fn f (tensor_product.tmul R a₁ b₁) * coe_fn f (tensor_product.tmul R a₂ b₂))
(w₂ :
∀ (r : R),
coe_fn f (tensor_product.tmul R (coe_fn (algebra_map R A) r) 1) =
coe_fn (algebra_map R C) r)
(x : tensor_product R A B) :
coe_fn (alg_equiv_of_linear_equiv_tensor_product f w₁ w₂) x = coe_fn f x :=
rfl
/--
Build an algebra equivalence from a linear equivalence out of a triple tensor product,
and evidence of multiplicativity on pure tensors.
-/
def alg_equiv_of_linear_equiv_triple_tensor_product {R : Type u} [comm_semiring R] {A : Type v₁}
[semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] {C : Type v₃} [semiring C]
[algebra R C] {D : Type v₄} [semiring D] [algebra R D]
(f : linear_equiv R (tensor_product R (tensor_product R A B) C) D)
(w₁ :
∀ (a₁ a₂ : A) (b₁ b₂ : B) (c₁ c₂ : C),
coe_fn f (tensor_product.tmul R (tensor_product.tmul R (a₁ * a₂) (b₁ * b₂)) (c₁ * c₂)) =
coe_fn f (tensor_product.tmul R (tensor_product.tmul R a₁ b₁) c₁) *
coe_fn f (tensor_product.tmul R (tensor_product.tmul R a₂ b₂) c₂))
(w₂ :
∀ (r : R),
coe_fn f (tensor_product.tmul R (tensor_product.tmul R (coe_fn (algebra_map R A) r) 1) 1) =
coe_fn (algebra_map R D) r) :
alg_equiv R (tensor_product R (tensor_product R A B) C) D :=
alg_equiv.mk (⇑f) (linear_equiv.inv_fun f) sorry sorry sorry sorry sorry
@[simp] theorem alg_equiv_of_linear_equiv_triple_tensor_product_apply {R : Type u} [comm_semiring R]
{A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] {C : Type v₃}
[semiring C] [algebra R C] {D : Type v₄} [semiring D] [algebra R D]
(f : linear_equiv R (tensor_product R (tensor_product R A B) C) D)
(w₁ :
∀ (a₁ a₂ : A) (b₁ b₂ : B) (c₁ c₂ : C),
coe_fn f (tensor_product.tmul R (tensor_product.tmul R (a₁ * a₂) (b₁ * b₂)) (c₁ * c₂)) =
coe_fn f (tensor_product.tmul R (tensor_product.tmul R a₁ b₁) c₁) *
coe_fn f (tensor_product.tmul R (tensor_product.tmul R a₂ b₂) c₂))
(w₂ :
∀ (r : R),
coe_fn f (tensor_product.tmul R (tensor_product.tmul R (coe_fn (algebra_map R A) r) 1) 1) =
coe_fn (algebra_map R D) r)
(x : tensor_product R (tensor_product R A B) C) :
coe_fn (alg_equiv_of_linear_equiv_triple_tensor_product f w₁ w₂) x = coe_fn f x :=
rfl
/--
The base ring is a left identity for the tensor product of algebra, up to algebra isomorphism.
-/
protected def lid (R : Type u) [comm_semiring R] (A : Type v₁) [semiring A] [algebra R A] :
alg_equiv R (tensor_product R R A) A :=
alg_equiv_of_linear_equiv_tensor_product (tensor_product.lid R A) sorry sorry
@[simp] theorem lid_tmul (R : Type u) [comm_semiring R] (A : Type v₁) [semiring A] [algebra R A]
(r : R) (a : A) : coe_fn (tensor_product.lid R A) (tensor_product.tmul R r a) = r • a :=
sorry
/--
The base ring is a right identity for the tensor product of algebra, up to algebra isomorphism.
-/
protected def rid (R : Type u) [comm_semiring R] (A : Type v₁) [semiring A] [algebra R A] :
alg_equiv R (tensor_product R A R) A :=
alg_equiv_of_linear_equiv_tensor_product (tensor_product.rid R A) sorry sorry
@[simp] theorem rid_tmul (R : Type u) [comm_semiring R] (A : Type v₁) [semiring A] [algebra R A]
(r : R) (a : A) : coe_fn (tensor_product.rid R A) (tensor_product.tmul R a r) = r • a :=
sorry
/--
The tensor product of R-algebras is commutative, up to algebra isomorphism.
-/
protected def comm (R : Type u) [comm_semiring R] (A : Type v₁) [semiring A] [algebra R A]
(B : Type v₂) [semiring B] [algebra R B] :
alg_equiv R (tensor_product R A B) (tensor_product R B A) :=
alg_equiv_of_linear_equiv_tensor_product (tensor_product.comm R A B) sorry sorry
@[simp] theorem comm_tmul (R : Type u) [comm_semiring R] (A : Type v₁) [semiring A] [algebra R A]
(B : Type v₂) [semiring B] [algebra R B] (a : A) (b : B) :
coe_fn (tensor_product.comm R A B) (tensor_product.tmul R a b) = tensor_product.tmul R b a :=
sorry
theorem assoc_aux_1 {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A]
{B : Type v₂} [semiring B] [algebra R B] {C : Type v₃} [semiring C] [algebra R C] (a₁ : A)
(a₂ : A) (b₁ : B) (b₂ : B) (c₁ : C) (c₂ : C) :
coe_fn (tensor_product.assoc R A B C)
(tensor_product.tmul R (tensor_product.tmul R (a₁ * a₂) (b₁ * b₂)) (c₁ * c₂)) =
coe_fn (tensor_product.assoc R A B C)
(tensor_product.tmul R (tensor_product.tmul R a₁ b₁) c₁) *
coe_fn (tensor_product.assoc R A B C)
(tensor_product.tmul R (tensor_product.tmul R a₂ b₂) c₂) :=
rfl
theorem assoc_aux_2 {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A]
{B : Type v₂} [semiring B] [algebra R B] {C : Type v₃} [semiring C] [algebra R C] (r : R) :
coe_fn (tensor_product.assoc R A B C)
(tensor_product.tmul R (tensor_product.tmul R (coe_fn (algebra_map R A) r) 1) 1) =
coe_fn (algebra_map R (tensor_product R A (tensor_product R B C))) r :=
rfl
-- variables (R A B C)
-- -- local attribute [elab_simple] alg_equiv_of_linear_equiv_triple_tensor_product
-- /-- The associator for tensor product of R-algebras, as an algebra isomorphism. -/
-- -- FIXME This is _really_ slow to compile. :-(
-- protected def assoc : ((A ⊗[R] B) ⊗[R] C) ≃ₐ[R] (A ⊗[R] (B ⊗[R] C)) :=
-- alg_equiv_of_linear_equiv_triple_tensor_product
-- (tensor_product.assoc R A B C)
-- assoc_aux_1 assoc_aux_2
-- variables {R A B C}
-- @[simp] theorem assoc_tmul (a : A) (b : B) (c : C) :
-- ((tensor_product.assoc R A B C) : (A ⊗[R] B) ⊗[R] C → A ⊗[R] (B ⊗[R] C)) ((a ⊗ₜ b) ⊗ₜ c) = a ⊗ₜ (b ⊗ₜ c) :=
-- rfl
/-- The tensor product of a pair of algebra morphisms. -/
def map {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂}
[semiring B] [algebra R B] {C : Type v₃} [semiring C] [algebra R C] {D : Type v₄} [semiring D]
[algebra R D] (f : alg_hom R A B) (g : alg_hom R C D) :
alg_hom R (tensor_product R A C) (tensor_product R B D) :=
alg_hom_of_linear_map_tensor_product
(tensor_product.map (alg_hom.to_linear_map f) (alg_hom.to_linear_map g)) sorry sorry
@[simp] theorem map_tmul {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A]
{B : Type v₂} [semiring B] [algebra R B] {C : Type v₃} [semiring C] [algebra R C] {D : Type v₄}
[semiring D] [algebra R D] (f : alg_hom R A B) (g : alg_hom R C D) (a : A) (c : C) :
coe_fn (map f g) (tensor_product.tmul R a c) =
tensor_product.tmul R (coe_fn f a) (coe_fn g c) :=
rfl
/--
Construct an isomorphism between tensor products of R-algebras
from isomorphisms between the tensor factors.
-/
def congr {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂}
[semiring B] [algebra R B] {C : Type v₃} [semiring C] [algebra R C] {D : Type v₄} [semiring D]
[algebra R D] (f : alg_equiv R A B) (g : alg_equiv R C D) :
alg_equiv R (tensor_product R A C) (tensor_product R B D) :=
alg_equiv.of_alg_hom (map ↑f ↑g) (map ↑(alg_equiv.symm f) ↑(alg_equiv.symm g)) sorry sorry
@[simp] theorem congr_apply {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A]
{B : Type v₂} [semiring B] [algebra R B] {C : Type v₃} [semiring C] [algebra R C] {D : Type v₄}
[semiring D] [algebra R D] (f : alg_equiv R A B) (g : alg_equiv R C D)
(x : tensor_product R A C) : coe_fn (congr f g) x = coe_fn (map ↑f ↑g) x :=
rfl
@[simp] theorem congr_symm_apply {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A]
[algebra R A] {B : Type v₂} [semiring B] [algebra R B] {C : Type v₃} [semiring C] [algebra R C]
{D : Type v₄} [semiring D] [algebra R D] (f : alg_equiv R A B) (g : alg_equiv R C D)
(x : tensor_product R B D) :
coe_fn (alg_equiv.symm (congr f g)) x =
coe_fn (map ↑(alg_equiv.symm f) ↑(alg_equiv.symm g)) x :=
rfl
end Mathlib |
107705d1813eeeb41e2e05820792b5ea8a2c37a5 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Meta/Tactic/UnifyEq.lean | 7bcf83f690a4bd64e088044a7a7010d1c4409c56 | [
"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 | 5,190 | lean | /-
Copyright (c) 2022 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Tactic.Injection
namespace Lean.Meta
/-- Convert heterogeneous equality into a homegeneous one -/
private def heqToEq' (mvarId : MVarId) (eqDecl : LocalDecl) : MetaM MVarId := do
/- Convert heterogeneous equality into a homegeneous one -/
let prf ← mkEqOfHEq (mkFVar eqDecl.fvarId)
let aEqb ← whnf (← inferType prf)
let mvarId ← mvarId.assert eqDecl.userName aEqb prf
mvarId.clear eqDecl.fvarId
structure UnifyEqResult where
mvarId : MVarId
subst : FVarSubst
numNewEqs : Nat := 0
/--
Helper method for methods such as `Cases.unifyEqs?`.
Given the given goal `mvarId` containing the local hypothesis `eqFVarId`, it performs the following operations:
- If `eqFVarId` is a heterogeneous equality, tries to convert it to a homogeneous one.
- If `eqFVarId` is a homogeneous equality of the form `a = b`, it tries
- If `a` and `b` are definitionally equal, clear it
- Normalize `a` and `b` using the current reducibility setting.
- If `a` (`b`) is a free variable not occurring in `b` (`a`), replace it everywhere.
- If `a` and `b` are distinct constructors, return `none` to indicate that the goal has been closed.
- If `a` and `b` are the same contructor, apply `injection`, the result contains the number of new equalities introduced in the goal.
- It also tries to apply the given `acyclic` method to try to close the goal.
Remark: It is a parameter because `simp` uses `unifyEq?`, and `acyclic` depends on `simp`.
-/
def unifyEq? (mvarId : MVarId) (eqFVarId : FVarId) (subst : FVarSubst := {})
(acyclic : MVarId → Expr → MetaM Bool := fun _ _ => return false)
(caseName? : Option Name := none)
: MetaM (Option UnifyEqResult) := do
mvarId.withContext do
let eqDecl ← eqFVarId.getDecl
if eqDecl.type.isHEq then
let mvarId ← heqToEq' mvarId eqDecl
return some { mvarId, subst, numNewEqs := 1 }
else match eqDecl.type.eq? with
| none => throwError "equality expected{indentExpr eqDecl.type}"
| some (_, a, b) =>
/-
Remark: we do not check `isDefeq` here because we would fail to substitute equalities
such as `x = t` and `t = x` when `x` and `t` are proofs (proof irrelanvance).
-/
/- Remark: we use `let rec` here because otherwise the compiler would generate an insane amount of code.
We can remove the `rec` after we fix the eagerly inlining issue in the compiler. -/
let rec substEq (symm : Bool) := do
/- Remark: `substCore` fails if the equation is of the form `x = x` -/
if let some (subst, mvarId) ← observing? (substCore mvarId eqFVarId symm subst) then
return some { mvarId, subst }
else if (← isDefEq a b) then
/- Skip equality -/
return some { mvarId := (← mvarId.clear eqFVarId), subst }
else if (← acyclic mvarId (mkFVar eqFVarId)) then
return none -- this alternative has been solved
else
throwError "dependent elimination failed, failed to solve equation{indentExpr eqDecl.type}"
let rec injection (a b : Expr) := do
let env ← getEnv
if a.isConstructorApp env && b.isConstructorApp env then
/- ctor_i ... = ctor_j ... -/
match (← injectionCore mvarId eqFVarId) with
| InjectionResultCore.solved => return none -- this alternative has been solved
| InjectionResultCore.subgoal mvarId numNewEqs => return some { mvarId, numNewEqs, subst }
else
let a' ← whnf a
let b' ← whnf b
if a' != a || b' != b then
/- Reduced lhs/rhs of current equality -/
let prf := mkFVar eqFVarId
let aEqb' ← mkEq a' b'
let mvarId ← mvarId.assert eqDecl.userName aEqb' prf
let mvarId ← mvarId.clear eqFVarId
return some { mvarId, subst, numNewEqs := 1 }
else
match caseName? with
| none => throwError "dependent elimination failed, failed to solve equation{indentExpr eqDecl.type}"
| some caseName => throwError "dependent elimination failed, failed to solve equation{indentExpr eqDecl.type}\nat case {mkConst caseName}"
let a ← instantiateMVars a
let b ← instantiateMVars b
match a, b with
| Expr.fvar aFVarId, Expr.fvar bFVarId =>
/- x = y -/
let aDecl ← aFVarId.getDecl
let bDecl ← bFVarId.getDecl
substEq (aDecl.index < bDecl.index)
| Expr.fvar .., _ => /- x = t -/ substEq (symm := false)
| _, Expr.fvar .. => /- t = x -/ substEq (symm := true)
| a, b =>
if (← isDefEq a b) then
/- Skip equality -/
return some { mvarId := (← mvarId.clear eqFVarId), subst }
else
injection a b
end Lean.Meta
|
ba939b6bb482b1bd0016fc1e49e58e5fb4114008 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /stage0/src/Lean/Compiler/IR/Format.lean | d63dfd1ad5ede72635e7b60a2888338f89042204 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | EdAyers/lean4 | 57ac632d6b0789cb91fab2170e8c9e40441221bd | 37ba0df5841bde51dbc2329da81ac23d4f6a4de4 | refs/heads/master | 1,676,463,245,298 | 1,660,619,433,000 | 1,660,619,433,000 | 183,433,437 | 1 | 0 | Apache-2.0 | 1,657,612,672,000 | 1,556,196,574,000 | Lean | UTF-8 | Lean | false | false | 6,997 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Compiler.IR.Basic
namespace Lean
namespace IR
private def formatArg : Arg → Format
| Arg.var id => format id
| Arg.irrelevant => "◾"
instance : ToFormat Arg := ⟨formatArg⟩
def formatArray {α : Type} [ToFormat α] (args : Array α) : Format :=
args.foldl (fun r a => r ++ " " ++ format a) Format.nil
private def formatLitVal : LitVal → Format
| LitVal.num v => format v
| LitVal.str v => format (repr v)
instance : ToFormat LitVal := ⟨formatLitVal⟩
private def formatCtorInfo : CtorInfo → Format
| { name := name, cidx := cidx, usize := usize, ssize := ssize, .. } => Id.run do
let mut r := f!"ctor_{cidx}"
if usize > 0 || ssize > 0 then
r := f!"{r}.{usize}.{ssize}"
if name != Name.anonymous then
r := f!"{r}[{name}]"
r
instance : ToFormat CtorInfo := ⟨formatCtorInfo⟩
private def formatExpr : Expr → Format
| Expr.ctor i ys => format i ++ formatArray ys
| Expr.reset n x => "reset[" ++ format n ++ "] " ++ format x
| Expr.reuse x i u ys => "reuse" ++ (if u then "!" else "") ++ " " ++ format x ++ " in " ++ format i ++ formatArray ys
| Expr.proj i x => "proj[" ++ format i ++ "] " ++ format x
| Expr.uproj i x => "uproj[" ++ format i ++ "] " ++ format x
| Expr.sproj n o x => "sproj[" ++ format n ++ ", " ++ format o ++ "] " ++ format x
| Expr.fap c ys => format c ++ formatArray ys
| Expr.pap c ys => "pap " ++ format c ++ formatArray ys
| Expr.ap x ys => "app " ++ format x ++ formatArray ys
| Expr.box _ x => "box " ++ format x
| Expr.unbox x => "unbox " ++ format x
| Expr.lit v => format v
| Expr.isShared x => "isShared " ++ format x
| Expr.isTaggedPtr x => "isTaggedPtr " ++ format x
instance : ToFormat Expr := ⟨formatExpr⟩
instance : ToString Expr := ⟨fun e => Format.pretty (format e)⟩
private partial def formatIRType : IRType → Format
| IRType.float => "float"
| IRType.uint8 => "u8"
| IRType.uint16 => "u16"
| IRType.uint32 => "u32"
| IRType.uint64 => "u64"
| IRType.usize => "usize"
| IRType.irrelevant => "◾"
| IRType.object => "obj"
| IRType.tobject => "tobj"
| IRType.struct _ tys =>
let _ : ToFormat IRType := ⟨formatIRType⟩
"struct " ++ Format.bracket "{" (Format.joinSep tys.toList ", ") "}"
| IRType.union _ tys =>
let _ : ToFormat IRType := ⟨formatIRType⟩
"union " ++ Format.bracket "{" (Format.joinSep tys.toList ", ") "}"
instance : ToFormat IRType := ⟨formatIRType⟩
instance : ToString IRType := ⟨toString ∘ format⟩
private def formatParam : Param → Format
| { x := name, borrow := b, ty := ty } => "(" ++ format name ++ " : " ++ (if b then "@& " else "") ++ format ty ++ ")"
instance : ToFormat Param := ⟨formatParam⟩
def formatAlt (fmt : FnBody → Format) (indent : Nat) : Alt → Format
| Alt.ctor i b => format i.name ++ " →" ++ Format.nest indent (Format.line ++ fmt b)
| Alt.default b => "default →" ++ Format.nest indent (Format.line ++ fmt b)
def formatParams (ps : Array Param) : Format :=
formatArray ps
@[export lean_ir_format_fn_body_head]
def formatFnBodyHead : FnBody → Format
| FnBody.vdecl x ty e _ => "let " ++ format x ++ " : " ++ format ty ++ " := " ++ format e
| FnBody.jdecl j xs _ _ => format j ++ formatParams xs ++ " := ..."
| FnBody.set x i y _ => "set " ++ format x ++ "[" ++ format i ++ "] := " ++ format y
| FnBody.uset x i y _ => "uset " ++ format x ++ "[" ++ format i ++ "] := " ++ format y
| FnBody.sset x i o y ty _ => "sset " ++ format x ++ "[" ++ format i ++ ", " ++ format o ++ "] : " ++ format ty ++ " := " ++ format y
| FnBody.setTag x cidx _ => "setTag " ++ format x ++ " := " ++ format cidx
| FnBody.inc x n _ _ _ => "inc" ++ (if n != 1 then Format.sbracket (format n) else "") ++ " " ++ format x
| FnBody.dec x n _ _ _ => "dec" ++ (if n != 1 then Format.sbracket (format n) else "") ++ " " ++ format x
| FnBody.del x _ => "del " ++ format x
| FnBody.mdata d _ => "mdata " ++ format d
| FnBody.case _ x _ _ => "case " ++ format x ++ " of ..."
| FnBody.jmp j ys => "jmp " ++ format j ++ formatArray ys
| FnBody.ret x => "ret " ++ format x
| FnBody.unreachable => "⊥"
partial def formatFnBody (fnBody : FnBody) (indent : Nat := 2) : Format :=
let rec loop : FnBody → Format
| FnBody.vdecl x ty e b => "let " ++ format x ++ " : " ++ format ty ++ " := " ++ format e ++ ";" ++ Format.line ++ loop b
| FnBody.jdecl j xs v b => format j ++ formatParams xs ++ " :=" ++ Format.nest indent (Format.line ++ loop v) ++ ";" ++ Format.line ++ loop b
| FnBody.set x i y b => "set " ++ format x ++ "[" ++ format i ++ "] := " ++ format y ++ ";" ++ Format.line ++ loop b
| FnBody.uset x i y b => "uset " ++ format x ++ "[" ++ format i ++ "] := " ++ format y ++ ";" ++ Format.line ++ loop b
| FnBody.sset x i o y ty b => "sset " ++ format x ++ "[" ++ format i ++ ", " ++ format o ++ "] : " ++ format ty ++ " := " ++ format y ++ ";" ++ Format.line ++ loop b
| FnBody.setTag x cidx b => "setTag " ++ format x ++ " := " ++ format cidx ++ ";" ++ Format.line ++ loop b
| FnBody.inc x n _ _ b => "inc" ++ (if n != 1 then Format.sbracket (format n) else "") ++ " " ++ format x ++ ";" ++ Format.line ++ loop b
| FnBody.dec x n _ _ b => "dec" ++ (if n != 1 then Format.sbracket (format n) else "") ++ " " ++ format x ++ ";" ++ Format.line ++ loop b
| FnBody.del x b => "del " ++ format x ++ ";" ++ Format.line ++ loop b
| FnBody.mdata d b => "mdata " ++ format d ++ ";" ++ Format.line ++ loop b
| FnBody.case _ x xType cs => "case " ++ format x ++ " : " ++ format xType ++ " of" ++ cs.foldl (fun r c => r ++ Format.line ++ formatAlt loop indent c) Format.nil
| FnBody.jmp j ys => "jmp " ++ format j ++ formatArray ys
| FnBody.ret x => "ret " ++ format x
| FnBody.unreachable => "⊥"
loop fnBody
instance : ToFormat FnBody := ⟨formatFnBody⟩
instance : ToString FnBody := ⟨fun b => (format b).pretty⟩
def formatDecl (decl : Decl) (indent : Nat := 2) : Format :=
match decl with
| Decl.fdecl f xs ty b _ => "def " ++ format f ++ formatParams xs ++ format " : " ++ format ty ++ " :=" ++ Format.nest indent (Format.line ++ formatFnBody b indent)
| Decl.extern f xs ty _ => "extern " ++ format f ++ formatParams xs ++ format " : " ++ format ty
instance : ToFormat Decl := ⟨formatDecl⟩
@[export lean_ir_decl_to_string]
def declToString (d : Decl) : String :=
(format d).pretty
instance : ToString Decl := ⟨declToString⟩
end Lean.IR
|
001b141aaa4cfe01729fc8dc8af370ec077e12ba | 4efff1f47634ff19e2f786deadd394270a59ecd2 | /src/tactic/derive_fintype.lean | a4274e7a7456f95a80d5ed635cd0c1f96ea3a0b9 | [
"Apache-2.0"
] | permissive | agjftucker/mathlib | d634cd0d5256b6325e3c55bb7fb2403548371707 | 87fe50de17b00af533f72a102d0adefe4a2285e8 | refs/heads/master | 1,625,378,131,941 | 1,599,166,526,000 | 1,599,166,526,000 | 160,748,509 | 0 | 0 | Apache-2.0 | 1,544,141,789,000 | 1,544,141,789,000 | null | UTF-8 | Lean | false | false | 15,318 | lean | /-
Copyright (c) 2020 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
-/
import logic.basic data.fintype.basic
/-!
# Derive handler for `fintype` instances
This file introduces a derive handler to automatically generate `fintype`
instances for structures and inductives.
## Implementation notes
To construct a fintype instance, we need 3 things:
1. A list `l` of elements
2. A proof that `l` has no duplicates
3. A proof that every element in the type is in `l`
Now fintype is defined as a finset which enumerates all elements, so steps (1) and (2) are
bundled together. It is possible to use finset operations that remove duplicates to avoid the need
to prove (2), but this adds unnecessary functions to the constructed term, which makes it more
expensive to compute the list, and it also adds a dependence on decidable equality for the type,
which we want to avoid.
Because we will rely on fintype instances for constructor arguments, we can't actually build a list
directly, so (1) and (2) are necessarily somewhat intertwined. The inductive types we will be
proving instances for look something like this:
```
@[derive fintype]
inductive foo
| zero : foo
| one : bool → foo
| two : ∀ x : fin 3, bar x → foo
```
The list of elements that we generate is
```
{foo.zero}
∪ (finset.univ : bool).map (λ b, finset.one b)
∪ (finset.univ : Σ' x : fin 3, bar x).map (λ ⟨x, y⟩, finset.two x y)
```
except that instead of `∪`, that is `finset.union`, we use `finset.disj_union` which doesn't
require any deduplication, but does require a proof that the two parts of the union are disjoint.
We use `finset.cons` to append singletons like `foo.zero`.
The proofs of disjointness would be somewhat expensive since there are quadratically many of them,
so instead we use a "discriminant" function. Essentially, we define
```
def foo.enum : foo → ℕ
| foo.zero := 0
| (foo.one _) := 1
| (foo.two _ _) := 2
```
and now the existence of this function implies that foo.zero is not foo.two and so on because they
map to different natural numbers. We can prove that sets of natural numbers are mutually disjoint
more easily because they have a linear order: `0 < 1 < 2` so `0 ≠ 2`.
To package this argument up, we define `finset_above foo foo.enum n` to be a finset `s` together
with a proof that all elements `a ∈ s` have `n ≤ enum a`. Now we only have to prove that
`enum foo.zero = 0`, `enum (foo.one _) = 1`, etc. (linearly many proofs, all `rfl`) in order to
prove that all variants are mutually distinct.
We mirror the `finset.cons` and `finset.disj_union` functions into `finset_above.cons` and
`finset_above.union`, and this forms the main part of the finset construction.
This only handles distinguishing variants of a finset. Now we must enumerate the elements of a
variant, for example `{foo.one ff, foo.one tt}`, while at the same time proving that all these
elements have discriminant `1` in this case. To do that, we use the `finset_in` type, which
is a finset satisfying a property `P`, here `λ a, foo.enum a = 1`.
We could use `finset.bind` many times to construct the finset but it turns out to be somewhat
complicated to get good side goals for a naturally nodup version of `finset.bind` in the same way
as we did with `finset.cons` and `finset.union`. Instead, we tuple up all arguments into one type,
leveraging the `fintype` instance on `psigma`, and then define a map from this type to the
inductive type that untuples them and applies the constructor. The injectivity property of the
constructor ensures that this function is injective, so we can use `finset.map` to apply it. This
is the content of the constructor `finset_in.mk`.
That completes the proofs of (1) and (2). To prove (3), we perform one case analysis over the
inductive type, proving theorems like
```
foo.one a ∈ {foo.zero}
∪ (finset.univ : bool).map (λ b, finset.one b)
∪ (finset.univ : Σ' x : fin 3, bar x).map (λ ⟨x, y⟩, finset.two x y)
```
by seeking to the relevant disjunct and then supplying the constructor arguments. This part of the
proof is quadratic, but quite simple. (We could do it in `O(n log n)` if we used a balanced tree
for the unions.)
The tactics perform the following parts of this proof scheme:
* `mk_sigma` constructs the type `Γ` in `finset_in.mk`
* `mk_sigma_elim` constructs the function `f` in `finset_in.mk`
* `mk_sigma_elim_inj` proves that `f` is injective
* `mk_sigma_elim_eq` proves that `∀ a, enum (f a) = k`
* `mk_finset` constructs the finset `S = {foo.zero} ∪ ...` by recursion on the variants
* `mk_finset_total` constructs the proof `|- foo.zero ∈ S; |- foo.one a ∈ S; |- foo.two a b ∈ S`
by recursion on the subgoals coming out of the initial `cases`
* `mk_fintype_instance` puts it all together to produce a proof of `fintype foo`.
The construction of `foo.enum` is also done in this function.
-/
namespace derive_fintype
/-- A step in the construction of `finset.univ` for a finite inductive type.
We will set `enum` to the discriminant of the inductive type, so a `finset_above`
represents a finset that enumerates all elements in a tail of the constructor list. -/
def finset_above (α) (enum : α → ℕ) (n : ℕ) :=
{s : finset α // ∀ x ∈ s, n ≤ enum x}
/-- Construct a fintype instance from a completed `finset_above`. -/
def mk_fintype {α} (enum : α → ℕ) (s : finset_above α enum 0) (H : ∀ x, x ∈ s.1) :
fintype α := ⟨s.1, H⟩
/-- This is the case for a simple variant (no arguments) in an inductive type. -/
def finset_above.cons {α} {enum : α → ℕ} (n)
(a : α) (h : enum a = n) (s : finset_above α enum (n+1)) : finset_above α enum n :=
begin
refine ⟨finset.cons a s.1 _, _⟩,
{ intro h',
have := s.2 _ h', rw h at this,
exact nat.not_succ_le_self n this },
{ intros x h', rcases finset.mem_cons.1 h' with rfl | h',
{ exact ge_of_eq h },
{ exact nat.le_of_succ_le (s.2 _ h') } }
end
theorem finset_above.mem_cons_self {α} {enum : α → ℕ} {n a h s} :
a ∈ (@finset_above.cons α enum n a h s).1 := multiset.mem_cons_self _ _
theorem finset_above.mem_cons_of_mem {α} {enum : α → ℕ} {n a h s b} :
b ∈ (s : finset_above _ _ _).1 → b ∈ (@finset_above.cons α enum n a h s).1 :=
multiset.mem_cons_of_mem
/-- The base case is when we run out of variants; we just put an empty finset at the end. -/
def finset_above.nil {α} {enum : α → ℕ} (n) : finset_above α enum n := ⟨∅, by rintro _ ⟨⟩⟩
instance (α enum n) : inhabited (finset_above α enum n) := ⟨finset_above.nil _⟩
/-- This is a finset covering a nontrivial variant (with one or more constructor arguments).
The property `P` here is `λ a, enum a = n` where `n` is the discriminant for the current
variant. -/
@[nolint has_inhabited_instance]
def finset_in {α} (P : α → Prop) := {s : finset α // ∀ x ∈ s, P x}
/-- To construct the finset, we use an injective map from the type `Γ`, which will be the
sigma over all constructor arguments. We use sigma instances and existing fintype instances
to prove that `Γ` is a fintype, and construct the function `f` that maps `⟨a, b, c, ...⟩`
to `C_n a b c ...` where `C_n` is the nth constructor, and `mem` asserts
`enum (C_n a b c ...) = n`. -/
def finset_in.mk {α} {P : α → Prop} (Γ) [fintype Γ]
(f : Γ → α) (inj : function.injective f) (mem : ∀ x, P (f x)) : finset_in P :=
⟨finset.univ.map ⟨f, inj⟩,
λ x h, by rcases finset.mem_map.1 h with ⟨x, _, rfl⟩; exact mem x⟩
theorem finset_in.mem_mk {α} {P : α → Prop} {Γ} {s : fintype Γ} {f : Γ → α} {inj mem a}
(b) (H : f b = a) : a ∈ (@finset_in.mk α P Γ s f inj mem).1 :=
finset.mem_map.2 ⟨_, finset.mem_univ _, H⟩
/-- For nontrivial variants, we split the constructor list into a `finset_in` component for the
current constructor and a `finset_above` for the rest. -/
def finset_above.union {α} {enum : α → ℕ} (n)
(s : finset_in (λ a, enum a = n)) (t : finset_above α enum (n+1)) : finset_above α enum n :=
begin
refine ⟨finset.disj_union s.1 t.1 _, _⟩,
{ intros a hs ht,
have := t.2 _ ht, rw s.2 _ hs at this,
exact nat.not_succ_le_self n this },
{ intros x h', rcases finset.mem_disj_union.1 h' with h' | h',
{ exact ge_of_eq (s.2 _ h') },
{ exact nat.le_of_succ_le (t.2 _ h') } }
end
theorem finset_above.mem_union_left {α} {enum : α → ℕ} {n s t a}
(H : a ∈ (s : finset_in _).1) : a ∈ (@finset_above.union α enum n s t).1 :=
multiset.mem_add.2 (or.inl H)
theorem finset_above.mem_union_right {α} {enum : α → ℕ} {n s t a}
(H : a ∈ (t : finset_above _ _ _).1) : a ∈ (@finset_above.union α enum n s t).1 :=
multiset.mem_add.2 (or.inr H)
end derive_fintype
namespace tactic
open derive_fintype tactic expr
namespace derive_fintype
/-- Construct the term `Σ' (a:A) (b:B a), C a b` from `Π (a:A) (b:B a), C a b → T` (the type of a
constructor). -/
meta def mk_sigma : expr → tactic expr
| (expr.pi n bi d b@(expr.pi _ _ _ _)) := do
p ← mk_local' n bi d,
e ← mk_sigma (expr.instantiate_var b p),
tactic.mk_app ``psigma [d, bind_lambda e p]
| (expr.pi n bi d b) := pure d
| _ := failed
/-- Prove the goal `(Σ' (a:A) (b:B a), C a b) → T` (this is the function `f` in `finset_in.mk`)
using recursive `psigma.elim`, finishing with the constructor. The two arguments are
the type of the constructor, and the constructor term itself; as we recurse we add arguments
to the constructor application and destructure the pi type of the constructor. We return the number
of `psigma.elim` applications constructed, which is one less than the number of constructor
arguments. -/
meta def mk_sigma_elim : expr → expr → tactic ℕ
| (expr.pi n bi d b@(expr.pi _ _ _ _)) c := do
refine ``(@psigma.elim %%d _ _ _),
i ← intro_fresh n,
(+ 1) <$> mk_sigma_elim (expr.instantiate_var b i) (c i)
| (expr.pi n bi d b) c := do
i ← intro_fresh n,
exact (c i) $> 0
| _ c := failed
/-- Prove the goal `a, b |- f a = f b → g a = g b` where `f` is the function we constructed in
`mk_sigma_elim`, and `g` is some other term that gets built up and eventually closed by
reflexivity. Here `a` and `b` have sigma types so the proof approach is to case on `a` and `b`
until the goal reduces to `C_n a1 ... am = C_n b1 ... bm → ⟨a1, ..., am⟩ = ⟨b1, ..., bm⟩`, at which
point cases on the equality reduces the problem to reflexivity.
The arguments are the number `m` returned from `mk_sigma_elim`, and the hypotheses `a,b` that we
need to case on. -/
meta def mk_sigma_elim_inj : ℕ → expr → expr → tactic unit
| (m+1) x y := do
[(_, [x1, x2])] ← cases x,
[(_, [y1, y2])] ← cases y,
mk_sigma_elim_inj m x2 y2
| 0 x y := do intro1 >>= cases, reflexivity
/-- Prove the goal `a |- enum (f a) = n`, where `f` is the function constructed in `mk_sigma_elim`,
and `enum` is a function that reduces to `n` on the constructor `C_n`. Here we just have to case on
`a` `m` times, and then `reflexivity` finishes the proof. -/
meta def mk_sigma_elim_eq : ℕ → expr → tactic unit
| (n+1) x := do
[(_, [x1, x2])] ← cases x,
mk_sigma_elim_eq n x2
| 0 x := reflexivity
/-- Prove the goal `|- finset_above T enum k`, where `T` is the inductive type and `enum` is the
discriminant function. The arguments are `args`, the parameters to the inductive type (and all
constructors), `k`, the index of the current variant, and `cs`, the list of constructor names.
This uses `finset_above.cons` for basic variants and `finset_above.union` for variants with
arguments, using the auxiliary functions `mk_sigma`, `mk_sigma_elim`, `mk_sigma_elim_inj`,
`mk_sigma_elim_eq` to close subgoals. -/
meta def mk_finset (args : list expr) : ℕ → list name → tactic unit
| k (c::cs) := do
e ← mk_const c,
let e := e.mk_app args,
t ← infer_type e,
if is_pi t then do
to_expr ``(finset_above.union %%(reflect k)) tt ff >>=
(λ c, apply c {new_goals := new_goals.all}),
Γ ← mk_sigma t,
to_expr ``(finset_in.mk %%Γ) tt ff >>= (λ c, apply c {new_goals := new_goals.all}),
n ← mk_sigma_elim t e,
intro1 >>= (λ x, intro1 >>= mk_sigma_elim_inj n x),
intro1 >>= mk_sigma_elim_eq n,
mk_finset (k+1) cs
else do
c ← to_expr ``(finset_above.cons %%(reflect k) %%e) tt ff,
apply c {new_goals := new_goals.all}, reflexivity,
mk_finset (k+1) cs
| k [] := applyc ``finset_above.nil
/-- Prove the goal `|- Σ' (a:A) (b: B a), C a b` given a list of terms `a, b, c`. -/
meta def mk_sigma_mem : list expr → tactic unit
| [x] := exact x
| (x::xs) := constructor >> exact x >> mk_sigma_mem xs
| [] := failed
/-- This function is called to prove `a : T |- a ∈ S.1` where `S` is the `finset_above` constructed
by `mk_finset`, after the initial cases on `a : T`, producing a list of subgoals. For each case,
we have to navigate past all the variants that don't apply (which is what the `tac` input tactic
does), and then call either `finset_above.mem_cons_self` for trivial variants or
`finset_above.mem_union_left` and `finset_in.mem_mk` for nontrivial variants. Either way the proof
is quite simple. -/
meta def mk_finset_total : tactic unit → list (name × list expr) → tactic unit
| tac [] := done
| tac ((_, xs) :: gs) := do
tac,
b ← succeeds (applyc ``finset_above.mem_cons_self),
if b then
mk_finset_total (tac >> applyc ``finset_above.mem_cons_of_mem) gs
else do
applyc ``finset_above.mem_union_left,
applyc ``finset_in.mem_mk {new_goals := new_goals.all},
mk_sigma_mem xs,
reflexivity,
mk_finset_total (tac >> applyc ``finset_above.mem_union_right) gs
end derive_fintype
open tactic.derive_fintype
/-- Proves `|- fintype T` where `T` is a non-recursive inductive type with no indices,
where all arguments to all constructors are fintypes. -/
meta def mk_fintype_instance : tactic unit :=
do
intros,
`(fintype %%e) ← target >>= whnf,
(const I ls, args) ← pure (get_app_fn_args e),
env ← get_env,
let cs := env.constructors_of I,
guard (env.inductive_num_indices I = 0) <|>
fail "@[derive fintype]: inductive indices are not supported",
guard (¬ env.is_recursive I) <|>
fail ("@[derive fintype]: recursive inductive types are " ++
"not supported (they are also usually infinite)"),
applyc ``mk_fintype {new_goals := new_goals.all},
intro1 >>= cases >>= (λ gs,
gs.enum.mmap' $ λ ⟨i, _⟩, exact (reflect i)),
mk_finset args 0 cs,
intro1 >>= cases >>= mk_finset_total skip
/--
Tries to derive a `fintype` instance for inductives and structures.
For example:
```
@[derive fintype]
inductive foo (n m : ℕ)
| zero : foo
| one : bool → foo
| two : fin n → fin m → foo
```
Here, `@[derive fintype]` adds the instance `foo.fintype`. The underlying finset
definitionally unfolds to a list that enumerates the elements of the inductive in
lexicographic order.
If the structure/inductive has a type parameter `α`, then the generated instance will have an
argument `fintype α`, even if it is not used. (This is due to the implementation using
`instance_derive_handler`.)
-/
@[derive_handler] meta def fintype_instance : derive_handler :=
instance_derive_handler ``fintype mk_fintype_instance
end tactic
|
cb5da243cc425e95766746f99aab5dc276342296 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/bundle.lean | b0bf890736593598151bdd4bf8568a82e3a4c8bc | [
"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 | 3,088 | lean | /-
Copyright © 2021 Nicolò Cavalleri. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Nicolò Cavalleri
-/
import tactic.basic
import algebra.module.basic
/-!
# Bundle
Basic data structure to implement fiber bundles, vector bundles (maybe fibrations?), etc. This file
should contain all possible results that do not involve any topology.
We provide a type synonym of `Σ x, E x` as `bundle.total_space E`, to be able to endow it with
a topology which is not the disjoint union topology `sigma.topological_space`. In general, the
constructions of fiber bundles we will make will be of this form.
## References
- https://en.wikipedia.org/wiki/Bundle_(mathematics)
-/
namespace bundle
variables {B : Type*} (E : B → Type*)
/--
`total_space E` is the total space of the bundle `Σ x, E x`. This type synonym is used to avoid
conflicts with general sigma types.
-/
def total_space := Σ x, E x
instance [inhabited B] [inhabited (E default)] :
inhabited (total_space E) := ⟨⟨default, default⟩⟩
/-- `bundle.proj E` is the canonical projection `total_space E → B` on the base space. -/
@[simp, reducible] def proj : total_space E → B := sigma.fst
/-- Constructor for the total space of a `topological_fiber_bundle_core`. -/
@[simp, reducible] def total_space_mk (E : B → Type*) (b : B) (a : E b) :
bundle.total_space E := ⟨b, a⟩
instance {x : B} : has_coe_t (E x) (total_space E) := ⟨sigma.mk x⟩
@[simp] lemma coe_fst (x : B) (v : E x) : (v : total_space E).fst = x := rfl
lemma to_total_space_coe {x : B} (v : E x) : (v : total_space E) = ⟨x, v⟩ := rfl
-- notation for the direct sum of two bundles over the same base
notation E₁ `×ᵇ`:100 E₂ := λ x, E₁ x × E₂ x
/-- `bundle.trivial B F` is the trivial bundle over `B` of fiber `F`. -/
def trivial (B : Type*) (F : Type*) : B → Type* := function.const B F
instance {F : Type*} [inhabited F] {b : B} : inhabited (bundle.trivial B F b) := ⟨(default : F)⟩
/-- The trivial bundle, unlike other bundles, has a canonical projection on the fiber. -/
def trivial.proj_snd (B : Type*) (F : Type*) : (total_space (bundle.trivial B F)) → F := sigma.snd
section fiber_structures
variable [∀ x, add_comm_monoid (E x)]
@[simp] lemma coe_snd_map_apply (x : B) (v w : E x) :
(↑(v + w) : total_space E).snd = (v : total_space E).snd + (w : total_space E).snd := rfl
variables (R : Type*) [semiring R] [∀ x, module R (E x)]
@[simp] lemma coe_snd_map_smul (x : B) (r : R) (v : E x) :
(↑(r • v) : total_space E).snd = r • (v : total_space E).snd := rfl
end fiber_structures
section trivial_instances
local attribute [reducible] bundle.trivial
variables {F : Type*} {R : Type*} [semiring R] (b : B)
instance [add_comm_monoid F] : add_comm_monoid (bundle.trivial B F b) := ‹add_comm_monoid F›
instance [add_comm_group F] : add_comm_group (bundle.trivial B F b) := ‹add_comm_group F›
instance [add_comm_monoid F] [module R F] : module R (bundle.trivial B F b) := ‹module R F›
end trivial_instances
end bundle
|
0e428d95e4ddfc883bb000bd6c9fdd97d285c80c | 66a6486e19b71391cc438afee5f081a4257564ec | /cohomology/basic.hlean | ec6bdbd0f344687271b1ffdb6ccd65b323d4e0ac | [
"Apache-2.0"
] | permissive | spiceghello/Spectral | c8ccd1e32d4b6a9132ccee20fcba44b477cd0331 | 20023aa3de27c22ab9f9b4a177f5a1efdec2b19f | refs/heads/master | 1,611,263,374,078 | 1,523,349,717,000 | 1,523,349,717,000 | 92,312,239 | 0 | 0 | null | 1,495,642,470,000 | 1,495,642,470,000 | null | UTF-8 | Lean | false | false | 20,263 | hlean | /-
Copyright (c) 2016 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Ulrik Buchholtz
Reduced cohomology of spectra and cohomology theories
-/
import ..spectrum.basic ..algebra.arrow_group ..homotopy.fwedge ..choice ..homotopy.pushout ..algebra.product_group
open eq spectrum int trunc pointed EM group algebra circle sphere nat EM.ops equiv susp is_trunc
function fwedge cofiber bool lift sigma is_equiv choice pushout algebra unit pi is_conn
namespace cohomology
/- The cohomology of X with coefficients in Y is
trunc 0 (A →* Ω[2] (Y (n+2)))
In the file arrow_group (in algebra) we construct the group structure on this type.
Equivalently, it's
πₛ[n] (sp_cotensor X Y)
-/
definition cohomology (X : Type*) (Y : spectrum) (n : ℤ) : AbGroup :=
AbGroup_trunc_pmap X (Y (n+2))
definition ordinary_cohomology [reducible] (X : Type*) (G : AbGroup) (n : ℤ) : AbGroup :=
cohomology X (EM_spectrum G) n
definition ordinary_cohomology_Z [reducible] (X : Type*) (n : ℤ) : AbGroup :=
ordinary_cohomology X agℤ n
definition unreduced_cohomology (X : Type) (Y : spectrum) (n : ℤ) : AbGroup :=
cohomology X₊ Y n
definition unreduced_ordinary_cohomology [reducible] (X : Type) (G : AbGroup) (n : ℤ) : AbGroup :=
unreduced_cohomology X (EM_spectrum G) n
definition unreduced_ordinary_cohomology_Z [reducible] (X : Type) (n : ℤ) : AbGroup :=
unreduced_ordinary_cohomology X agℤ n
definition parametrized_cohomology {X : Type*} (Y : X → spectrum) (n : ℤ) : AbGroup :=
AbGroup_trunc_ppi (λx, Y x (n+2))
definition ordinary_parametrized_cohomology [reducible] {X : Type*} (G : X → AbGroup) (n : ℤ) :
AbGroup :=
parametrized_cohomology (λx, EM_spectrum (G x)) n
definition unreduced_parametrized_cohomology {X : Type} (Y : X → spectrum) (n : ℤ) : AbGroup :=
parametrized_cohomology (add_point_spectrum Y) n
definition unreduced_ordinary_parametrized_cohomology [reducible] {X : Type} (G : X → AbGroup)
(n : ℤ) : AbGroup :=
unreduced_parametrized_cohomology (λx, EM_spectrum (G x)) n
notation `H^` n `[`:0 X:0 `, ` Y:0 `]`:0 := cohomology X Y n
notation `oH^` n `[`:0 X:0 `, ` G:0 `]`:0 := ordinary_cohomology X G n
notation `H^` n `[`:0 X:0 `]`:0 := ordinary_cohomology_Z X n
notation `uH^` n `[`:0 X:0 `, ` Y:0 `]`:0 := unreduced_cohomology X Y n
notation `uoH^` n `[`:0 X:0 `, ` G:0 `]`:0 := unreduced_ordinary_cohomology X G n
notation `uH^` n `[`:0 X:0 `]`:0 := unreduced_ordinary_cohomology_Z X n
notation `pH^` n `[`:0 binders `, ` r:(scoped Y, parametrized_cohomology Y n) `]`:0 := r
notation `opH^` n `[`:0 binders `, ` r:(scoped G, ordinary_parametrized_cohomology G n) `]`:0 := r
notation `upH^` n `[`:0 binders `, ` r:(scoped Y, unreduced_parametrized_cohomology Y n) `]`:0 := r
notation `uopH^` n `[`:0 binders `, ` r:(scoped G, unreduced_ordinary_parametrized_cohomology G n) `]`:0 := r
/- an alternate definition of cohomology -/
definition parametrized_cohomology_isomorphism_shomotopy_group_spi {X : Type*} (Y : X → spectrum)
{n m : ℤ} (p : -m = n) : pH^n[(x : X), Y x] ≃g πₛ[m] (spi X Y) :=
begin
apply isomorphism.trans (trunc_ppi_loop_isomorphism (λx, Ω (Y x (n + 2))))⁻¹ᵍ,
apply homotopy_group_isomorphism_of_pequiv 0, esimp,
have q : sub 2 m = n + 2,
from (int.add_comm (of_nat 2) (-m) ⬝ ap (λk, k + of_nat 2) p),
rewrite q, symmetry, apply loop_pppi_pequiv
end
definition unreduced_parametrized_cohomology_isomorphism_shomotopy_group_supi {X : Type}
(Y : X → spectrum) {n m : ℤ} (p : -m = n) : upH^n[(x : X), Y x] ≃g πₛ[m] (supi X Y) :=
begin
refine parametrized_cohomology_isomorphism_shomotopy_group_spi (add_point_spectrum Y) p ⬝g _,
apply shomotopy_group_isomorphism_of_pequiv, intro k,
apply pppi_add_point_over
end
definition cohomology_isomorphism_shomotopy_group_sp_cotensor (X : Type*) (Y : spectrum) {n m : ℤ}
(p : -m = n) : H^n[X, Y] ≃g πₛ[m] (sp_cotensor X Y) :=
begin
refine !trunc_ppi_isomorphic_pmap⁻¹ᵍ ⬝g _,
refine parametrized_cohomology_isomorphism_shomotopy_group_spi (λx, Y) p ⬝g _,
apply shomotopy_group_isomorphism_of_pequiv, intro k,
apply pppi_pequiv_ppmap
end
definition unreduced_cohomology_isomorphism_shomotopy_group_sp_ucotensor (X : Type) (Y : spectrum)
{n m : ℤ} (p : -m = n) : uH^n[X, Y] ≃g πₛ[m] (sp_ucotensor X Y) :=
begin
refine cohomology_isomorphism_shomotopy_group_sp_cotensor X₊ Y p ⬝g _,
apply shomotopy_group_isomorphism_of_pequiv, intro k, apply ppmap_add_point
end
/- functoriality -/
definition cohomology_functor [constructor] {X X' : Type*} (f : X' →* X) (Y : spectrum)
(n : ℤ) : cohomology X Y n →g cohomology X' Y n :=
Group_trunc_pmap_homomorphism f
definition cohomology_functor_pid (X : Type*) (Y : spectrum) (n : ℤ) (f : H^n[X, Y]) :
cohomology_functor (pid X) Y n f = f :=
!Group_trunc_pmap_pid
definition cohomology_functor_pcompose {X X' X'' : Type*} (f : X' →* X) (g : X'' →* X')
(Y : spectrum) (n : ℤ) (h : H^n[X, Y]) : cohomology_functor (f ∘* g) Y n h =
cohomology_functor g Y n (cohomology_functor f Y n h) :=
!Group_trunc_pmap_pcompose
definition cohomology_functor_phomotopy {X X' : Type*} {f g : X' →* X} (p : f ~* g)
(Y : spectrum) (n : ℤ) : cohomology_functor f Y n ~ cohomology_functor g Y n :=
Group_trunc_pmap_phomotopy p
definition cohomology_functor_phomotopy_refl {X X' : Type*} (f : X' →* X) (Y : spectrum) (n : ℤ)
(x : H^n[X, Y]) : cohomology_functor_phomotopy (phomotopy.refl f) Y n x = idp :=
Group_trunc_pmap_phomotopy_refl f x
definition cohomology_functor_pconst {X X' : Type*} (Y : spectrum) (n : ℤ) (f : H^n[X, Y]) :
cohomology_functor (pconst X' X) Y n f = 1 :=
!Group_trunc_pmap_pconst
definition cohomology_isomorphism {X X' : Type*} (f : X' ≃* X) (Y : spectrum) (n : ℤ) :
H^n[X, Y] ≃g H^n[X', Y] :=
Group_trunc_pmap_isomorphism f
definition cohomology_isomorphism_refl (X : Type*) (Y : spectrum) (n : ℤ) (x : H^n[X,Y]) :
cohomology_isomorphism (pequiv.refl X) Y n x = x :=
!Group_trunc_pmap_isomorphism_refl
definition cohomology_isomorphism_right (X : Type*) {Y Y' : spectrum} (e : Πn, Y n ≃* Y' n)
(n : ℤ) : H^n[X, Y] ≃g H^n[X, Y'] :=
cohomology_isomorphism_shomotopy_group_sp_cotensor X Y !neg_neg ⬝g
shomotopy_group_isomorphism_of_pequiv (-n) (λk, pequiv_ppcompose_left (e k)) ⬝g
(cohomology_isomorphism_shomotopy_group_sp_cotensor X Y' !neg_neg)⁻¹ᵍ
definition unreduced_cohomology_isomorphism {X X' : Type} (f : X' ≃ X) (Y : spectrum) (n : ℤ) :
uH^n[X, Y] ≃g uH^n[X', Y] :=
cohomology_isomorphism (add_point_pequiv f) Y n
definition unreduced_cohomology_isomorphism_right (X : Type) {Y Y' : spectrum} (e : Πn, Y n ≃* Y' n)
(n : ℤ) : uH^n[X, Y] ≃g uH^n[X, Y'] :=
cohomology_isomorphism_right X₊ e n
definition unreduced_ordinary_cohomology_isomorphism {X X' : Type} (f : X' ≃ X) (G : AbGroup)
(n : ℤ) : uoH^n[X, G] ≃g uoH^n[X', G] :=
unreduced_cohomology_isomorphism f (EM_spectrum G) n
definition unreduced_ordinary_cohomology_isomorphism_right (X : Type) {G G' : AbGroup}
(e : G ≃g G') (n : ℤ) : uoH^n[X, G] ≃g uoH^n[X, G'] :=
unreduced_cohomology_isomorphism_right X (EM_spectrum_pequiv e) n
definition parametrized_cohomology_isomorphism_right {X : Type*} {Y Y' : X → spectrum}
(e : Πx n, Y x n ≃* Y' x n) (n : ℤ) : pH^n[(x : X), Y x] ≃g pH^n[(x : X), Y' x] :=
parametrized_cohomology_isomorphism_shomotopy_group_spi Y !neg_neg ⬝g
shomotopy_group_isomorphism_of_pequiv (-n) (λk, ppi_pequiv_right (λx, e x k)) ⬝g
(parametrized_cohomology_isomorphism_shomotopy_group_spi Y' !neg_neg)⁻¹ᵍ
definition unreduced_parametrized_cohomology_isomorphism_right {X : Type} {Y Y' : X → spectrum}
(e : Πx n, Y x n ≃* Y' x n) (n : ℤ) : upH^n[(x : X), Y x] ≃g upH^n[(x : X), Y' x] :=
parametrized_cohomology_isomorphism_right (λx' k, add_point_over_pequiv (λx, e x k) x') n
definition unreduced_ordinary_parametrized_cohomology_isomorphism_right {X : Type}
{G G' : X → AbGroup} (e : Πx, G x ≃g G' x) (n : ℤ) :
uopH^n[(x : X), G x] ≃g uopH^n[(x : X), G' x] :=
unreduced_parametrized_cohomology_isomorphism_right (λx, EM_spectrum_pequiv (e x)) n
definition ordinary_cohomology_isomorphism_right (X : Type*) {G G' : AbGroup} (e : G ≃g G')
(n : ℤ) : oH^n[X, G] ≃g oH^n[X, G'] :=
cohomology_isomorphism_right X (EM_spectrum_pequiv e) n
definition ordinary_parametrized_cohomology_isomorphism_right {X : Type*} {G G' : X → AbGroup}
(e : Πx, G x ≃g G' x) (n : ℤ) : opH^n[(x : X), G x] ≃g opH^n[(x : X), G' x] :=
parametrized_cohomology_isomorphism_right (λx, EM_spectrum_pequiv (e x)) n
definition uopH_isomorphism_opH {X : Type} (G : X → AbGroup) (n : ℤ) :
uopH^n[(x : X), G x] ≃g opH^n[(x : X₊), add_point_AbGroup G x] :=
parametrized_cohomology_isomorphism_right
begin
intro x n, induction x with x,
{ symmetry, apply EM_spectrum_trivial, },
{ reflexivity }
end
n
definition pH_isomorphism_H {X : Type*} (Y : spectrum) (n : ℤ) : pH^n[(x : X), Y] ≃g H^n[X, Y] :=
by reflexivity
definition opH_isomorphism_oH {X : Type*} (G : AbGroup) (n : ℤ) : opH^n[(x : X), G] ≃g oH^n[X, G] :=
by reflexivity
definition upH_isomorphism_uH {X : Type} (Y : spectrum) (n : ℤ) : upH^n[(x : X), Y] ≃g uH^n[X, Y] :=
unreduced_parametrized_cohomology_isomorphism_shomotopy_group_supi _ !neg_neg ⬝g
(unreduced_cohomology_isomorphism_shomotopy_group_sp_ucotensor _ _ !neg_neg)⁻¹ᵍ
definition uopH_isomorphism_uoH {X : Type} (G : AbGroup) (n : ℤ) :
uopH^n[(x : X), G] ≃g uoH^n[X, G] :=
!upH_isomorphism_uH
definition uopH_isomorphism_uoH_of_is_conn {X : Type*} (G : X → AbGroup) (n : ℤ) (H : is_conn 1 X) :
uopH^n[(x : X), G x] ≃g uoH^n[X, G pt] :=
begin
refine _ ⬝g !uopH_isomorphism_uoH,
apply unreduced_ordinary_parametrized_cohomology_isomorphism_right,
refine is_conn.elim 0 _ _, reflexivity
end
definition cohomology_change_int (X : Type*) (Y : spectrum) {n n' : ℤ} (p : n = n') :
H^n[X, Y] ≃g H^n'[X, Y] :=
isomorphism_of_eq (ap (λn, H^n[X, Y]) p)
definition parametrized_cohomology_change_int (X : Type*) (Y : X → spectrum) {n n' : ℤ}
(p : n = n') : pH^n[(x : X), Y x] ≃g pH^n'[(x : X), Y x] :=
isomorphism_of_eq (ap (λn, pH^n[(x : X), Y x]) p)
/- suspension axiom -/
definition cohomology_susp_2 (Y : spectrum) (n : ℤ) :
Ω (Ω[2] (Y ((n+1)+2))) ≃* Ω[2] (Y (n+2)) :=
begin
apply loopn_pequiv_loopn 2,
exact loop_pequiv_loop (pequiv_of_eq (ap Y (add.right_comm n 1 2))) ⬝e* !equiv_glue⁻¹ᵉ*
end
definition cohomology_susp_1 (X : Type*) (Y : spectrum) (n : ℤ) :
susp X →* Ω (Ω (Y (n + 1 + 2))) ≃ X →* Ω (Ω (Y (n+2))) :=
calc
susp X →* Ω[2] (Y (n + 1 + 2)) ≃ X →* Ω (Ω[2] (Y (n + 1 + 2))) : susp_adjoint_loop_unpointed
... ≃ X →* Ω[2] (Y (n+2)) : equiv_of_pequiv (pequiv_ppcompose_left
(cohomology_susp_2 Y n))
definition cohomology_susp_1_pmap_mul {X : Type*} {Y : spectrum} {n : ℤ}
(f g : susp X →* Ω (Ω (Y (n + 1 + 2)))) : cohomology_susp_1 X Y n (pmap_mul f g) ~*
pmap_mul (cohomology_susp_1 X Y n f) (cohomology_susp_1 X Y n g) :=
begin
unfold [cohomology_susp_1],
refine pwhisker_left _ !loop_susp_intro_pmap_mul ⬝* _,
apply pcompose_pmap_mul
end
definition cohomology_susp_equiv (X : Type*) (Y : spectrum) (n : ℤ) :
H^n+1[susp X, Y] ≃ H^n[X, Y] :=
trunc_equiv_trunc _ (cohomology_susp_1 X Y n)
definition cohomology_susp (X : Type*) (Y : spectrum) (n : ℤ) :
H^n+1[susp X, Y] ≃g H^n[X, Y] :=
isomorphism_of_equiv (cohomology_susp_equiv X Y n)
begin
intro f₁ f₂, induction f₁ with f₁, induction f₂ with f₂,
apply ap tr, apply eq_of_phomotopy, exact cohomology_susp_1_pmap_mul f₁ f₂
end
definition cohomology_susp_natural {X X' : Type*} (f : X →* X') (Y : spectrum) (n : ℤ) :
cohomology_susp X Y n ∘ cohomology_functor (susp_functor f) Y (n+1) ~
cohomology_functor f Y n ∘ cohomology_susp X' Y n :=
begin
refine (trunc_functor_compose _ _ _)⁻¹ʰᵗʸ ⬝hty _ ⬝hty trunc_functor_compose _ _ _,
apply trunc_functor_homotopy, intro g,
apply eq_of_phomotopy, refine _ ⬝* !passoc⁻¹*, apply pwhisker_left,
apply loop_susp_intro_natural
end
/- exactness -/
definition cohomology_exact {X X' : Type*} (f : X →* X') (Y : spectrum) (n : ℤ) :
is_exact_g (cohomology_functor (pcod f) Y n) (cohomology_functor f Y n) :=
is_exact_trunc_functor (cofiber_exact f)
/- additivity -/
definition additive_hom [constructor] {I : Type} (X : I → Type*) (Y : spectrum) (n : ℤ) :
H^n[⋁X, Y] →g Πᵍ i, H^n[X i, Y] :=
Group_pi_intro (λi, cohomology_functor (pinl i) Y n)
definition additive_equiv.{u} {I : Type.{u}} (H : has_choice 0 I) (X : I → Type*) (Y : spectrum)
(n : ℤ) : H^n[⋁X, Y] ≃ Πᵍ i, H^n[X i, Y] :=
trunc_fwedge_pmap_equiv H X (Ω[2] (Y (n+2)))
definition spectrum_additive {I : Type} (H : has_choice 0 I) (X : I → Type*) (Y : spectrum)
(n : ℤ) : is_equiv (additive_hom X Y n) :=
is_equiv_of_equiv_of_homotopy (additive_equiv H X Y n) begin intro f, induction f, reflexivity end
/- dimension axiom for ordinary cohomology -/
open is_conn trunc_index
theorem EM_dimension' (G : AbGroup) (n : ℤ) (H : n ≠ 0) :
is_contr (oH^n[pbool, G]) :=
begin
apply is_conn_equiv_closed 0 !pmap_pbool_equiv⁻¹ᵉ,
apply is_conn_equiv_closed 0 !equiv_glue2⁻¹ᵉ,
cases n with n n,
{ cases n with n,
{ exfalso, apply H, reflexivity },
{ apply is_conn_of_le, apply zero_le_of_nat n, exact is_conn_EMadd1 G n, }},
{ apply is_trunc_trunc_of_is_trunc, apply @is_contr_loop_of_is_trunc (n+1) (K G 0),
apply is_trunc_of_le _ (zero_le_of_nat n) }
end
theorem EM_dimension (G : AbGroup) (n : ℤ) (H : n ≠ 0) :
is_contr (ordinary_cohomology (plift pbool) G n) :=
@(is_trunc_equiv_closed_rev -2
(equiv_of_isomorphism (cohomology_isomorphism (pequiv_plift pbool) _ _)))
(EM_dimension' G n H)
open group algebra
theorem ordinary_cohomology_pbool (G : AbGroup) : oH^0[pbool, G] ≃g G :=
sorry
--isomorphism_of_equiv (trunc_equiv_trunc 0 (ppmap_pbool_pequiv _ ⬝e _) ⬝e !trunc_equiv) sorry
theorem is_contr_cohomology_of_is_contr_spectrum (n : ℤ) (X : Type*) (Y : spectrum) (H : is_contr (Y n)) :
is_contr (H^n[X, Y]) :=
begin
apply is_trunc_trunc_of_is_trunc,
apply is_trunc_pmap,
apply is_trunc_equiv_closed_rev,
exact loop_pequiv_loop (loop_pequiv_loop (pequiv_ap Y (add.assoc n 1 1)⁻¹) ⬝e* (equiv_glue Y (n+1))⁻¹ᵉ*) ⬝e
(equiv_glue Y n)⁻¹ᵉ*
end
theorem is_contr_ordinary_cohomology (n : ℤ) (X : Type*) (G : AbGroup) (H : is_contr G) :
is_contr (oH^n[X, G]) :=
begin
apply is_contr_cohomology_of_is_contr_spectrum,
exact is_contr_EM_spectrum _ _ H
end
theorem is_contr_unreduced_ordinary_cohomology (n : ℤ) (X : Type) (G : AbGroup) (H : is_contr G) :
is_contr (uoH^n[X, G]) :=
is_contr_ordinary_cohomology _ _ _ H
theorem is_contr_ordinary_cohomology_of_neg {n : ℤ} (X : Type*) (G : AbGroup) (H : n < 0) :
is_contr (oH^n[X, G]) :=
begin
apply is_contr_cohomology_of_is_contr_spectrum,
cases n with n n, contradiction,
apply is_contr_EM_spectrum_neg
end
/- cohomology theory -/
structure cohomology_theory.{u} : Type.{u+1} :=
(HH : ℤ → pType.{u} → AbGroup.{u})
(Hiso : Π(n : ℤ) {X Y : Type*} (f : X ≃* Y), HH n Y ≃g HH n X)
(Hiso_refl : Π(n : ℤ) (X : Type*) (x : HH n X), Hiso n pequiv.rfl x = x)
(Hh : Π(n : ℤ) {X Y : Type*} (f : X →* Y), HH n Y →g HH n X)
(Hhomotopy : Π(n : ℤ) {X Y : Type*} {f g : X →* Y} (p : f ~* g), Hh n f ~ Hh n g)
(Hhomotopy_refl : Π(n : ℤ) {X Y : Type*} (f : X →* Y) (x : HH n Y),
Hhomotopy n (phomotopy.refl f) x = idp)
(Hid : Π(n : ℤ) {X : Type*} (x : HH n X), Hh n (pid X) x = x)
(Hcompose : Π(n : ℤ) {X Y Z : Type*} (g : Y →* Z) (f : X →* Y) (z : HH n Z),
Hh n (g ∘* f) z = Hh n f (Hh n g z))
(Hsusp : Π(n : ℤ) (X : Type*), HH (succ n) (susp X) ≃g HH n X)
(Hsusp_natural : Π(n : ℤ) {X Y : Type*} (f : X →* Y),
Hsusp n X ∘ Hh (succ n) (susp_functor f) ~ Hh n f ∘ Hsusp n Y)
(Hexact : Π(n : ℤ) {X Y : Type*} (f : X →* Y), is_exact_g (Hh n (pcod f)) (Hh n f))
(Hadditive : Π(n : ℤ) {I : Type.{u}} (X : I → Type*), has_choice 0 I →
is_equiv (Group_pi_intro (λi, Hh n (pinl i)) : HH n (⋁ X) → Πᵍ i, HH n (X i)))
structure ordinary_cohomology_theory.{u} extends cohomology_theory.{u} : Type.{u+1} :=
(Hdimension : Π(n : ℤ), n ≠ 0 → is_contr (HH n (plift pbool)))
attribute cohomology_theory.HH [coercion]
postfix `^→`:90 := cohomology_theory.Hh
open cohomology_theory
definition Hequiv (H : cohomology_theory) (n : ℤ) {X Y : Type*} (f : X ≃* Y) : H n Y ≃ H n X :=
equiv_of_isomorphism (Hiso H n f)
definition Hsusp_neg (H : cohomology_theory) (n : ℤ) (X : Type*) : H n (susp X) ≃g H (pred n) X :=
isomorphism_of_eq (ap (λn, H n _) proof (sub_add_cancel n 1)⁻¹ qed) ⬝g cohomology_theory.Hsusp H (pred n) X
definition Hsusp_neg_natural (H : cohomology_theory) (n : ℤ) {X Y : Type*} (f : X →* Y) :
Hsusp_neg H n X ∘ H ^→ n (susp_functor f) ~ H ^→ (pred n) f ∘ Hsusp_neg H n Y :=
sorry
definition Hsusp_inv_natural (H : cohomology_theory) (n : ℤ) {X Y : Type*} (f : X →* Y) :
H ^→ (succ n) (susp_functor f) ∘g (Hsusp H n Y)⁻¹ᵍ ~ (Hsusp H n X)⁻¹ᵍ ∘ H ^→ n f :=
sorry
definition Hsusp_neg_inv_natural (H : cohomology_theory) (n : ℤ) {X Y : Type*} (f : X →* Y) :
H ^→ n (susp_functor f) ∘g (Hsusp_neg H n Y)⁻¹ᵍ ~ (Hsusp_neg H n X)⁻¹ᵍ ∘ H ^→ (pred n) f :=
sorry
definition Hadditive_equiv (H : cohomology_theory) (n : ℤ) {I : Type} (X : I → Type*) (H2 : has_choice 0 I)
: H n (⋁ X) ≃g Πᵍ i, H n (X i) :=
isomorphism.mk _ (Hadditive H n X H2)
definition Hlift_empty.{u} (H : cohomology_theory.{u}) (n : ℤ) :
is_contr (H n (plift punit)) :=
let P : lift empty → Type* := lift.rec empty.elim in
let x := Hadditive H n P _ in
begin
note z := equiv.mk _ x,
refine @(is_trunc_equiv_closed_rev -2 (_ ⬝e z ⬝e _)) !is_contr_unit,
refine Hequiv H n (pequiv_punit_of_is_contr _ _ ⬝e* !pequiv_plift),
apply is_contr_fwedge_of_neg, intro y, induction y with y, exact y,
apply equiv_unit_of_is_contr, apply is_contr_pi_of_neg, intro y, induction y with y, exact y
end
definition Hempty (H : cohomology_theory.{0}) (n : ℤ) :
is_contr (H n punit) :=
@(is_trunc_equiv_closed _ (Hequiv H n !pequiv_plift)) (Hlift_empty H n)
definition Hconst (H : cohomology_theory) (n : ℤ) {X Y : Type*} (y : H n Y) : H ^→ n (pconst X Y) y = 1 :=
begin
refine Hhomotopy H n (pconst_pcompose (pconst X (plift punit)))⁻¹* y ⬝ _,
refine Hcompose H n _ _ y ⬝ _,
refine ap (H ^→ n _) (@eq_of_is_contr _ (Hlift_empty H n) _ 1) ⬝ _,
apply respect_one
end
-- definition Hwedge (H : cohomology_theory) (n : ℤ) (A B : Type*) : H n (A ∨ B) ≃g H n A ×ag H n B :=
-- begin
-- refine Hiso H n (wedge_pequiv_fwedge A B)⁻¹ᵉ* ⬝g _,
-- refine Hadditive_equiv H n _ _ ⬝g _
-- end
definition cohomology_theory_spectrum.{u} [constructor] (Y : spectrum.{u}) : cohomology_theory.{u} :=
cohomology_theory.mk
(λn A, H^n[A, Y])
(λn A B f, cohomology_isomorphism f Y n)
(λn A, cohomology_isomorphism_refl A Y n)
(λn A B f, cohomology_functor f Y n)
(λn A B f g p, cohomology_functor_phomotopy p Y n)
(λn A B f x, cohomology_functor_phomotopy_refl f Y n x)
(λn A x, cohomology_functor_pid A Y n x)
(λn A B C g f x, cohomology_functor_pcompose g f Y n x)
(λn A, cohomology_susp A Y n)
(λn A B f, cohomology_susp_natural f Y n)
(λn A B f, cohomology_exact f Y n)
(λn I A H, spectrum_additive H A Y n)
-- set_option pp.universes true
-- set_option pp.abbreviations false
-- print cohomology_theory_spectrum
-- print EM_spectrum
-- print has_choice_lift
-- print equiv_lift
-- print has_choice_equiv_closed
definition ordinary_cohomology_theory_EM [constructor] (G : AbGroup) : ordinary_cohomology_theory :=
⦃ordinary_cohomology_theory, cohomology_theory_spectrum (EM_spectrum G), Hdimension := EM_dimension G ⦄
end cohomology
|
74b3d2dc26a593807dab6acc9613c3999a6d78fe | 58a8dc607943b813203ac4154540f27c779e93c3 | /src/lempel-ziv.lean | 8cf0bc7e437f85a101490e8b7e77f641d91ef07f | [] | no_license | dupuisf/lean4-experimentation | 14a07693730531d995f8226142621beb6d771d53 | f623dc7c427cd8a235a3c9c11e82f3b038521e86 | refs/heads/master | 1,678,500,967,656 | 1,614,653,652,000 | 1,614,653,652,000 | 327,968,123 | 4 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 3,314 | lean | /-
Copyright (c) 2021 Frédéric Dupuis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Frédéric Dupuis
-/
/-
A toy Lempel-Ziv compressor and decompressor.
Only works for `List (Fin 2)`
-/
inductive LZBlock (α : Type u) [BEq α] where
| reg : Nat → List α → α → LZBlock α -- regular block
| last : Nat → List α → LZBlock α -- last block (so no final character)
open LZBlock
variables {α : Type u} [BEq α]
namespace LZBlock
def getStr : LZBlock α → List α
| reg n s c => s ++ [c]
| last n s => s
def getId : LZBlock α → Nat
| reg n s c => n
| last n s => n
def getPrefix : LZBlock α → List α
| reg n s c => s
| last n s => s
def mkEmpty : LZBlock α := last 0 []
instance [ToString α] : ToString (LZBlock α) where
toString b := match b with
| reg n s c => "R" ++ toString s ++ toString c
| last n s => "L" ++ toString s
end LZBlock
class HasBitstringRepr (α : Type u) where
toBitstring : α → List (Fin 2)
def toBitstr [HasBitstringRepr α] (x : α) : List (Fin 2) :=
HasBitstringRepr.toBitstring x
def toBitstrPr [HasBitstringRepr α] (x : α) (pr : Nat) : List (Fin 2) :=
let xs := toBitstr x
let s := List.replicate pr (0 : Fin 2) ++ xs
List.drop (s.length - pr) s
partial def natToBitstring : Nat → List (Fin 2)
| 0 => []
| 1 => [1]
| Nat.succ (Nat.succ n) => let n' := n+2
if n' % 2 = 1 then (natToBitstring (n'/2)) ++ [1] else (natToBitstring (n'/2)) ++ [0]
instance : HasBitstringRepr Bool where
toBitstring := fun n => if n then [1] else [0]
instance : HasBitstringRepr Nat := ⟨natToBitstring⟩
instance {n : Nat} : HasBitstringRepr (Fin n) := ⟨natToBitstring ∘ Coe.coe⟩
instance : HasBitstringRepr Char := ⟨natToBitstring ∘ Char.toNat⟩
/-- Segment the input string into LZ blocks -/
def toBlocks (curList : List (LZBlock α)) (curBlock : List α) : List α → List (LZBlock α)
| [] => curList ++ [last curList.length curBlock]
| (x :: xs) => let nextBlk := curBlock ++ [x]
match curList.find? (fun blk => (blk.getStr == nextBlk)) with
| none => toBlocks (curList ++ [reg curList.length curBlock x]) [] xs
| some b => toBlocks curList nextBlk xs
def getPrefixId (lst : List (LZBlock α)) (b : LZBlock α) : Nat :=
let lstn := List.enum lst
match lstn.find? (fun blk => blk.2.getStr == b.getPrefix) with
| none => panic! "Help!"
| some blk => blk.1
def compressBlocks [HasBitstringRepr α] (s : List α) : List (List (Fin 2)) :=
let blks := toBlocks [mkEmpty] [] s
let ids := List.map (getPrefixId blks) blks
let ids_enum := List.enum ids
let f : LZBlock α → Nat × Nat → List (Fin 2)
| last _ str, (k₁, k₂) => toBitstrPr k₂ (toBitstr (k₁ - 1)).length
| reg _ str c, (k₁, k₂) => (toBitstrPr k₂ (toBitstr (k₁ - 1)).length) ++ (toBitstrPr c 1)
List.map₂ f blks ids_enum
def main : IO Unit :=
do let str := [0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1]
let strLZ := toBlocks [mkEmpty] [] str
IO.print strLZ
IO.print "\n"
IO.print $ List.map (getPrefixId strLZ) $ strLZ
IO.print "\n"
IO.print $ compressBlocks str
IO.print "\n"
IO.print $ toBitstr 0
#eval main |
8452f54745546c0aa1b33c1ea6fa89b913d006bf | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/set_theory/cofinality.lean | 839dbd61e655bdfd8716a0d1bcb425adab71c00f | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 17,376 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
Cofinality on ordinals, regular cardinals.
-/
import set_theory.ordinal
noncomputable theory
open function cardinal
local attribute [instance] classical.prop_decidable
universes u v w
variables {α : Type*} {r : α → α → Prop}
/-- Cofinality of a reflexive order `≼`. This is the smallest cardinality
of a subset `S : set α` such that `∀ a, ∃ b ∈ S, a ≼ b`. -/
def order.cof (r : α → α → Prop) [is_refl α r] : cardinal :=
@cardinal.min {S : set α // ∀ a, ∃ b ∈ S, r a b}
⟨⟨set.univ, λ a, ⟨a, ⟨⟩, refl _⟩⟩⟩
(λ S, mk S)
theorem order_iso.cof.aux {α : Type u} {β : Type v} {r s}
[is_refl α r] [is_refl β s] (f : r ≃o s) :
cardinal.lift.{u (max u v)} (order.cof r) ≤
cardinal.lift.{v (max u v)} (order.cof s) :=
begin
rw [order.cof, order.cof, lift_min, lift_min, cardinal.le_min],
intro S, cases S with S H, simp [(∘)],
refine le_trans (min_le _ _) _,
{ exact ⟨f ⁻¹' S, λ a,
let ⟨b, bS, h⟩ := H (f a) in ⟨f.symm b, by simp [bS, f.ord', h,
-coe_fn_coe_base, -coe_fn_coe_trans, principal_seg.coe_coe_fn', initial_seg.coe_coe_fn]⟩⟩ },
{ exact lift_mk_le.{u v (max u v)}.2
⟨⟨λ ⟨x, h⟩, ⟨f x, h⟩, λ ⟨x, h₁⟩ ⟨y, h₂⟩ h₃,
by congr; injection h₃ with h'; exact f.to_equiv.injective h'⟩⟩ }
end
theorem order_iso.cof {α : Type u} {β : Type v} {r s}
[is_refl α r] [is_refl β s] (f : r ≃o s) :
cardinal.lift.{u (max u v)} (order.cof r) =
cardinal.lift.{v (max u v)} (order.cof s) :=
le_antisymm (order_iso.cof.aux f) (order_iso.cof.aux f.symm)
namespace ordinal
/-- Cofinality of an ordinal. This is the smallest cardinal of a
subset `S` of the ordinal which is unbounded, in the sense
`∀ a, ∃ b ∈ S, ¬(b > a)`. It is defined for all ordinals, but
`cof 0 = 0` and `cof (succ o) = 1`, so it is only really
interesting on limit ordinals (when it is an infinite cardinal). -/
def cof (o : ordinal.{u}) : cardinal.{u} :=
quot.lift_on o (λ ⟨α, r, _⟩,
@order.cof α (λ x y, ¬ r y x) ⟨λ a, by resetI; apply irrefl⟩) $
λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨⟨f, hf⟩⟩, begin
show @order.cof α (λ x y, ¬ r y x) ⟨_⟩ = @order.cof β (λ x y, ¬ s y x) ⟨_⟩,
refine cardinal.lift_inj.1 (@order_iso.cof _ _ _ _ ⟨_⟩ ⟨_⟩ _),
exact ⟨f, λ a b, not_congr hf⟩,
end
theorem le_cof_type [is_well_order α r] {c} : c ≤ cof (type r) ↔
∀ S : set α, (∀ a, ∃ b ∈ S, ¬ r b a) → c ≤ mk S :=
by dsimp [cof, order.cof, type, quotient.mk, quot.lift_on];
rw [cardinal.le_min, subtype.forall]; refl
theorem cof_type_le [is_well_order α r] (S : set α) (h : ∀ a, ∃ b ∈ S, ¬ r b a) :
cof (type r) ≤ mk S :=
le_cof_type.1 (le_refl _) S h
theorem lt_cof_type [is_well_order α r] (S : set α) (hl : mk S < cof (type r)) :
∃ a, ∀ b ∈ S, r b a :=
not_forall_not.1 $ λ h, not_le_of_lt hl $ cof_type_le S (λ a, not_ball.1 (h a))
theorem cof_eq (r : α → α → Prop) [is_well_order α r] :
∃ S : set α, (∀ a, ∃ b ∈ S, ¬ r b a) ∧ mk S = cof (type r) :=
begin
have : ∃ i, cof (type r) = _,
{ dsimp [cof, order.cof, type, quotient.mk, quot.lift_on],
apply cardinal.min_eq },
exact let ⟨⟨S, hl⟩, e⟩ := this in ⟨S, hl, e.symm⟩,
end
theorem ord_cof_eq (r : α → α → Prop) [is_well_order α r] :
∃ S : set α, (∀ a, ∃ b ∈ S, ¬ r b a) ∧ type (subrel r S) = (cof (type r)).ord :=
let ⟨S, hS, e⟩ := cof_eq r, ⟨s, _, e'⟩ := cardinal.ord_eq S,
T : set α := {a | ∃ aS : a ∈ S, ∀ b : S, s b ⟨_, aS⟩ → r b a} in
begin
resetI, suffices,
{ refine ⟨T, this,
le_antisymm _ (cardinal.ord_le.2 $ cof_type_le T this)⟩,
rw [← e, e'],
refine type_le'.2 ⟨order_embedding.of_monotone
(λ a, ⟨a, let ⟨aS, _⟩ := a.2 in aS⟩) (λ a b h, _)⟩,
rcases a with ⟨a, aS, ha⟩, rcases b with ⟨b, bS, hb⟩,
change s ⟨a, _⟩ ⟨b, _⟩,
refine ((trichotomous_of s _ _).resolve_left (λ hn, _)).resolve_left _,
{ exact asymm h (ha _ hn) },
{ intro e, injection e with e, subst b,
exact irrefl _ h } },
{ intro a,
have : {b : S | ¬ r b a} ≠ ∅ := let ⟨b, bS, ba⟩ := hS a in
@set.ne_empty_of_mem S {b | ¬ r b a} ⟨b, bS⟩ ba,
let b := (is_well_order.wf s).min _ this,
have ba : ¬r b a := (is_well_order.wf s).min_mem _ this,
refine ⟨b, ⟨b.2, λ c, not_imp_not.1 $ λ h, _⟩, ba⟩,
rw [show ∀b:S, (⟨b, b.2⟩:S) = b, by intro b; cases b; refl],
exact (is_well_order.wf s).not_lt_min _ this
(is_order_connected.neg_trans h ba) }
end
theorem lift_cof (o) : (cof o).lift = cof o.lift :=
induction_on o $ begin introsI α r _,
cases lift_type r with _ e, rw e,
apply le_antisymm,
{ refine le_cof_type.2 (λ S H, _),
have : (mk (ulift.up ⁻¹' S)).lift ≤ mk S :=
⟨⟨λ ⟨⟨x, h⟩⟩, ⟨⟨x⟩, h⟩,
λ ⟨⟨x, h₁⟩⟩ ⟨⟨y, h₂⟩⟩ e, by simp at e; congr; injection e⟩⟩,
refine le_trans (cardinal.lift_le.2 $ cof_type_le _ _) this,
exact λ a, let ⟨⟨b⟩, bs, br⟩ := H ⟨a⟩ in ⟨b, bs, br⟩ },
{ rcases cof_eq r with ⟨S, H, e'⟩,
have : mk (ulift.down ⁻¹' S) ≤ (mk S).lift :=
⟨⟨λ ⟨⟨x⟩, h⟩, ⟨⟨x, h⟩⟩,
λ ⟨⟨x⟩, h₁⟩ ⟨⟨y⟩, h₂⟩ e, by simp at e; congr; injections⟩⟩,
rw e' at this,
refine le_trans (cof_type_le _ _) this,
exact λ ⟨a⟩, let ⟨b, bs, br⟩ := H a in ⟨⟨b⟩, bs, br⟩ }
end
theorem cof_le_card (o) : cof o ≤ card o :=
induction_on o $ λ α r _, begin
resetI,
have : mk (@set.univ α) = card (type r) :=
quotient.sound ⟨equiv.set.univ _⟩,
rw ← this, exact cof_type_le set.univ (λ a, ⟨a, ⟨⟩, irrefl a⟩)
end
theorem cof_ord_le (c : cardinal) : cof c.ord ≤ c :=
by simpa using cof_le_card c.ord
@[simp] theorem cof_zero : cof 0 = 0 :=
le_antisymm (by simpa using cof_le_card 0) (cardinal.zero_le _)
@[simp] theorem cof_eq_zero {o} : cof o = 0 ↔ o = 0 :=
⟨induction_on o $ λ α r _ z, by exactI
let ⟨S, hl, e⟩ := cof_eq r in type_eq_zero_iff_empty.2 $
λ ⟨a⟩, let ⟨b, h, _⟩ := hl a in
ne_zero_iff_nonempty.2 (by exact ⟨⟨_, h⟩⟩) (e.trans z),
λ e, by simp [e]⟩
@[simp] theorem cof_succ (o) : cof (succ o) = 1 :=
begin
apply le_antisymm,
{ refine induction_on o (λ α r _, _),
change cof (type _) ≤ _,
rw [← (_ : mk _ = 1)], apply cof_type_le,
{ refine λ a, ⟨sum.inr punit.star, set.mem_singleton _, _⟩,
rcases a with a|⟨⟨⟨⟩⟩⟩; simp [empty_relation] },
{ rw [cardinal.fintype_card, set.card_singleton], simp } },
{ rw [← cardinal.succ_zero, cardinal.succ_le],
simpa [lt_iff_le_and_ne, cardinal.zero_le] using
λ h, succ_ne_zero o (cof_eq_zero.1 (eq.symm h)) }
end
@[simp] theorem cof_eq_one_iff_is_succ {o} : cof.{u} o = 1 ↔ ∃ a, o = succ a :=
⟨induction_on o $ λ α r _ z, begin
resetI,
rcases cof_eq r with ⟨S, hl, e⟩, rw z at e,
cases ne_zero_iff_nonempty.1 (by rw e; exact one_ne_zero) with a,
refine ⟨typein r a, eq.symm $ quotient.sound
⟨order_iso.of_surjective (order_embedding.of_monotone _
(λ x y, _)) (λ x, _)⟩⟩,
{ apply sum.rec; [exact subtype.val, exact λ _, a] },
{ rcases x with x|⟨⟨⟨⟩⟩⟩; rcases y with y|⟨⟨⟨⟩⟩⟩;
simp [subrel, order.preimage, empty_relation],
exact x.2 },
{ suffices : r x a ∨ ∃ (b : punit), ↑a = x, {simpa},
rcases trichotomous_of r x a with h|h|h,
{ exact or.inl h },
{ exact or.inr ⟨punit.star, h.symm⟩ },
{ rcases hl x with ⟨a', aS, hn⟩,
rw (_ : ↑a = a') at h, {exact absurd h hn},
refine congr_arg subtype.val (_ : a = ⟨a', aS⟩),
haveI := le_one_iff_subsingleton.1 (le_of_eq e),
apply subsingleton.elim } }
end, λ ⟨a, e⟩, by simp [e]⟩
@[simp] theorem cof_add (a b : ordinal) : b ≠ 0 → cof (a + b) = cof b :=
induction_on a $ λ α r _, induction_on b $ λ β s _ b0, begin
resetI,
change cof (type _) = _,
refine eq_of_forall_le_iff (λ c, _),
rw [le_cof_type, le_cof_type],
split; intros H S hS,
{ refine le_trans (H {a | sum.rec_on a (∅:set α) S} (λ a, _)) ⟨⟨_, _⟩⟩,
{ cases a with a b,
{ cases type_ne_zero_iff_nonempty.1 b0 with b,
rcases hS b with ⟨b', bs, _⟩,
exact ⟨sum.inr b', bs, by simp⟩ },
{ rcases hS b with ⟨b', bs, h⟩,
exact ⟨sum.inr b', bs, by simp [h]⟩ } },
{ exact λ a, match a with ⟨sum.inr b, h⟩ := ⟨b, h⟩ end },
{ exact λ a b, match a, b with
⟨sum.inr a, h₁⟩, ⟨sum.inr b, h₂⟩, h := by congr; injection h
end } },
{ refine le_trans (H (sum.inr ⁻¹' S) (λ a, _)) ⟨⟨_, _⟩⟩,
{ rcases hS (sum.inr a) with ⟨a'|b', bs, h⟩; simp at h,
{ cases h }, { exact ⟨b', bs, h⟩ } },
{ exact λ ⟨a, h⟩, ⟨_, h⟩ },
{ exact λ ⟨a, h₁⟩ ⟨b, h₂⟩ h,
by injection h with h; congr; injection h } }
end
@[simp] theorem cof_cof (o : ordinal) : cof (cof o).ord = cof o :=
le_antisymm (le_trans (cof_le_card _) (by simp)) $
induction_on o $ λ α r _, by exactI
let ⟨S, hS, e₁⟩ := ord_cof_eq r,
⟨T, hT, e₂⟩ := cof_eq (subrel r S) in begin
rw e₁ at e₂, rw ← e₂,
refine le_trans (cof_type_le {a | ∃ h, (subtype.mk a h : S) ∈ T} (λ a, _)) ⟨⟨_, _⟩⟩,
{ rcases hS a with ⟨b, bS, br⟩,
rcases hT ⟨b, bS⟩ with ⟨⟨c, cS⟩, cT, cs⟩,
exact ⟨c, ⟨cS, cT⟩, is_order_connected.neg_trans cs br⟩ },
{ exact λ ⟨a, h⟩, ⟨⟨a, h.fst⟩, h.snd⟩ },
{ exact λ ⟨a, ha⟩ ⟨b, hb⟩ h,
by injection h with h; congr; injection h },
end
theorem omega_le_cof {o} : cardinal.omega ≤ cof o ↔ is_limit o :=
begin
rcases zero_or_succ_or_limit o with rfl|⟨o,rfl⟩|l,
{ simp [not_zero_is_limit, cardinal.omega_ne_zero] },
{ simp [not_succ_is_limit, cardinal.one_lt_omega] },
{ simp [l], refine le_of_not_lt (λ h, _),
cases cardinal.lt_omega.1 h with n e,
have := cof_cof o,
rw [e, ord_nat] at this,
cases n,
{ simp at e, simpa [e, not_zero_is_limit] using l },
{ rw [← nat_cast_succ, cof_succ] at this,
rw [← this, cof_eq_one_iff_is_succ] at e,
rcases e with ⟨a, rfl⟩,
exact not_succ_is_limit _ l } }
end
@[simp] theorem cof_omega : cof omega = cardinal.omega :=
le_antisymm
(by rw ← card_omega; apply cof_le_card)
(omega_le_cof.2 omega_is_limit)
theorem cof_eq' (r : α → α → Prop) [is_well_order α r] (h : is_limit (type r)) :
∃ S : set α, (∀ a, ∃ b ∈ S, r a b) ∧ mk S = cof (type r) :=
let ⟨S, H, e⟩ := cof_eq r in
⟨S, λ a,
let a' := enum r _ (h.2 _ (typein_lt_type r a)) in
let ⟨b, h, ab⟩ := H a' in
⟨b, h, (is_order_connected.conn a b a' $ (typein_lt_typein r).1
(by rw typein_enum; apply ordinal.lt_succ_self)).resolve_right ab⟩,
e⟩
theorem cof_sup_le_lift {ι} (f : ι → ordinal) (H : ∀ i, f i < sup f) :
cof (sup f) ≤ (mk ι).lift :=
begin
generalize e : sup f = o,
refine ordinal.induction_on o _ e, introsI α r _ e',
rw e' at H,
refine le_trans (cof_type_le (set.range (λ i, enum r _ (H i))) _)
⟨embedding.of_surjective _⟩,
{ intro a, by_contra h,
apply not_le_of_lt (typein_lt_type r a),
rw [← e', sup_le],
intro i,
simp [set.range] at h,
simpa using le_of_lt ((typein_lt_typein r).2 (h _ i rfl)) },
{ exact λ i, ⟨_, set.mem_range_self i.1⟩ },
{ intro a, rcases a with ⟨_, i, rfl⟩, exact ⟨⟨i⟩, by simp⟩ }
end
theorem cof_sup_le {ι} (f : ι → ordinal) (H : ∀ i, f i < sup.{u u} f) :
cof (sup.{u u} f) ≤ mk ι :=
by simpa using cof_sup_le_lift.{u u} f H
theorem cof_bsup_le_lift {o : ordinal} : ∀ (f : Π a < o, ordinal), (∀ i h, f i h < bsup o f) →
cof (bsup o f) ≤ o.card.lift :=
induction_on o $ λ α r _ f H,
by rw bsup_type; refine cof_sup_le_lift _ _;
rw ← bsup_type; intro a; apply H
theorem cof_bsup_le {o : ordinal} : ∀ (f : Π a < o, ordinal), (∀ i h, f i h < bsup.{u u} o f) →
cof (bsup.{u u} o f) ≤ o.card :=
induction_on o $ λ α r _ f H,
by simpa using cof_bsup_le_lift.{u u} f H
@[simp] theorem cof_univ : cof univ.{u v} = cardinal.univ :=
le_antisymm (cof_le_card _) begin
refine le_of_forall_lt (λ c h, _),
rcases lt_univ'.1 h with ⟨c, rfl⟩,
rcases @cof_eq ordinal.{u} (<) _ with ⟨S, H, Se⟩,
rw [univ, ← lift_cof, ← cardinal.lift_lift, cardinal.lift_lt, ← Se],
refine lt_of_not_ge (λ h, _),
cases cardinal.lift_down h with a e,
refine quotient.induction_on a (λ α e, _) e,
cases quotient.exact e with f,
have f := equiv.ulift.symm.trans f,
let g := λ a, (f a).1,
let o := succ (sup.{u u} g),
rcases H o with ⟨b, h, l⟩,
refine l (lt_succ.2 _),
rw ← show g (f.symm ⟨b, h⟩) = b, by dsimp [g]; simp,
apply le_sup
end
end ordinal
namespace cardinal
open ordinal
local infixr ^ := @pow cardinal.{u} cardinal cardinal.has_pow
/-- A cardinal is a limit if it is not zero or a successor
cardinal. Note that `ω` is a limit cardinal by this definition. -/
def is_limit (c : cardinal) : Prop :=
c ≠ 0 ∧ ∀ x < c, succ x < c
/-- A cardinal is a strong limit if it is not zero and it is
closed under powersets. Note that `ω` is a strong limit by this definition. -/
def is_strong_limit (c : cardinal) : Prop :=
c ≠ 0 ∧ ∀ x < c, 2 ^ x < c
theorem is_strong_limit.is_limit {c} (H : is_strong_limit c) : is_limit c :=
⟨H.1, λ x h, lt_of_le_of_lt (succ_le.2 $ cantor _) (H.2 _ h)⟩
/-- A cardinal is regular if it is infinite and it equals its own cofinality. -/
def is_regular (c : cardinal) : Prop :=
omega ≤ c ∧ c.ord.cof = c
theorem cof_is_regular {o : ordinal} (h : o.is_limit) : is_regular o.cof :=
⟨omega_le_cof.2 h, cof_cof _⟩
theorem omega_is_regular : is_regular omega :=
⟨le_refl _, by simp⟩
theorem succ_is_regular {c : cardinal.{u}} (h : omega ≤ c) : is_regular (succ c) :=
⟨le_trans h (le_of_lt $ lt_succ_self _), begin
refine le_antisymm (cof_ord_le _) (succ_le.2 _),
cases quotient.exists_rep (succ c) with α αe, simp at αe,
rcases ord_eq α with ⟨r, wo, re⟩, resetI,
have := ord_is_limit (le_trans h $ le_of_lt $ lt_succ_self _),
rw [← αe, re] at this ⊢,
rcases cof_eq' r this with ⟨S, H, Se⟩,
rw [← Se],
apply lt_imp_lt_of_le_imp_le (mul_le_mul_right c),
rw [mul_eq_self h, ← succ_le, ← αe, ← sum_const],
refine le_trans _ (sum_le_sum (λ x:S, card (typein r x)) _ _),
{ simp [typein, sum_mk (λ x:S, {a//r a x})],
refine ⟨embedding.of_surjective _⟩,
{ exact λ x, x.2.1 },
{ exact λ a, let ⟨b, h, ab⟩ := H a in ⟨⟨⟨_, h⟩, _, ab⟩, rfl⟩ } },
{ intro i,
rw [← lt_succ, ← lt_ord, ← αe, re],
apply typein_lt_type }
end⟩
theorem sup_lt_of_is_regular {ι} (f : ι → cardinal)
{c} (hc : is_regular c) (H1 : cardinal.mk ι < c)
(H2 : ∀ i, f i < c) : sup.{u u} f < c :=
begin
refine lt_of_le_of_ne (sup_le.2 (λ i, le_of_lt $ H2 i)) _,
rintro rfl, apply not_le_of_lt H1,
simpa [sup_ord, H2, hc.2] using cof_sup_le.{u} (λ i, (f i).ord)
end
theorem sum_lt_of_is_regular {ι} (f : ι → cardinal)
{c} (hc : is_regular c) (H1 : cardinal.mk ι < c)
(H2 : ∀ i, f i < c) : sum.{u u} f < c :=
lt_of_le_of_lt (sum_le_sup _) $ mul_lt_of_lt hc.1 H1 $
sup_lt_of_is_regular f hc H1 H2
/-- A cardinal is inaccessible if it is an
uncountable regular strong limit cardinal. -/
def is_inaccessible (c : cardinal) :=
omega < c ∧ is_regular c ∧ is_strong_limit c
theorem is_inaccessible.mk {c}
(h₁ : omega < c) (h₂ : c ≤ c.ord.cof) (h₃ : ∀ x < c, 2 ^ x < c) :
is_inaccessible c :=
⟨h₁, ⟨le_of_lt h₁, le_antisymm (cof_ord_le _) h₂⟩,
ne_of_gt (lt_trans omega_pos h₁), h₃⟩
/- Lean's foundations prove the existence of ω many inaccessible
cardinals -/
theorem univ_inaccessible : is_inaccessible (univ.{u v}) :=
is_inaccessible.mk
(by simpa using lift_lt_univ' omega)
(by simp)
(λ c h, begin
rcases lt_univ'.1 h with ⟨c, rfl⟩,
rw ← lift_two_power.{u (max (u+1) v)},
apply lift_lt_univ'
end)
theorem lt_power_cof {c : cardinal.{u}} : omega ≤ c → c < c ^ cof c.ord :=
quotient.induction_on c $ λ α h, begin
rcases ord_eq α with ⟨r, wo, re⟩, resetI,
have := ord_is_limit h,
rw [mk_def, re] at this ⊢,
rcases cof_eq' r this with ⟨S, H, Se⟩,
have := sum_lt_prod (λ a:S, mk {x // r x a}) (λ _, mk α) (λ i, _),
{ simp [Se.symm] at this ⊢,
refine lt_of_le_of_lt _ this,
refine ⟨embedding.of_surjective _⟩,
{ exact λ x, x.2.1 },
{ exact λ a, let ⟨b, h, ab⟩ := H a in ⟨⟨⟨_, h⟩, _, ab⟩, rfl⟩ } },
{ have := typein_lt_type r i,
rwa [← re, lt_ord] at this }
end
theorem lt_cof_power {a b : cardinal} (ha : omega ≤ a) (b1 : 1 < b) :
a < cof (b ^ a).ord :=
begin
have b0 : b ≠ 0 := ne_of_gt (lt_trans zero_lt_one b1),
apply lt_imp_lt_of_le_imp_le (power_le_power_left $ power_ne_zero a b0),
rw [power_mul, mul_eq_self ha],
exact lt_power_cof (le_trans ha $ le_of_lt $ cantor' _ b1),
end
end cardinal
|
52fcac0f0e3b57add6a70295c555f2af32dc04d7 | bdb33f8b7ea65f7705fc342a178508e2722eb851 | /data/pnat.lean | 3a6f616819fe89b89307cc306f211e517ad664de | [
"Apache-2.0"
] | permissive | rwbarton/mathlib | 939ae09bf8d6eb1331fc2f7e067d39567e10e33d | c13c5ea701bb1eec057e0a242d9f480a079105e9 | refs/heads/master | 1,584,015,335,862 | 1,524,142,167,000 | 1,524,142,167,000 | 130,614,171 | 0 | 0 | Apache-2.0 | 1,548,902,667,000 | 1,524,437,371,000 | Lean | UTF-8 | Lean | false | false | 2,533 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
import tactic.basic
/-- `ℕ+` is the type of positive natural numbers. It is defined as a subtype,
and the VM representation of `ℕ+` is the same as `ℕ` because the proof
is not stored. -/
def pnat := {n : ℕ // n > 0}
notation `ℕ+` := pnat
instance coe_pnat_nat : has_coe ℕ+ ℕ := ⟨subtype.val⟩
namespace nat
/-- Convert a natural number to a positive natural number. The
positivity assumption is inferred by `dec_trivial`. -/
def to_pnat (n : ℕ) (h : n > 0 . tactic.exact_dec_trivial) : ℕ+ := ⟨n, h⟩
/-- Write a successor as an element of `ℕ+`. -/
def succ_pnat (n : ℕ) : ℕ+ := ⟨succ n, succ_pos n⟩
@[simp] theorem succ_pnat_coe (n : ℕ) : (succ_pnat n : ℕ) = succ n := rfl
/-- Convert a natural number to a pnat. `n+1` is mapped to itself,
and `0` becomes `1`. -/
def to_pnat' (n : ℕ) : ℕ+ := succ_pnat (pred n)
end nat
instance coe_nat_pnat : has_coe ℕ ℕ+ := ⟨nat.to_pnat'⟩
namespace pnat
open nat
@[simp] theorem pos (n : ℕ+) : (n : ℕ) > 0 := n.2
theorem eq {m n : ℕ+} : (m : ℕ) = n → m = n := subtype.eq
@[simp] theorem mk_coe (n h) : ((⟨n, h⟩ : ℕ+) : ℕ) = n := rfl
instance : has_add ℕ+ := ⟨λ m n, ⟨m + n, add_pos m.2 n.2⟩⟩
@[simp] theorem add_coe (m n : ℕ+) : ((m + n : ℕ+) : ℕ) = m + n := rfl
@[simp] theorem ne_zero (n : ℕ+) : (n : ℕ) ≠ 0 := ne_of_gt n.2
@[simp] theorem nat_coe_coe {n : ℕ} : n > 0 → ((n : ℕ+) : ℕ) = n := succ_pred_eq_of_pos
@[simp] theorem to_pnat'_coe {n : ℕ} : n > 0 → (n.to_pnat' : ℕ) = n := succ_pred_eq_of_pos
@[simp] theorem coe_nat_coe (n : ℕ+) : ((n : ℕ) : ℕ+) = n := eq (nat_coe_coe n.pos)
instance : comm_monoid ℕ+ :=
{ mul := λ m n, ⟨m.1 * n.1, mul_pos m.2 n.2⟩,
mul_assoc := λ a b c, subtype.eq (mul_assoc _ _ _),
one := succ_pnat 0,
one_mul := λ a, subtype.eq (one_mul _),
mul_one := λ a, subtype.eq (mul_one _),
mul_comm := λ a b, subtype.eq (mul_comm _ _) }
@[simp] theorem one_coe : ((1 : ℕ+) : ℕ) = 1 := rfl
@[simp] theorem mul_coe (m n : ℕ+) : ((m * n : ℕ+) : ℕ) = m * n := rfl
/-- The power of a pnat and a nat is a pnat. -/
def pow (m : ℕ+) (n : ℕ) : ℕ+ :=
⟨m ^ n, nat.pos_pow_of_pos _ m.pos⟩
instance : has_pow ℕ+ ℕ := ⟨pow⟩
@[simp] theorem pow_coe (m : ℕ+) (n : ℕ) : (↑(m ^ n) : ℕ) = m ^ n := rfl
end pnat
|
25bb28d7acc350244d6db3dacfb8ca3facc05f77 | d1a52c3f208fa42c41df8278c3d280f075eb020c | /stage0/src/Lean/Elab/Attributes.lean | 23535e117ac99c825f31dae21b949a86aa20ef16 | [
"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 | 3,064 | 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, Sebastian Ullrich
-/
import Lean.Parser.Attr
import Lean.Attributes
import Lean.MonadEnv
import Lean.Elab.Util
namespace Lean.Elab
structure Attribute where
kind : AttributeKind := AttributeKind.global
name : Name
stx : Syntax := Syntax.missing
instance : ToFormat Attribute where
format attr :=
let kindStr := match attr.kind with
| AttributeKind.global => ""
| AttributeKind.local => "local "
| AttributeKind.scoped => "scoped "
Format.bracket "@[" f!"{kindStr}{attr.name}{toString attr.stx}" "]"
instance : Inhabited Attribute where
default := { name := arbitrary }
/-
```
attrKind := leading_parser optional («scoped» <|> «local»)
```
-/
def toAttributeKind (attrKindStx : Syntax) : MacroM AttributeKind := do
if attrKindStx[0].isNone then
return AttributeKind.global
else if attrKindStx[0][0].getKind == ``Lean.Parser.Term.scoped then
if (← Macro.getCurrNamespace).isAnonymous then
throw <| Macro.Exception.error (← getRef) "scoped attributes must be used inside namespaces"
return AttributeKind.scoped
else
return AttributeKind.local
def mkAttrKindGlobal : Syntax :=
mkNode ``Lean.Parser.Term.attrKind #[mkNullNode]
def elabAttr {m} [Monad m] [MonadEnv m] [MonadResolveName m] [MonadError m] [MonadMacroAdapter m] [MonadRecDepth m] [MonadTrace m] [MonadOptions m] [AddMessageContext m] (attrInstance : Syntax) : m Attribute := do
/- attrInstance := ppGroup $ leading_parser attrKind >> attrParser -/
let attrKind ← liftMacroM <| toAttributeKind attrInstance[0]
let attr := attrInstance[1]
let attr ← liftMacroM <| expandMacros attr
let attrName ←
if attr.getKind == ``Parser.Attr.simple then
pure attr[0].getId.eraseMacroScopes
else
match attr.getKind with
| Name.str _ s _ => pure <| Name.mkSimple s
| _ => throwErrorAt attr "unknown attribute"
unless isAttribute (← getEnv) attrName do
throwError "unknown attribute [{attrName}]"
/- The `AttrM` does not have sufficient information for expanding macros in `args`.
So, we expand them before here before we invoke the attributer handlers implemented using `AttrM`. -/
pure { kind := attrKind, name := attrName, stx := attr }
def elabAttrs {m} [Monad m] [MonadEnv m] [MonadResolveName m] [MonadError m] [MonadMacroAdapter m] [MonadRecDepth m] [MonadTrace m] [MonadOptions m] [AddMessageContext m] (attrInstances : Array Syntax) : m (Array Attribute) := do
let mut attrs := #[]
for attr in attrInstances do
attrs := attrs.push (← elabAttr attr)
return attrs
-- leading_parser "@[" >> sepBy1 attrInstance ", " >> "]"
def elabDeclAttrs {m} [Monad m] [MonadEnv m] [MonadResolveName m] [MonadError m] [MonadMacroAdapter m] [MonadRecDepth m] [MonadTrace m] [MonadOptions m] [AddMessageContext m] (stx : Syntax) : m (Array Attribute) :=
elabAttrs stx[1].getSepArgs
end Lean.Elab
|
03eeb32fd9417c2aebf5fc9a74036c69ed56b706 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/algebra/group/semiconj.lean | d3d2213fe6138a6bdec3a78b6d1b0684057df3af | [
"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 | 5,601 | lean | /-
Copyright (c) 2019 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
Some proofs and docs came from `algebra/commute` (c) Neil Strickland
-/
import algebra.group.units
/-!
# Semiconjugate elements of a semigroup
## Main definitions
We say that `x` is semiconjugate to `y` by `a` (`semiconj_by a x y`), if `a * x = y * a`.
In this file we provide operations on `semiconj_by _ _ _`.
In the names of these operations, we treat `a` as the “left” argument, and both `x` and `y` as
“right” arguments. This way most names in this file agree with the names of the corresponding lemmas
for `commute a b = semiconj_by a b b`. As a side effect, some lemmas have only `_right` version.
Lean does not immediately recognise these terms as equations, so for rewriting we need syntax like
`rw [(h.pow_right 5).eq]` rather than just `rw [h.pow_right 5]`.
This file provides only basic operations (`mul_left`, `mul_right`, `inv_right` etc). Other
operations (`pow_right`, field inverse etc) are in the files that define corresponding notions.
-/
universes u v
/-- `x` is semiconjugate to `y` by `a`, if `a * x = y * a`. -/
@[to_additive add_semiconj_by "`x` is additive semiconjugate to `y` by `a` if `a + x = y + a`"]
def semiconj_by {M : Type u} [has_mul M] (a x y : M) : Prop := a * x = y * a
namespace semiconj_by
/-- Equality behind `semiconj_by a x y`; useful for rewriting. -/
@[to_additive]
protected lemma eq {S : Type u} [has_mul S] {a x y : S} (h : semiconj_by a x y) :
a * x = y * a := h
section semigroup
variables {S : Type u} [semigroup S] {a b x y z x' y' : S}
/-- If `a` semiconjugates `x` to `y` and `x'` to `y'`,
then it semiconjugates `x * x'` to `y * y'`. -/
@[to_additive, simp] lemma mul_right (h : semiconj_by a x y) (h' : semiconj_by a x' y') :
semiconj_by a (x * x') (y * y') :=
by unfold semiconj_by; assoc_rw [h.eq, h'.eq]
/-- If both `a` and `b` semiconjugate `x` to `y`, then so does `a * b`. -/
@[to_additive]
lemma mul_left (ha : semiconj_by a y z) (hb : semiconj_by b x y) :
semiconj_by (a * b) x z :=
by unfold semiconj_by; assoc_rw [hb.eq, ha.eq, mul_assoc]
end semigroup
section monoid
variables {M : Type u} [monoid M]
/-- Any element semiconjugates `1` to `1`. -/
@[simp, to_additive]
lemma one_right (a : M) : semiconj_by a 1 1 := by rw [semiconj_by, mul_one, one_mul]
/-- One semiconjugates any element to itself. -/
@[simp, to_additive]
lemma one_left (x : M) : semiconj_by 1 x x := eq.symm $ one_right x
/-- If `a` semiconjugates a unit `x` to a unit `y`, then it semiconjugates `x⁻¹` to `y⁻¹`. -/
@[to_additive] lemma units_inv_right {a : M} {x y : units M} (h : semiconj_by a x y) :
semiconj_by a ↑x⁻¹ ↑y⁻¹ :=
calc a * ↑x⁻¹ = ↑y⁻¹ * (y * a) * ↑x⁻¹ : by rw [units.inv_mul_cancel_left]
... = ↑y⁻¹ * a : by rw [← h.eq, mul_assoc, units.mul_inv_cancel_right]
@[simp, to_additive] lemma units_inv_right_iff {a : M} {x y : units M} :
semiconj_by a ↑x⁻¹ ↑y⁻¹ ↔ semiconj_by a x y :=
⟨units_inv_right, units_inv_right⟩
/-- If a unit `a` semiconjugates `x` to `y`, then `a⁻¹` semiconjugates `y` to `x`. -/
@[to_additive] lemma units_inv_symm_left {a : units M} {x y : M} (h : semiconj_by ↑a x y) :
semiconj_by ↑a⁻¹ y x :=
calc ↑a⁻¹ * y = ↑a⁻¹ * (y * a * ↑a⁻¹) : by rw [units.mul_inv_cancel_right]
... = x * ↑a⁻¹ : by rw [← h.eq, ← mul_assoc, units.inv_mul_cancel_left]
@[simp, to_additive] lemma units_inv_symm_left_iff {a : units M} {x y : M} :
semiconj_by ↑a⁻¹ y x ↔ semiconj_by ↑a x y :=
⟨units_inv_symm_left, units_inv_symm_left⟩
@[to_additive] theorem units_coe {a x y : units M} (h : semiconj_by a x y) :
semiconj_by (a : M) x y :=
congr_arg units.val h
@[to_additive] theorem units_of_coe {a x y : units M} (h : semiconj_by (a : M) x y) :
semiconj_by a x y :=
units.ext h
@[simp, to_additive] theorem units_coe_iff {a x y : units M} :
semiconj_by (a : M) x y ↔ semiconj_by a x y :=
⟨units_of_coe, units_coe⟩
end monoid
section group
variables {G : Type u} [group G] {a x y : G}
@[simp, to_additive] lemma inv_right_iff : semiconj_by a x⁻¹ y⁻¹ ↔ semiconj_by a x y :=
@units_inv_right_iff G _ a ⟨x, x⁻¹, mul_inv_self x, inv_mul_self x⟩
⟨y, y⁻¹, mul_inv_self y, inv_mul_self y⟩
@[to_additive] lemma inv_right : semiconj_by a x y → semiconj_by a x⁻¹ y⁻¹ :=
inv_right_iff.2
@[simp, to_additive] lemma inv_symm_left_iff : semiconj_by a⁻¹ y x ↔ semiconj_by a x y :=
@units_inv_symm_left_iff G _ ⟨a, a⁻¹, mul_inv_self a, inv_mul_self a⟩ _ _
@[to_additive] lemma inv_symm_left : semiconj_by a x y → semiconj_by a⁻¹ y x :=
inv_symm_left_iff.2
@[to_additive] lemma inv_inv_symm (h : semiconj_by a x y) : semiconj_by a⁻¹ y⁻¹ x⁻¹ :=
h.inv_right.inv_symm_left
-- this is not a simp lemma because it can be deduced from other simp lemmas
@[to_additive] lemma inv_inv_symm_iff : semiconj_by a⁻¹ y⁻¹ x⁻¹ ↔ semiconj_by a x y :=
inv_right_iff.trans inv_symm_left_iff
/-- `a` semiconjugates `x` to `a * x * a⁻¹`. -/
@[to_additive] lemma conj_mk (a x : G) : semiconj_by a x (a * x * a⁻¹) :=
by unfold semiconj_by; rw [mul_assoc, inv_mul_self, mul_one]
end group
end semiconj_by
/-- `a` semiconjugates `x` to `a * x * a⁻¹`. -/
@[to_additive]
lemma units.mk_semiconj_by {M : Type u} [monoid M] (u : units M) (x : M) :
semiconj_by ↑u x (u * x * ↑u⁻¹) :=
by unfold semiconj_by; rw [units.inv_mul_cancel_right]
|
a25497c77106da8418111a47a7aa14a3d38e0f63 | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /tests/lean/run/noindexAnnotation.lean | 17a5632827b6ac4a5808cfde18ded468b48764d6 | [
"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 | 318 | lean | structure Fin2 (n : Nat) :=
(val : Nat)
(isLt : val < n)
protected def Fin2.ofNat {n : Nat} (a : Nat) : Fin2 (Nat.succ n) :=
⟨a % Nat.succ n, Nat.mod_lt _ (Nat.zeroLtSucc _)⟩
instance : OfNat (Fin2 (no_index (n+1))) i where
ofNat := Fin2.ofNat i
def ex1 : Fin2 (9 + 1) :=
0
def ex2 : Fin2 10 :=
0
|
e41119fbe4cca48b06a298802dec7bba728a4642 | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/set_theory/cardinal.lean | 27520750760c5839780ea95ea4de6035b796bf67 | [
"Apache-2.0"
] | permissive | dupuisf/mathlib | 62de4ec6544bf3b79086afd27b6529acfaf2c1bb | 8582b06b0a5d06c33ee07d0bdf7c646cae22cf36 | refs/heads/master | 1,669,494,854,016 | 1,595,692,409,000 | 1,595,692,409,000 | 272,046,630 | 0 | 0 | Apache-2.0 | 1,592,066,143,000 | 1,592,066,142,000 | null | UTF-8 | Lean | false | false | 46,248 | 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, Mario Carneiro
-/
import data.set.countable
import set_theory.schroeder_bernstein
import data.fintype.card
/-!
# Cardinal Numbers
We define cardinal numbers as a quotient of types under the equivalence relation of equinumerity.
We define the order on cardinal numbers, define omega, and do basic cardinal arithmetic:
addition, multiplication, power, cardinal successor, minimum, supremum,
infinitary sums and products
The fact that the cardinality of `α × α` coincides with that of `α` when `α` is infinite is not
proved in this file, as it relies on facts on well-orders. Instead, it is in
`cardinal_ordinal.lean` (together with many other facts on cardinals, for instance the
cardinality of `list α`).
## Implementation notes
* There is a type of cardinal numbers in every universe level: `cardinal.{u} : Type (u + 1)`
is the quotient of types in `Type u`.
There is a lift operation lifting cardinal numbers to a higher level.
* Cardinal arithmetic specifically for infinite cardinals (like `κ * κ = κ`) is in the file
`set_theory/ordinal.lean`, because concepts from that file are used in the proof.
## References
* <https://en.wikipedia.org/wiki/Cardinal_number>
## Tags
cardinal number, cardinal arithmetic, cardinal exponentiation, omega
-/
open function set
open_locale classical
universes u v w x
variables {α β : Type u}
/-- The equivalence relation on types given by equivalence (bijective correspondence) of types.
Quotienting by this equivalence relation gives the cardinal numbers.
-/
instance cardinal.is_equivalent : setoid (Type u) :=
{ r := λα β, nonempty (α ≃ β),
iseqv := ⟨λα,
⟨equiv.refl α⟩,
λα β ⟨e⟩, ⟨e.symm⟩,
λα β γ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ }
/-- `cardinal.{u}` is the type of cardinal numbers in `Type u`,
defined as the quotient of `Type u` by existence of an equivalence
(a bijection with explicit inverse). -/
def cardinal : Type (u + 1) := quotient cardinal.is_equivalent
namespace cardinal
/-- The cardinal number of a type -/
def mk : Type u → cardinal := quotient.mk
localized "notation `#` := cardinal.mk" in cardinal
protected lemma eq : mk α = mk β ↔ nonempty (α ≃ β) := quotient.eq
@[simp] theorem mk_def (α : Type u) : @eq cardinal ⟦α⟧ (mk α) := rfl
@[simp] theorem mk_out (c : cardinal) : mk (c.out) = c := quotient.out_eq _
/-- We define the order on cardinal numbers by `mk α ≤ mk β` if and only if
there exists an embedding (injective function) from α to β. -/
instance : has_le cardinal.{u} :=
⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, nonempty $ α ↪ β) $
assume α β γ δ ⟨e₁⟩ ⟨e₂⟩,
propext ⟨assume ⟨e⟩, ⟨e.congr e₁ e₂⟩, assume ⟨e⟩, ⟨e.congr e₁.symm e₂.symm⟩⟩⟩
theorem mk_le_of_injective {α β : Type u} {f : α → β} (hf : injective f) : mk α ≤ mk β :=
⟨⟨f, hf⟩⟩
theorem mk_le_of_surjective {α β : Type u} {f : α → β} (hf : surjective f) : mk β ≤ mk α :=
⟨embedding.of_surjective f hf⟩
theorem le_mk_iff_exists_set {c : cardinal} {α : Type u} :
c ≤ mk α ↔ ∃ p : set α, mk p = c :=
⟨quotient.induction_on c $ λ β ⟨⟨f, hf⟩⟩,
⟨set.range f, eq.symm $ quot.sound ⟨equiv.set.range f hf⟩⟩,
λ ⟨p, e⟩, e ▸ ⟨⟨subtype.val, λ a b, subtype.eq⟩⟩⟩
theorem out_embedding {c c' : cardinal} : c ≤ c' ↔ nonempty (c.out ↪ c'.out) :=
by { transitivity _, rw [←quotient.out_eq c, ←quotient.out_eq c'], refl }
instance : linear_order cardinal.{u} :=
{ le := (≤),
le_refl := by rintros ⟨α⟩; exact ⟨embedding.refl _⟩,
le_trans := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.trans e₂⟩,
le_antisymm := by rintros ⟨α⟩ ⟨β⟩ ⟨e₁⟩ ⟨e₂⟩; exact quotient.sound (e₁.antisymm e₂),
le_total := by rintros ⟨α⟩ ⟨β⟩; exact embedding.total }
noncomputable instance : decidable_linear_order cardinal.{u} := classical.DLO _
noncomputable instance : distrib_lattice cardinal.{u} := by apply_instance -- short-circuit type class inference
instance : has_zero cardinal.{u} := ⟨⟦pempty⟧⟩
instance : inhabited cardinal.{u} := ⟨0⟩
theorem ne_zero_iff_nonempty {α : Type u} : mk α ≠ 0 ↔ nonempty α :=
not_iff_comm.1
⟨λ h, quotient.sound ⟨(equiv.empty_of_not_nonempty h).trans equiv.empty_equiv_pempty⟩,
λ e, let ⟨h⟩ := quotient.exact e in λ ⟨a⟩, (h a).elim⟩
instance : has_one cardinal.{u} := ⟨⟦punit⟧⟩
instance : nontrivial cardinal.{u} :=
⟨⟨1, 0, ne_zero_iff_nonempty.2 ⟨punit.star⟩⟩⟩
theorem le_one_iff_subsingleton {α : Type u} : mk α ≤ 1 ↔ subsingleton α :=
⟨λ ⟨f⟩, ⟨λ a b, f.injective (subsingleton.elim _ _)⟩,
λ ⟨h⟩, ⟨⟨λ a, punit.star, λ a b _, h _ _⟩⟩⟩
theorem one_lt_iff_nontrivial {α : Type u} : 1 < mk α ↔ nontrivial α :=
by { rw [← not_iff_not, not_nontrivial_iff_subsingleton, ← le_one_iff_subsingleton], simp }
instance : has_add cardinal.{u} :=
⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α ⊕ β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩,
quotient.sound ⟨equiv.sum_congr e₁ e₂⟩⟩
@[simp] theorem add_def (α β) : mk α + mk β = mk (α ⊕ β) := rfl
instance : has_mul cardinal.{u} :=
⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α × β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩,
quotient.sound ⟨equiv.prod_congr e₁ e₂⟩⟩
@[simp] theorem mul_def (α β : Type u) : mk α * mk β = mk (α × β) := rfl
private theorem add_comm (a b : cardinal.{u}) : a + b = b + a :=
quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.sum_comm α β⟩
private theorem mul_comm (a b : cardinal.{u}) : a * b = b * a :=
quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.prod_comm α β⟩
private theorem zero_add (a : cardinal.{u}) : 0 + a = a :=
quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_sum α⟩
private theorem zero_mul (a : cardinal.{u}) : 0 * a = 0 :=
quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_prod α⟩
private theorem one_mul (a : cardinal.{u}) : 1 * a = a :=
quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_prod α⟩
private theorem left_distrib (a b c : cardinal.{u}) : a * (b + c) = a * b + a * c :=
quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_sum_distrib α β γ⟩
instance : comm_semiring cardinal.{u} :=
{ zero := 0,
one := 1,
add := (+),
mul := (*),
zero_add := zero_add,
add_zero := assume a, by rw [add_comm a 0, zero_add a],
add_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.sum_assoc α β γ⟩,
add_comm := add_comm,
zero_mul := zero_mul,
mul_zero := assume a, by rw [mul_comm a 0, zero_mul a],
one_mul := one_mul,
mul_one := assume a, by rw [mul_comm a 1, one_mul a],
mul_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.prod_assoc α β γ⟩,
mul_comm := mul_comm,
left_distrib := left_distrib,
right_distrib := assume a b c,
by rw [mul_comm (a + b) c, left_distrib c a b, mul_comm c a, mul_comm c b] }
/-- The cardinal exponential. `mk α ^ mk β` is the cardinal of `β → α`. -/
protected def power (a b : cardinal.{u}) : cardinal.{u} :=
quotient.lift_on₂ a b (λα β, mk (β → α)) $ assume α₁ α₂ β₁ β₂ ⟨e₁⟩ ⟨e₂⟩,
quotient.sound ⟨equiv.arrow_congr e₂ e₁⟩
instance : has_pow cardinal cardinal := ⟨cardinal.power⟩
local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow
@[simp] theorem power_def (α β) : mk α ^ mk β = mk (β → α) := rfl
@[simp] theorem power_zero {a : cardinal} : a ^ 0 = 1 :=
quotient.induction_on a $ assume α, quotient.sound
⟨equiv.pempty_arrow_equiv_punit α⟩
@[simp] theorem power_one {a : cardinal} : a ^ 1 = a :=
quotient.induction_on a $ assume α, quotient.sound
⟨equiv.punit_arrow_equiv α⟩
@[simp] theorem one_power {a : cardinal} : 1 ^ a = 1 :=
quotient.induction_on a $ assume α, quotient.sound
⟨equiv.arrow_punit_equiv_punit α⟩
@[simp] theorem prop_eq_two : mk (ulift Prop) = 2 :=
quot.sound ⟨equiv.ulift.trans $ equiv.Prop_equiv_bool.trans equiv.bool_equiv_punit_sum_punit⟩
@[simp] theorem zero_power {a : cardinal} : a ≠ 0 → 0 ^ a = 0 :=
quotient.induction_on a $ assume α heq,
nonempty.rec_on (ne_zero_iff_nonempty.1 heq) $ assume a,
quotient.sound ⟨equiv.equiv_pempty $ assume f, pempty.rec (λ _, false) (f a)⟩
theorem power_ne_zero {a : cardinal} (b) : a ≠ 0 → a ^ b ≠ 0 :=
quotient.induction_on₂ a b $ λ α β h,
let ⟨a⟩ := ne_zero_iff_nonempty.1 h in
ne_zero_iff_nonempty.2 ⟨λ _, a⟩
theorem mul_power {a b c : cardinal} : (a * b) ^ c = a ^ c * b ^ c :=
quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.arrow_prod_equiv_prod_arrow α β γ⟩
theorem power_add {a b c : cardinal} : a ^ (b + c) = a ^ b * a ^ c :=
quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.sum_arrow_equiv_prod_arrow β γ α⟩
theorem power_mul {a b c : cardinal} : (a ^ b) ^ c = a ^ (b * c) :=
by rw [_root_.mul_comm b c];
from (quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.arrow_arrow_equiv_prod_arrow γ β α⟩)
@[simp] lemma pow_cast_right (κ : cardinal.{u}) :
∀ n : ℕ, (κ ^ (↑n : cardinal.{u})) = @has_pow.pow _ _ monoid.has_pow κ n
| 0 := by simp
| (_+1) := by rw [nat.cast_succ, power_add, power_one, _root_.mul_comm, pow_succ, pow_cast_right]
section order_properties
open sum
theorem zero_le : ∀(a : cardinal), 0 ≤ a :=
by rintro ⟨α⟩; exact ⟨embedding.of_not_nonempty $ λ ⟨a⟩, a.elim⟩
theorem le_zero (a : cardinal) : a ≤ 0 ↔ a = 0 :=
by simp [le_antisymm_iff, zero_le]
theorem pos_iff_ne_zero {o : cardinal} : 0 < o ↔ o ≠ 0 :=
by simp [lt_iff_le_and_ne, eq_comm, zero_le]
@[simp] theorem zero_lt_one : (0 : cardinal) < 1 :=
lt_of_le_of_ne (zero_le _) zero_ne_one
lemma zero_power_le (c : cardinal.{u}) : (0 : cardinal.{u}) ^ c ≤ 1 :=
by { by_cases h : c = 0, rw [h, power_zero], rw [zero_power h], apply zero_le }
theorem add_le_add : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a + c ≤ b + d :=
by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.sum_map e₂⟩
theorem add_le_add_left (a) {b c : cardinal} : b ≤ c → a + b ≤ a + c :=
add_le_add (le_refl _)
theorem add_le_add_right {a b : cardinal} (c) (h : a ≤ b) : a + c ≤ b + c :=
add_le_add h (le_refl _)
theorem le_add_right (a b : cardinal) : a ≤ a + b :=
by simpa using add_le_add_left a (zero_le b)
theorem le_add_left (a b : cardinal) : a ≤ b + a :=
by simpa using add_le_add_right a (zero_le b)
theorem mul_le_mul : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a * c ≤ b * d :=
by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.prod_map e₂⟩
theorem mul_le_mul_left (a) {b c : cardinal} : b ≤ c → a * b ≤ a * c :=
mul_le_mul (le_refl _)
theorem mul_le_mul_right {a b : cardinal} (c) (h : a ≤ b) : a * c ≤ b * c :=
mul_le_mul h (le_refl _)
theorem power_le_power_left : ∀{a b c : cardinal}, a ≠ 0 → b ≤ c → a ^ b ≤ a ^ c :=
by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ hα ⟨e⟩; exact
let ⟨a⟩ := ne_zero_iff_nonempty.1 hα in
⟨@embedding.arrow_congr_right _ _ _ ⟨a⟩ e⟩
theorem power_le_max_power_one {a b c : cardinal} (h : b ≤ c) : a ^ b ≤ max (a ^ c) 1 :=
begin
by_cases ha : a = 0,
simp [ha, zero_power_le],
exact le_trans (power_le_power_left ha h) (le_max_left _ _)
end
theorem power_le_power_right {a b c : cardinal} : a ≤ b → a ^ c ≤ b ^ c :=
quotient.induction_on₃ a b c $ assume α β γ ⟨e⟩, ⟨embedding.arrow_congr_left e⟩
theorem le_iff_exists_add {a b : cardinal} : a ≤ b ↔ ∃ c, b = a + c :=
⟨quotient.induction_on₂ a b $ λ α β ⟨⟨f, hf⟩⟩,
have (α ⊕ ((range f)ᶜ : set β)) ≃ β, from
(equiv.sum_congr (equiv.set.range f hf) (equiv.refl _)).trans $
(equiv.set.sum_compl (range f)),
⟨⟦↥(range f)ᶜ⟧, quotient.sound ⟨this.symm⟩⟩,
λ ⟨c, e⟩, add_zero a ▸ e.symm ▸ add_le_add_left _ (zero_le _)⟩
end order_properties
instance : order_bot cardinal.{u} :=
{ bot := 0, bot_le := zero_le, ..cardinal.linear_order }
instance : canonically_ordered_add_monoid cardinal.{u} :=
{ add_le_add_left := λ a b h c, add_le_add_left _ h,
lt_of_add_lt_add_left := λ a b c, lt_imp_lt_of_le_imp_le (add_le_add_left _),
le_iff_exists_add := @le_iff_exists_add,
..cardinal.order_bot,
..cardinal.comm_semiring, ..cardinal.linear_order }
theorem cantor : ∀(a : cardinal.{u}), a < 2 ^ a :=
by rw ← prop_eq_two; rintros ⟨a⟩; exact ⟨
⟨⟨λ a b, ⟨a = b⟩, λ a b h, cast (ulift.up.inj (@congr_fun _ _ _ _ h b)).symm rfl⟩⟩,
λ ⟨⟨f, hf⟩⟩, cantor_injective (λ s, f (λ a, ⟨s a⟩)) $
λ s t h, by funext a; injection congr_fun (hf h) a⟩
instance : no_top_order cardinal.{u} :=
{ no_top := λ a, ⟨_, cantor a⟩, ..cardinal.linear_order }
/-- The minimum cardinal in a family of cardinals (the existence
of which is provided by `injective_min`). -/
noncomputable def min {ι} (I : nonempty ι) (f : ι → cardinal) : cardinal :=
f $ classical.some $
@embedding.min_injective _ (λ i, (f i).out) I
theorem min_eq {ι} (I) (f : ι → cardinal) : ∃ i, min I f = f i :=
⟨_, rfl⟩
theorem min_le {ι I} (f : ι → cardinal) (i) : min I f ≤ f i :=
by rw [← mk_out (min I f), ← mk_out (f i)]; exact
let ⟨g⟩ := classical.some_spec
(@embedding.min_injective _ (λ i, (f i).out) I) in
⟨g i⟩
theorem le_min {ι I} {f : ι → cardinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i :=
⟨λ h i, le_trans h (min_le _ _),
λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩
protected theorem wf : @well_founded cardinal.{u} (<) :=
⟨λ a, classical.by_contradiction $ λ h,
let ι := {c :cardinal // ¬ acc (<) c},
f : ι → cardinal := subtype.val,
⟨⟨c, hc⟩, hi⟩ := @min_eq ι ⟨⟨_, h⟩⟩ f in
hc (acc.intro _ (λ j ⟨_, h'⟩,
classical.by_contradiction $ λ hj, h' $
by have := min_le f ⟨j, hj⟩; rwa hi at this))⟩
instance has_wf : @has_well_founded cardinal.{u} := ⟨(<), cardinal.wf⟩
instance wo : @is_well_order cardinal.{u} (<) := ⟨cardinal.wf⟩
/-- The successor cardinal - the smallest cardinal greater than
`c`. This is not the same as `c + 1` except in the case of finite `c`. -/
noncomputable def succ (c : cardinal) : cardinal :=
@min {c' // c < c'} ⟨⟨_, cantor _⟩⟩ subtype.val
theorem lt_succ_self (c : cardinal) : c < succ c :=
by cases min_eq _ _ with s e; rw [succ, e]; exact s.2
theorem succ_le {a b : cardinal} : succ a ≤ b ↔ a < b :=
⟨lt_of_lt_of_le (lt_succ_self _), λ h,
by exact min_le _ (subtype.mk b h)⟩
theorem lt_succ {a b : cardinal} : a < succ b ↔ a ≤ b :=
by rw [← not_le, succ_le, not_lt]
theorem add_one_le_succ (c : cardinal) : c + 1 ≤ succ c :=
begin
refine quot.induction_on c (λ α, _) (lt_succ_self c),
refine quot.induction_on (succ (quot.mk setoid.r α)) (λ β h, _),
cases h.left with f,
have : ¬ surjective f := λ hn,
ne_of_lt h (quotient.sound ⟨equiv.of_bijective f ⟨f.injective, hn⟩⟩),
cases classical.not_forall.1 this with b nex,
refine ⟨⟨sum.rec (by exact f) _, _⟩⟩,
{ exact λ _, b },
{ intros a b h, rcases a with a|⟨⟨⟨⟩⟩⟩; rcases b with b|⟨⟨⟨⟩⟩⟩,
{ rw f.injective h },
{ exact nex.elim ⟨_, h⟩ },
{ exact nex.elim ⟨_, h.symm⟩ },
{ refl } }
end
lemma succ_ne_zero (c : cardinal) : succ c ≠ 0 :=
by { rw [←pos_iff_ne_zero, lt_succ], apply zero_le }
/-- The indexed sum of cardinals is the cardinality of the
indexed disjoint union, i.e. sigma type. -/
def sum {ι} (f : ι → cardinal) : cardinal := mk Σ i, (f i).out
theorem le_sum {ι} (f : ι → cardinal) (i) : f i ≤ sum f :=
by rw ← quotient.out_eq (f i); exact
⟨⟨λ a, ⟨i, a⟩, λ a b h, eq_of_heq $ by injection h⟩⟩
@[simp] theorem sum_mk {ι} (f : ι → Type*) : sum (λ i, mk (f i)) = mk (Σ i, f i) :=
quot.sound ⟨equiv.sigma_congr_right $ λ i,
classical.choice $ quotient.exact $ quot.out_eq $ mk (f i)⟩
theorem sum_const (ι : Type u) (a : cardinal.{u}) : sum (λ _:ι, a) = mk ι * a :=
quotient.induction_on a $ λ α, by simp; exact
quotient.sound ⟨equiv.sigma_equiv_prod _ _⟩
theorem sum_le_sum {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sum f ≤ sum g :=
⟨(embedding.refl _).sigma_map $ λ i, classical.choice $
by have := H i; rwa [← quot.out_eq (f i), ← quot.out_eq (g i)] at this⟩
/-- The indexed supremum of cardinals is the smallest cardinal above
everything in the family. -/
noncomputable def sup {ι} (f : ι → cardinal) : cardinal :=
@min {c // ∀ i, f i ≤ c} ⟨⟨sum f, le_sum f⟩⟩ (λ a, a.1)
theorem le_sup {ι} (f : ι → cardinal) (i) : f i ≤ sup f :=
by dsimp [sup]; cases min_eq _ _ with c hc; rw hc; exact c.2 i
theorem sup_le {ι} {f : ι → cardinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a :=
⟨λ h i, le_trans (le_sup _ _) h,
λ h, by dsimp [sup]; change a with (⟨a, h⟩:subtype _).1; apply min_le⟩
theorem sup_le_sup {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sup f ≤ sup g :=
sup_le.2 $ λ i, le_trans (H i) (le_sup _ _)
theorem sup_le_sum {ι} (f : ι → cardinal) : sup f ≤ sum f :=
sup_le.2 $ le_sum _
theorem sum_le_sup {ι : Type u} (f : ι → cardinal.{u}) : sum f ≤ mk ι * sup.{u u} f :=
by rw ← sum_const; exact sum_le_sum _ _ (le_sup _)
theorem sup_eq_zero {ι} {f : ι → cardinal} (h : ι → false) : sup f = 0 :=
by { rw [←le_zero, sup_le], intro x, exfalso, exact h x }
/-- The indexed product of cardinals is the cardinality of the Pi type
(dependent product). -/
def prod {ι : Type u} (f : ι → cardinal) : cardinal := mk (Π i, (f i).out)
@[simp] theorem prod_mk {ι} (f : ι → Type*) : prod (λ i, mk (f i)) = mk (Π i, f i) :=
quot.sound ⟨equiv.Pi_congr_right $ λ i,
classical.choice $ quotient.exact $ mk_out $ mk (f i)⟩
theorem prod_const (ι : Type u) (a : cardinal.{u}) : prod (λ _:ι, a) = a ^ mk ι :=
quotient.induction_on a $ by simp
theorem prod_le_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : prod f ≤ prod g :=
⟨embedding.Pi_congr_right $ λ i, classical.choice $
by have := H i; rwa [← mk_out (f i), ← mk_out (g i)] at this⟩
theorem prod_ne_zero {ι} (f : ι → cardinal) : prod f ≠ 0 ↔ ∀ i, f i ≠ 0 :=
begin
conv in (f _) {rw ← mk_out (f i)},
simp [prod, ne_zero_iff_nonempty, -mk_out, -ne.def],
exact ⟨λ ⟨F⟩ i, ⟨F i⟩, λ h, ⟨λ i, classical.choice (h i)⟩⟩,
end
theorem prod_eq_zero {ι} (f : ι → cardinal) : prod f = 0 ↔ ∃ i, f i = 0 :=
not_iff_not.1 $ by simpa using prod_ne_zero f
/-- The universe lift operation on cardinals. You can specify the universes explicitly with
`lift.{u v} : cardinal.{u} → cardinal.{max u v}` -/
def lift (c : cardinal.{u}) : cardinal.{max u v} :=
quotient.lift_on c (λ α, ⟦ulift α⟧) $ λ α β ⟨e⟩,
quotient.sound ⟨equiv.ulift.trans $ e.trans equiv.ulift.symm⟩
theorem lift_mk (α) : lift.{u v} (mk α) = mk (ulift.{v u} α) := rfl
theorem lift_umax : lift.{u (max u v)} = lift.{u v} :=
funext $ λ a, quot.induction_on a $ λ α,
quotient.sound ⟨equiv.ulift.trans equiv.ulift.symm⟩
theorem lift_id' (a : cardinal) : lift a = a :=
quot.induction_on a $ λ α, quot.sound ⟨equiv.ulift⟩
@[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u}
@[simp] theorem lift_lift (a : cardinal) : lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a :=
quot.induction_on a $ λ α,
quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩
theorem lift_mk_le {α : Type u} {β : Type v} :
lift.{u (max v w)} (mk α) ≤ lift.{v (max u w)} (mk β) ↔ nonempty (α ↪ β) :=
⟨λ ⟨f⟩, ⟨embedding.congr equiv.ulift equiv.ulift f⟩,
λ ⟨f⟩, ⟨embedding.congr equiv.ulift.symm equiv.ulift.symm f⟩⟩
theorem lift_mk_eq {α : Type u} {β : Type v} :
lift.{u (max v w)} (mk α) = lift.{v (max u w)} (mk β) ↔ nonempty (α ≃ β) :=
quotient.eq.trans
⟨λ ⟨f⟩, ⟨equiv.ulift.symm.trans $ f.trans equiv.ulift⟩,
λ ⟨f⟩, ⟨equiv.ulift.trans $ f.trans equiv.ulift.symm⟩⟩
@[simp] theorem lift_le {a b : cardinal} : lift a ≤ lift b ↔ a ≤ b :=
quotient.induction_on₂ a b $ λ α β,
by rw ← lift_umax; exact lift_mk_le
@[simp] theorem lift_inj {a b : cardinal} : lift a = lift b ↔ a = b :=
by simp [le_antisymm_iff]
@[simp] theorem lift_lt {a b : cardinal} : lift a < lift b ↔ a < b :=
by simp [lt_iff_le_not_le, -not_le]
@[simp] theorem lift_zero : lift 0 = 0 :=
quotient.sound ⟨equiv.ulift.trans equiv.pempty_equiv_pempty⟩
@[simp] theorem lift_one : lift 1 = 1 :=
quotient.sound ⟨equiv.ulift.trans equiv.punit_equiv_punit⟩
@[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b :=
quotient.induction_on₂ a b $ λ α β,
quotient.sound ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm⟩
@[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b :=
quotient.induction_on₂ a b $ λ α β,
quotient.sound ⟨equiv.ulift.trans (equiv.prod_congr equiv.ulift equiv.ulift).symm⟩
@[simp] theorem lift_power (a b) : lift (a ^ b) = lift a ^ lift b :=
quotient.induction_on₂ a b $ λ α β,
quotient.sound ⟨equiv.ulift.trans (equiv.arrow_congr equiv.ulift equiv.ulift).symm⟩
@[simp] theorem lift_two_power (a) : lift (2 ^ a) = 2 ^ lift a :=
by simp [bit0]
@[simp] theorem lift_min {ι I} (f : ι → cardinal) : lift (min I f) = min I (lift ∘ f) :=
le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $
let ⟨i, e⟩ := min_eq I (lift ∘ f) in
by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $
by have := min_le (lift ∘ f) j; rwa e at this)
theorem lift_down {a : cardinal.{u}} {b : cardinal.{max u v}} :
b ≤ lift a → ∃ a', lift a' = b :=
quotient.induction_on₂ a b $ λ α β,
by dsimp; rw [← lift_id (mk β), ← lift_umax, ← lift_umax.{u v}, lift_mk_le]; exact
λ ⟨f⟩, ⟨mk (set.range f), eq.symm $ lift_mk_eq.2
⟨embedding.equiv_of_surjective
(embedding.cod_restrict _ f set.mem_range_self)
$ λ ⟨a, ⟨b, e⟩⟩, ⟨b, subtype.eq e⟩⟩⟩
theorem le_lift_iff {a : cardinal.{u}} {b : cardinal.{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 : cardinal.{u}} {b : cardinal.{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⟩
@[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) :=
le_antisymm
(le_of_not_gt $ λ h, begin
rcases lt_lift_iff.1 h with ⟨b, e, h⟩,
rw [lt_succ, ← lift_le, e] at h,
exact not_lt_of_le h (lt_succ_self _)
end)
(succ_le.2 $ lift_lt.2 $ lt_succ_self _)
@[simp] theorem lift_max {a : cardinal.{u}} {b : cardinal.{v}} :
lift.{u (max v w)} a = lift.{v (max u w)} b ↔ lift.{u v} a = lift.{v u} b :=
calc lift.{u (max v w)} a = lift.{v (max u w)} b
↔ lift.{(max u v) w} (lift.{u v} a)
= lift.{(max u v) w} (lift.{v u} b) : by simp
... ↔ lift.{u v} a = lift.{v u} b : lift_inj
theorem mk_prod {α : Type u} {β : Type v} :
mk (α × β) = lift.{u v} (mk α) * lift.{v u} (mk β) :=
quotient.sound ⟨equiv.prod_congr (equiv.ulift).symm (equiv.ulift).symm⟩
theorem sum_const_eq_lift_mul (ι : Type u) (a : cardinal.{v}) :
sum (λ _:ι, a) = lift.{u v} (mk ι) * lift.{v u} a :=
begin
apply quotient.induction_on a,
intro α,
simp only [cardinal.mk_def, cardinal.sum_mk, cardinal.lift_id],
convert mk_prod using 1,
exact quotient.sound ⟨equiv.sigma_equiv_prod ι α⟩,
end
/-- `ω` is the smallest infinite cardinal, also known as ℵ₀. -/
def omega : cardinal.{u} := lift (mk ℕ)
lemma mk_nat : mk nat = omega := (lift_id _).symm
theorem omega_ne_zero : omega ≠ 0 :=
ne_zero_iff_nonempty.2 ⟨⟨0⟩⟩
theorem omega_pos : 0 < omega :=
pos_iff_ne_zero.2 omega_ne_zero
@[simp] theorem lift_omega : lift omega = omega := lift_lift _
/- properties about the cast from nat -/
@[simp] theorem mk_fin : ∀ (n : ℕ), mk (fin n) = n
| 0 := quotient.sound ⟨(equiv.pempty_of_not_nonempty $ λ ⟨h⟩, h.elim0)⟩
| (n+1) := by rw [nat.cast_succ, ← mk_fin]; exact
quotient.sound (fintype.card_eq.1 $ by simp)
@[simp] theorem lift_nat_cast (n : ℕ) : lift n = n :=
by induction n; simp *
lemma lift_eq_nat_iff {a : cardinal.{u}} {n : ℕ} : lift.{u v} a = n ↔ a = n :=
by rw [← lift_nat_cast.{u v} n, lift_inj]
lemma nat_eq_lift_eq_iff {n : ℕ} {a : cardinal.{u}} :
(n : cardinal) = lift.{u v} a ↔ (n : cardinal) = a :=
by rw [← lift_nat_cast.{u v} n, lift_inj]
theorem lift_mk_fin (n : ℕ) : lift (mk (fin n)) = n := by simp
theorem fintype_card (α : Type u) [fintype α] : mk α = fintype.card α :=
by rw [← lift_mk_fin.{u}, ← lift_id (mk α), lift_mk_eq.{u 0 u}];
exact fintype.card_eq.1 (by simp)
theorem card_le_of_finset {α} (s : finset α) :
(s.card : cardinal) ≤ cardinal.mk α :=
begin
rw (_ : (s.card : cardinal) = cardinal.mk (↑s : set α)),
{ exact ⟨function.embedding.subtype _⟩ },
rw [cardinal.fintype_card, fintype.card_coe]
end
@[simp, norm_cast] theorem nat_cast_pow {m n : ℕ} : (↑(pow m n) : cardinal) = m ^ n :=
by induction n; simp [nat.pow_succ, -_root_.add_comm, power_add, *]
@[simp, norm_cast] theorem nat_cast_le {m n : ℕ} : (m : cardinal) ≤ n ↔ m ≤ n :=
by rw [← lift_mk_fin, ← lift_mk_fin, lift_le]; exact
⟨λ ⟨⟨f, hf⟩⟩, begin
have : _ = fintype.card _ := finset.card_image_of_injective finset.univ hf,
simp at this,
rw [← fintype.card_fin n, ← this],
exact finset.card_le_of_subset (finset.subset_univ _)
end,
λ h, ⟨⟨λ i, ⟨i.1, lt_of_lt_of_le i.2 h⟩, λ a b h,
have _, from fin.veq_of_eq h, fin.eq_of_veq this⟩⟩⟩
@[simp, norm_cast] theorem nat_cast_lt {m n : ℕ} : (m : cardinal) < n ↔ m < n :=
by simp [lt_iff_le_not_le, -not_le]
@[simp, norm_cast] theorem nat_cast_inj {m n : ℕ} : (m : cardinal) = n ↔ m = n :=
by simp [le_antisymm_iff]
@[simp, norm_cast, priority 900] theorem nat_succ (n : ℕ) : (n.succ : cardinal) = succ n :=
le_antisymm (add_one_le_succ _) (succ_le.2 $ nat_cast_lt.2 $ nat.lt_succ_self _)
@[simp] theorem succ_zero : succ 0 = 1 :=
by norm_cast
theorem cantor' (a) {b : cardinal} (hb : 1 < b) : a < b ^ a :=
by rw [← succ_le, (by norm_cast : succ 1 = 2)] at hb;
exact lt_of_lt_of_le (cantor _) (power_le_power_right hb)
theorem one_le_iff_pos {c : cardinal} : 1 ≤ c ↔ 0 < c :=
by rw [← succ_zero, succ_le]
theorem one_le_iff_ne_zero {c : cardinal} : 1 ≤ c ↔ c ≠ 0 :=
by rw [one_le_iff_pos, pos_iff_ne_zero]
theorem nat_lt_omega (n : ℕ) : (n : cardinal.{u}) < omega :=
succ_le.1 $ by rw [← nat_succ, ← lift_mk_fin, omega, lift_mk_le.{0 0 u}]; exact
⟨⟨fin.val, λ a b, fin.eq_of_veq⟩⟩
@[simp] theorem one_lt_omega : 1 < omega :=
by simpa using nat_lt_omega 1
theorem lt_omega {c : cardinal.{u}} : c < omega ↔ ∃ n : ℕ, c = n :=
⟨λ h, begin
rcases lt_lift_iff.1 h with ⟨c, rfl, h'⟩,
rcases le_mk_iff_exists_set.1 h'.1 with ⟨S, rfl⟩,
suffices : finite S,
{ cases this, resetI,
existsi fintype.card S,
rw [← lift_nat_cast.{0 u}, lift_inj, fintype_card S] },
by_contra nf,
have P : ∀ (n : ℕ) (IH : ∀ i<n, S), ∃ a : S, ¬ ∃ y h, IH y h = a :=
λ n IH,
let g : {i | i < n} → S := λ ⟨i, h⟩, IH i h in
classical.not_forall.1 (λ h, nf
⟨fintype.of_surjective g (λ a, subtype.exists.2 (h a))⟩),
let F : ℕ → S := nat.lt_wf.fix (λ n IH, classical.some (P n IH)),
refine not_le_of_lt h' ⟨⟨F, _⟩⟩,
suffices : ∀ (n : ℕ) (m < n), F m ≠ F n,
{ refine λ m n, not_imp_not.1 (λ ne, _),
rcases lt_trichotomy m n with h|h|h,
{ exact this n m h },
{ contradiction },
{ exact (this m n h).symm } },
intros n m h,
have := classical.some_spec (P n (λ y _, F y)),
rw [← show F n = classical.some (P n (λ y _, F y)),
from nat.lt_wf.fix_eq (λ n IH, classical.some (P n IH)) n] at this,
exact λ e, this ⟨m, h, e⟩,
end, λ ⟨n, e⟩, e.symm ▸ nat_lt_omega _⟩
theorem omega_le {c : cardinal.{u}} : omega ≤ c ↔ ∀ n : ℕ, (n:cardinal) ≤ c :=
⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h,
λ h, le_of_not_lt $ λ hn, begin
rcases lt_omega.1 hn with ⟨n, rfl⟩,
exact not_le_of_lt (nat.lt_succ_self _) (nat_cast_le.1 (h (n+1)))
end⟩
theorem lt_omega_iff_fintype {α : Type u} : mk α < omega ↔ nonempty (fintype α) :=
lt_omega.trans ⟨λ ⟨n, e⟩, begin
rw [← lift_mk_fin n] at e,
cases quotient.exact e with f,
exact ⟨fintype.of_equiv _ f.symm⟩
end, λ ⟨_⟩, by exactI ⟨_, fintype_card _⟩⟩
theorem lt_omega_iff_finite {α} {S : set α} : mk S < omega ↔ finite S :=
lt_omega_iff_fintype
instance can_lift_cardinal_nat : can_lift cardinal ℕ :=
⟨ coe, λ x, x < omega, λ x hx, let ⟨n, hn⟩ := lt_omega.mp hx in ⟨n, hn.symm⟩⟩
theorem add_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a + b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega
end
lemma add_lt_omega_iff {a b : cardinal} : a + b < omega ↔ a < omega ∧ b < omega :=
⟨λ h, ⟨lt_of_le_of_lt (le_add_right _ _) h, lt_of_le_of_lt (le_add_left _ _) h⟩,
λ⟨h1, h2⟩, add_lt_omega h1 h2⟩
theorem mul_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a * b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_mul]; apply nat_lt_omega
end
lemma mul_lt_omega_iff {a b : cardinal} : a * b < omega ↔ a = 0 ∨ b = 0 ∨ a < omega ∧ b < omega :=
begin
split,
{ intro h, by_cases ha : a = 0, { left, exact ha },
right, by_cases hb : b = 0, { left, exact hb },
right, rw [← ne, ← one_le_iff_ne_zero] at ha hb, split,
{ rw [← mul_one a], refine lt_of_le_of_lt (mul_le_mul (le_refl a) hb) h },
{ rw [← _root_.one_mul b], refine lt_of_le_of_lt (mul_le_mul ha (le_refl b)) h }},
rintro (rfl|rfl|⟨ha,hb⟩); simp only [*, mul_lt_omega, omega_pos, _root_.zero_mul, mul_zero]
end
lemma mul_lt_omega_iff_of_ne_zero {a b : cardinal} (ha : a ≠ 0) (hb : b ≠ 0) :
a * b < omega ↔ a < omega ∧ b < omega :=
by simp [mul_lt_omega_iff, ha, hb]
theorem power_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_pow]; apply nat_lt_omega
end
lemma eq_one_iff_subsingleton_and_nonempty {α : Type*} :
mk α = 1 ↔ (subsingleton α ∧ nonempty α) :=
calc mk α = 1 ↔ mk α ≤ 1 ∧ ¬mk α < 1 : eq_iff_le_not_lt
... ↔ subsingleton α ∧ nonempty α :
begin
apply and_congr le_one_iff_subsingleton,
push_neg,
rw [one_le_iff_ne_zero, ne_zero_iff_nonempty]
end
theorem infinite_iff {α : Type u} : infinite α ↔ omega ≤ mk α :=
by rw [←not_lt, lt_omega_iff_fintype, not_nonempty_fintype]
lemma countable_iff (s : set α) : countable s ↔ mk s ≤ omega :=
begin
rw [countable_iff_exists_injective], split,
rintro ⟨f, hf⟩, exact ⟨embedding.trans ⟨f, hf⟩ equiv.ulift.symm.to_embedding⟩,
rintro ⟨f'⟩, cases embedding.trans f' equiv.ulift.to_embedding with f hf, exact ⟨f, hf⟩
end
lemma denumerable_iff {α : Type u} : nonempty (denumerable α) ↔ mk α = omega :=
⟨λ⟨h⟩, quotient.sound $ by exactI ⟨ (denumerable.eqv α).trans equiv.ulift.symm ⟩,
λ h, by { cases quotient.exact h with f, exact ⟨denumerable.mk' $ f.trans equiv.ulift⟩ }⟩
lemma mk_int : mk ℤ = omega :=
denumerable_iff.mp ⟨by apply_instance⟩
lemma mk_pnat : mk ℕ+ = omega :=
denumerable_iff.mp ⟨by apply_instance⟩
lemma two_le_iff : (2 : cardinal) ≤ mk α ↔ ∃x y : α, x ≠ y :=
begin
split,
{ rintro ⟨f⟩, refine ⟨f $ sum.inl ⟨⟩, f $ sum.inr ⟨⟩, _⟩, intro h, cases f.2 h },
{ rintro ⟨x, y, h⟩, by_contra h',
rw [not_le, ←nat.cast_two, nat_succ, lt_succ, nat.cast_one, le_one_iff_subsingleton] at h',
apply h, exactI subsingleton.elim _ _ }
end
lemma two_le_iff' (x : α) : (2 : cardinal) ≤ mk α ↔ ∃y : α, x ≠ y :=
begin
rw [two_le_iff],
split,
{ rintro ⟨y, z, h⟩, refine classical.by_cases (λ(h' : x = y), _) (λ h', ⟨y, h'⟩),
rw [←h'] at h, exact ⟨z, h⟩ },
{ rintro ⟨y, h⟩, exact ⟨x, y, h⟩ }
end
/-- König's theorem -/
theorem sum_lt_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i < g i) : sum f < prod g :=
lt_of_not_ge $ λ ⟨F⟩, begin
have : inhabited (Π (i : ι), (g i).out),
{ refine ⟨λ i, classical.choice $ ne_zero_iff_nonempty.1 _⟩,
rw mk_out,
exact ne_of_gt (lt_of_le_of_lt (zero_le _) (H i)) }, resetI,
let G := inv_fun F,
have sG : surjective G := inv_fun_surjective F.2,
choose C hc using show ∀ i, ∃ b, ∀ a, G ⟨i, a⟩ i ≠ b,
{ assume i,
simp only [- not_exists, not_exists.symm, classical.not_forall.symm],
refine λ h, not_le_of_lt (H i) _,
rw [← mk_out (f i), ← mk_out (g i)],
exact ⟨embedding.of_surjective _ h⟩ },
exact (let ⟨⟨i, a⟩, h⟩ := sG C in hc i a (congr_fun h _))
end
@[simp] theorem mk_empty : mk empty = 0 :=
fintype_card empty
@[simp] theorem mk_pempty : mk pempty = 0 :=
fintype_card pempty
@[simp] theorem mk_plift_of_false {p : Prop} (h : ¬ p) : mk (plift p) = 0 :=
quotient.sound ⟨equiv.plift.trans $ equiv.equiv_pempty h⟩
theorem mk_unit : mk unit = 1 :=
(fintype_card unit).trans nat.cast_one
@[simp] theorem mk_punit : mk punit = 1 :=
(fintype_card punit).trans nat.cast_one
@[simp] theorem mk_singleton {α : Type u} (x : α) : mk ({x} : set α) = 1 :=
quotient.sound ⟨equiv.set.singleton x⟩
@[simp] theorem mk_plift_of_true {p : Prop} (h : p) : mk (plift p) = 1 :=
quotient.sound ⟨equiv.plift.trans $ equiv.prop_equiv_punit h⟩
@[simp] theorem mk_bool : mk bool = 2 :=
quotient.sound ⟨equiv.bool_equiv_punit_sum_punit⟩
@[simp] theorem mk_Prop : mk Prop = 2 :=
(quotient.sound ⟨equiv.Prop_equiv_bool⟩ : mk Prop = mk bool).trans mk_bool
@[simp] theorem mk_option {α : Type u} : mk (option α) = mk α + 1 :=
quotient.sound ⟨equiv.option_equiv_sum_punit α⟩
theorem mk_list_eq_sum_pow (α : Type u) : mk (list α) = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) :=
calc mk (list α)
= mk (Σ n, vector α n) : quotient.sound ⟨(equiv.sigma_preimage_equiv list.length).symm⟩
... = mk (Σ n, fin n → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n,
⟨vector.nth, vector.of_fn, vector.of_fn_nth, λ f, funext $ vector.nth_of_fn f⟩⟩
... = mk (Σ n : ℕ, ulift.{u} (fin n) → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n,
equiv.arrow_congr equiv.ulift.symm (equiv.refl α)⟩
... = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) : by simp only [(lift_mk_fin _).symm, lift_mk, power_def, sum_mk]
theorem mk_quot_le {α : Type u} {r : α → α → Prop} : mk (quot r) ≤ mk α :=
mk_le_of_surjective quot.exists_rep
theorem mk_quotient_le {α : Type u} {s : setoid α} : mk (quotient s) ≤ mk α :=
mk_quot_le
theorem mk_subtype_le {α : Type u} (p : α → Prop) : mk (subtype p) ≤ mk α :=
⟨embedding.subtype p⟩
theorem mk_subtype_le_of_subset {α : Type u} {p q : α → Prop} (h : ∀ ⦃x⦄, p x → q x) :
mk (subtype p) ≤ mk (subtype q) :=
⟨embedding.subtype_map (embedding.refl α) h⟩
@[simp] theorem mk_emptyc (α : Type u) : mk (∅ : set α) = 0 :=
quotient.sound ⟨equiv.set.pempty α⟩
lemma mk_emptyc_iff {α : Type u} {s : set α} : mk s = 0 ↔ s = ∅ :=
begin
split,
{ intro h,
have h2 : cardinal.mk s = cardinal.mk pempty, by simp [h],
refine set.eq_empty_iff_forall_not_mem.mpr (λ _ hx, _),
rcases cardinal.eq.mp h2 with ⟨f, _⟩,
cases f ⟨_, hx⟩ },
{ intro, convert mk_emptyc _ }
end
theorem mk_univ {α : Type u} : mk (@univ α) = mk α :=
quotient.sound ⟨equiv.set.univ α⟩
theorem mk_image_le {α β : Type u} {f : α → β} {s : set α} : mk (f '' s) ≤ mk s :=
mk_le_of_surjective surjective_onto_image
theorem mk_image_le_lift {α : Type u} {β : Type v} {f : α → β} {s : set α} :
lift.{v u} (mk (f '' s)) ≤ lift.{u v} (mk s) :=
lift_mk_le.{v u 0}.mpr ⟨embedding.of_surjective _ surjective_onto_image⟩
theorem mk_range_le {α β : Type u} {f : α → β} : mk (range f) ≤ mk α :=
mk_le_of_surjective surjective_onto_range
lemma mk_range_eq (f : α → β) (h : injective f) : mk (range f) = mk α :=
quotient.sound ⟨(equiv.set.range f h).symm⟩
lemma mk_range_eq_of_injective {α : Type u} {β : Type v} {f : α → β} (hf : injective f) :
lift.{v u} (mk (range f)) = lift.{u v} (mk α) :=
begin
have := (@lift_mk_eq.{v u max u v} (range f) α).2 ⟨(equiv.set.range f hf).symm⟩,
simp only [lift_umax.{u v}, lift_umax.{v u}] at this,
exact this
end
lemma mk_range_eq_lift {α : Type u} {β : Type v} {f : α → β} (hf : injective f) :
lift.{v (max u w)} (# (range f)) = lift.{u (max v w)} (# α) :=
lift_mk_eq.mpr ⟨(equiv.set.range f hf).symm⟩
theorem mk_image_eq {α β : Type u} {f : α → β} {s : set α} (hf : injective f) :
mk (f '' s) = mk s :=
quotient.sound ⟨(equiv.set.image f s hf).symm⟩
theorem mk_Union_le_sum_mk {α ι : Type u} {f : ι → set α} : mk (⋃ i, f i) ≤ sum (λ i, mk (f i)) :=
calc mk (⋃ i, f i) ≤ mk (Σ i, f i) : mk_le_of_surjective (set.sigma_to_Union_surjective f)
... = sum (λ i, mk (f i)) : (sum_mk _).symm
theorem mk_Union_eq_sum_mk {α ι : Type u} {f : ι → set α} (h : ∀i j, i ≠ j → disjoint (f i) (f j)) :
mk (⋃ i, f i) = sum (λ i, mk (f i)) :=
calc mk (⋃ i, f i) = mk (Σi, f i) : quot.sound ⟨set.Union_eq_sigma_of_disjoint h⟩
... = sum (λi, mk (f i)) : (sum_mk _).symm
lemma mk_Union_le {α ι : Type u} (f : ι → set α) :
mk (⋃ i, f i) ≤ mk ι * cardinal.sup.{u u} (λ i, mk (f i)) :=
le_trans mk_Union_le_sum_mk (sum_le_sup _)
lemma mk_sUnion_le {α : Type u} (A : set (set α)) :
mk (⋃₀ A) ≤ mk A * cardinal.sup.{u u} (λ s : A, mk s) :=
by { rw [sUnion_eq_Union], apply mk_Union_le }
lemma mk_bUnion_le {ι α : Type u} (A : ι → set α) (s : set ι) :
mk (⋃(x ∈ s), A x) ≤ mk s * cardinal.sup.{u u} (λ x : s, mk (A x.1)) :=
by { rw [bUnion_eq_Union], apply mk_Union_le }
@[simp] lemma finset_card {α : Type u} {s : finset α} : ↑(finset.card s) = mk (↑s : set α) :=
by rw [fintype_card, nat_cast_inj, fintype.card_coe]
lemma finset_card_lt_omega (s : finset α) : mk (↑s : set α) < omega :=
by { rw [lt_omega_iff_fintype], exact ⟨finset.subtype.fintype s⟩ }
theorem mk_union_add_mk_inter {α : Type u} {S T : set α} :
mk (S ∪ T : set α) + mk (S ∩ T : set α) = mk S + mk T :=
quot.sound ⟨equiv.set.union_sum_inter S T⟩
/-- The cardinality of a union is at most the sum of the cardinalities
of the two sets. -/
lemma mk_union_le {α : Type u} (S T : set α) : mk (S ∪ T : set α) ≤ mk S + mk T :=
@mk_union_add_mk_inter α S T ▸ le_add_right (mk (S ∪ T : set α)) (mk (S ∩ T : set α))
theorem mk_union_of_disjoint {α : Type u} {S T : set α} (H : disjoint S T) :
mk (S ∪ T : set α) = mk S + mk T :=
quot.sound ⟨equiv.set.union H⟩
lemma mk_sum_compl {α} (s : set α) : #s + #(sᶜ : set α) = #α :=
quotient.sound ⟨equiv.set.sum_compl s⟩
lemma mk_le_mk_of_subset {α} {s t : set α} (h : s ⊆ t) : mk s ≤ mk t :=
⟨set.embedding_of_subset s t h⟩
lemma mk_subtype_mono {p q : α → Prop} (h : ∀x, p x → q x) : mk {x // p x} ≤ mk {x // q x} :=
⟨embedding_of_subset _ _ h⟩
lemma mk_set_le (s : set α) : mk s ≤ mk α :=
mk_subtype_le s
lemma mk_image_eq_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : injective f) :
lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) :=
lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image f s h).symm⟩
lemma mk_image_eq_of_inj_on_lift {α : Type u} {β : Type v} (f : α → β) (s : set α)
(h : inj_on f s) : lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) :=
lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image_of_inj_on f s h).symm⟩
lemma mk_image_eq_of_inj_on {α β : Type u} (f : α → β) (s : set α) (h : inj_on f s) :
mk (f '' s) = mk s :=
quotient.sound ⟨(equiv.set.image_of_inj_on f s h).symm⟩
lemma mk_subtype_of_equiv {α β : Type u} (p : β → Prop) (e : α ≃ β) :
mk {a : α // p (e a)} = mk {b : β // p b} :=
quotient.sound ⟨equiv.subtype_equiv_of_subtype e⟩
lemma mk_sep (s : set α) (t : α → Prop) : mk ({ x ∈ s | t x } : set α) = mk { x : s | t x.1 } :=
quotient.sound ⟨equiv.set.sep s t⟩
lemma mk_preimage_of_injective_lift {α : Type u} {β : Type v} (f : α → β) (s : set β)
(h : injective f) : lift.{u v} (mk (f ⁻¹' s)) ≤ lift.{v u} (mk s) :=
begin
rw lift_mk_le.{u v 0}, use subtype.coind (λ x, f x.1) (λ x, x.2),
apply subtype.coind_injective, exact h.comp subtype.val_injective
end
lemma mk_preimage_of_subset_range_lift {α : Type u} {β : Type v} (f : α → β) (s : set β)
(h : s ⊆ range f) : lift.{v u} (mk s) ≤ lift.{u v} (mk (f ⁻¹' s)) :=
begin
rw lift_mk_le.{v u 0},
refine ⟨⟨_, _⟩⟩,
{ rintro ⟨y, hy⟩, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, exact ⟨x, hy⟩ },
rintro ⟨y, hy⟩ ⟨y', hy'⟩, dsimp,
rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩,
rcases classical.subtype_of_exists (h hy') with ⟨x', rfl⟩,
simp, intro hxx', rw hxx'
end
lemma mk_preimage_of_injective_of_subset_range_lift {β : Type v} (f : α → β) (s : set β)
(h : injective f) (h2 : s ⊆ range f) : lift.{u v} (mk (f ⁻¹' s)) = lift.{v u} (mk s) :=
le_antisymm (mk_preimage_of_injective_lift f s h) (mk_preimage_of_subset_range_lift f s h2)
lemma mk_preimage_of_injective (f : α → β) (s : set β) (h : injective f) :
mk (f ⁻¹' s) ≤ mk s :=
by { convert mk_preimage_of_injective_lift.{u u} f s h using 1; rw [lift_id] }
lemma mk_preimage_of_subset_range (f : α → β) (s : set β)
(h : s ⊆ range f) : mk s ≤ mk (f ⁻¹' s) :=
by { convert mk_preimage_of_subset_range_lift.{u u} f s h using 1; rw [lift_id] }
lemma mk_preimage_of_injective_of_subset_range (f : α → β) (s : set β)
(h : injective f) (h2 : s ⊆ range f) : mk (f ⁻¹' s) = mk s :=
by { convert mk_preimage_of_injective_of_subset_range_lift.{u u} f s h h2 using 1; rw [lift_id] }
lemma mk_subset_ge_of_subset_image_lift {α : Type u} {β : Type v} (f : α → β) {s : set α}
{t : set β} (h : t ⊆ f '' s) :
lift.{v u} (mk t) ≤ lift.{u v} (mk ({ x ∈ s | f x ∈ t } : set α)) :=
by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range_lift _ _ h using 1, rw [mk_sep], refl }
lemma mk_subset_ge_of_subset_image (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) :
mk t ≤ mk ({ x ∈ s | f x ∈ t } : set α) :=
by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range _ _ h using 1, rw [mk_sep], refl }
theorem le_mk_iff_exists_subset {c : cardinal} {α : Type u} {s : set α} :
c ≤ mk s ↔ ∃ p : set α, p ⊆ s ∧ mk p = c :=
begin
rw [le_mk_iff_exists_set, ←subtype.exists_set_subtype],
apply exists_congr, intro t, rw [mk_image_eq], apply subtype.val_injective
end
/-- The function α^{<β}, defined to be sup_{γ < β} α^γ.
We index over {s : set β.out // mk s < β } instead of {γ // γ < β}, because the latter lives in a
higher universe -/
noncomputable def powerlt (α β : cardinal.{u}) : cardinal.{u} :=
sup.{u u} (λ(s : {s : set β.out // mk s < β}), α ^ mk.{u} s)
infix ` ^< `:80 := powerlt
theorem powerlt_aux {c c' : cardinal} (h : c < c') :
∃(s : {s : set c'.out // mk s < c'}), mk s = c :=
begin
cases out_embedding.mp (le_of_lt h) with f,
have : mk ↥(range ⇑f) = c, { rwa [mk_range_eq, mk, quotient.out_eq c], exact f.2 },
exact ⟨⟨range f, by convert h⟩, this⟩
end
lemma le_powerlt {c₁ c₂ c₃ : cardinal} (h : c₂ < c₃) : c₁ ^ c₂ ≤ c₁ ^< c₃ :=
by { rcases powerlt_aux h with ⟨s, rfl⟩, apply le_sup _ s }
lemma powerlt_le {c₁ c₂ c₃ : cardinal} : c₁ ^< c₂ ≤ c₃ ↔ ∀(c₄ < c₂), c₁ ^ c₄ ≤ c₃ :=
begin
rw [powerlt, sup_le],
split,
{ intros h c₄ hc₄, rcases powerlt_aux hc₄ with ⟨s, rfl⟩, exact h s },
intros h s, exact h _ s.2
end
lemma powerlt_le_powerlt_left {a b c : cardinal} (h : b ≤ c) : a ^< b ≤ a ^< c :=
by { rw [powerlt, sup_le], rintro ⟨s, hs⟩, apply le_powerlt, exact lt_of_lt_of_le hs h }
lemma powerlt_succ {c₁ c₂ : cardinal} (h : c₁ ≠ 0) : c₁ ^< c₂.succ = c₁ ^ c₂ :=
begin
apply le_antisymm,
{ rw powerlt_le, intros c₃ h2, apply power_le_power_left h, rwa [←lt_succ] },
{ apply le_powerlt, apply lt_succ_self }
end
lemma powerlt_max {c₁ c₂ c₃ : cardinal} : c₁ ^< max c₂ c₃ = max (c₁ ^< c₂) (c₁ ^< c₃) :=
by { cases le_total c₂ c₃; simp only [max_eq_left, max_eq_right, h, powerlt_le_powerlt_left] }
lemma zero_powerlt {a : cardinal} (h : a ≠ 0) : 0 ^< a = 1 :=
begin
apply le_antisymm,
{ rw [powerlt_le], intros c hc, apply zero_power_le },
convert le_powerlt (pos_iff_ne_zero.2 h), rw [power_zero]
end
lemma powerlt_zero {a : cardinal} : a ^< 0 = 0 :=
by { apply sup_eq_zero, rintro ⟨x, hx⟩, rw [←not_le] at hx, apply hx, apply zero_le }
end cardinal
|
92da2ce56c3b24ccd8e64a8fa22cb800010eac68 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/pp_zero_bug.lean | 11803d963a4c23834c282282e423f0401d738660 | [
"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 | 48 | lean | #check @has_zero.zero
#check @has_zero.zero nat
|
11c87e400fadb403918d78516bd46abed6cd35ec | 432d948a4d3d242fdfb44b81c9e1b1baacd58617 | /src/algebra/big_operators/basic.lean | 8549610f1ea183f692c600c5f07311e187b4e13a | [
"Apache-2.0"
] | permissive | JLimperg/aesop3 | 306cc6570c556568897ed2e508c8869667252e8a | a4a116f650cc7403428e72bd2e2c4cda300fe03f | refs/heads/master | 1,682,884,916,368 | 1,620,320,033,000 | 1,620,320,033,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 59,842 | 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.fold
import data.equiv.mul_add
import tactic.abel
/-!
# 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}
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
@[simp, to_additive] lemma prod_mk [comm_monoid β] (s : multiset α) (hs) (f : α → β) :
(⟨s, hs⟩ : finset α).prod f = (s.map f).prod :=
rfl
end finset
/--
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*.)
-/
library_note "operator precedence of big operators"
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
@[simp] lemma sum_multiset_singleton (s : finset α) :
s.sum (λ x, x ::ₘ 0) = s.val :=
by simp [sum_eq_multiset_sum]
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]
@[to_additive]
lemma mul_equiv.map_prod [comm_monoid β] [comm_monoid γ] (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_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
@[to_additive]
lemma monoid_hom.coe_prod [mul_one_class β] [comm_monoid γ] (f : α → β →* γ) (s : finset α) :
⇑(∏ x in s, f x) = ∏ x in s, f x :=
(monoid_hom.coe_fn β γ).map_prod _ _
-- See also `finset.prod_apply`, with the same conclusion
-- but with the weaker hypothesis `f : α → β → γ`.
@[simp, to_additive]
lemma monoid_hom.finset_prod_apply [mul_one_class β] [comm_monoid γ] (f : α → β →* γ)
(s : finset α) (b : β) : (∏ x in s, f x) b = ∏ x in s, f x b :=
(monoid_hom.eval b).map_prod _ _
variables {s s₁ s₂ : finset α} {a : α} {f g : α → β}
namespace finset
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
/--
The product of `f` over `insert a s` is the same as
the product over `s`, as long as `a` is in `s` or `f a = 1`.
-/
@[simp, to_additive "The sum of `f` over `insert a s` is the same as
the sum over `s`, as long as `a` is in `s` or `f a = 0`."]
lemma prod_insert_of_eq_one_if_not_mem [decidable_eq α] (h : a ∉ s → f a = 1) :
∏ x in insert a s, f x = ∏ x in s, f x :=
begin
by_cases hm : a ∈ s,
{ simp_rw insert_eq_of_mem hm },
{ rw [prod_insert hm, h hm, one_mul] },
end
/--
The product of `f` over `insert a s` is the same as the product over `s`, as long as `f a = 1`.
-/
@[simp, to_additive "The sum of `f` over `insert a s` is the same as
the sum over `s`, as long as `f a = 0`."]
lemma prod_insert_one [decidable_eq α] (h : f a = 1) :
∏ x in insert a s, f x = ∏ x in s, f x :=
prod_insert_of_eq_one_if_not_mem (λ _, h)
@[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
end comm_monoid
end finset
section
open finset
variables [fintype α] [decidable_eq α] [comm_monoid β]
@[to_additive]
lemma is_compl.prod_mul_prod {s t : finset α} (h : is_compl s t) (f : α → β) :
(∏ i in s, f i) * (∏ i in t, f i) = ∏ i, f i :=
(finset.prod_union h.disjoint).symm.trans $ by rw [← finset.sup_eq_union, h.sup_eq_top]; refl
end
namespace finset
section comm_monoid
variables [comm_monoid β]
@[to_additive]
lemma prod_mul_prod_compl [fintype α] [decidable_eq α] (s : finset α) (f : α → β) :
(∏ i in s, f i) * (∏ i in sᶜ, f i) = ∏ i, f i :=
is_compl_compl.prod_mul_prod f
@[to_additive]
lemma prod_compl_mul_prod [fintype α] [decidable_eq α] (s : finset α) (f : α → β) :
(∏ i in sᶜ, f i) * (∏ i in s, f i) = ∏ i, f i :=
is_compl_compl.symm.prod_mul_prod f
@[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.map function.embedding.inl ∪ t.map function.embedding.inr, sum.elim f g x =
(∏ x in s, f x) * (∏ x in t, g x) :=
begin
rw [prod_union, prod_map, prod_map],
{ simp only [sum.elim_inl, function.embedding.inl_apply, function.embedding.inr_apply,
sum.elim_inr] },
{ simp only [disjoint_left, finset.mem_map, finset.mem_map],
rintros _ ⟨i, hi, rfl⟩ ⟨j, hj, H⟩,
cases H }
end
@[to_additive]
lemma prod_bUnion [decidable_eq α] {s : finset γ} {t : γ → finset α} :
(∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y)) →
(∏ x in (s.bUnion 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 [bUnion_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.bUnion s t),
from (disjoint_bUnion_right _ _ _).mpr this,
by simp only [bUnion_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_bUnion, prod_bUnion],
{ congr, funext, exact prod_image (λ _ _ _ _ H, (prod.mk.inj H).2) },
simp only [disjoint_iff_ne, mem_image],
rintros _ _ _ _ h ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ _,
apply h, cc
end
/-- An uncurried version of `finset.prod_product`. -/
@[to_additive "An uncurried version of `finset.sum_product`"]
lemma prod_product' {s : finset γ} {t : finset α} {f : γ → α → β} :
(∏ x in s.product t, f x.1 x.2) = ∏ x in s, ∏ y in t, f x y :=
prod_product
/-- Product over a sigma type equals the product of fiberwise products. For rewriting
in the reverse direction, use `finset.prod_sigma'`. -/
@[to_additive "Sum over a sigma type equals the sum of fiberwise sums. For rewriting
in the reverse direction, use `finset.sum_sigma'`"]
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 classical;
calc (∏ x in s.sigma t, f x) =
∏ x in s.bUnion (λa, (t a).map (function.embedding.sigma_mk a)), f x : by rw sigma_eq_bUnion
... = ∏ a in s, ∏ x in (t a).map (function.embedding.sigma_mk a), f x :
prod_bUnion $ assume a₁ ha a₂ ha₂ h x hx,
by { simp only [inf_eq_inter, mem_inter, mem_map, function.embedding.sigma_mk_apply] at hx,
rcases hx with ⟨⟨y, hy, rfl⟩, ⟨z, hz, hz'⟩⟩, cc }
... = ∏ a in s, ∏ s in t a, f ⟨a, s⟩ :
prod_congr rfl $ λ _ _, prod_map _ _ _
@[to_additive]
lemma prod_sigma' {σ : α → Type*}
(s : finset α) (t : Πa, finset (σ a)) (f : Πa, σ a → β) :
(∏ a in s, ∏ s in (t a), f a s) = ∏ x in s.sigma t, f x.1 x.2 :=
eq.symm $ prod_sigma s t (λ x, f x.1 x.2)
@[to_additive]
lemma prod_fiberwise_of_maps_to [decidable_eq γ] {s : finset α} {t : finset γ} {g : α → γ}
(h : ∀ x ∈ s, g x ∈ t) (f : α → β) :
(∏ y in t, ∏ x in s.filter (λ x, g x = y), f x) = ∏ x in s, f x :=
begin
letI := classical.dec_eq α,
rw [← bUnion_filter_eq_of_maps_to h] {occs := occurrences.pos [2]},
refine (prod_bUnion $ λ x' hx y' hy hne, _).symm,
rw [disjoint_filter],
rintros x hx rfl,
exact hne
end
@[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 :=
calc (∏ x in s.image g, f x) = ∏ x in s.image g, ∏ x in s.filter (λ c', g c' = x), h x :
prod_congr rfl $ λ x hx, let ⟨c, hcs, hc⟩ := mem_image.1 hx in hc ▸ (eq c hcs)
... = ∏ x in s, h x : prod_fiberwise_of_maps_to (λ x, mem_image_of_mem g) _
@[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]
@[to_additive]
lemma prod_filter_of_ne {p : α → Prop} [decidable_pred p] (hp : ∀ x ∈ s, f x ≠ 1 → p x) :
(∏ x in (s.filter p), f x) = (∏ x in s, f x) :=
prod_subset (filter_subset _ _) $ λ x,
by { classical, rw [not_imp_comm, mem_filter], exact λ h₁ h₂, ⟨h₁, hp _ h₁ h₂⟩ }
-- 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_filter_of_ne $ λ _ _, id
@[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_of_mem {s : finset α} {f : α → β} (a : α) (h : a ∈ s)
(h₀ : ∀ b ∈ s, b ≠ a → f b = 1) : (∏ x in s, f x) = f a :=
begin
haveI := classical.dec_eq α,
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
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, prod_eq_single_of_mem a this h₀)
(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_eq_mul_of_mem {s : finset α} {f : α → β} (a b : α) (ha : a ∈ s) (hb : b ∈ s) (hn : a ≠ b)
(h₀ : ∀ c ∈ s, c ≠ a ∧ c ≠ b → f c = 1) : (∏ x in s, f x) = (f a) * (f b) :=
begin
haveI := classical.dec_eq α;
let s' := ({a, b} : finset α),
have hu : s' ⊆ s,
{ refine insert_subset.mpr _, apply and.intro ha, apply singleton_subset_iff.mpr hb },
have hf : ∀ c ∈ s, c ∉ s' → f c = 1,
{ intros c hc hcs,
apply h₀ c hc,
apply not_or_distrib.mp,
intro hab,
apply hcs,
apply mem_insert.mpr,
rw mem_singleton,
exact hab },
rw ←prod_subset hu hf,
exact finset.prod_pair hn
end
@[to_additive]
lemma prod_eq_mul {s : finset α} {f : α → β} (a b : α) (hn : a ≠ b)
(h₀ : ∀ c ∈ s, c ≠ a ∧ c ≠ b → f c = 1) (ha : a ∉ s → f a = 1) (hb : b ∉ s → f b = 1) :
(∏ x in s, f x) = (f a) * (f b) :=
begin
haveI := classical.dec_eq α;
by_cases h₁ : a ∈ s; by_cases h₂ : b ∈ s,
{ exact prod_eq_mul_of_mem a b h₁ h₂ hn h₀ },
{ rw [hb h₂, mul_one],
apply prod_eq_single_of_mem a h₁,
exact λ c hc hca, h₀ c hc ⟨hca, ne_of_mem_of_not_mem hc h₂⟩ },
{ rw [ha h₁, one_mul],
apply prod_eq_single_of_mem b h₂,
exact λ c hc hcb, h₀ c hc ⟨ne_of_mem_of_not_mem hc h₁, hcb⟩ },
{ rw [ha h₁, hb h₂, mul_one],
exact trans
(prod_congr rfl (λ c hc, h₀ c hc ⟨ne_of_mem_of_not_mem hc h₁, ne_of_mem_of_not_mem hc h₂⟩))
prod_const_one }
end
@[to_additive]
lemma prod_attach {f : α → β} : (∏ x in s.attach, f x) = (∏ 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]
/-- A product over `s.subtype p` equals one over `s.filter p`. -/
@[simp, to_additive "A sum over `s.subtype p` equals one over `s.filter p`."]
lemma prod_subtype_eq_prod_filter (f : α → β) {p : α → Prop} [decidable_pred p] :
∏ x in s.subtype p, f x = ∏ x in s.filter p, f x :=
begin
conv_lhs {
erw ←prod_map (s.subtype p) (function.embedding.subtype _) f
},
exact prod_congr (subtype_map _) (λ x hx, rfl)
end
/-- If all elements of a `finset` satisfy the predicate `p`, a product
over `s.subtype p` equals that product over `s`. -/
@[to_additive "If all elements of a `finset` satisfy the predicate `p`, a sum
over `s.subtype p` equals that sum over `s`."]
lemma prod_subtype_of_mem (f : α → β) {p : α → Prop} [decidable_pred p]
(h : ∀ x ∈ s, p x) : ∏ x in s.subtype p, f x = ∏ x in s, f x :=
by simp_rw [prod_subtype_eq_prod_filter, filter_true_of_mem h]
/-- A product of a function over a `finset` in a subtype equals a
product in the main type of a function that agrees with the first
function on that `finset`. -/
@[to_additive "A sum of a function over a `finset` in a subtype equals a
sum in the main type of a function that agrees with the first
function on that `finset`."]
lemma prod_subtype_map_embedding {p : α → Prop} {s : finset {x // p x}} {f : {x // p x} → β}
{g : α → β} (h : ∀ x : {x // p x}, x ∈ s → g x = f x) :
∏ x in s.map (function.embedding.subtype _), g x = ∏ x in s, f x :=
begin
rw finset.prod_map,
exact finset.prod_congr rfl h
end
@[to_additive]
lemma prod_finset_coe (f : α → β) (s : finset α) :
∏ (i : (s : set α)), f i = ∏ i in s, f i :=
prod_attach
@[to_additive]
lemma prod_subtype {p : α → Prop} {F : fintype (subtype p)} (s : finset α)
(h : ∀ x, x ∈ s ↔ p x) (f : α → β) :
∏ a in s, f a = ∏ a : subtype p, f a :=
have (∈ s) = p, from set.ext h, by { substI p, rw [←prod_finset_coe], congr }
@[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
@[to_additive] lemma prod_apply_dite {s : finset α} {p : α → Prop} {hp : decidable_pred p}
(f : Π (x : α), p x → γ) (g : Π (x : α), ¬p x → γ) (h : γ → β) :
(∏ x in s, h (if hx : p x then f x hx else g x hx)) =
(∏ x in (s.filter p).attach, h (f x.1 (mem_filter.mp x.2).2)) *
(∏ x in (s.filter (λ x, ¬ p x)).attach, h (g x.1 (mem_filter.mp x.2).2)) :=
by letI := classical.dec_eq α; exact
calc ∏ x in s, h (if hx : p x then f x hx else g x hx)
= ∏ x in s.filter p ∪ s.filter (λ x, ¬ p x), h (if hx : p x then f x hx else g x hx) :
by rw [filter_union_filter_neg_eq]
... = (∏ x in s.filter p, h (if hx : p x then f x hx else g x hx)) *
(∏ x in s.filter (λ x, ¬ p x), h (if hx : p x then f x hx else g x hx)) :
prod_union (by simp [disjoint_right] {contextual := tt})
... = (∏ x in (s.filter p).attach, h (if hx : p x.1 then f x.1 hx else g x.1 hx)) *
(∏ x in (s.filter (λ x, ¬ p x)).attach, h (if hx : p x.1 then f x.1 hx else g x.1 hx)) :
congr_arg2 _ prod_attach.symm prod_attach.symm
... = (∏ x in (s.filter p).attach, h (f x.1 (mem_filter.mp x.2).2)) *
(∏ x in (s.filter (λ x, ¬ p x)).attach, h (g x.1 (mem_filter.mp x.2).2)) :
congr_arg2 _
(prod_congr rfl (λ x hx, congr_arg h (dif_pos (mem_filter.mp x.2).2)))
(prod_congr rfl (λ x hx, congr_arg h (dif_neg (mem_filter.mp x.2).2)))
@[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)) :=
trans (prod_apply_dite _ _ _)
(congr_arg2 _ (@prod_attach _ _ _ _ (h ∘ f)) (@prod_attach _ _ _ _ (h ∘ g)))
@[to_additive] lemma prod_dite {s : finset α} {p : α → Prop} {hp : decidable_pred p}
(f : Π (x : α), p x → β) (g : Π (x : α), ¬p x → β) :
(∏ x in s, if hx : p x then f x hx else g x hx) =
(∏ x in (s.filter p).attach, f x.1 (mem_filter.mp x.2).2) *
(∏ x in (s.filter (λ x, ¬ p x)).attach, g x.1 (mem_filter.mp x.2).2) :=
by simp [prod_apply_dite _ _ (λ x, x)]
@[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)]
@[to_additive] lemma prod_ite_of_false {p : α → Prop} {hp : decidable_pred p} (f g : α → β)
(h : ∀ x ∈ s, ¬p x) : (∏ x in s, if p x then f x else g x) = (∏ x in s, g x) :=
by { rw prod_ite, simp [filter_false_of_mem h, filter_true_of_mem h] }
@[to_additive] lemma prod_ite_of_true {p : α → Prop} {hp : decidable_pred p} (f g : α → β)
(h : ∀ x ∈ s, p x) : (∏ x in s, if p x then f x else g x) = (∏ x in s, f x) :=
by { simp_rw ←(ite_not (p _)), apply prod_ite_of_false, simpa }
@[to_additive] lemma prod_apply_ite_of_false {p : α → Prop} {hp : decidable_pred p} (f g : α → γ)
(k : γ → β) (h : ∀ x ∈ s, ¬p x) :
(∏ x in s, k (if p x then f x else g x)) = (∏ x in s, k (g x)) :=
by { simp_rw apply_ite k, exact prod_ite_of_false _ _ h }
@[to_additive] lemma prod_apply_ite_of_true {p : α → Prop} {hp : decidable_pred p} (f g : α → γ)
(k : γ → β) (h : ∀ x ∈ s, p x) :
(∏ x in s, k (if p x then f x else g x)) = (∏ x in s, k (f x)) :=
by { simp_rw apply_ite k, exact prod_ite_of_true _ _ h }
@[to_additive]
lemma prod_extend_by_one [decidable_eq α] (s : finset α) (f : α → β) :
∏ i in s, (if i ∈ s then f i else 1) = ∏ i in s, f i :=
prod_congr rfl $ λ i hi, if_pos hi
@[simp, to_additive]
lemma prod_dite_eq [decidable_eq α] (s : finset α) (a : α) (b : Π x : α, a = x → β) :
(∏ x in s, (if h : a = x then b x h else 1)) = ite (a ∈ s) (b a rfl) 1 :=
begin
split_ifs with h,
{ rw [finset.prod_eq_single a, dif_pos rfl],
{ intros, rw dif_neg, cc },
{ cc } },
{ rw finset.prod_eq_one,
intros, rw dif_neg, intro, cc }
end
@[simp, to_additive]
lemma prod_dite_eq' [decidable_eq α] (s : finset α) (a : α) (b : Π x : α, x = a → β) :
(∏ x in s, (if h : x = a then b x h else 1)) = ite (a ∈ s) (b a rfl) 1 :=
begin
split_ifs with h,
{ rw [finset.prod_eq_single a, dif_pos rfl],
{ intros, rw dif_neg, cc },
{ cc } },
{ rw finset.prod_eq_one,
intros, rw dif_neg, intro, cc }
end
@[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 :=
prod_dite_eq s a (λ x _, b x)
/--
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 :=
prod_dite_eq' s a (λ x _, b x)
@[to_additive]
lemma prod_ite_index (p : Prop) [decidable p] (s t : finset α) (f : α → β) :
(∏ x in if p then s else t, f x) = if p then ∏ x in s, f x else ∏ x in t, f x :=
apply_ite (λ s, ∏ x in s, f x) _ _ _
@[simp, to_additive]
lemma prod_dite_irrel (p : Prop) [decidable p] (s : finset α) (f : p → α → β) (g : ¬p → α → β):
(∏ x in s, if h : p then f h x else g h x) = if h : p then ∏ x in s, f h x else ∏ x in s, g h x :=
by { split_ifs with h; refl }
@[simp] lemma sum_pi_single' {ι M : Type*} [decidable_eq ι] [add_comm_monoid M]
(i : ι) (x : M) (s : finset ι) :
∑ j in s, pi.single i x j = if i ∈ s then x else 0 :=
sum_dite_eq' _ _ _
@[simp] lemma sum_pi_single {ι : Type*} {M : ι → Type*}
[decidable_eq ι] [Π i, add_comm_monoid (M i)] (i : ι) (f : Π i, M i) (s : finset ι) :
∑ j in s, pi.single j (f j) i = if i ∈ s then f i else 0 :=
sum_dite_eq _ _ _
/--
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 "
Reorder a sum.
The difference with `sum_bij'` is that the bijection is specified as a surjective injection,
rather than by an inverse function.
"]
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 "
Reorder a sum.
The difference with `sum_bij` is that the bijection is specified with an inverse, rather than
as a surjective injection.
"]
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)
(i_inj : ∀a₁ a₂ h₁₁ h₁₂ h₂₁ h₂₂, i a₁ h₁₁ h₁₂ = i a₂ h₂₁ h₂₂ → a₁ = a₂)
(i_surj : ∀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₂₂, i_inj a₁ a₂ _ _ _ _)
(assume b hb, (mem_filter.mp hb).elim $ λh₁ h₂,
let ⟨a, ha₁, ha₂, eq⟩ := i_surj 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
@[to_additive]
lemma prod_subset_one_on_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) (hg : ∀ x ∈ (s₂ \ s₁), g x = 1)
(hfg : ∀ x ∈ s₁, f x = g x) : ∏ i in s₁, f i = ∏ i in s₂, g i :=
begin
rw [← prod_sdiff h, prod_eq_one hg, one_mul],
exact prod_congr rfl hfg
end
lemma sum_range_succ_comm {β} [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]
lemma sum_range_succ {β} [add_comm_monoid β] (f : ℕ → β) (n : ℕ) :
∑ x in range (n + 1), f x = ∑ x in range n, f x + f n :=
by simp only [add_comm, sum_range_succ_comm]
@[to_additive]
lemma prod_range_succ_comm (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]
@[to_additive]
lemma prod_range_succ (f : ℕ → β) (n : ℕ) :
∏ x in range (n + 1), f x = (∏ x in range n, f x) * f n :=
by simp only [mul_comm, prod_range_succ_comm]
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 _ _
| (n + 1) := by rw [prod_range_succ _ n, mul_right_comm, ← prod_range_succ', prod_range_succ]
lemma prod_range_add (f : ℕ → β) (n m : ℕ) :
∏ x in range (n + m), f x =
(∏ x in range n, f x) * (∏ x in range m, f (n + x)) :=
begin
induction m with m hm,
{ simp },
{ rw [nat.add_succ, prod_range_succ, hm, prod_range_succ, mul_assoc], },
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
open multiset
lemma prod_multiset_map_count [decidable_eq α] (s : multiset α)
{M : Type*} [comm_monoid M] (f : α → M) :
(s.map f).prod = ∏ m in s.to_finset, (f m) ^ (s.count m) :=
begin
apply s.induction_on, { simp only [prod_const_one, count_zero, prod_zero, pow_zero, map_zero] },
intros a s ih,
simp only [prod_cons, map_cons, to_finset_cons, ih],
by_cases has : a ∈ s.to_finset,
{ rw [insert_eq_of_mem has, ← insert_erase has, prod_insert (not_mem_erase _ _),
prod_insert (not_mem_erase _ _), ← mul_assoc, count_cons_self, pow_succ],
congr' 1, refine prod_congr rfl (λ x hx, _),
rw [count_cons_of_ne (ne_of_mem_erase hx)] },
rw [prod_insert has, count_cons_self, count_eq_zero_of_not_mem (mt mem_to_finset.2 has), pow_one],
congr' 1, refine prod_congr rfl (λ x hx, _),
rw count_cons_of_ne,
rintro rfl, exact has hx
end
lemma sum_multiset_map_count [decidable_eq α] (s : multiset α)
{M : Type*} [add_comm_monoid M] (f : α → M) :
(s.map f).sum = ∑ m in s.to_finset, s.count m • f m :=
@prod_multiset_map_count _ _ _ (multiplicative M) _ f
attribute [to_additive] prod_multiset_map_count
lemma prod_multiset_count [decidable_eq α] [comm_monoid α] (s : multiset α) :
s.prod = ∏ m in s.to_finset, m ^ (s.count m) :=
by { convert prod_multiset_map_count s id, rw map_id }
lemma sum_multiset_count [decidable_eq α] [add_comm_monoid α] (s : multiset α) :
s.sum = ∑ m in s.to_finset, s.count m • m :=
@prod_multiset_count (multiplicative α) _ _ s
attribute [to_additive] prod_multiset_count
/--
To prove a property of a product, it suffices to prove that
the property is multiplicative and holds on factors.
-/
@[to_additive "To prove a property of a sum, it suffices to prove that
the property is additive and holds on summands."]
lemma prod_induction {M : Type*} [comm_monoid M] (f : α → M) (p : M → Prop)
(p_mul : ∀ a b, p a → p b → p (a * b)) (p_one : p 1) (p_s : ∀ x ∈ s, p $ f x) :
p $ ∏ x in s, f x :=
multiset.prod_induction _ _ p_mul p_one (multiset.forall_mem_map_iff.mpr p_s)
/--
To prove a property of a product, it suffices to prove that
the property is multiplicative and holds on factors.
-/
@[to_additive "To prove a property of a sum, it suffices to prove that
the property is additive and holds on summands."]
lemma prod_induction_nonempty {M : Type*} [comm_monoid M] (f : α → M) (p : M → Prop)
(p_mul : ∀ a b, p a → p b → p (a * b)) (hs_nonempty : s.nonempty) (p_s : ∀ x ∈ s, p $ f x) :
p $ ∏ x in s, f x :=
multiset.prod_induction_nonempty p p_mul (by simp [nonempty_iff_ne_empty.mp hs_nonempty])
(multiset.forall_mem_map_iff.mpr p_s)
/--
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 additive commutative group valued function
reduces to the difference of the last and first terms.-/
lemma sum_range_sub {G : Type*} [add_comm_group G] (f : ℕ → G) (n : ℕ) :
∑ i in range n, (f (i+1) - f i) = f n - f 0 :=
by { apply sum_range_induction; abel, simp }
lemma sum_range_sub' {G : Type*} [add_comm_group G] (f : ℕ → G) (n : ℕ) :
∑ i in range n, (f i - f (i+1)) = f 0 - f n :=
by { apply sum_range_induction; abel, simp }
/-- A telescoping product along `{0, ..., n-1}` of a commutative group valued function
reduces to the ratio of the last and first factors.-/
@[to_additive]
lemma prod_range_div {M : Type*} [comm_group M] (f : ℕ → M) (n : ℕ) :
∏ i in range n, (f (i+1) * (f i)⁻¹) = f n * (f 0)⁻¹ :=
by simpa only [← div_eq_mul_inv] using @sum_range_sub (additive M) _ f n
@[to_additive]
lemma prod_range_div' {M : Type*} [comm_group M] (f : ℕ → M) (n : ℕ) :
∏ i in range n, (f i * (f (i+1))⁻¹) = (f 0) * (f n)⁻¹ :=
by simpa only [← div_eq_mul_inv] using @sum_range_sub' (additive M) _ f 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 h₁ : f n ≤ f (n+1) := h (nat.le_succ _),
have h₂ : f 0 ≤ f n := h (nat.zero_le _),
rw [←nat.sub_add_comm h₂, nat.add_sub_cancel' h₁],
end
@[simp] lemma prod_const (b : β) : (∏ x in s, b) = b ^ s.card :=
by haveI := classical.dec_eq α; exact
finset.induction_on s (by simp) (λ a s has ih,
by rw [prod_insert has, card_insert_of_not_mem has, pow_succ, ih])
lemma pow_eq_prod_const (b : β) : ∀ n, b ^ n = ∏ k in range n, b
| 0 := by simp
| (n+1) := by simp
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 [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)],
simp [← ih] }
end
@[to_additive]
lemma prod_involution {s : finset α} {f : α → β} :
∀ (g : Π a ∈ s, α)
(h : ∀ a ha, f a * f (g a ha) = 1)
(g_ne : ∀ a ha, f a ≠ 1 → g a ha ≠ a)
(g_mem : ∀ a ha, g a ha ∈ s)
(g_inv : ∀ a ha, g (g a ha) (g_mem 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 g_ne g_mem g_inv,
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 [← g_inv x hx, ← g_inv 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 (g_mem x hx))⟩
(λ y hy, g y (hmem y hy))
(λ y hy, h y (hmem y hy))
(λ y hy, g_ne 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 g_inv y (hmem y hy) ▸ by simp [h],
by simpa [this] using hy, g_mem y (hmem y hy)⟩⟩)
(λ y hy, g_inv 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 (λ hy, hy.symm ▸ hx1)
(λ hy, h x hx ▸ hy ▸ hx1.symm ▸ (one_mul _).symm)))
else by rw [← insert_erase hx, prod_insert (not_mem_erase _ _),
← insert_erase (mem_erase.2 ⟨g_ne x hx hx1, g_mem 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_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], }
@[to_additive]
lemma prod_inter_mul_prod_diff [decidable_eq α] (s t : finset α) (f : α → β) :
(∏ x in s ∩ t, f x) * (∏ x in s \ t, f x) = (∏ x in s, f x) :=
by { convert (s.prod_piecewise t f f).symm, simp [finset.piecewise] }
@[to_additive]
lemma prod_eq_mul_prod_diff_singleton [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s)
(f : α → β) : ∏ x in s, f x = f i * ∏ x in s \ {i}, f x :=
by { convert (s.prod_inter_mul_prod_diff {i} f).symm, simp [h] }
@[to_additive]
lemma prod_eq_prod_diff_singleton_mul [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s)
(f : α → β) : ∏ x in s, f x = (∏ x in s \ {i}, f x) * f i :=
by { rw [prod_eq_mul_prod_diff_singleton h, mul_comm] }
@[to_additive]
lemma _root_.fintype.prod_eq_mul_prod_compl [decidable_eq α] [fintype α] (a : α) (f : α → β) :
∏ i, f i = (f a) * ∏ i in {a}ᶜ, f i :=
prod_eq_mul_prod_diff_singleton (mem_univ a) f
@[to_additive]
lemma _root_.fintype.prod_eq_prod_compl_mul [decidable_eq α] [fintype α] (a : α) (f : α → β) :
∏ i, f i = (∏ i in {a}ᶜ, f i) * f a :=
prod_eq_prod_diff_singleton_mul (mem_univ a) f
/-- A product can be partitioned into a product of products, each equivalent under a setoid. -/
@[to_additive "A sum can be partitioned into a sum of sums, each equivalent under a setoid."]
lemma prod_partition (R : setoid α) [decidable_rel R.r] :
(∏ x in s, f x) = ∏ xbar in s.image quotient.mk, ∏ y in s.filter (λ y, ⟦y⟧ = xbar), f y :=
begin
refine (finset.prod_image' f (λ x hx, _)).symm,
refl,
end
/-- If we can partition a product into subsets that cancel out, then the whole product cancels. -/
@[to_additive "If we can partition a sum into subsets that cancel out, then the whole sum cancels."]
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
rw [prod_partition R, ←finset.prod_eq_one],
intros xbar xbar_in_s,
obtain ⟨x, x_in_s, xbar_eq_x⟩ := mem_image.mp xbar_in_s,
rw [←xbar_eq_x, filter_congr (λ y _, @quotient.eq _ R y x)],
apply h x x_in_s,
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] }
/-- If a product of a `finset` of size at most 1 has a given value, so
do the terms in that product. -/
lemma eq_of_card_le_one_of_prod_eq {s : finset α} (hc : s.card ≤ 1) {f : α → β} {b : β}
(h : ∏ x in s, f x = b) : ∀ x ∈ s, f x = b :=
begin
intros x hx,
by_cases hc0 : s.card = 0,
{ exact false.elim (card_ne_zero_of_mem hx hc0) },
{ have h1 : s.card = 1 := le_antisymm hc (nat.one_le_of_lt (nat.pos_of_ne_zero hc0)),
rw card_eq_one at h1,
cases h1 with x2 hx2,
rw [hx2, mem_singleton] at hx,
simp_rw hx2 at h,
rw hx,
rw prod_singleton at h,
exact h }
end
/-- If a sum of a `finset` of size at most 1 has a given value, so do
the terms in that sum. -/
lemma eq_of_card_le_one_of_sum_eq [add_comm_monoid γ] {s : finset α} (hc : s.card ≤ 1)
{f : α → γ} {b : γ} (h : ∑ x in s, f x = b) : ∀ x ∈ s, f x = b :=
begin
intros x hx,
by_cases hc0 : s.card = 0,
{ exact false.elim (card_ne_zero_of_mem hx hc0) },
{ have h1 : s.card = 1 := le_antisymm hc (nat.one_le_of_lt (nat.pos_of_ne_zero hc0)),
rw card_eq_one at h1,
cases h1 with x2 hx2,
rw [hx2, mem_singleton] at hx,
simp_rw hx2 at h,
rw hx,
rw sum_singleton at h,
exact h }
end
attribute [to_additive eq_of_card_le_one_of_sum_eq] eq_of_card_le_one_of_prod_eq
/-- If a function applied at a point is 1, a product is unchanged by
removing that point, if present, from a `finset`. -/
@[to_additive "If a function applied at a point is 0, a sum is unchanged by
removing that point, if present, from a `finset`."]
lemma prod_erase [decidable_eq α] (s : finset α) {f : α → β} {a : α} (h : f a = 1) :
∏ x in s.erase a, f x = ∏ x in s, f x :=
begin
rw ←sdiff_singleton_eq_erase,
refine prod_subset (sdiff_subset _ _) (λ x hx hnx, _),
rw sdiff_singleton_eq_erase at hnx,
rwa eq_of_mem_of_not_mem_erase hx hnx
end
/-- If a product is 1 and the function is 1 except possibly at one
point, it is 1 everywhere on the `finset`. -/
@[to_additive "If a sum is 0 and the function is 0 except possibly at one
point, it is 0 everywhere on the `finset`."]
lemma eq_one_of_prod_eq_one {s : finset α} {f : α → β} {a : α} (hp : ∏ x in s, f x = 1)
(h1 : ∀ x ∈ s, x ≠ a → f x = 1) : ∀ x ∈ s, f x = 1 :=
begin
intros x hx,
classical,
by_cases h : x = a,
{ rw h,
rw h at hx,
rw [←prod_subset (singleton_subset_iff.2 hx)
(λ t ht ha, h1 t ht (not_mem_singleton.1 ha)),
prod_singleton] at hp,
exact hp },
{ exact h1 x hx h }
end
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
/-- If `f = g = h` everywhere but at `i`, where `f i = g i + h i`, then the product of `f` over `s`
is the sum of the products of `g` and `h`. -/
lemma prod_add_prod_eq [comm_semiring β] {s : finset α} {i : α} {f g h : α → β}
(hi : i ∈ s) (h1 : g i + h i = f i) (h2 : ∀ j ∈ s, j ≠ i → g j = f j)
(h3 : ∀ j ∈ s, j ≠ i → h j = f j) : ∏ i in s, g i + ∏ i in s, h i = ∏ i in s, f i :=
by { classical, simp_rw [prod_eq_mul_prod_diff_singleton hi, ← h1, right_distrib],
congr' 2; apply prod_congr rfl; simpa }
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 card_eq_sum_ones (s : finset α) : s.card = ∑ _ in s, 1 :=
by simp
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]
@[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 sum_int_cast [add_comm_group β] [has_one β] (s : finset α) (f : α → ℤ) :
↑(∑ x in s, f x : ℤ) = (∑ x in s, (f x : β)) :=
(int.cast_add_hom β).map_sum f s
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_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_range_add {β} [add_comm_monoid β] (f : ℕ → β) (n : ℕ) (m : ℕ) :
(∑ x in range (n + m), f x) =
(∑ x in range n, f x) + (∑ x in range m, f (n + x)) :=
@prod_range_add (multiplicative β) _ _ _ _
attribute [to_additive] prod_range_add
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
section opposite
open opposite
/-- Moving to the opposite additive commutative monoid commutes with summing. -/
@[simp] lemma op_sum [add_comm_monoid β] {s : finset α} (f : α → β) :
op (∑ x in s, f x) = ∑ x in s, op (f x) :=
(op_add_equiv : β ≃+ βᵒᵖ).map_sum _ _
@[simp] lemma unop_sum [add_comm_monoid β] {s : finset α} (f : α → βᵒᵖ) :
unop (∑ x in s, f x) = ∑ x in s, unop (f x) :=
(op_add_equiv : β ≃+ βᵒᵖ).symm.map_sum _ _
end opposite
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_bUnion [decidable_eq β] {s : finset α} {t : α → finset β}
(h : ∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y)) :
(s.bUnion t).card = ∑ u in s, card (t u) :=
calc (s.bUnion t).card = ∑ i in s.bUnion t, 1 : by simp
... = ∑ a in s, ∑ i in t a, 1 : finset.sum_bUnion h
... = ∑ u in s, card (t u) : by simp
lemma card_bUnion_le [decidable_eq β] {s : finset α} {t : α → finset β} :
(s.bUnion 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).bUnion t).card ≤ (t a).card + (s.bUnion t).card :
by rw bUnion_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_fiberwise [decidable_eq β] {f : α → β} {s : finset α} {t : finset β}
(H : ∀ x ∈ s, f x ∈ t) :
s.card = ∑ a in t, (s.filter (λ x, f x = a)).card :=
by simp only [card_eq_sum_ones, sum_fiberwise_of_maps_to H]
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 :=
card_eq_sum_card_fiberwise (λ _, mem_image_of_mem _)
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
@[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) :=
by simpa only [sub_eq_add_neg] using sum_add_distrib.trans (congr_arg _ sum_neg_distrib)
section prod_eq_zero
variables [comm_monoid_with_zero β]
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]
lemma prod_boole {s : finset α} {p : α → Prop} [decidable_pred p] :
∏ i in s, ite (p i) (1 : β) (0 : β) = ite (∀ i ∈ s, p i) 1 0 :=
begin
split_ifs,
{ apply prod_eq_one,
intros i hi,
rw if_pos (h i hi) },
{ push_neg at h,
rcases h with ⟨i, hi, hq⟩,
apply prod_eq_zero hi,
rw [if_neg hq] },
end
variables [nontrivial β] [no_zero_divisors β]
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, 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 prod_eq_zero
section comm_group_with_zero
variables [comm_group_with_zero β]
@[simp]
lemma prod_inv_distrib' : (∏ x in s, (f x)⁻¹) = (∏ x in s, f x)⁻¹ :=
begin
classical,
by_cases h : ∃ x ∈ s, f x = 0,
{ simpa [prod_eq_zero_iff.mpr h, prod_eq_zero_iff] using h },
{ push_neg at h,
have h' := prod_ne_zero_iff.mpr h,
have hf : ∀ x ∈ s, (f x)⁻¹ * f x = 1 := λ x hx, inv_mul_cancel (h x hx),
apply mul_right_cancel' h',
simp [h, h', ← finset.prod_mul_distrib, prod_congr rfl hf] }
end
end comm_group_with_zero
end finset
namespace fintype
open finset
/-- `fintype.prod_bijective` is a variant of `finset.prod_bij` that accepts `function.bijective`.
See `function.bijective.prod_comp` for a version without `h`. -/
@[to_additive "`fintype.sum_equiv` is a variant of `finset.sum_bij` that accepts
`function.bijective`.
See `function.bijective.sum_comp` for a version without `h`. "]
lemma prod_bijective {α β M : Type*} [fintype α] [fintype β] [comm_monoid M]
(e : α → β) (he : function.bijective e) (f : α → M) (g : β → M) (h : ∀ x, f x = g (e x)) :
∏ x : α, f x = ∏ x : β, g x :=
prod_bij
(λ x _, e x)
(λ x _, mem_univ (e x))
(λ x _, h x)
(λ x x' _ _ h, he.injective h)
(λ y _, (he.surjective y).imp $ λ a h, ⟨mem_univ _, h.symm⟩)
/-- `fintype.prod_equiv` is a specialization of `finset.prod_bij` that
automatically fills in most arguments.
See `equiv.prod_comp` for a version without `h`.
-/
@[to_additive "`fintype.sum_equiv` is a specialization of `finset.sum_bij` that
automatically fills in most arguments.
See `equiv.sum_comp` for a version without `h`.
"]
lemma prod_equiv {α β M : Type*} [fintype α] [fintype β] [comm_monoid M]
(e : α ≃ β) (f : α → M) (g : β → M) (h : ∀ x, f x = g (e x)) :
∏ x : α, f x = ∏ x : β, g x :=
prod_bijective e e.bijective f g h
@[to_additive]
lemma prod_finset_coe [comm_monoid β] :
∏ (i : (s : set α)), f i = ∏ i in s, f i :=
(finset.prod_subtype s (λ _, iff.rfl) f).symm
end fintype
namespace list
@[to_additive] lemma prod_to_finset {M : Type*} [decidable_eq α] [comm_monoid M]
(f : α → M) : ∀ {l : list α} (hl : l.nodup), l.to_finset.prod f = (l.map f).prod
| [] _ := by simp
| (a :: l) hl := let ⟨not_mem, hl⟩ := list.nodup_cons.mp hl in
by simp [finset.prod_insert (mt list.mem_to_finset.mp not_mem), prod_to_finset hl]
end list
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)
lemma count_sum' {s : finset β} {a : α} {f : β → multiset α} :
count a (∑ x in s, f x) = ∑ x in s, count a (f x) :=
by { dunfold finset.sum, rw count_sum }
@[simp] lemma to_finset_sum_count_nsmul_eq (s : multiset α) :
(∑ a in s.to_finset, s.count a • (a ::ₘ 0)) = s :=
begin
apply ext', intro b,
rw count_sum',
have h : count b s = count b (count b s • (b ::ₘ 0)),
{ rw [singleton_coe, count_nsmul, ← singleton_coe, count_singleton, mul_one] },
rw h, clear h,
apply finset.sum_eq_single b,
{ intros c h hcb, rw count_nsmul, convert mul_zero (count c s),
apply count_eq_zero.mpr, exact finset.not_mem_singleton.mpr (ne.symm hcb) },
{ intro hb, rw [count_eq_zero_of_not_mem (mt mem_to_finset.2 hb), count_nsmul, zero_mul]}
end
theorem exists_smul_of_dvd_count (s : multiset α) {k : ℕ} (h : ∀ (a : α), k ∣ multiset.count a s) :
∃ (u : multiset α), s = k • u :=
begin
use ∑ a in s.to_finset, (s.count a / k) • (a ::ₘ 0),
have h₂ : ∑ (x : α) in s.to_finset, k • (count x s / k) • (x ::ₘ 0) =
∑ (x : α) in s.to_finset, count x s • (x ::ₘ 0),
{ refine congr_arg s.to_finset.sum _,
apply funext, intro x,
rw [← mul_nsmul, nat.mul_div_cancel' (h x)] },
rw [← finset.sum_nsmul, h₂, to_finset_sum_count_nsmul_eq]
end
end multiset
@[simp, norm_cast] lemma nat.coe_prod {R : Type*} [comm_semiring R]
(f : α → ℕ) (s : finset α) : (↑∏ i in s, f i : R) = ∏ i in s, f i :=
(nat.cast_ring_hom R).map_prod _ _
@[simp, norm_cast] lemma int.coe_prod {R : Type*} [comm_ring R]
(f : α → ℤ) (s : finset α) : (↑∏ i in s, f i : R) = ∏ i in s, f i :=
(int.cast_ring_hom R).map_prod _ _
@[simp, norm_cast] lemma units.coe_prod {M : Type*} [comm_monoid M]
(f : α → units M) (s : finset α) : (↑∏ i in s, f i : M) = ∏ i in s, f i :=
(units.coe_hom M).map_prod _ _
|
b72db174a91587935280bb0de3b5f2c807ca2968 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/data/real/sqrt.lean | 3be9eb443f665427a537b26da501deb4f346a0c2 | [
"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 | 13,104 | lean | /-
Copyright (c) 2020 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Floris van Doorn, Yury Kudryashov
-/
import topology.algebra.order.monotone_continuity
import topology.instances.nnreal
import tactic.norm_cast
/-!
# Square root of a real number
In this file we define
* `nnreal.sqrt` to be the square root of a nonnegative real number.
* `real.sqrt` to be the square root of a real number, defined to be zero on negative numbers.
Then we prove some basic properties of these functions.
## Implementation notes
We define `nnreal.sqrt` as the noncomputable inverse to the function `x ↦ x * x`. We use general
theory of inverses of strictly monotone functions to prove that `nnreal.sqrt x` exists. As a side
effect, `nnreal.sqrt` is a bundled `order_iso`, so for `nnreal` numbers we get continuity as well as
theorems like `sqrt x ≤ y ↔ x ≤ y * y` for free.
Then we define `real.sqrt x` to be `nnreal.sqrt (real.to_nnreal x)`. We also define a Cauchy
sequence `real.sqrt_aux (f : cau_seq ℚ abs)` which converges to `sqrt (mk f)` but do not prove (yet)
that this sequence actually converges to `sqrt (mk f)`.
## Tags
square root
-/
open set filter
open_locale filter nnreal topological_space
namespace nnreal
variables {x y : ℝ≥0}
/-- Square root of a nonnegative real number. -/
@[pp_nodot] noncomputable def sqrt : ℝ≥0 ≃o ℝ≥0 :=
order_iso.symm $ strict_mono.order_iso_of_surjective (λ x, x * x)
(λ x y h, mul_self_lt_mul_self x.2 h) $
(continuous_id.mul continuous_id).surjective tendsto_mul_self_at_top $
by simp [order_bot.at_bot_eq]
lemma sqrt_le_sqrt_iff : sqrt x ≤ sqrt y ↔ x ≤ y :=
sqrt.le_iff_le
lemma sqrt_lt_sqrt_iff : sqrt x < sqrt y ↔ x < y :=
sqrt.lt_iff_lt
lemma sqrt_eq_iff_sq_eq : sqrt x = y ↔ y * y = x :=
sqrt.to_equiv.apply_eq_iff_eq_symm_apply.trans eq_comm
lemma sqrt_le_iff : sqrt x ≤ y ↔ x ≤ y * y :=
sqrt.to_galois_connection _ _
lemma le_sqrt_iff : x ≤ sqrt y ↔ x * x ≤ y :=
(sqrt.symm.to_galois_connection _ _).symm
@[simp] lemma sqrt_eq_zero : sqrt x = 0 ↔ x = 0 :=
sqrt_eq_iff_sq_eq.trans $ by rw [eq_comm, zero_mul]
@[simp] lemma sqrt_zero : sqrt 0 = 0 := sqrt_eq_zero.2 rfl
@[simp] lemma sqrt_one : sqrt 1 = 1 := sqrt_eq_iff_sq_eq.2 $ mul_one 1
@[simp] lemma mul_self_sqrt (x : ℝ≥0) : sqrt x * sqrt x = x :=
sqrt.symm_apply_apply x
@[simp] lemma sqrt_mul_self (x : ℝ≥0) : sqrt (x * x) = x := sqrt.apply_symm_apply x
@[simp] lemma sq_sqrt (x : ℝ≥0) : (sqrt x)^2 = x :=
by rw [sq, mul_self_sqrt x]
@[simp] lemma sqrt_sq (x : ℝ≥0) : sqrt (x^2) = x :=
by rw [sq, sqrt_mul_self x]
lemma sqrt_mul (x y : ℝ≥0) : sqrt (x * y) = sqrt x * sqrt y :=
by rw [sqrt_eq_iff_sq_eq, mul_mul_mul_comm, mul_self_sqrt, mul_self_sqrt]
/-- `nnreal.sqrt` as a `monoid_with_zero_hom`. -/
noncomputable def sqrt_hom : ℝ≥0 →*₀ ℝ≥0 := ⟨sqrt, sqrt_zero, sqrt_one, sqrt_mul⟩
lemma sqrt_inv (x : ℝ≥0) : sqrt (x⁻¹) = (sqrt x)⁻¹ := sqrt_hom.map_inv x
lemma sqrt_div (x y : ℝ≥0) : sqrt (x / y) = sqrt x / sqrt y := sqrt_hom.map_div x y
lemma continuous_sqrt : continuous sqrt := sqrt.continuous
end nnreal
namespace real
/-- An auxiliary sequence of rational numbers that converges to `real.sqrt (mk f)`.
Currently this sequence is not used in `mathlib`. -/
def sqrt_aux (f : cau_seq ℚ abs) : ℕ → ℚ
| 0 := rat.mk_nat (f 0).num.to_nat.sqrt (f 0).denom.sqrt
| (n + 1) := let s := sqrt_aux n in max 0 $ (s + f (n+1) / s) / 2
theorem sqrt_aux_nonneg (f : cau_seq ℚ abs) : ∀ i : ℕ, 0 ≤ sqrt_aux f i
| 0 := by rw [sqrt_aux, rat.mk_nat_eq, rat.mk_eq_div];
apply div_nonneg; exact int.cast_nonneg.2 (int.of_nat_nonneg _)
| (n + 1) := le_max_left _ _
/- TODO(Mario): finish the proof
theorem sqrt_aux_converges (f : cau_seq ℚ abs) : ∃ h x, 0 ≤ x ∧ x * x = max 0 (mk f) ∧
mk ⟨sqrt_aux f, h⟩ = x :=
begin
rcases sqrt_exists (le_max_left 0 (mk f)) with ⟨x, x0, hx⟩,
suffices : ∃ h, mk ⟨sqrt_aux f, h⟩ = x,
{ exact this.imp (λ h e, ⟨x, x0, hx, e⟩) },
apply of_near,
suffices : ∃ δ > 0, ∀ i, abs (↑(sqrt_aux f i) - x) < δ / 2 ^ i,
{ rcases this with ⟨δ, δ0, hδ⟩,
intros }
end -/
/-- The square root of a real number. This returns 0 for negative inputs. -/
@[pp_nodot] noncomputable def sqrt (x : ℝ) : ℝ :=
nnreal.sqrt (real.to_nnreal x)
/-quotient.lift_on x
(λ f, mk ⟨sqrt_aux f, (sqrt_aux_converges f).fst⟩)
(λ f g e, begin
rcases sqrt_aux_converges f with ⟨hf, x, x0, xf, xs⟩,
rcases sqrt_aux_converges g with ⟨hg, y, y0, yg, ys⟩,
refine xs.trans (eq.trans _ ys.symm),
rw [← @mul_self_inj_of_nonneg ℝ _ x y x0 y0, xf, yg],
congr' 1, exact quotient.sound e
end)-/
variables {x y : ℝ}
@[simp, norm_cast] lemma coe_sqrt {x : ℝ≥0} : (nnreal.sqrt x : ℝ) = real.sqrt x :=
by rw [real.sqrt, real.to_nnreal_coe]
@[continuity]
lemma continuous_sqrt : continuous sqrt :=
nnreal.continuous_coe.comp $ nnreal.sqrt.continuous.comp continuous_real_to_nnreal
theorem sqrt_eq_zero_of_nonpos (h : x ≤ 0) : sqrt x = 0 :=
by simp [sqrt, real.to_nnreal_eq_zero.2 h]
theorem sqrt_nonneg (x : ℝ) : 0 ≤ sqrt x := nnreal.coe_nonneg _
@[simp] theorem mul_self_sqrt (h : 0 ≤ x) : sqrt x * sqrt x = x :=
by rw [sqrt, ← nnreal.coe_mul, nnreal.mul_self_sqrt, real.coe_to_nnreal _ h]
@[simp] theorem sqrt_mul_self (h : 0 ≤ x) : sqrt (x * x) = x :=
(mul_self_inj_of_nonneg (sqrt_nonneg _) h).1 (mul_self_sqrt (mul_self_nonneg _))
theorem sqrt_eq_cases : sqrt x = y ↔ y * y = x ∧ 0 ≤ y ∨ x < 0 ∧ y = 0 :=
begin
split,
{ rintro rfl,
cases le_or_lt 0 x with hle hlt,
{ exact or.inl ⟨mul_self_sqrt hle, sqrt_nonneg x⟩ },
{ exact or.inr ⟨hlt, sqrt_eq_zero_of_nonpos hlt.le⟩ } },
{ rintro (⟨rfl, hy⟩|⟨hx, rfl⟩),
exacts [sqrt_mul_self hy, sqrt_eq_zero_of_nonpos hx.le] }
end
theorem sqrt_eq_iff_mul_self_eq (hx : 0 ≤ x) (hy : 0 ≤ y) :
sqrt x = y ↔ y * y = x :=
⟨λ h, by rw [← h, mul_self_sqrt hx], λ h, by rw [← h, sqrt_mul_self hy]⟩
theorem sqrt_eq_iff_mul_self_eq_of_pos (h : 0 < y) :
sqrt x = y ↔ y * y = x :=
by simp [sqrt_eq_cases, h.ne', h.le]
@[simp] lemma sqrt_eq_one : sqrt x = 1 ↔ x = 1 :=
calc sqrt x = 1 ↔ 1 * 1 = x :
sqrt_eq_iff_mul_self_eq_of_pos zero_lt_one
... ↔ x = 1 : by rw [eq_comm, mul_one]
@[simp] theorem sq_sqrt (h : 0 ≤ x) : (sqrt x)^2 = x :=
by rw [sq, mul_self_sqrt h]
@[simp] theorem sqrt_sq (h : 0 ≤ x) : sqrt (x ^ 2) = x :=
by rw [sq, sqrt_mul_self h]
theorem sqrt_eq_iff_sq_eq (hx : 0 ≤ x) (hy : 0 ≤ y) :
sqrt x = y ↔ y ^ 2 = x :=
by rw [sq, sqrt_eq_iff_mul_self_eq hx hy]
theorem sqrt_mul_self_eq_abs (x : ℝ) : sqrt (x * x) = |x| :=
by rw [← abs_mul_abs_self x, sqrt_mul_self (abs_nonneg _)]
theorem sqrt_sq_eq_abs (x : ℝ) : sqrt (x ^ 2) = |x| :=
by rw [sq, sqrt_mul_self_eq_abs]
@[simp] theorem sqrt_zero : sqrt 0 = 0 := by simp [sqrt]
@[simp] theorem sqrt_one : sqrt 1 = 1 := by simp [sqrt]
@[simp] theorem sqrt_le_sqrt_iff (hy : 0 ≤ y) : sqrt x ≤ sqrt y ↔ x ≤ y :=
by rw [sqrt, sqrt, nnreal.coe_le_coe, nnreal.sqrt_le_sqrt_iff, real.to_nnreal_le_to_nnreal_iff hy]
@[simp] theorem sqrt_lt_sqrt_iff (hx : 0 ≤ x) : sqrt x < sqrt y ↔ x < y :=
lt_iff_lt_of_le_iff_le (sqrt_le_sqrt_iff hx)
theorem sqrt_lt_sqrt_iff_of_pos (hy : 0 < y) : sqrt x < sqrt y ↔ x < y :=
by rw [sqrt, sqrt, nnreal.coe_lt_coe, nnreal.sqrt_lt_sqrt_iff, to_nnreal_lt_to_nnreal_iff hy]
theorem sqrt_le_sqrt (h : x ≤ y) : sqrt x ≤ sqrt y :=
by { rw [sqrt, sqrt, nnreal.coe_le_coe, nnreal.sqrt_le_sqrt_iff], exact to_nnreal_le_to_nnreal h }
theorem sqrt_lt_sqrt (hx : 0 ≤ x) (h : x < y) : sqrt x < sqrt y :=
(sqrt_lt_sqrt_iff hx).2 h
theorem sqrt_le_left (hy : 0 ≤ y) : sqrt x ≤ y ↔ x ≤ y ^ 2 :=
by rw [sqrt, ← real.le_to_nnreal_iff_coe_le hy, nnreal.sqrt_le_iff, ← real.to_nnreal_mul hy,
real.to_nnreal_le_to_nnreal_iff (mul_self_nonneg y), sq]
theorem sqrt_le_iff : sqrt x ≤ y ↔ 0 ≤ y ∧ x ≤ y ^ 2 :=
begin
rw [← and_iff_right_of_imp (λ h, (sqrt_nonneg x).trans h), and.congr_right_iff],
exact sqrt_le_left
end
lemma sqrt_lt (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x < y ↔ x < y ^ 2 :=
by rw [←sqrt_lt_sqrt_iff hx, sqrt_sq hy]
lemma sqrt_lt' (hy : 0 < y) : sqrt x < y ↔ x < y ^ 2 :=
by rw [←sqrt_lt_sqrt_iff_of_pos (pow_pos hy _), sqrt_sq hy.le]
/- note: if you want to conclude `x ≤ sqrt y`, then use `le_sqrt_of_sq_le`.
if you have `x > 0`, consider using `le_sqrt'` -/
theorem le_sqrt (hx : 0 ≤ x) (hy : 0 ≤ y) : x ≤ sqrt y ↔ x ^ 2 ≤ y :=
le_iff_le_iff_lt_iff_lt.2 $ sqrt_lt hy hx
lemma le_sqrt' (hx : 0 < x) : x ≤ sqrt y ↔ x ^ 2 ≤ y := le_iff_le_iff_lt_iff_lt.2 $ sqrt_lt' hx
theorem abs_le_sqrt (h : x^2 ≤ y) : |x| ≤ sqrt y :=
by rw ← sqrt_sq_eq_abs; exact sqrt_le_sqrt h
theorem sq_le (h : 0 ≤ y) : x^2 ≤ y ↔ -sqrt y ≤ x ∧ x ≤ sqrt y :=
begin
split,
{ simpa only [abs_le] using abs_le_sqrt },
{ rw [← abs_le, ← sq_abs],
exact (le_sqrt (abs_nonneg x) h).mp },
end
theorem neg_sqrt_le_of_sq_le (h : x^2 ≤ y) : -sqrt y ≤ x :=
((sq_le ((sq_nonneg x).trans h)).mp h).1
theorem le_sqrt_of_sq_le (h : x^2 ≤ y) : x ≤ sqrt y :=
((sq_le ((sq_nonneg x).trans h)).mp h).2
@[simp] theorem sqrt_inj (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x = sqrt y ↔ x = y :=
by simp [le_antisymm_iff, hx, hy]
@[simp] theorem sqrt_eq_zero (h : 0 ≤ x) : sqrt x = 0 ↔ x = 0 :=
by simpa using sqrt_inj h le_rfl
theorem sqrt_eq_zero' : sqrt x = 0 ↔ x ≤ 0 :=
by rw [sqrt, nnreal.coe_eq_zero, nnreal.sqrt_eq_zero, real.to_nnreal_eq_zero]
theorem sqrt_ne_zero (h : 0 ≤ x) : sqrt x ≠ 0 ↔ x ≠ 0 :=
by rw [not_iff_not, sqrt_eq_zero h]
theorem sqrt_ne_zero' : sqrt x ≠ 0 ↔ 0 < x :=
by rw [← not_le, not_iff_not, sqrt_eq_zero']
@[simp] theorem sqrt_pos : 0 < sqrt x ↔ 0 < x :=
lt_iff_lt_of_le_iff_le (iff.trans
(by simp [le_antisymm_iff, sqrt_nonneg]) sqrt_eq_zero')
@[simp] theorem sqrt_mul (hx : 0 ≤ x) (y : ℝ) : sqrt (x * y) = sqrt x * sqrt y :=
by simp_rw [sqrt, ← nnreal.coe_mul, nnreal.coe_eq, real.to_nnreal_mul hx, nnreal.sqrt_mul]
@[simp] theorem sqrt_mul' (x) {y : ℝ} (hy : 0 ≤ y) : sqrt (x * y) = sqrt x * sqrt y :=
by rw [mul_comm, sqrt_mul hy, mul_comm]
@[simp] theorem sqrt_inv (x : ℝ) : sqrt x⁻¹ = (sqrt x)⁻¹ :=
by rw [sqrt, real.to_nnreal_inv, nnreal.sqrt_inv, nnreal.coe_inv, sqrt]
@[simp] theorem sqrt_div (hx : 0 ≤ x) (y : ℝ) : sqrt (x / y) = sqrt x / sqrt y :=
by rw [division_def, sqrt_mul hx, sqrt_inv, division_def]
@[simp] theorem div_sqrt : x / sqrt x = sqrt x :=
begin
cases le_or_lt x 0,
{ rw [sqrt_eq_zero'.mpr h, div_zero] },
{ rw [div_eq_iff (sqrt_ne_zero'.mpr h), mul_self_sqrt h.le] },
end
theorem sqrt_div_self' : sqrt x / x = 1 / sqrt x :=
by rw [←div_sqrt, one_div_div, div_sqrt]
theorem sqrt_div_self : sqrt x / x = (sqrt x)⁻¹ :=
by rw [sqrt_div_self', one_div]
lemma lt_sqrt (hx : 0 ≤ x) : x < sqrt y ↔ x ^ 2 < y :=
by rw [←sqrt_lt_sqrt_iff (sq_nonneg _), sqrt_sq hx]
lemma sq_lt : x^2 < y ↔ -sqrt y < x ∧ x < sqrt y := by rw [←abs_lt, ←sq_abs, lt_sqrt (abs_nonneg _)]
theorem neg_sqrt_lt_of_sq_lt (h : x^2 < y) : -sqrt y < x := (sq_lt.mp h).1
theorem lt_sqrt_of_sq_lt (h : x^2 < y) : x < sqrt y := (sq_lt.mp h).2
lemma lt_sq_of_sqrt_lt {x y : ℝ} (h : sqrt x < y) : x < y ^ 2 :=
by { have hy := x.sqrt_nonneg.trans_lt h,
rwa [←sqrt_lt_sqrt_iff_of_pos (sq_pos_of_pos hy), sqrt_sq hy.le] }
/-- The natural square root is at most the real square root -/
lemma nat_sqrt_le_real_sqrt {a : ℕ} : ↑(nat.sqrt a) ≤ real.sqrt ↑a :=
begin
rw real.le_sqrt (nat.cast_nonneg _) (nat.cast_nonneg _),
norm_cast,
exact nat.sqrt_le' a,
end
/-- The real square root is at most the natural square root plus one -/
lemma real_sqrt_le_nat_sqrt_succ {a : ℕ} : real.sqrt ↑a ≤ nat.sqrt a + 1 :=
begin
rw real.sqrt_le_iff,
split,
{ norm_cast, simp, },
{ norm_cast, exact le_of_lt (nat.lt_succ_sqrt' a), },
end
instance : star_ordered_ring ℝ :=
{ nonneg_iff := λ r, by
{ refine ⟨λ hr, ⟨sqrt r, show r = sqrt r * sqrt r, by rw [←sqrt_mul hr, sqrt_mul_self hr]⟩, _⟩,
rintros ⟨s, rfl⟩,
exact mul_self_nonneg s },
..real.ordered_add_comm_group }
end real
open real
variables {α : Type*}
lemma filter.tendsto.sqrt {f : α → ℝ} {l : filter α} {x : ℝ} (h : tendsto f l (𝓝 x)) :
tendsto (λ x, sqrt (f x)) l (𝓝 (sqrt x)) :=
(continuous_sqrt.tendsto _).comp h
variables [topological_space α] {f : α → ℝ} {s : set α} {x : α}
lemma continuous_within_at.sqrt (h : continuous_within_at f s x) :
continuous_within_at (λ x, sqrt (f x)) s x :=
h.sqrt
lemma continuous_at.sqrt (h : continuous_at f x) : continuous_at (λ x, sqrt (f x)) x := h.sqrt
lemma continuous_on.sqrt (h : continuous_on f s) : continuous_on (λ x, sqrt (f x)) s :=
λ x hx, (h x hx).sqrt
@[continuity]
lemma continuous.sqrt (h : continuous f) : continuous (λ x, sqrt (f x)) := continuous_sqrt.comp h
|
079f15b7933d7965f7aa2674bad8c86db53c0b76 | b561a44b48979a98df50ade0789a21c79ee31288 | /stage0/src/Lean/Elab/Extra.lean | c26ec6c940a66bc3dedff9cc886834d6ebc27a1d | [
"Apache-2.0"
] | permissive | 3401ijk/lean4 | 97659c475ebd33a034fed515cb83a85f75ccfb06 | a5b1b8de4f4b038ff752b9e607b721f15a9a4351 | refs/heads/master | 1,693,933,007,651 | 1,636,424,845,000 | 1,636,424,845,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 12,600 | 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.Elab.App
/-
Auxiliary elaboration functions: AKA custom elaborators
-/
namespace Lean.Elab.Term
open Meta
@[builtinTermElab binrel] def elabBinRel : TermElab := fun stx expectedType? => do
match (← resolveId? stx[1]) with
| some f =>
let s ← saveState
let (lhs, rhs) ← withSynthesize (mayPostpone := true) do
let mut lhs ← elabTerm stx[2] none
let mut rhs ← elabTerm stx[3] none
if lhs.isAppOfArity ``OfNat.ofNat 3 then
lhs ← ensureHasType (← inferType rhs) lhs
else if rhs.isAppOfArity ``OfNat.ofNat 3 then
rhs ← ensureHasType (← inferType lhs) rhs
return (lhs, rhs)
let lhsType ← inferType lhs
let rhsType ← inferType rhs
let (lhs, rhs) ←
try
pure (lhs, ← withRef stx[3] do ensureHasType lhsType rhs)
catch _ =>
try
pure (← withRef stx[2] do ensureHasType rhsType lhs, rhs)
catch _ =>
s.restore
-- Use default approach
let lhs ← elabTerm stx[2] none
let rhs ← elabTerm stx[3] none
let lhsType ← inferType lhs
let rhsType ← inferType rhs
pure (lhs, ← withRef stx[3] do ensureHasType lhsType rhs)
elabAppArgs f #[] #[Arg.expr lhs, Arg.expr rhs] expectedType? (explicit := false) (ellipsis := false)
| none => throwUnknownConstant stx[1].getId
@[builtinTermElab forInMacro] def elabForIn : TermElab := fun stx expectedType? => do
match stx with
| `(for_in% $col $init $body) =>
match (← isLocalIdent? col) with
| none => elabTerm (← `(let col := $col; for_in% col $init $body)) expectedType?
| some colFVar =>
tryPostponeIfNoneOrMVar expectedType?
let m ← getMonad expectedType?
let colType ← inferType colFVar
let elemType ← mkFreshExprMVar (mkSort (mkLevelSucc (← mkFreshLevelMVar)))
let forInInstance ←
try
mkAppM ``ForIn #[m, colType, elemType]
catch
ex => tryPostpone; throwError "failed to construct 'ForIn' instance for collection{indentExpr colType}\nand monad{indentExpr m}"
match (← trySynthInstance forInInstance) with
| LOption.some val =>
let ref ← getRef
let forInFn ← mkConst ``forIn
elabAppArgs forInFn #[] #[Arg.stx col, Arg.stx init, Arg.stx body] expectedType? (explicit := false) (ellipsis := false)
| LOption.undef => tryPostpone; throwFailure forInInstance
| LOption.none => throwFailure forInInstance
| _ => throwUnsupportedSyntax
where
getMonad (expectedType? : Option Expr) : TermElabM Expr := do
match expectedType? with
| none => throwError "invalid 'for_in%' notation, expected type is not available"
| some expectedType =>
match (← isTypeApp? expectedType) with
| some (m, _) => return m
| none => throwError "invalid 'for_in%' notation, expected type is not of of the form `M α`{indentExpr expectedType}"
throwFailure (forInInstance : Expr) : TermElabM Expr :=
throwError "failed to synthesize instance for 'for_in%' notation{indentExpr forInInstance}"
namespace BinOp
/-
The elaborator for `binop%` terms works as follows:
1- Expand macros.
2- Convert `Syntax` object corresponding to the `binop%` term into a `Tree`.
The `toTree` method visits nested `binop%` terms and parentheses.
3- Synthesize pending metavariables without applying default instances and using the
`(mayPostpone := true)`.
4- Tries to compute a maximal type for the tree computed at step 2.
We say a type α is smaller than type β if there is a (nondependent) coercion from α to β.
We are currently ignoring the case we may have cycles in the coercion graph.
If there are "uncomparable" types α and β in the tree, we skip the next step.
We say two types are "uncomparable" if there isn't a coercion between them.
Note that two types may be "uncomparable" because some typing information may still be missing.
5- We traverse the tree and inject coercions to the "maximal" type when needed.
Recall that the coercions are expanded eagerly by the elaborator.
Properties:
a) Given `n : Nat` and `i : Nat`, it can successfully elaborate `n + i` and `i + n`. Recall that Lean 3
fails on the former.
b) The coercions are inserted in the "leaves" like in Lean 3.
c) There are no coercions "hidden" inside instances, and we can elaborate
```
axiom Int.add_comm (i j : Int) : i + j = j + i
example (n : Nat) (i : Int) : n + i = i + n := by
rw [Int.add_comm]
```
Recall that the `rw` tactic used to fail because our old `binop%` elaborator would hide
coercions inside of a `HAdd` instance.
Remarks:
In the new `binop%` elaborator the decision whether a coercion will be inserted or not
is made at `binop%` elaboration time. This was not the case in the old elaborator.
For example, an instance, such as `HAdd Int ?m ?n`, could be created when executing
the `binop%` elaborator, and only resolved much later. We try to minimize this problem
by synthesizing pending metavariables at step 3.
For types containing heterogeneous operators (e.g., matrix multiplication), step 4 will fail
and we will skip coercion insertion. For example, `x : Matrix Real 5 4` and `y : Matrix Real 4 8`,
there is no coercion `Matrix Real 5 4` from `Matrix Real 4 8` and vice-versa, but
`x * y` is elaborated successfully and has type `Matrix Real 5 8`.
-/
private inductive Tree where
| term (ref : Syntax) (val : Expr)
| op (ref : Syntax) (lazy : Bool) (f : Expr) (lhs rhs : Tree)
private partial def toTree (s : Syntax) : TermElabM Tree := do
let result ← go (← liftMacroM <| expandMacros s)
synthesizeSyntheticMVars (mayPostpone := true)
return result
where
go (s : Syntax) := do
match s with
| `(binop% $f $lhs $rhs) => processOp (lazy := false) f lhs rhs
| `(binop_lazy% $f $lhs $rhs) => processOp (lazy := true) f lhs rhs
| `(($e)) => (← go e)
| _ =>
return Tree.term s (← elabTerm s none)
processOp (f lhs rhs : Syntax) (lazy : Bool) := do
let some f ← resolveId? f | throwUnknownConstant f.getId
return Tree.op s (lazy := lazy) f (← go lhs) (← go rhs)
-- Auxiliary function used at `analyze`
private def hasCoe (fromType toType : Expr) : TermElabM Bool := do
if (← getEnv).contains ``CoeHTCT then
let u ← getLevel fromType
let v ← getLevel toType
let coeInstType := mkAppN (Lean.mkConst ``CoeHTCT [u, v]) #[fromType, toType]
match ← trySynthInstance coeInstType (some (maxCoeSize.get (← getOptions))) with
| LOption.some _ => return true
| LOption.none => return false
| LOption.undef => return false -- TODO: should we do something smarter here?
else
return false
private structure AnalyzeResult where
max? : Option Expr := none
hasUncomparable : Bool := false -- `true` if there are two types `α` and `β` where we don't have coercions in any direction.
private def isUnknow : Expr → Bool
| Expr.mvar .. => true
| Expr.app f .. => isUnknow f
| Expr.letE _ _ _ b _ => isUnknow b
| Expr.mdata _ b _ => isUnknow b
| _ => false
private def analyze (t : Tree) (expectedType? : Option Expr) : TermElabM AnalyzeResult := do
let max? ←
match expectedType? with
| none => pure none
| some expectedType =>
let expectedType ← instantiateMVars expectedType
if isUnknow expectedType then pure none else pure (some expectedType)
(go t *> get).run' { max? }
where
go (t : Tree) : StateRefT AnalyzeResult TermElabM Unit := do
unless (← get).hasUncomparable do
match t with
| Tree.op _ _ _ lhs rhs => go lhs; go rhs
| Tree.term _ val =>
let type ← instantiateMVars (← inferType val)
unless isUnknow type do
match (← get).max? with
| none => modify fun s => { s with max? := type }
| some max =>
unless (← withNewMCtxDepth <| isDefEqGuarded max type) do
if (← hasCoe type max) then
return ()
else if (← hasCoe max type) then
modify fun s => { s with max? := type }
else
trace[Elab.binop] "uncomparable types: {max}, {type}"
modify fun s => { s with hasUncomparable := true }
private def mkOp (f : Expr) (lhs rhs : Expr) : TermElabM Expr :=
elabAppArgs f #[] #[Arg.expr lhs, Arg.expr rhs] (expectedType? := none) (explicit := false) (ellipsis := false)
private def toExpr (t : Tree) : TermElabM Expr := do
match t with
| Tree.term _ e => return e
| Tree.op ref true f lhs rhs => withRef ref <| mkOp f (← toExpr lhs) (← mkFunUnit (← toExpr rhs))
| Tree.op ref false f lhs rhs => withRef ref <| mkOp f (← toExpr lhs) (← toExpr rhs)
private def applyCoe (t : Tree) (maxType : Expr) : TermElabM Tree := do
go t
where
go (t : Tree) : TermElabM Tree := do
match t with
| Tree.op ref lazy f lhs rhs => return Tree.op ref lazy f (← go lhs) (← go rhs)
| Tree.term ref e =>
let type ← inferType e
trace[Elab.binop] "visiting {e} : {type} =?= {maxType}"
if (← isDefEqGuarded maxType type) then
return t
else
trace[Elab.binop] "added coercion: {e} : {type} => {maxType}"
withRef ref <| return Tree.term ref (← mkCoe maxType type e)
@[builtinTermElab binop]
def elabBinOp : TermElab := fun stx expectedType? => do
let tree ← toTree stx
let r ← analyze tree expectedType?
trace[Elab.binop] "hasUncomparable: {r.hasUncomparable}, maxType: {r.max?}"
if r.hasUncomparable || r.max?.isNone then
let result ← toExpr tree
ensureHasType expectedType? result
else
let result ← toExpr (← applyCoe tree r.max?.get!)
trace[Elab.binop] "result: {result}"
ensureHasType expectedType? result
@[builtinTermElab binop_lazy]
def elabBinOpLazy : TermElab := elabBinOp
/--
Decompose `e` into `(r, a, b)`.
Remark: it assumes the last two arguments are explicit. -/
private def relation? (e : Expr) : MetaM (Option (Expr × Expr × Expr)) :=
if e.getAppNumArgs < 2 then
return none
else
return some (e.appFn!.appFn!, e.appFn!.appArg!, e.appArg!)
@[builtinTermElab «calc»]
def elabBinCalc : TermElab := fun stx expectedType? => do
let stepStxs := stx[1].getArgs
let mut proofs := #[]
let mut types := #[]
for stepStx in stepStxs do
let type ← elabType stepStx[0]
let some (_, lhs, _) ← relation? type |
throwErrorAt stepStx[0] "invalid 'calc' step, relation expected{indentExpr type}"
if types.size > 0 then
let some (_, _, prevRhs) ← relation? types.back | unreachable!
unless (← isDefEqGuarded lhs prevRhs) do
throwErrorAt stepStx[0] "invalid 'calc' step, left-hand-side is {indentD m!"{lhs} : {← inferType lhs}"}\nprevious right-hand-side is{indentD m!"{prevRhs} : {← inferType prevRhs}"}"
types := types.push type
let proof ← elabTermEnsuringType stepStx[2] type
synthesizeSyntheticMVars
proofs := proofs.push proof
let mut result := proofs[0]
let mut resultType := types[0]
for i in [1:proofs.size] do
let some (r, a, b) ← relation? resultType | unreachable!
let some (s, _, c) ← relation? (← instantiateMVars types[i]) | unreachable!
let (α, β, γ) := (← inferType a, ← inferType b, ← inferType c)
let (u_1, u_2, u_3) := (← getLevel α, ← getLevel β, ← getLevel γ)
let t ← mkFreshExprMVar (← mkArrow α (← mkArrow γ (mkSort levelZero)))
let selfType := mkAppN (Lean.mkConst ``Trans [u_1, u_2, u_3]) #[α, β, γ, r, s, t]
match (← trySynthInstance selfType) with
| LOption.some self =>
result := mkAppN (Lean.mkConst ``Trans.trans [u_1, u_2, u_3]) #[α, β, γ, r, s, t, self, a, b, c, result, proofs[i]]
resultType := (← instantiateMVars (← inferType result)).headBeta
unless (← relation? resultType).isSome do
throwErrorAt stepStxs[i] "invalid 'calc' step, step result is not a relation{indentExpr resultType}"
| _ => throwErrorAt stepStxs[i] "invalid 'calc' step, failed to synthesize `Trans` instance{indentExpr selfType}"
pure ()
ensureHasType expectedType? result
builtin_initialize
registerTraceClass `Elab.binop
end BinOp
end Lean.Elab.Term
|
cdfc47f44a404ff4baeafb0a14fb685030520393 | 367134ba5a65885e863bdc4507601606690974c1 | /src/data/fin2.lean | af64c5e3b49d98b06785f3ae40d41a943244d690 | [
"Apache-2.0"
] | permissive | kodyvajjha/mathlib | 9bead00e90f68269a313f45f5561766cfd8d5cad | b98af5dd79e13a38d84438b850a2e8858ec21284 | refs/heads/master | 1,624,350,366,310 | 1,615,563,062,000 | 1,615,563,062,000 | 162,666,963 | 0 | 0 | Apache-2.0 | 1,545,367,651,000 | 1,545,367,651,000 | null | UTF-8 | Lean | false | false | 3,184 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
open nat
universes u
/-- An alternate definition of `fin n` defined as an inductive type
instead of a subtype of `nat`. This is useful for its induction
principle and different definitional equalities. -/
inductive fin2 : ℕ → Type
| fz {n} : fin2 (succ n)
| fs {n} : fin2 n → fin2 (succ n)
namespace fin2
/-- Define a dependent function on `fin2 (succ n)` by giving its value at
zero (`H1`) and by giving a dependent function on the rest (`H2`). -/
@[elab_as_eliminator]
protected def cases' {n} {C : fin2 (succ n) → Sort u} (H1 : C fz) (H2 : Π n, C (fs n)) :
Π (i : fin2 (succ n)), C i
| fz := H1
| (fs n) := H2 n
/-- Ex falso. The dependent eliminator for the empty `fin2 0` type. -/
def elim0 {C : fin2 0 → Sort u} : Π (i : fin2 0), C i.
/-- convert a `fin2` into a `nat` -/
def to_nat : Π {n}, fin2 n → ℕ
| ._ (@fz n) := 0
| ._ (@fs n i) := succ (to_nat i)
/-- convert a `nat` into a `fin2` if it is in range -/
def opt_of_nat : Π {n} (k : ℕ), option (fin2 n)
| 0 _ := none
| (succ n) 0 := some fz
| (succ n) (succ k) := fs <$> @opt_of_nat n k
/-- `i + k : fin2 (n + k)` when `i : fin2 n` and `k : ℕ` -/
def add {n} (i : fin2 n) : Π k, fin2 (n + k)
| 0 := i
| (succ k) := fs (add k)
/-- `left k` is the embedding `fin2 n → fin2 (k + n)` -/
def left (k) : Π {n}, fin2 n → fin2 (k + n)
| ._ (@fz n) := fz
| ._ (@fs n i) := fs (left i)
/-- `insert_perm a` is a permutation of `fin2 n` with the following properties:
* `insert_perm a i = i+1` if `i < a`
* `insert_perm a a = 0`
* `insert_perm a i = i` if `i > a` -/
def insert_perm : Π {n}, fin2 n → fin2 n → fin2 n
| ._ (@fz n) (@fz ._) := fz
| ._ (@fz n) (@fs ._ j) := fs j
| ._ (@fs (succ n) i) (@fz ._) := fs fz
| ._ (@fs (succ n) i) (@fs ._ j) := match insert_perm i j with fz := fz | fs k := fs (fs k) end
/-- `remap_left f k : fin2 (m + k) → fin2 (n + k)` applies the function
`f : fin2 m → fin2 n` to inputs less than `m`, and leaves the right part
on the right (that is, `remap_left f k (m + i) = n + i`). -/
def remap_left {m n} (f : fin2 m → fin2 n) : Π k, fin2 (m + k) → fin2 (n + k)
| 0 i := f i
| (succ k) (@fz ._) := fz
| (succ k) (@fs ._ i) := fs (remap_left _ i)
/-- This is a simple type class inference prover for proof obligations
of the form `m < n` where `m n : ℕ`. -/
class is_lt (m n : ℕ) := (h : m < n)
instance is_lt.zero (n) : is_lt 0 (succ n) := ⟨succ_pos _⟩
instance is_lt.succ (m n) [l : is_lt m n] : is_lt (succ m) (succ n) := ⟨succ_lt_succ l.h⟩
/-- Use type class inference to infer the boundedness proof, so that we
can directly convert a `nat` into a `fin2 n`. This supports
notation like `&1 : fin 3`. -/
def of_nat' : Π {n} m [is_lt m n], fin2 n
| 0 m ⟨h⟩ := absurd h (not_lt_zero _)
| (succ n) 0 ⟨h⟩ := fz
| (succ n) (succ m) ⟨h⟩ := fs (@of_nat' n m ⟨lt_of_succ_lt_succ h⟩)
local prefix `&`:max := of_nat'
instance : inhabited (fin2 1) := ⟨fz⟩
end fin2
|
9b0c42d63584829b71bbc5ac26be90585857cddc | ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5 | /src/Lean/Meta/Transform.lean | 0d8b87a9898fb96c96a6bac1f72515fd6a9ab069 | [
"Apache-2.0"
] | permissive | dupuisf/lean4 | d082d13b01243e1de29ae680eefb476961221eef | 6a39c65bd28eb0e28c3870188f348c8914502718 | refs/heads/master | 1,676,948,755,391 | 1,610,665,114,000 | 1,610,665,114,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,015 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Basic
namespace Lean
inductive TransformStep where
| done (e : Expr)
| visit (e : Expr)
namespace Core
/--
Tranform the expression `input` using `pre` and `post`.
- `pre s` is invoked before visiting the children of subterm 's'. If the result is `TransformStep.visit sNew`, then
`sNew` is traversed by transform. If the result is `TransformStep.visit sNew`, then `s` is just replaced with `sNew`.
In both cases, `sNew` must be definitionally equal to `s`
- `post s` is invoked after visiting the children of subterm `s`.
The term `s` in both `pre s` and `post s` may contain loose bound variables. So, this method is not appropriate for
if one needs to apply operations (e.g., `whnf`, `inferType`) that do not handle loose bound variables.
Consider using `Meta.transform` to avoid loose bound variables.
This method is useful for applying transformations such as beta-reduction and delta-reduction.
-/
partial def transform {m} [Monad m] [MonadLiftT CoreM m] [MonadControlT CoreM m]
(input : Expr)
(pre : Expr → m TransformStep := fun e => return TransformStep.visit e)
(post : Expr → m TransformStep := fun e => return TransformStep.done e)
: m Expr :=
let inst : STWorld IO.RealWorld m := ⟨⟩
let inst : MonadLiftT (ST IO.RealWorld) m := { monadLift := fun x => liftM (m := CoreM) (liftM (m := ST IO.RealWorld) x) }
let rec visit (e : Expr) : MonadCacheT Expr Expr m Expr :=
checkCache e fun _ => Core.withIncRecDepth do
let rec visitPost (e : Expr) : MonadCacheT Expr Expr m Expr := do
match (← post e) with
| TransformStep.done e => pure e
| TransformStep.visit e => visit e
match (← pre e) with
| TransformStep.done e => pure e
| TransformStep.visit e => match e with
| Expr.forallE _ d b _ => visitPost (e.updateForallE! (← visit d) (← visit b))
| Expr.lam _ d b _ => visitPost (e.updateLambdaE! (← visit d) (← visit b))
| Expr.letE _ t v b _ => visitPost (e.updateLet! (← visit t) (← visit v) (← visit b))
| Expr.app .. => e.withApp fun f args => do visitPost (mkAppN (← visit f) (← args.mapM visit))
| Expr.mdata _ b _ => visitPost (e.updateMData! (← visit b))
| Expr.proj _ _ b _ => visitPost (e.updateProj! (← visit b))
| _ => visitPost e
visit input |>.run
def betaReduce (e : Expr) : CoreM Expr :=
transform e (pre := fun e => return TransformStep.visit e.headBeta)
end Core
namespace Meta
/--
Similar to `Core.transform`, but terms provided to `pre` and `post` do not contain loose bound variables.
So, it is safe to use any `MetaM` method at `pre` and `post`. -/
partial def transform {m} [Monad m] [MonadLiftT MetaM m] [MonadControlT MetaM m]
(input : Expr)
(pre : Expr → m TransformStep := fun e => return TransformStep.visit e)
(post : Expr → m TransformStep := fun e => return TransformStep.done e)
: m Expr :=
let inst : STWorld IO.RealWorld m := ⟨⟩
let inst : MonadLiftT (ST IO.RealWorld) m := { monadLift := fun x => liftM (m := MetaM) (liftM (m := ST IO.RealWorld) x) }
let rec visit (e : Expr) : MonadCacheT Expr Expr m Expr :=
checkCache e fun _ => Meta.withIncRecDepth do
let rec visitPost (e : Expr) : MonadCacheT Expr Expr m Expr := do
match (← post e) with
| TransformStep.done e => pure e
| TransformStep.visit e => visit e
let rec visitLambda (fvars : Array Expr) (e : Expr) : MonadCacheT Expr Expr m Expr := do
match e with
| Expr.lam n d b c =>
withLocalDecl n c.binderInfo (← visit (d.instantiateRev fvars)) fun x =>
visitLambda (fvars.push x) b
| e => visitPost (← mkLambdaFVars fvars (← visit (e.instantiateRev fvars)))
let rec visitForall (fvars : Array Expr) (e : Expr) : MonadCacheT Expr Expr m Expr := do
match e with
| Expr.forallE n d b c =>
withLocalDecl n c.binderInfo (← visit (d.instantiateRev fvars)) fun x =>
visitForall (fvars.push x) b
| e => visitPost (← mkForallFVars fvars (← visit (e.instantiateRev fvars)))
let rec visitLet (fvars : Array Expr) (e : Expr) : MonadCacheT Expr Expr m Expr := do
match e with
| Expr.letE n t v b _ =>
withLetDecl n (← visit (t.instantiateRev fvars)) (← visit (v.instantiateRev fvars)) fun x =>
visitLet (fvars.push x) b
| e => visitPost (← mkLetFVars fvars (← visit (e.instantiateRev fvars)))
let visitApp (e : Expr) : MonadCacheT Expr Expr m Expr :=
e.withApp fun f args => do
visitPost (mkAppN (← visit f) (← args.mapM visit))
match (← pre e) with
| TransformStep.done e => pure e
| TransformStep.visit e => match e with
| Expr.forallE .. => visitLambda #[] e
| Expr.lam .. => visitForall #[] e
| Expr.letE .. => visitLet #[] e
| Expr.app .. => visitApp e
| Expr.mdata _ b _ => visitPost (e.updateMData! (← visit b))
| Expr.proj _ _ b _ => visitPost (e.updateProj! (← visit b))
| _ => visitPost e
visit input |>.run
def zetaReduce (e : Expr) : MetaM Expr := do
let lctx ← getLCtx
let pre (e : Expr) : CoreM TransformStep := do
match e with
| Expr.fvar fvarId _ =>
match lctx.find? fvarId with
| none => return TransformStep.done e
| some localDecl =>
if let some value := localDecl.value? then
return TransformStep.visit value
else
return TransformStep.done e
| e => if e.hasFVar then return TransformStep.visit e else return TransformStep.done e
liftM (m := CoreM) <| Core.transform e (pre := pre)
end Meta
end Lean
|
41061bca0a7e60300900f4f3cea57a2063618dd0 | 957a80ea22c5abb4f4670b250d55534d9db99108 | /library/init/data/subtype/basic.lean | e512ae3a620610717a27e37894a95515fc42e013 | [
"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 | 814 | 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, Jeremy Avigad
-/
prelude
import init.logic
open decidable
universes u
namespace subtype
def exists_of_subtype {α : Type u} {p : α → Prop} : { x // p x } → ∃ x, p x
| ⟨a, h⟩ := ⟨a, h⟩
variables {α : Type u} {p : α → Prop}
lemma tag_irrelevant {a : α} (h1 h2 : p a) : mk a h1 = mk a h2 :=
rfl
protected lemma eq : ∀ {a1 a2 : {x // p x}}, val a1 = val a2 → a1 = a2
| ⟨x, h1⟩ ⟨.(x), h2⟩ rfl := rfl
@[simp] lemma eta (a : {x // p x}) (h : p (val a)) : mk (val a) h = a :=
subtype.eq rfl
end subtype
open subtype
instance {α : Type u} {p : α → Prop} {a : α} (h : p a) : inhabited {x // p x} :=
⟨⟨a, h⟩⟩
|
e33dfcf512909f086c4072a3bddc5f87aad2bdeb | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/analysis/convex/uniform.lean | 442e50d6e55a479420a440a378bcc44a3a9f0327 | [
"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 | 6,177 | lean | /-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import analysis.convex.strict_convex_space
/-!
# Uniformly convex spaces
This file defines uniformly convex spaces, which are real normed vector spaces in which for all
strictly positive `ε`, there exists some strictly positive `δ` such that `ε ≤ ∥x - y∥` implies
`∥x + y∥ ≤ 2 - δ` for all `x` and `y` of norm at most than `1`. This means that the triangle
inequality is strict with a uniform bound, as opposed to strictly convex spaces where the triangle
inequality is strict but not necessarily uniformly (`∥x + y∥ < ∥x∥ + ∥y∥` for all `x` and `y` not in
the same ray).
## Main declarations
`uniform_convex_space E` means that `E` is a uniformly convex space.
## TODO
* Milman-Pettis
* Hanner's inequalities
## Tags
convex, uniformly convex
-/
open set metric
open_locale convex pointwise
/-- A *uniformly convex space* is a real normed space where the triangle inequality is strict with a
uniform bound. Namely, over the `x` and `y` of norm `1`, `∥x + y∥` is uniformly bounded above
by a constant `< 2` when `∥x - y∥` is uniformly bounded below by a positive constant.
See also `uniform_convex_space.of_uniform_convex_closed_unit_ball`. -/
class uniform_convex_space (E : Type*) [seminormed_add_comm_group E] : Prop :=
(uniform_convex : ∀ ⦃ε : ℝ⦄, 0 < ε → ∃ δ, 0 < δ ∧
∀ ⦃x : E⦄, ∥x∥ = 1 → ∀ ⦃y⦄, ∥y∥ = 1 → ε ≤ ∥x - y∥ → ∥x + y∥ ≤ 2 - δ)
variables {E : Type*}
section seminormed_add_comm_group
variables (E) [seminormed_add_comm_group E] [uniform_convex_space E] {ε : ℝ}
lemma exists_forall_sphere_dist_add_le_two_sub (hε : 0 < ε) :
∃ δ, 0 < δ ∧ ∀ ⦃x : E⦄, ∥x∥ = 1 → ∀ ⦃y⦄, ∥y∥ = 1 → ε ≤ ∥x - y∥ → ∥x + y∥ ≤ 2 - δ :=
uniform_convex_space.uniform_convex hε
variables [normed_space ℝ E]
lemma exists_forall_closed_ball_dist_add_le_two_sub (hε : 0 < ε) :
∃ δ, 0 < δ ∧ ∀ ⦃x : E⦄, ∥x∥ ≤ 1 → ∀ ⦃y⦄, ∥y∥ ≤ 1 → ε ≤ ∥x - y∥ → ∥x + y∥ ≤ 2 - δ :=
begin
have hε' : 0 < ε / 3 := div_pos hε zero_lt_three,
obtain ⟨δ, hδ, h⟩ := exists_forall_sphere_dist_add_le_two_sub E hε',
set δ' := min (1/2) (min (ε/3) $ δ/3),
refine ⟨δ', lt_min one_half_pos $ lt_min hε' (div_pos hδ zero_lt_three), λ x hx y hy hxy, _⟩,
obtain hx' | hx' := le_or_lt (∥x∥) (1 - δ'),
{ exact (norm_add_le_of_le hx' hy).trans (sub_add_eq_add_sub _ _ _).le },
obtain hy' | hy' := le_or_lt (∥y∥) (1 - δ'),
{ exact (norm_add_le_of_le hx hy').trans (add_sub_assoc _ _ _).ge },
have hδ' : 0 < 1 - δ' := sub_pos_of_lt (min_lt_of_left_lt one_half_lt_one),
have h₁ : ∀ z : E, 1 - δ' < ∥z∥ → ∥∥z∥⁻¹ • z∥ = 1,
{ rintro z hz,
rw [norm_smul_of_nonneg (inv_nonneg.2 $ norm_nonneg _), inv_mul_cancel (hδ'.trans hz).ne'] },
have h₂ : ∀ z : E, ∥z∥ ≤ 1 → 1 - δ' ≤ ∥z∥ → ∥∥z∥⁻¹ • z - z∥ ≤ δ',
{ rintro z hz hδz,
nth_rewrite 2 ←one_smul ℝ z,
rwa [←sub_smul, norm_smul_of_nonneg (sub_nonneg_of_le $ one_le_inv (hδ'.trans_le hδz) hz),
sub_mul, inv_mul_cancel (hδ'.trans_le hδz).ne', one_mul, sub_le] },
set x' := ∥x∥⁻¹ • x,
set y' := ∥y∥⁻¹ • y,
have hxy' : ε/3 ≤ ∥x' - y'∥ :=
calc ε/3 = ε - (ε/3 + ε/3) : by ring
... ≤ ∥x - y∥ - (∥x' - x∥ + ∥y' - y∥) : sub_le_sub hxy (add_le_add
((h₂ _ hx hx'.le).trans $ min_le_of_right_le $ min_le_left _ _) $
(h₂ _ hy hy'.le).trans $ min_le_of_right_le $ min_le_left _ _)
... ≤ _ : begin
have : ∀ x' y', x - y = x' - y' + (x - x') + (y' - y) := λ _ _, by abel,
rw [sub_le_iff_le_add, norm_sub_rev _ x, ←add_assoc, this],
exact norm_add₃_le _ _ _,
end,
calc ∥x + y∥ ≤ ∥x' + y'∥ + ∥x' - x∥ + ∥y' - y∥ : begin
have : ∀ x' y', x + y = x' + y' + (x - x') + (y - y') := λ _ _, by abel,
rw [norm_sub_rev, norm_sub_rev y', this],
exact norm_add₃_le _ _ _,
end
... ≤ 2 - δ + δ' + δ'
: add_le_add_three (h (h₁ _ hx') (h₁ _ hy') hxy') (h₂ _ hx hx'.le) (h₂ _ hy hy'.le)
... ≤ 2 - δ' : begin
rw [←le_sub_iff_add_le, ←le_sub_iff_add_le, sub_sub, sub_sub],
refine sub_le_sub_left _ _,
ring_nf,
rw ←mul_div_cancel' δ three_ne_zero,
exact mul_le_mul_of_nonneg_left (min_le_of_right_le $ min_le_right _ _) three_pos.le,
end,
end
lemma exists_forall_closed_ball_dist_add_le_two_mul_sub (hε : 0 < ε) (r : ℝ) :
∃ δ, 0 < δ ∧ ∀ ⦃x : E⦄, ∥x∥ ≤ r → ∀ ⦃y⦄, ∥y∥ ≤ r → ε ≤ ∥x - y∥ → ∥x + y∥ ≤ 2 * r - δ :=
begin
obtain hr | hr := le_or_lt r 0,
{ exact ⟨1, one_pos, λ x hx y hy h, (hε.not_le $ h.trans $ (norm_sub_le _ _).trans $
add_nonpos (hx.trans hr) (hy.trans hr)).elim⟩ },
obtain ⟨δ, hδ, h⟩ := exists_forall_closed_ball_dist_add_le_two_sub E (div_pos hε hr),
refine ⟨δ * r, mul_pos hδ hr, λ x hx y hy hxy, _⟩,
rw [←div_le_one hr, div_eq_inv_mul, ←norm_smul_of_nonneg (inv_nonneg.2 hr.le)] at hx hy;
try { apply_instance },
have := h hx hy,
simp_rw [←smul_add, ←smul_sub, norm_smul_of_nonneg (inv_nonneg.2 hr.le), ←div_eq_inv_mul,
div_le_div_right hr, div_le_iff hr, sub_mul] at this,
exact this hxy,
end
end seminormed_add_comm_group
variables [normed_add_comm_group E] [normed_space ℝ E] [uniform_convex_space E]
@[priority 100] -- See note [lower instance priority]
instance uniform_convex_space.to_strict_convex_space : strict_convex_space ℝ E :=
strict_convex_space.of_norm_add_lt one_half_pos one_half_pos (add_halves _) $ λ x y hx hy hxy, begin
obtain ⟨δ, hδ, h⟩ := exists_forall_closed_ball_dist_add_le_two_sub E (norm_sub_pos_iff.2 hxy),
rw [←smul_add, norm_smul_of_nonneg one_half_pos.le, ←lt_div_iff' one_half_pos, one_div_one_div],
exact (h hx hy le_rfl).trans_lt (sub_lt_self _ hδ),
end
|
e068feddde209d77b21209ee76038421083d0c8f | 97c8e5d8aca4afeebb5b335f26a492c53680efc8 | /ground_zero/HITs/rat.lean | 5b21d4d62bf2962600d74df3c2e97995d6752cc2 | [] | no_license | jfrancese/lean | cf32f0d8d5520b6f0e9d3987deb95841c553c53c | 06e7efaecce4093d97fb5ecc75479df2ef1dbbdb | refs/heads/master | 1,587,915,151,351 | 1,551,012,140,000 | 1,551,012,140,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 646 | lean | import ground_zero.HITs.int
/-
Rational numbers as quotient of ℤ × ℕ.
* HoTT 11.1
-/
local notation ℤ := ground_zero.HITs.int
namespace ground_zero.HITs
def rat.rel : ℤ × ℕ → ℤ × ℕ → Prop
| ⟨u, a⟩ ⟨v, b⟩ := u * int.pos (b + 1) = v * int.pos (a + 1)
def rat := quot rat.rel
notation `ℚ` := rat
namespace rat
namespace product
def add : ℤ × ℕ → ℤ × ℕ → ℤ × ℕ
| ⟨u, a⟩ ⟨v, b⟩ := ⟨u * int.pos b + v * int.pos a, a * b⟩
def mul : ℤ × ℕ → ℤ × ℕ → ℤ × ℕ
| ⟨u, a⟩ ⟨v, b⟩ := ⟨u * v, a * b⟩
end product
end rat
end ground_zero.HITs |
4e8a89baaa0f7291f18eff1c35ba47cb442abf23 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/category_theory/category/ulift.lean | 69d4220351f155e8ad28c194a701027320b4e64f | [
"Apache-2.0"
] | permissive | AntoineChambert-Loir/mathlib | 64aabb896129885f12296a799818061bc90da1ff | 07be904260ab6e36a5769680b6012f03a4727134 | refs/heads/master | 1,693,187,631,771 | 1,636,719,886,000 | 1,636,719,886,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,269 | lean | /-
Copyright (c) 2021 Adam Topaz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Adam Topaz
-/
import category_theory.category.basic
import category_theory.equivalence
import category_theory.filtered
/-!
# Basic API for ulift
This file contains a very basic API for working with the categorical
instance on `ulift C` where `C` is a type with a category instance.
1. `category_theory.ulift.up` is the functorial version of the usual `ulift.up`.
2. `category_theory.ulift.down` is the functorial version of the usual `ulift.down`.
3. `category_theory.ulift.equivalence` is the categorical equivalence between
`C` and `ulift C`.
# ulift_hom
Given a type `C : Type u`, `ulift_hom.{w} C` is just an alias for `C`.
If we have `category.{v} C`, then `ulift_hom.{w} C` is endowed with a category instance
whose morphisms are obtained by applying `ulift.{w}` to the morphisms from `C`.
This is a category equivalent to `C`. The forward direction of the equivalence is `ulift_hom.up`,
the backward direction is `ulift_hom.donw` and the equivalence is `ulift_hom.equiv`.
# as_small
This file also contains a construction which takes a type `C : Type u` with a
category instance `category.{v} C` and makes a small category
`as_small.{w} C : Type (max w v u)` equivalent to `C`.
The forward direction of the equivalence, `C ⥤ as_small C`, is denoted `as_small.up`
and the backward direction is `as_small.down`. The equivalence itself is `as_small.equiv`.
-/
universes w₁ v₁ v₂ u₁ u₂
namespace category_theory
variables {C : Type u₁} [category.{v₁} C]
/-- The functorial version of `ulift.up`. -/
@[simps]
def ulift.up : C ⥤ (ulift.{u₂} C) :=
{ obj := ulift.up,
map := λ X Y f, f }
/-- The functorial version of `ulift.down`. -/
@[simps]
def ulift.down : (ulift.{u₂} C) ⥤ C :=
{ obj := ulift.down,
map := λ X Y f, f }
/-- The categorical equivalence between `C` and `ulift C`. -/
@[simps]
def ulift.equivalence : C ≌ (ulift.{u₂} C) :=
{ functor := ulift.up,
inverse := ulift.down,
unit_iso :=
{ hom := 𝟙 _,
inv := 𝟙 _ },
counit_iso :=
{ hom :=
{ app := λ X, 𝟙 _,
naturality' := λ X Y f, by {change f ≫ 𝟙 _ = 𝟙 _ ≫ f, simp} },
inv :=
{ app := λ X, 𝟙 _,
naturality' := λ X Y f, by {change f ≫ 𝟙 _ = 𝟙 _ ≫ f, simp} },
hom_inv_id' := by {ext, change (𝟙 _) ≫ (𝟙 _) = 𝟙 _, simp},
inv_hom_id' := by {ext, change (𝟙 _) ≫ (𝟙 _) = 𝟙 _, simp} },
functor_unit_iso_comp' := λ X, by {change (𝟙 X) ≫ (𝟙 X) = 𝟙 X, simp} }
instance [is_filtered C] : is_filtered (ulift.{u₂} C) :=
is_filtered.of_equivalence ulift.equivalence
instance [is_cofiltered C] : is_cofiltered (ulift.{u₂} C) :=
is_cofiltered.of_equivalence ulift.equivalence
section ulift_hom
/-- `ulift_hom.{w} C` is an alias for `C`, which is endowed with a category instance
whose morphisms are obtained by applying `ulift.{w}` to the morphisms from `C`.
-/
def {w u} ulift_hom (C : Type u) := C
instance {C} [inhabited C] : inhabited (ulift_hom C) := ⟨(arbitrary C : C)⟩
/-- The obvious function `ulift_hom C → C`. -/
def ulift_hom.obj_down {C} (A : ulift_hom C) : C := A
/-- The obvious function `C → ulift_hom C`. -/
def ulift_hom.obj_up {C} (A : C) : ulift_hom C := A
@[simp] lemma obj_down_obj_up {C} (A : C) : (ulift_hom.obj_up A).obj_down = A := rfl
@[simp] lemma obj_up_obj_down {C} (A : ulift_hom C) : ulift_hom.obj_up A.obj_down = A := rfl
instance : category.{max v₂ v₁} (ulift_hom.{v₂} C) :=
{ hom := λ A B, ulift.{v₂} $ A.obj_down ⟶ B.obj_down,
id := λ A, ⟨𝟙 _⟩,
comp := λ A B C f g, ⟨f.down ≫ g.down⟩}
/-- One half of the quivalence between `C` and `ulift_hom C`. -/
@[simps]
def ulift_hom.up : C ⥤ ulift_hom C :=
{ obj := ulift_hom.obj_up,
map := λ X Y f, ⟨f⟩ }
/-- One half of the quivalence between `C` and `ulift_hom C`. -/
@[simps]
def ulift_hom.down : ulift_hom C ⥤ C :=
{ obj := ulift_hom.obj_down,
map := λ X Y f, f.down }
/-- The equivalence between `C` and `ulift_hom C`. -/
def ulift_hom.equiv : C ≌ ulift_hom C :=
{ functor := ulift_hom.up,
inverse := ulift_hom.down,
unit_iso := nat_iso.of_components (λ A, eq_to_iso rfl) (by tidy),
counit_iso := nat_iso.of_components (λ A, eq_to_iso rfl) (by tidy) }
instance [is_filtered C] : is_filtered (ulift_hom C) :=
is_filtered.of_equivalence ulift_hom.equiv
instance [is_cofiltered C] : is_cofiltered (ulift_hom C) :=
is_cofiltered.of_equivalence ulift_hom.equiv
end ulift_hom
/-- `as_small C` is a small category equivalent to `C`.
More specifically, if `C : Type u` is endowed with `category.{v} C`, then
`as_small.{w} C : Type (max w v u)` is endowed with an instance of a small category.
The objects and morphisms of `as_small C` are defined by applying `ulift` to the
objects and morphisms of `C`.
Note: We require a category instance for this definition in order to have direct
access to the universe level `v`.
-/
@[nolint unused_arguments]
def {w v u} as_small (C : Type u) [category.{v} C] := ulift.{max w v} C
instance : small_category (as_small.{w₁} C) :=
{ hom := λ X Y, ulift.{(max w₁ u₁)} $ X.down ⟶ Y.down,
id := λ X, ⟨𝟙 _⟩,
comp := λ X Y Z f g, ⟨f.down ≫ g.down⟩ }
/-- One half of the equivalence between `C` and `as_small C`. -/
@[simps]
def as_small.up : C ⥤ as_small C :=
{ obj := λ X, ⟨X⟩,
map := λ X Y f, ⟨f⟩ }
/-- One half of the equivalence between `C` and `as_small C`. -/
@[simps]
def as_small.down : as_small C ⥤ C :=
{ obj := λ X, X.down,
map := λ X Y f, f.down }
/-- The equivalence between `C` and `as_small C`. -/
@[simps]
def as_small.equiv : C ≌ as_small C :=
{ functor := as_small.up,
inverse := as_small.down,
unit_iso := nat_iso.of_components (λ X, eq_to_iso rfl) (by tidy),
counit_iso := nat_iso.of_components (λ X, eq_to_iso $ by { ext, refl }) (by tidy) }
instance [inhabited C] : inhabited (as_small C) := ⟨⟨arbitrary _⟩⟩
instance [is_filtered C] : is_filtered (as_small C) :=
is_filtered.of_equivalence as_small.equiv
instance [is_cofiltered C] : is_cofiltered (as_small C) :=
is_cofiltered.of_equivalence as_small.equiv
end category_theory
|
1bcf24500d698121bbc5aebaeb4cff0ff5c2dcca | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/section_var_bug.lean | 7f48bd207e22c0be81408d5023b641022bc0bd2a | [
"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 | 217 | lean | section
variable {A : Type}
variable [s : setoid A]
variable {B : quotient s → Type}
include s
attribute [reducible]
protected definition ex (f : Π a, B ⟦a⟧) (a : A) : Σ q, B q :=
sigma.mk ⟦a⟧ (f a)
end
|
b572a24150dbacf68204eb27eec0081445d056ea | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/analysis/inner_product_space/l2_space.lean | 10d087817b0ce32aaec7b0c6dccb6c562ed64848 | [
"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 | 25,381 | lean | /-
Copyright (c) 2022 Heather Macbeth. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Heather Macbeth
-/
import analysis.inner_product_space.projection
import analysis.normed_space.lp_space
import analysis.inner_product_space.pi_L2
/-!
# Hilbert sum of a family of inner product spaces
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Given a family `(G : ι → Type*) [Π i, inner_product_space 𝕜 (G i)]` of inner product spaces, this
file equips `lp G 2` with an inner product space structure, where `lp G 2` consists of those
dependent functions `f : Π i, G i` for which `∑' i, ‖f i‖ ^ 2`, the sum of the norms-squared, is
summable. This construction is sometimes called the *Hilbert sum* of the family `G`. By choosing
`G` to be `ι → 𝕜`, the Hilbert space `ℓ²(ι, 𝕜)` may be seen as a special case of this construction.
We also define a *predicate* `is_hilbert_sum 𝕜 G V`, where `V : Π i, G i →ₗᵢ[𝕜] E`, expressing that
`V` is an `orthogonal_family` and that the associated map `lp G 2 →ₗᵢ[𝕜] E` is surjective.
## Main definitions
* `orthogonal_family.linear_isometry`: Given a Hilbert space `E`, a family `G` of inner product
spaces and a family `V : Π i, G i →ₗᵢ[𝕜] E` of isometric embeddings of the `G i` into `E` with
mutually-orthogonal images, there is an induced isometric embedding of the Hilbert sum of `G`
into `E`.
* `is_hilbert_sum`: Given a Hilbert space `E`, a family `G` of inner product
spaces and a family `V : Π i, G i →ₗᵢ[𝕜] E` of isometric embeddings of the `G i` into `E`,
`is_hilbert_sum 𝕜 G V` means that `V` is an `orthogonal_family` and that the above
linear isometry is surjective.
* `is_hilbert_sum.linear_isometry_equiv`: If a Hilbert space `E` is a Hilbert sum of the
inner product spaces `G i` with respect to the family `V : Π i, G i →ₗᵢ[𝕜] E`, then the
corresponding `orthogonal_family.linear_isometry` can be upgraded to a `linear_isometry_equiv`.
* `hilbert_basis`: We define a *Hilbert basis* of a Hilbert space `E` to be a structure whose single
field `hilbert_basis.repr` is an isometric isomorphism of `E` with `ℓ²(ι, 𝕜)` (i.e., the Hilbert
sum of `ι` copies of `𝕜`). This parallels the definition of `basis`, in `linear_algebra.basis`,
as an isomorphism of an `R`-module with `ι →₀ R`.
* `hilbert_basis.has_coe_to_fun`: More conventionally a Hilbert basis is thought of as a family
`ι → E` of vectors in `E` satisfying certain properties (orthonormality, completeness). We obtain
this interpretation of a Hilbert basis `b` by defining `⇑b`, of type `ι → E`, to be the image
under `b.repr` of `lp.single 2 i (1:𝕜)`. This parallels the definition `basis.has_coe_to_fun` in
`linear_algebra.basis`.
* `hilbert_basis.mk`: Make a Hilbert basis of `E` from an orthonormal family `v : ι → E` of vectors
in `E` whose span is dense. This parallels the definition `basis.mk` in `linear_algebra.basis`.
* `hilbert_basis.mk_of_orthogonal_eq_bot`: Make a Hilbert basis of `E` from an orthonormal family
`v : ι → E` of vectors in `E` whose span has trivial orthogonal complement.
## Main results
* `lp.inner_product_space`: Construction of the inner product space instance on the Hilbert sum
`lp G 2`. Note that from the file `analysis.normed_space.lp_space`, the space `lp G 2` already
held a normed space instance (`lp.normed_space`), and if each `G i` is a Hilbert space (i.e.,
complete), then `lp G 2` was already known to be complete (`lp.complete_space`). So the work
here is to define the inner product and show it is compatible.
* `orthogonal_family.range_linear_isometry`: Given a family `G` of inner product spaces and a family
`V : Π i, G i →ₗᵢ[𝕜] E` of isometric embeddings of the `G i` into `E` with mutually-orthogonal
images, the image of the embedding `orthogonal_family.linear_isometry` of the Hilbert sum of `G`
into `E` is the closure of the span of the images of the `G i`.
* `hilbert_basis.repr_apply_apply`: Given a Hilbert basis `b` of `E`, the entry `b.repr x i` of
`x`'s representation in `ℓ²(ι, 𝕜)` is the inner product `⟪b i, x⟫`.
* `hilbert_basis.has_sum_repr`: Given a Hilbert basis `b` of `E`, a vector `x` in `E` can be
expressed as the "infinite linear combination" `∑' i, b.repr x i • b i` of the basis vectors
`b i`, with coefficients given by the entries `b.repr x i` of `x`'s representation in `ℓ²(ι, 𝕜)`.
* `exists_hilbert_basis`: A Hilbert space admits a Hilbert basis.
## Keywords
Hilbert space, Hilbert sum, l2, Hilbert basis, unitary equivalence, isometric isomorphism
-/
open is_R_or_C submodule filter
open_locale big_operators nnreal ennreal classical complex_conjugate topology
noncomputable theory
variables {ι : Type*}
variables {𝕜 : Type*} [is_R_or_C 𝕜] {E : Type*}
variables [normed_add_comm_group E] [inner_product_space 𝕜 E] [cplt : complete_space E]
variables {G : ι → Type*} [Π i, normed_add_comm_group (G i)] [Π i, inner_product_space 𝕜 (G i)]
local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y
notation `ℓ²(`ι`, `𝕜`)` := lp (λ i : ι, 𝕜) 2
/-! ### Inner product space structure on `lp G 2` -/
namespace lp
lemma summable_inner (f g : lp G 2) : summable (λ i, ⟪f i, g i⟫) :=
begin
-- Apply the Direct Comparison Test, comparing with ∑' i, ‖f i‖ * ‖g i‖ (summable by Hölder)
refine summable_of_norm_bounded (λ i, ‖f i‖ * ‖g i‖) (lp.summable_mul _ f g) _,
{ rw real.is_conjugate_exponent_iff; norm_num },
intros i,
-- Then apply Cauchy-Schwarz pointwise
exact norm_inner_le_norm _ _,
end
instance : inner_product_space 𝕜 (lp G 2) :=
{ inner := λ f g, ∑' i, ⟪f i, g i⟫,
norm_sq_eq_inner := λ f, begin
calc ‖f‖ ^ 2 = ‖f‖ ^ (2:ℝ≥0∞).to_real : by norm_cast
... = ∑' i, ‖f i‖ ^ (2:ℝ≥0∞).to_real : lp.norm_rpow_eq_tsum _ f
... = ∑' i, ‖f i‖ ^ 2 : by norm_cast
... = ∑' i, re ⟪f i, f i⟫ : by simp only [@norm_sq_eq_inner 𝕜]
... = re (∑' i, ⟪f i, f i⟫) : (is_R_or_C.re_clm.map_tsum _).symm
... = _ : by congr,
{ norm_num },
{ exact summable_inner f f },
end,
conj_symm := λ f g, begin
calc conj _ = conj ∑' i, ⟪g i, f i⟫ : by congr
... = ∑' i, conj ⟪g i, f i⟫ : is_R_or_C.conj_cle.map_tsum
... = ∑' i, ⟪f i, g i⟫ : by simp only [inner_conj_symm]
... = _ : by congr,
end,
add_left := λ f₁ f₂ g, begin
calc _ = ∑' i, ⟪(f₁ + f₂) i, g i⟫ : _
... = ∑' i, (⟪f₁ i, g i⟫ + ⟪f₂ i, g i⟫) :
by simp only [inner_add_left, pi.add_apply, coe_fn_add]
... = (∑' i, ⟪f₁ i, g i⟫) + ∑' i, ⟪f₂ i, g i⟫ : tsum_add _ _
... = _ : by congr,
{ congr, },
{ exact summable_inner f₁ g },
{ exact summable_inner f₂ g }
end,
smul_left := λ f g c, begin
calc _ = ∑' i, ⟪c • f i, g i⟫ : _
... = ∑' i, conj c * ⟪f i, g i⟫ : by simp only [inner_smul_left]
... = conj c * ∑' i, ⟪f i, g i⟫ : tsum_mul_left
... = _ : _,
{ simp only [coe_fn_smul, pi.smul_apply] },
{ congr },
end,
.. lp.normed_space }
lemma inner_eq_tsum (f g : lp G 2) : ⟪f, g⟫ = ∑' i, ⟪f i, g i⟫ := rfl
lemma has_sum_inner (f g : lp G 2) : has_sum (λ i, ⟪f i, g i⟫) ⟪f, g⟫ :=
(summable_inner f g).has_sum
lemma inner_single_left (i : ι) (a : G i) (f : lp G 2) : ⟪lp.single 2 i a, f⟫ = ⟪a, f i⟫ :=
begin
refine (has_sum_inner (lp.single 2 i a) f).unique _,
convert has_sum_ite_eq i ⟪a, f i⟫,
ext j,
rw lp.single_apply,
split_ifs,
{ subst h },
{ simp }
end
lemma inner_single_right (i : ι) (a : G i) (f : lp G 2) : ⟪f, lp.single 2 i a⟫ = ⟪f i, a⟫ :=
by simpa [inner_conj_symm] using congr_arg conj (@inner_single_left _ 𝕜 _ _ _ _ i a f)
end lp
/-! ### Identification of a general Hilbert space `E` with a Hilbert sum -/
namespace orthogonal_family
variables {V : Π i, G i →ₗᵢ[𝕜] E} (hV : orthogonal_family 𝕜 G V)
include cplt hV
protected lemma summable_of_lp (f : lp G 2) : summable (λ i, V i (f i)) :=
begin
rw hV.summable_iff_norm_sq_summable,
convert (lp.mem_ℓp f).summable _,
{ norm_cast },
{ norm_num }
end
/-- A mutually orthogonal family of subspaces of `E` induce a linear isometry from `lp 2` of the
subspaces into `E`. -/
protected def linear_isometry : lp G 2 →ₗᵢ[𝕜] E :=
{ to_fun := λ f, ∑' i, V i (f i),
map_add' := λ f g, by simp only [tsum_add (hV.summable_of_lp f) (hV.summable_of_lp g),
lp.coe_fn_add, pi.add_apply, linear_isometry.map_add],
map_smul' := λ c f, by simpa only [linear_isometry.map_smul, pi.smul_apply, lp.coe_fn_smul]
using tsum_const_smul c (hV.summable_of_lp f),
norm_map' := λ f, begin
classical, -- needed for lattice instance on `finset ι`, for `filter.at_top_ne_bot`
have H : 0 < (2:ℝ≥0∞).to_real := by norm_num,
suffices : ‖∑' (i : ι), V i (f i)‖ ^ ((2:ℝ≥0∞).to_real) = ‖f‖ ^ ((2:ℝ≥0∞).to_real),
{ exact real.rpow_left_inj_on H.ne' (norm_nonneg _) (norm_nonneg _) this },
refine tendsto_nhds_unique _ (lp.has_sum_norm H f),
convert (hV.summable_of_lp f).has_sum.norm.rpow_const (or.inr H.le),
ext s,
exact_mod_cast (hV.norm_sum f s).symm,
end }
protected lemma linear_isometry_apply (f : lp G 2) :
hV.linear_isometry f = ∑' i, V i (f i) :=
rfl
protected lemma has_sum_linear_isometry (f : lp G 2) :
has_sum (λ i, V i (f i)) (hV.linear_isometry f) :=
(hV.summable_of_lp f).has_sum
@[simp] protected lemma linear_isometry_apply_single {i : ι} (x : G i) :
hV.linear_isometry (lp.single 2 i x) = V i x :=
begin
rw [hV.linear_isometry_apply, ← tsum_ite_eq i (V i x)],
congr,
ext j,
rw [lp.single_apply],
split_ifs,
{ subst h },
{ simp }
end
@[simp] protected lemma linear_isometry_apply_dfinsupp_sum_single (W₀ : Π₀ (i : ι), G i) :
hV.linear_isometry (W₀.sum (lp.single 2)) = W₀.sum (λ i, V i) :=
begin
have : hV.linear_isometry (∑ i in W₀.support, lp.single 2 i (W₀ i))
= ∑ i in W₀.support, hV.linear_isometry (lp.single 2 i (W₀ i)),
{ exact hV.linear_isometry.to_linear_map.map_sum },
simp [dfinsupp.sum, this] {contextual := tt},
end
/-- The canonical linear isometry from the `lp 2` of a mutually orthogonal family of subspaces of
`E` into E, has range the closure of the span of the subspaces. -/
protected lemma range_linear_isometry [Π i, complete_space (G i)] :
hV.linear_isometry.to_linear_map.range = (⨆ i, (V i).to_linear_map.range).topological_closure :=
begin
refine le_antisymm _ _,
{ rintros x ⟨f, rfl⟩,
refine mem_closure_of_tendsto (hV.has_sum_linear_isometry f) (eventually_of_forall _),
intros s,
rw set_like.mem_coe,
refine sum_mem _,
intros i hi,
refine mem_supr_of_mem i _,
exact linear_map.mem_range_self _ (f i) },
{ apply topological_closure_minimal,
{ refine supr_le _,
rintros i x ⟨x, rfl⟩,
use lp.single 2 i x,
exact hV.linear_isometry_apply_single x },
exact hV.linear_isometry.isometry.uniform_inducing.is_complete_range.is_closed }
end
end orthogonal_family
section is_hilbert_sum
variables (𝕜 G) (V : Π i, G i →ₗᵢ[𝕜] E) (F : ι → submodule 𝕜 E)
include cplt
/-- Given a family of Hilbert spaces `G : ι → Type*`, a Hilbert sum of `G` consists of a Hilbert
space `E` and an orthogonal family `V : Π i, G i →ₗᵢ[𝕜] E` such that the induced isometry
`Φ : lp G 2 → E` is surjective.
Keeping in mind that `lp G 2` is "the" external Hilbert sum of `G : ι → Type*`, this is analogous
to `direct_sum.is_internal`, except that we don't express it in terms of actual submodules. -/
@[protect_proj] structure is_hilbert_sum : Prop := of_surjective ::
(orthogonal_family : orthogonal_family 𝕜 G V)
(surjective_isometry : function.surjective (orthogonal_family.linear_isometry))
variables {𝕜 G V}
/-- If `V : Π i, G i →ₗᵢ[𝕜] E` is an orthogonal family such that the supremum of the ranges of
`V i` is dense, then `(E, V)` is a Hilbert sum of `G`. -/
lemma is_hilbert_sum.mk [Π i, complete_space $ G i]
(hVortho : orthogonal_family 𝕜 G V)
(hVtotal : ⊤ ≤ (⨆ i, (V i).to_linear_map.range).topological_closure) :
is_hilbert_sum 𝕜 G V :=
{ orthogonal_family := hVortho,
surjective_isometry :=
begin
rw [←linear_isometry.coe_to_linear_map],
exact linear_map.range_eq_top.mp (eq_top_iff.mpr $
hVtotal.trans_eq hVortho.range_linear_isometry.symm)
end }
/-- This is `orthogonal_family.is_hilbert_sum` in the case of actual inclusions from subspaces. -/
lemma is_hilbert_sum.mk_internal [Π i, complete_space $ F i]
(hFortho : orthogonal_family 𝕜 (λ i, F i) (λ i, (F i).subtypeₗᵢ))
(hFtotal : ⊤ ≤ (⨆ i, (F i)).topological_closure) :
is_hilbert_sum 𝕜 (λ i, F i) (λ i, (F i).subtypeₗᵢ) :=
is_hilbert_sum.mk hFortho (by simpa [subtypeₗᵢ_to_linear_map, range_subtype] using hFtotal)
/-- *A* Hilbert sum `(E, V)` of `G` is canonically isomorphic to *the* Hilbert sum of `G`,
i.e `lp G 2`.
Note that this goes in the opposite direction from `orthogonal_family.linear_isometry`. -/
noncomputable def is_hilbert_sum.linear_isometry_equiv (hV : is_hilbert_sum 𝕜 G V) :
E ≃ₗᵢ[𝕜] lp G 2 :=
linear_isometry_equiv.symm $
linear_isometry_equiv.of_surjective
hV.orthogonal_family.linear_isometry hV.surjective_isometry
/-- In the canonical isometric isomorphism between a Hilbert sum `E` of `G` and `lp G 2`,
a vector `w : lp G 2` is the image of the infinite sum of the associated elements in `E`. -/
protected lemma is_hilbert_sum.linear_isometry_equiv_symm_apply
(hV : is_hilbert_sum 𝕜 G V) (w : lp G 2) :
hV.linear_isometry_equiv.symm w = ∑' i, V i (w i) :=
by simp [is_hilbert_sum.linear_isometry_equiv, orthogonal_family.linear_isometry_apply]
/-- In the canonical isometric isomorphism between a Hilbert sum `E` of `G` and `lp G 2`,
a vector `w : lp G 2` is the image of the infinite sum of the associated elements in `E`, and this
sum indeed converges. -/
protected lemma is_hilbert_sum.has_sum_linear_isometry_equiv_symm
(hV : is_hilbert_sum 𝕜 G V) (w : lp G 2) :
has_sum (λ i, V i (w i)) (hV.linear_isometry_equiv.symm w) :=
by simp [is_hilbert_sum.linear_isometry_equiv, orthogonal_family.has_sum_linear_isometry]
/-- In the canonical isometric isomorphism between a Hilbert sum `E` of `G : ι → Type*` and
`lp G 2`, an "elementary basis vector" in `lp G 2` supported at `i : ι` is the image of the
associated element in `E`. -/
@[simp] protected lemma is_hilbert_sum.linear_isometry_equiv_symm_apply_single
(hV : is_hilbert_sum 𝕜 G V) {i : ι} (x : G i) :
hV.linear_isometry_equiv.symm (lp.single 2 i x) = V i x :=
by simp [is_hilbert_sum.linear_isometry_equiv, orthogonal_family.linear_isometry_apply_single]
/-- In the canonical isometric isomorphism between a Hilbert sum `E` of `G : ι → Type*` and
`lp G 2`, a finitely-supported vector in `lp G 2` is the image of the associated finite sum of
elements of `E`. -/
@[simp] protected lemma is_hilbert_sum.linear_isometry_equiv_symm_apply_dfinsupp_sum_single
(hV : is_hilbert_sum 𝕜 G V) (W₀ : Π₀ (i : ι), G i) :
hV.linear_isometry_equiv.symm (W₀.sum (lp.single 2)) = (W₀.sum (λ i, V i)) :=
by simp [is_hilbert_sum.linear_isometry_equiv,
orthogonal_family.linear_isometry_apply_dfinsupp_sum_single]
/-- In the canonical isometric isomorphism between a Hilbert sum `E` of `G : ι → Type*` and
`lp G 2`, a finitely-supported vector in `lp G 2` is the image of the associated finite sum of
elements of `E`. -/
@[simp] protected lemma is_hilbert_sum.linear_isometry_equiv_apply_dfinsupp_sum_single
(hV : is_hilbert_sum 𝕜 G V) (W₀ : Π₀ (i : ι), G i) :
(hV.linear_isometry_equiv (W₀.sum (λ i, V i)) : Π i, G i) = W₀ :=
begin
rw ← hV.linear_isometry_equiv_symm_apply_dfinsupp_sum_single,
rw linear_isometry_equiv.apply_symm_apply,
ext i,
simp [dfinsupp.sum, lp.single_apply] {contextual := tt},
end
/-- Given a total orthonormal family `v : ι → E`, `E` is a Hilbert sum of `λ i : ι, 𝕜` relative to
the family of linear isometries `λ i, λ k, k • v i`. -/
lemma orthonormal.is_hilbert_sum {v : ι → E} (hv : orthonormal 𝕜 v)
(hsp : ⊤ ≤ (span 𝕜 (set.range v)).topological_closure) :
is_hilbert_sum 𝕜 (λ i : ι, 𝕜) (λ i, linear_isometry.to_span_singleton 𝕜 E (hv.1 i)) :=
is_hilbert_sum.mk hv.orthogonal_family
begin
convert hsp,
simp [← linear_map.span_singleton_eq_range, ← submodule.span_Union],
end
lemma submodule.is_hilbert_sum_orthogonal (K : submodule 𝕜 E) [hK : complete_space K] :
is_hilbert_sum 𝕜 (λ b, ↥(cond b K Kᗮ)) (λ b, (cond b K Kᗮ).subtypeₗᵢ) :=
begin
haveI : Π b, complete_space ↥(cond b K Kᗮ),
{ intro b,
cases b;
exact orthogonal.complete_space K <|> assumption },
refine is_hilbert_sum.mk_internal _ K.orthogonal_family_self _,
refine le_trans _ (submodule.le_topological_closure _),
rw [supr_bool_eq, cond, cond],
refine codisjoint.top_le _,
exact submodule.is_compl_orthogonal_of_complete_space.codisjoint
end
end is_hilbert_sum
/-! ### Hilbert bases -/
section
variables (ι) (𝕜) (E)
/-- A Hilbert basis on `ι` for an inner product space `E` is an identification of `E` with the `lp`
space `ℓ²(ι, 𝕜)`. -/
structure hilbert_basis := of_repr :: (repr : E ≃ₗᵢ[𝕜] ℓ²(ι, 𝕜))
end
namespace hilbert_basis
instance {ι : Type*} : inhabited (hilbert_basis ι 𝕜 ℓ²(ι, 𝕜)) :=
⟨of_repr (linear_isometry_equiv.refl 𝕜 _)⟩
/-- `b i` is the `i`th basis vector. -/
instance : has_coe_to_fun (hilbert_basis ι 𝕜 E) (λ _, ι → E) :=
{ coe := λ b i, b.repr.symm (lp.single 2 i (1:𝕜)) }
@[simp] protected lemma repr_symm_single (b : hilbert_basis ι 𝕜 E) (i : ι) :
b.repr.symm (lp.single 2 i (1:𝕜)) = b i :=
rfl
@[simp] protected lemma repr_self (b : hilbert_basis ι 𝕜 E) (i : ι) :
b.repr (b i) = lp.single 2 i (1:𝕜) :=
by rw [← b.repr_symm_single, linear_isometry_equiv.apply_symm_apply]
protected lemma repr_apply_apply (b : hilbert_basis ι 𝕜 E) (v : E) (i : ι) :
b.repr v i = ⟪b i, v⟫ :=
begin
rw [← b.repr.inner_map_map (b i) v, b.repr_self, lp.inner_single_left],
simp,
end
@[simp] protected lemma orthonormal (b : hilbert_basis ι 𝕜 E) : orthonormal 𝕜 b :=
begin
rw orthonormal_iff_ite,
intros i j,
rw [← b.repr.inner_map_map (b i) (b j), b.repr_self, b.repr_self, lp.inner_single_left,
lp.single_apply],
simp,
end
protected lemma has_sum_repr_symm (b : hilbert_basis ι 𝕜 E) (f : ℓ²(ι, 𝕜)) :
has_sum (λ i, f i • b i) (b.repr.symm f) :=
begin
suffices H : (λ (i : ι), f i • b i) =
(λ (b_1 : ι), (b.repr.symm.to_continuous_linear_equiv) ((λ (i : ι), lp.single 2 i (f i)) b_1)),
{ rw H,
have : has_sum (λ (i : ι), lp.single 2 i (f i)) f := lp.has_sum_single ennreal.two_ne_top f,
exact (↑(b.repr.symm.to_continuous_linear_equiv) : ℓ²(ι, 𝕜) →L[𝕜] E).has_sum this },
ext i,
apply b.repr.injective,
letI : normed_space 𝕜 ↥(lp (λ i : ι, 𝕜) 2) := by apply_instance,
have : lp.single 2 i (f i * 1) = f i • lp.single 2 i 1 := lp.single_smul 2 i (1:𝕜) (f i),
rw mul_one at this,
rw [linear_isometry_equiv.map_smul, b.repr_self, ← this,
linear_isometry_equiv.coe_to_continuous_linear_equiv],
exact (b.repr.apply_symm_apply (lp.single 2 i (f i))).symm,
end
protected lemma has_sum_repr (b : hilbert_basis ι 𝕜 E) (x : E) :
has_sum (λ i, b.repr x i • b i) x :=
by simpa using b.has_sum_repr_symm (b.repr x)
@[simp] protected lemma dense_span (b : hilbert_basis ι 𝕜 E) :
(span 𝕜 (set.range b)).topological_closure = ⊤ :=
begin
classical,
rw eq_top_iff,
rintros x -,
refine mem_closure_of_tendsto (b.has_sum_repr x) (eventually_of_forall _),
intros s,
simp only [set_like.mem_coe],
refine sum_mem _,
rintros i -,
refine smul_mem _ _ _,
exact subset_span ⟨i, rfl⟩
end
protected lemma has_sum_inner_mul_inner (b : hilbert_basis ι 𝕜 E) (x y : E) :
has_sum (λ i, ⟪x, b i⟫ * ⟪b i, y⟫) ⟪x, y⟫ :=
begin
convert (b.has_sum_repr y).mapL (innerSL _ x),
ext i,
rw [innerSL_apply, b.repr_apply_apply, inner_smul_right, mul_comm]
end
protected lemma summable_inner_mul_inner (b : hilbert_basis ι 𝕜 E) (x y : E) :
summable (λ i, ⟪x, b i⟫ * ⟪b i, y⟫) :=
(b.has_sum_inner_mul_inner x y).summable
protected lemma tsum_inner_mul_inner (b : hilbert_basis ι 𝕜 E) (x y : E) :
∑' i, ⟪x, b i⟫ * ⟪b i, y⟫ = ⟪x, y⟫ :=
(b.has_sum_inner_mul_inner x y).tsum_eq
-- Note : this should be `b.repr` composed with an identification of `lp (λ i : ι, 𝕜) p` with
-- `pi_Lp p (λ i : ι, 𝕜)` (in this case with `p = 2`), but we don't have this yet (July 2022).
/-- A finite Hilbert basis is an orthonormal basis. -/
protected def to_orthonormal_basis [fintype ι] (b : hilbert_basis ι 𝕜 E) :
orthonormal_basis ι 𝕜 E :=
orthonormal_basis.mk b.orthonormal
begin
refine eq.ge _,
have := (span 𝕜 (finset.univ.image b : set E)).closed_of_finite_dimensional,
simpa only [finset.coe_image, finset.coe_univ, set.image_univ, hilbert_basis.dense_span] using
this.submodule_topological_closure_eq.symm
end
@[simp] lemma coe_to_orthonormal_basis [fintype ι] (b : hilbert_basis ι 𝕜 E) :
(b.to_orthonormal_basis : ι → E) = b :=
orthonormal_basis.coe_mk _ _
protected lemma has_sum_orthogonal_projection {U : submodule 𝕜 E}
[complete_space U] (b : hilbert_basis ι 𝕜 U) (x : E) :
has_sum (λ i, ⟪(b i : E), x⟫ • b i) (orthogonal_projection U x) :=
by simpa only [b.repr_apply_apply, inner_orthogonal_projection_eq_of_mem_left]
using b.has_sum_repr (orthogonal_projection U x)
lemma finite_spans_dense (b : hilbert_basis ι 𝕜 E) :
(⨆ J : finset ι, span 𝕜 (J.image b : set E)).topological_closure = ⊤ :=
eq_top_iff.mpr $ b.dense_span.ge.trans
begin
simp_rw [← submodule.span_Union],
exact topological_closure_mono (span_mono $ set.range_subset_iff.mpr $
λ i, set.mem_Union_of_mem {i} $ finset.mem_coe.mpr $ finset.mem_image_of_mem _ $
finset.mem_singleton_self i)
end
variables {v : ι → E} (hv : orthonormal 𝕜 v)
include hv cplt
/-- An orthonormal family of vectors whose span is dense in the whole module is a Hilbert basis. -/
protected def mk (hsp : ⊤ ≤ (span 𝕜 (set.range v)).topological_closure) :
hilbert_basis ι 𝕜 E :=
hilbert_basis.of_repr $
(hv.is_hilbert_sum hsp).linear_isometry_equiv
lemma _root_.orthonormal.linear_isometry_equiv_symm_apply_single_one (h i) :
(hv.is_hilbert_sum h).linear_isometry_equiv.symm (lp.single 2 i 1) = v i :=
by rw [is_hilbert_sum.linear_isometry_equiv_symm_apply_single,
linear_isometry.to_span_singleton_apply, one_smul]
@[simp] protected lemma coe_mk (hsp : ⊤ ≤ (span 𝕜 (set.range v)).topological_closure) :
⇑(hilbert_basis.mk hv hsp) = v :=
by apply (funext $ orthonormal.linear_isometry_equiv_symm_apply_single_one hv hsp)
/-- An orthonormal family of vectors whose span has trivial orthogonal complement is a Hilbert
basis. -/
protected def mk_of_orthogonal_eq_bot (hsp : (span 𝕜 (set.range v))ᗮ = ⊥) : hilbert_basis ι 𝕜 E :=
hilbert_basis.mk hv
(by rw [← orthogonal_orthogonal_eq_closure, ← eq_top_iff, orthogonal_eq_top_iff, hsp])
@[simp] protected lemma coe_of_orthogonal_eq_bot_mk (hsp : (span 𝕜 (set.range v))ᗮ = ⊥) :
⇑(hilbert_basis.mk_of_orthogonal_eq_bot hv hsp) = v :=
hilbert_basis.coe_mk hv _
omit hv
-- Note : this should be `b.repr` composed with an identification of `lp (λ i : ι, 𝕜) p` with
-- `pi_Lp p (λ i : ι, 𝕜)` (in this case with `p = 2`), but we don't have this yet (July 2022).
/-- An orthonormal basis is an Hilbert basis. -/
protected def _root_.orthonormal_basis.to_hilbert_basis [fintype ι] (b : orthonormal_basis ι 𝕜 E) :
hilbert_basis ι 𝕜 E :=
hilbert_basis.mk b.orthonormal $
by simpa only [← orthonormal_basis.coe_to_basis, b.to_basis.span_eq, eq_top_iff]
using @subset_closure E _ _
@[simp] lemma _root_.orthonormal_basis.coe_to_hilbert_basis [fintype ι]
(b : orthonormal_basis ι 𝕜 E) : (b.to_hilbert_basis : ι → E) = b :=
hilbert_basis.coe_mk _ _
/-- A Hilbert space admits a Hilbert basis extending a given orthonormal subset. -/
lemma _root_.orthonormal.exists_hilbert_basis_extension
{s : set E} (hs : orthonormal 𝕜 (coe : s → E)) :
∃ (w : set E) (b : hilbert_basis w 𝕜 E), s ⊆ w ∧ ⇑b = (coe : w → E) :=
let ⟨w, hws, hw_ortho, hw_max⟩ := exists_maximal_orthonormal hs in
⟨ w,
hilbert_basis.mk_of_orthogonal_eq_bot hw_ortho
(by simpa [maximal_orthonormal_iff_orthogonal_complement_eq_bot hw_ortho] using hw_max),
hws,
hilbert_basis.coe_of_orthogonal_eq_bot_mk _ _ ⟩
variables (𝕜 E)
/-- A Hilbert space admits a Hilbert basis. -/
lemma _root_.exists_hilbert_basis :
∃ (w : set E) (b : hilbert_basis w 𝕜 E), ⇑b = (coe : w → E) :=
let ⟨w, hw, hw', hw''⟩ := (orthonormal_empty 𝕜 E).exists_hilbert_basis_extension in ⟨w, hw, hw''⟩
end hilbert_basis
|
7b5689285f8eeb49d204b483b82dbc69dd95742e | c3e8fac5ab7ca328e55bccf82a0207a97f96678c | /lean/src/grammar.lean | 484b22a3e82214dcf60999744acb9d2f3f48164f | [
"Unlicense"
] | permissive | Rotsor/brainfuck | 941bb33862ce3e9d61f0454db5ca02942f4b5775 | 3e6f30f298b8ba76d0bc71b8b5a47cedaf2f0b97 | refs/heads/master | 1,619,718,778,100 | 1,532,913,653,000 | 1,532,913,653,000 | 121,682,141 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 750 | lean | import .byte
def Grammar (A : Type) : Type := list byte → A → Prop
def Unambiguous {A} (G : Grammar A) : Prop :=
∀ s p1 p2, G s p1 → G s p2 → p1 = p2
def Delimited {A} (G : Grammar A) : Prop :=
∀ pre s suf p1 p2, G s p1 → G (pre ++ s ++ suf) p2 → pre = [] ∧ suf = [] ∧ p1 = p2
def Nonempty {A} (G : Grammar A) : Prop :=
¬ (∃ a, G [] a)
inductive Kleene_star {A} (G : Grammar A) : Grammar (list A)
| Empty : Kleene_star [] []
| Cons : ∀ s a ss as, G s a → Kleene_star ss as → Kleene_star (s ++ ss) (a :: as)
def kleene_star_unambiguous :
∀ {A} {G : Grammar A},
Delimited G →
Nonempty G →
Unambiguous (Kleene_star G)
:=
λ A G delimited nonempty s p1 p2 p1_good p2_good, _ |
8395414542e8d40da136719bf01dfeba42b2c961 | 2c096fdfecf64e46ea7bc6ce5521f142b5926864 | /tests/lean/conv1.lean | 55667aa56aaaba097bcf0284272b7dd3a9dce77b | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | Kha/lean4 | 1005785d2c8797ae266a303968848e5f6ce2fe87 | b99e11346948023cd6c29d248cd8f3e3fb3474cf | refs/heads/master | 1,693,355,498,027 | 1,669,080,461,000 | 1,669,113,138,000 | 184,748,176 | 0 | 0 | Apache-2.0 | 1,665,995,520,000 | 1,556,884,930,000 | Lean | UTF-8 | Lean | false | false | 4,849 | lean | import Lean
set_option pp.analyze false
def p (x y : Nat) := x = y
example (x y : Nat) : p (x + y) (y + x + 0) := by
conv =>
trace_state
whnf
tactic' => trace_state
trace_state
congr
next => rfl
any_goals whnf; rfl
conv' =>
trace_state
apply id ?x
conv =>
fail_if_success case x => whnf
trace_state
rw [Nat.add_comm]
rfl
def foo (x y : Nat) : Nat := x + y
example : foo (0 + a) (b + 0) = a + b := by
conv =>
apply id
lhs
trace_state
congr
trace_state
case x =>
simp
trace_state
fail_if_success case x => skip
case' y => skip
case y => skip
done
example : foo (0 + a) (b + 0) = a + b := by
conv =>
lhs
conv =>
congr
trace_state
focus
trace_state
tactic => simp
trace_state
all_goals dsimp (config := {}) []
simp [foo]
trace_state
example : foo (0 + a) (b + 0) = a + b := by
conv =>
lhs
congr <;> simp
fail_if_success lhs
try lhs
trace_state
example (x y : Nat) : p (x + y) (y + x + 0) := by
conv =>
whnf
rhs
whnf
trace_state
rw [Nat.add_comm]
rfl
example (x y : Nat) : p (x + y) (y + x + 0) := by
conv =>
whnf
lhs
whnf
conv =>
rhs
whnf
trace_state
apply Nat.add_comm x y
def f (x y z : Nat) : Nat :=
y
example (x y : Nat) : f x (x + y + 0) y = y + x := by
conv =>
lhs
arg 2
whnf
trace_state
simp [f]
apply Nat.add_comm
example (x y : Nat) : f x (x + y + 0) y = y + x := by
conv =>
lhs
arg 2
change x + y
trace_state
rw [Nat.add_comm]
example : id (fun x y => 0 + x + y) = Nat.add := by
conv =>
lhs
arg 1
ext a b
trace_state
rw [Nat.zero_add]
trace_state
example : id (fun x y => 0 + x + y) = Nat.add := by
conv =>
lhs
arg 1
intro a b
rw [Nat.zero_add]
example : id (fun x y => 0 + x + y) = Nat.add := by
conv =>
enter [1, 1, a, b]
trace_state
rw [Nat.zero_add]
example (p : Nat → Prop) (h : ∀ a, p a) : ∀ a, p (id (0 + a)) := by
conv =>
intro x
trace_state
arg 1
trace_state
simp only [id]
trace_state
rw [Nat.zero_add]
exact h
example (p : Prop) (x : Nat) : (x = x → p) → p := by
conv =>
congr
. trace_state
congr
. simp
trace_state
conv =>
lhs
simp
intros
assumption
example : (fun x => 0 + x) = id := by
conv =>
lhs
tactic => funext x
trace_state
rw [Nat.zero_add]
example (p : Prop) (x : Nat) : (x = x → p) → p := by
conv =>
apply implies_congr
. apply implies_congr
simp
trace_state
conv =>
lhs
simp
intros; assumption
example (x y : Nat) (f : Nat → Nat → Nat) (g : Nat → Nat) (h₁ : ∀ z, f z z = z) (h₂ : ∀ x y, f (g x) (g y) = y) : f (g (0 + y)) (f (g x) (g (0 + x))) = x := by
conv =>
pattern _ + _
apply Nat.zero_add
trace_state
conv =>
pattern 0 + _
apply Nat.zero_add
trace_state
simp [h₁, h₂]
example (x y : Nat) (h : y = 0) : x + ((y + x) + x) = x + (x + x) := by
conv =>
lhs
rhs
lhs
trace_state
rw [h, Nat.zero_add]
example (p : Nat → Prop) (x y : Nat) (h1 : y = 0) (h2 : p x) : p (y + x) := by
conv =>
rhs
trace_state
rw [h1]
apply Nat.zero_add
exact h2
example (p : (n : Nat) → Fin n → Prop) (i : Fin 5) (hp : p 5 i) (hi : j = i) : p 5 j := by
conv =>
arg 2
trace_state
rw [hi]
exact hp
example (p : {_ : Nat} → Nat → Prop) (x y : Nat) (h1 : y = 0) (h2 : @p x x) : @p (y + x) (y + x) := by
conv =>
enter [@1, 1]
trace_state
rw [h1]
conv =>
enter [@2, 1]
trace_state
rw [h1]
rw [Nat.zero_add]
exact h2
example (p : Nat → Prop) (x y : Nat) (h : y = 0) : p (y + x) := by
conv => lhs
example (p : Nat → Prop) (x y : Nat) (h : y = 0) : p (y + x) := by
conv => arg 2
example (p : Prop) : p := by
conv => rhs
example (p : (n : Nat) → Fin n → Prop) (i : Fin 5) (hp : p 5 i) : p 5 j := by
conv => arg 1
-- repeated `zeta`
example : let a := 0; let b := a; b = 0 := by
intros
conv =>
zeta
trace_state
example : ((x + y) + z : Nat) = x + (y + z) := by
conv in _ + _ => trace_state
conv in (occs := *) _ + _ => trace_state
conv in (occs := 1 3) _ + _ => trace_state
conv in (occs := 3 1) _ + _ => trace_state
conv in (occs := 2 3) _ + _ => trace_state
conv in (occs := 2 4) _ + _ => trace_state
apply Nat.add_assoc
example : ((x + y) + z : Nat) = x + (y + z) := by conv => pattern (occs := 5) _ + _
example : ((x + y) + z : Nat) = x + (y + z) := by conv => pattern (occs := 2 5) _ + _
example : ((x + y) + z : Nat) = x + (y + z) := by conv => pattern (occs := 1 5) _ + _
example : ((x + y) + z : Nat) = x + (y + z) := by conv => pattern (occs := 1 2 5) _ + _
|
c85224916e91be9a2aade9421f560238510d9ccf | 1437b3495ef9020d5413178aa33c0a625f15f15f | /tactic/linarith.lean | 9185bd85e6c50fe34be5651143b8421ec308a309 | [
"Apache-2.0"
] | permissive | jean002/mathlib | c66bbb2d9fdc9c03ae07f869acac7ddbfce67a30 | dc6c38a765799c99c4d9c8d5207d9e6c9e0e2cfd | refs/heads/master | 1,587,027,806,375 | 1,547,306,358,000 | 1,547,306,358,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 30,402 | lean | /-
Copyright (c) 2018 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Robert Y. Lewis
A tactic for discharging linear arithmetic goals using Fourier-Motzkin elimination.
`linarith` is (in principle) complete for ℚ and ℝ. It is not complete for non-dense orders, i.e. ℤ.
@TODO: investigate storing comparisons in a list instead of a set, for possible efficiency gains
@TODO: perform slightly better on ℤ by strengthening t < 0 hyps to t + 1 ≤ 0
@TODO: alternative discharger to `ring`
@TODO: delay proofs of denominator normalization and nat casting until after contradiction is found
-/
import tactic.ring data.nat.gcd data.list.basic meta.rb_map
meta def nat.to_pexpr : ℕ → pexpr
| 0 := ``(0)
| 1 := ``(1)
| n := if n % 2 = 0 then ``(bit0 %%(nat.to_pexpr (n/2))) else ``(bit1 %%(nat.to_pexpr (n/2)))
open native
namespace linarith
section lemmas
lemma int.coe_nat_bit0 (n : ℕ) : (↑(bit0 n : ℕ) : ℤ) = bit0 (↑n : ℤ) := by simp [bit0]
lemma int.coe_nat_bit1 (n : ℕ) : (↑(bit1 n : ℕ) : ℤ) = bit1 (↑n : ℤ) := by simp [bit1, bit0]
lemma int.coe_nat_bit0_mul (n : ℕ) (x : ℕ) : (↑(bit0 n * x) : ℤ) = (↑(bit0 n) : ℤ) * (↑x : ℤ) := by simp
lemma int.coe_nat_bit1_mul (n : ℕ) (x : ℕ) : (↑(bit1 n * x) : ℤ) = (↑(bit1 n) : ℤ) * (↑x : ℤ) := by simp
lemma int.coe_nat_one_mul (x : ℕ) : (↑(1 * x) : ℤ) = 1 * (↑x : ℤ) := by simp
lemma int.coe_nat_zero_mul (x : ℕ) : (↑(0 * x) : ℤ) = 0 * (↑x : ℤ) := by simp
lemma int.coe_nat_mul_bit0 (n : ℕ) (x : ℕ) : (↑(x * bit0 n) : ℤ) = (↑x : ℤ) * (↑(bit0 n) : ℤ) := by simp
lemma int.coe_nat_mul_bit1 (n : ℕ) (x : ℕ) : (↑(x * bit1 n) : ℤ) = (↑x : ℤ) * (↑(bit1 n) : ℤ) := by simp
lemma int.coe_nat_mul_one (x : ℕ) : (↑(x * 1) : ℤ) = (↑x : ℤ) * 1 := by simp
lemma int.coe_nat_mul_zero (x : ℕ) : (↑(x * 0) : ℤ) = (↑x : ℤ) * 0 := by simp
lemma nat_eq_subst {n1 n2 : ℕ} {z1 z2 : ℤ} (hn : n1 = n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 = z2 :=
by simpa [eq.symm h1, eq.symm h2, int.coe_nat_eq_coe_nat_iff]
lemma nat_le_subst {n1 n2 : ℕ} {z1 z2 : ℤ} (hn : n1 ≤ n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 ≤ z2 :=
by simpa [eq.symm h1, eq.symm h2, int.coe_nat_le]
lemma nat_lt_subst {n1 n2 : ℕ} {z1 z2 : ℤ} (hn : n1 < n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 < z2 :=
by simpa [eq.symm h1, eq.symm h2, int.coe_nat_lt]
lemma eq_of_eq_of_eq {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b = 0) : a + b = 0 :=
by simp *
lemma le_of_eq_of_le {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b ≤ 0) : a + b ≤ 0 :=
by simp *
lemma lt_of_eq_of_lt {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b < 0) : a + b < 0 :=
by simp *
lemma le_of_le_of_eq {α} [ordered_semiring α] {a b : α} (ha : a ≤ 0) (hb : b = 0) : a + b ≤ 0 :=
by simp *
lemma lt_of_lt_of_eq {α} [ordered_semiring α] {a b : α} (ha : a < 0) (hb : b = 0) : a + b < 0 :=
by simp *
lemma mul_neg {α} [ordered_ring α] {a b : α} (ha : a < 0) (hb : b > 0) : b * a < 0 :=
have (-b)*a > 0, from mul_pos_of_neg_of_neg (neg_neg_of_pos hb) ha,
neg_of_neg_pos (by simpa)
lemma mul_nonpos {α} [ordered_ring α] {a b : α} (ha : a ≤ 0) (hb : b > 0) : b * a ≤ 0 :=
have (-b)*a ≥ 0, from mul_nonneg_of_nonpos_of_nonpos (le_of_lt (neg_neg_of_pos hb)) ha,
nonpos_of_neg_nonneg (by simp at this; exact this)
lemma mul_eq {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b > 0) : b * a = 0 :=
by simp *
lemma eq_of_not_lt_of_not_gt {α} [linear_order α] (a b : α) (h1 : ¬ a < b) (h2 : ¬ b < a) : a = b :=
le_antisymm (le_of_not_gt h2) (le_of_not_gt h1)
lemma add_subst {α} [ring α] {n e1 e2 t1 t2 : α} (h1 : n * e1 = t1) (h2 : n * e2 = t2) :
n * (e1 + e2) = t1 + t2 := by simp [left_distrib, *]
lemma sub_subst {α} [ring α] {n e1 e2 t1 t2 : α} (h1 : n * e1 = t1) (h2 : n * e2 = t2) :
n * (e1 - e2) = t1 - t2 := by simp [left_distrib, *]
lemma neg_subst {α} [ring α] {n e t : α} (h1 : n * e = t) : n * (-e) = -t := by simp *
private meta def apnn : tactic unit := `[norm_num]
lemma mul_subst {α} [comm_ring α] {n1 n2 k e1 e2 t1 t2 : α} (h1 : n1 * e1 = t1) (h2 : n2 * e2 = t2)
(h3 : n1*n2 = k . apnn) : k * (e1 * e2) = t1 * t2 :=
have h3 : n1 * n2 = k, from h3,
by rw [←h3, mul_comm n1, mul_assoc n2, ←mul_assoc n1, h1, ←mul_assoc n2, mul_comm n2, mul_assoc, h2] -- OUCH
lemma div_subst {α} [field α] {n1 n2 k e1 e2 t1 : α} (h1 : n1 * e1 = t1) (h2 : n2 / e2 = 1) (h3 : n1*n2 = k) :
k * (e1 / e2) = t1 :=
by rw [←h3, mul_assoc, mul_div_comm, h2, ←mul_assoc, h1, mul_comm, one_mul]
end lemmas
section datatypes
@[derive decidable_eq]
inductive ineq
| eq | le | lt
open ineq
def ineq.max : ineq → ineq → ineq
| eq a := a
| le a := a
| lt a := lt
def ineq.is_lt : ineq → ineq → bool
| eq le := tt
| eq lt := tt
| le lt := tt
| _ _ := ff
def ineq.to_string : ineq → string
| eq := "="
| le := "≤"
| lt := "<"
instance : has_to_string ineq := ⟨ineq.to_string⟩
/--
The main datatype for FM elimination.
Variables are represented by natural numbers, each of which has an integer coefficient.
Index 0 is reserved for constants, i.e. `coeffs.find 0` is the coefficient of 1.
The represented term is coeffs.keys.sum (λ i, coeffs.find i * Var[i]).
str determines the direction of the comparison -- is it < 0, ≤ 0, or = 0?
-/
meta structure comp :=
(str : ineq)
(coeffs : rb_map ℕ int)
meta instance : inhabited comp := ⟨⟨ineq.eq, mk_rb_map⟩⟩
meta inductive comp_source
| assump : ℕ → comp_source
| add : comp_source → comp_source → comp_source
| scale : ℕ → comp_source → comp_source
meta def comp_source.flatten : comp_source → rb_map ℕ ℕ
| (comp_source.assump n) := mk_rb_map.insert n 1
| (comp_source.add c1 c2) := (comp_source.flatten c1).add (comp_source.flatten c2)
| (comp_source.scale n c) := (comp_source.flatten c).map (λ v, v * n)
meta def comp_source.to_string : comp_source → string
| (comp_source.assump e) := to_string e
| (comp_source.add c1 c2) := comp_source.to_string c1 ++ " + " ++ comp_source.to_string c2
| (comp_source.scale n c) := to_string n ++ " * " ++ comp_source.to_string c
meta instance comp_source.has_to_format : has_to_format comp_source :=
⟨λ a, comp_source.to_string a⟩
meta structure pcomp :=
(c : comp)
(src : comp_source)
meta def map_lt (m1 m2 : rb_map ℕ int) : bool :=
list.lex (prod.lex (<) (<)) m1.to_list m2.to_list
-- make more efficient
meta def comp.lt (c1 c2 : comp) : bool :=
(c1.str.is_lt c2.str) || (c1.str = c2.str) && map_lt c1.coeffs c2.coeffs
meta instance comp.has_lt : has_lt comp := ⟨λ a b, comp.lt a b⟩
meta instance pcomp.has_lt : has_lt pcomp := ⟨λ p1 p2, p1.c < p2.c⟩
meta instance pcomp.has_lt_dec : decidable_rel ((<) : pcomp → pcomp → Prop) := by apply_instance
meta def comp.coeff_of (c : comp) (a : ℕ) : ℤ :=
c.coeffs.zfind a
meta def comp.scale (c : comp) (n : ℕ) : comp :=
{ c with coeffs := c.coeffs.map ((*) (n : ℤ)) }
meta def comp.add (c1 c2 : comp) : comp :=
⟨c1.str.max c2.str, c1.coeffs.add c2.coeffs⟩
meta def pcomp.scale (c : pcomp) (n : ℕ) : pcomp :=
⟨c.c.scale n, comp_source.scale n c.src⟩
meta def pcomp.add (c1 c2 : pcomp) : pcomp :=
⟨c1.c.add c2.c, comp_source.add c1.src c2.src⟩
meta instance pcomp.to_format : has_to_format pcomp :=
⟨λ p, to_fmt p.c.coeffs ++ to_string p.c.str ++ "0"⟩
meta instance comp.to_format : has_to_format comp :=
⟨λ p, to_fmt p.coeffs⟩
end datatypes
section fm_elim
/-- If c1 and c2 both contain variable a with opposite coefficients,
produces v1, v2, and c such that a has been cancelled in c := v1*c1 + v2*c2 -/
meta def elim_var (c1 c2 : comp) (a : ℕ) : option (ℕ × ℕ × comp) :=
let v1 := c1.coeff_of a,
v2 := c2.coeff_of a in
if v1 * v2 < 0 then
let vlcm := nat.lcm v1.nat_abs v2.nat_abs,
v1' := vlcm / v1.nat_abs,
v2' := vlcm / v2.nat_abs in
some ⟨v1', v2', comp.add (c1.scale v1') (c2.scale v2')⟩
else none
meta def pelim_var (p1 p2 : pcomp) (a : ℕ) : option pcomp :=
do (n1, n2, c) ← elim_var p1.c p2.c a,
return ⟨c, comp_source.add (p1.src.scale n1) (p2.src.scale n2)⟩
meta def comp.is_contr (c : comp) : bool := c.coeffs.empty ∧ c.str = ineq.lt
meta def pcomp.is_contr (p : pcomp) : bool := p.c.is_contr
meta def elim_with_set (a : ℕ) (p : pcomp) (comps : rb_set pcomp) : rb_set pcomp :=
if ¬ p.c.coeffs.contains a then mk_rb_set.insert p else
comps.fold mk_rb_set $ λ pc s,
match pelim_var p pc a with
| some pc := s.insert pc
| none := s
end
/--
The state for the elimination monad.
vars: the set of variables present in comps
comps: a set of comparisons
inputs: a set of pairs of exprs (t, pf), where t is a term and pf is a proof that t {<, ≤, =} 0,
indexed by ℕ.
has_false: stores a pcomp of 0 < 0 if one has been found
TODO: is it more efficient to store comps as a list, to avoid comparisons?
-/
meta structure linarith_structure :=
(vars : rb_set ℕ)
(comps : rb_set pcomp)
@[reducible] meta def linarith_monad :=
state_t linarith_structure (except_t pcomp id)
meta instance : monad linarith_monad := state_t.monad
meta instance : monad_except pcomp linarith_monad :=
state_t.monad_except pcomp
meta def get_vars : linarith_monad (rb_set ℕ) :=
linarith_structure.vars <$> get
meta def get_var_list : linarith_monad (list ℕ) :=
rb_set.to_list <$> get_vars
meta def get_comps : linarith_monad (rb_set pcomp) :=
linarith_structure.comps <$> get
meta def validate : linarith_monad unit :=
do ⟨_, comps⟩ ← get,
match comps.to_list.find (λ p : pcomp, p.is_contr) with
| none := return ()
| some c := throw c
end
meta def update (vars : rb_set ℕ) (comps : rb_set pcomp) : linarith_monad unit :=
state_t.put ⟨vars, comps⟩ >> validate
meta def monad.elim_var (a : ℕ) : linarith_monad unit :=
do vs ← get_vars,
when (vs.contains a) $
do comps ← get_comps,
let cs' := comps.fold mk_rb_set (λ p s, s.union (elim_with_set a p comps)),
update (vs.erase a) cs'
meta def elim_all_vars : linarith_monad unit :=
get_var_list >>= list.mmap' monad.elim_var
end fm_elim
section parse
open ineq tactic
meta def map_of_expr_mul_aux (c1 c2 : rb_map ℕ ℤ) : option (rb_map ℕ ℤ) :=
match c1.keys, c2.keys with
| [0], _ := some $ c2.scale (c1.zfind 0)
| _, [0] := some $ c1.scale (c2.zfind 0)
| _, _ := none
end
/--
Turns an expression into a map from ℕ to ℤ, for use in a comp object.
The expr_map ℕ argument identifies which expressions have already been assigned numbers.
Returns a new map.
-/
meta def map_of_expr : expr_map ℕ → expr → option (expr_map ℕ × rb_map ℕ ℤ)
| m e@`(%%e1 * %%e2) :=
(do (m', comp1) ← map_of_expr m e1,
(m', comp2) ← map_of_expr m' e2,
mp ← map_of_expr_mul_aux comp1 comp2,
return (m', mp)) <|>
(match m.find e with
| some k := return (m, mk_rb_map.insert k 1)
| none := let n := m.size + 1 in return (m.insert e n, mk_rb_map.insert n 1)
end)
| m `(%%e1 + %%e2) :=
do (m', comp1) ← map_of_expr m e1,
(m', comp2) ← map_of_expr m' e2,
return (m', comp1.add comp2)
| m `(%%e1 - %%e2) :=
do (m', comp1) ← map_of_expr m e1,
(m', comp2) ← map_of_expr m' e2,
return (m', comp1.add (comp2.scale (-1)))
| m `(-%%e) := do (m', comp) ← map_of_expr m e, return (m', comp.scale (-1))
| m e :=
match e.to_int, m.find e with
| some 0, _ := return ⟨m, mk_rb_map⟩
| some z, _ := return ⟨m, mk_rb_map.insert 0 z⟩
| none, some k := return (m, mk_rb_map.insert k 1)
| none, none := let n := m.size + 1 in
return (m.insert e n, mk_rb_map.insert n 1)
end
meta def parse_into_comp_and_expr : expr → option (ineq × expr)
| `(%%e < 0) := (ineq.lt, e)
| `(%%e ≤ 0) := (ineq.le, e)
| `(%%e = 0) := (ineq.eq, e)
| _ := none
meta def to_comp (e : expr) (m : expr_map ℕ) : option (comp × expr_map ℕ) :=
do (iq, e) ← parse_into_comp_and_expr e,
(m', comp') ← map_of_expr m e,
return ⟨⟨iq, comp'⟩, m'⟩
meta def to_comp_fold : expr_map ℕ → list expr →
(list (option comp) × expr_map ℕ)
| m [] := ([], m)
| m (h::t) :=
match to_comp h m with
| some (c, m') := let (l, mp) := to_comp_fold m' t in (c::l, mp)
| none := let (l, mp) := to_comp_fold m t in (none::l, mp)
end
/--
Takes a list of proofs of props of the form t {<, ≤, =} 0, and creates a linarith_structure.
-/
meta def mk_linarith_structure (l : list expr) : tactic (linarith_structure × rb_map ℕ (expr × expr)) :=
do pftps ← l.mmap infer_type,
let (l', map) := to_comp_fold mk_rb_map pftps,
let lz := list.enum $ ((l.zip pftps).zip l').filter_map (λ ⟨a, b⟩, prod.mk a <$> b),
let prmap := rb_map.of_list $ lz.map (λ ⟨n, x⟩, (n, x.1)),
let vars : rb_set ℕ := rb_map.set_of_list $ list.range map.size.succ,
let pc : rb_set pcomp := rb_map.set_of_list $
lz.map (λ ⟨n, x⟩, ⟨x.2, comp_source.assump n⟩),
return (⟨vars, pc⟩, prmap)
meta def linarith_monad.run {α} (tac : linarith_monad α) (l : list expr) : tactic ((pcomp ⊕ α) × rb_map ℕ (expr × expr)) :=
do (struct, inputs) ← mk_linarith_structure l,
match (state_t.run (validate >> tac) struct).run with
| (except.ok (a, _)) := return (sum.inr a, inputs)
| (except.error contr) := return (sum.inl contr, inputs)
end
end parse
section prove
open ineq tactic
meta def get_rel_sides : expr → tactic (expr × expr)
| `(%%a < %%b) := return (a, b)
| `(%%a ≤ %%b) := return (a, b)
| `(%%a = %%b) := return (a, b)
| `(%%a ≥ %%b) := return (a, b)
| `(%%a > %%b) := return (a, b)
| _ := failed
meta def mul_expr (n : ℕ) (e : expr) : pexpr :=
if n = 1 then ``(%%e) else
``(%%(nat.to_pexpr n) * %%e)
meta def add_exprs_aux : pexpr → list pexpr → pexpr
| p [] := p
| p [a] := ``(%%p + %%a)
| p (h::t) := add_exprs_aux ``(%%p + %%h) t
meta def add_exprs : list pexpr → pexpr
| [] := ``(0)
| (h::t) := add_exprs_aux h t
meta def find_contr (m : rb_set pcomp) : option pcomp :=
m.keys.find (λ p, p.c.is_contr)
meta def ineq_const_mul_nm : ineq → name
| lt := ``mul_neg
| le := ``mul_nonpos
| eq := ``mul_eq
meta def ineq_const_nm : ineq → ineq → (name × ineq)
| eq eq := (``eq_of_eq_of_eq, eq)
| eq le := (``le_of_eq_of_le, le)
| eq lt := (``lt_of_eq_of_lt, lt)
| le eq := (``le_of_le_of_eq, le)
| le le := (`add_nonpos, le)
| le lt := (`add_neg_of_nonpos_of_neg, lt)
| lt eq := (``lt_of_lt_of_eq, lt)
| lt le := (`add_neg_of_neg_of_nonpos, lt)
| lt lt := (`add_neg, lt)
meta def mk_single_comp_zero_pf (c : ℕ) (h : expr) : tactic (ineq × expr) :=
do tp ← infer_type h,
some (iq, e) ← return $ parse_into_comp_and_expr tp,
if c = 0 then
do e' ← mk_app ``zero_mul [e], return (eq, e')
else if c = 1 then return (iq, h)
else
do nm ← resolve_name (ineq_const_mul_nm iq),
tp ← (prod.snd <$> (infer_type h >>= get_rel_sides)) >>= infer_type,
cpos ← to_expr ``((%%c.to_pexpr : %%tp) > 0),
(_, ex) ← solve_aux cpos `[norm_num, done],
-- e' ← mk_app (ineq_const_mul_nm iq) [h, ex], -- this takes many seconds longer in some examples! why?
e' ← to_expr ``(%%nm %%h %%ex) ff,
return (iq, e')
meta def mk_lt_zero_pf_aux (c : ineq) (pf npf : expr) (coeff : ℕ) : tactic (ineq × expr) :=
do (iq, h') ← mk_single_comp_zero_pf coeff npf,
let (nm, niq) := ineq_const_nm c iq,
n ← resolve_name nm,
e' ← to_expr ``(%%n %%pf %%h'),
return (niq, e')
/--
Takes a list of coefficients [c] and list of expressions, of equal length.
Each expression is a proof of a prop of the form t {<, ≤, =} 0.
Produces a proof that the sum of (c*t) {<, ≤, =} 0, where the comp is as strong as possible.
-/
meta def mk_lt_zero_pf : list ℕ → list expr → tactic expr
| _ [] := fail "no linear hypotheses found"
| [c] [h] := prod.snd <$> mk_single_comp_zero_pf c h
| (c::ct) (h::t) :=
do (iq, h') ← mk_single_comp_zero_pf c h,
prod.snd <$> (ct.zip t).mfoldl (λ pr ce, mk_lt_zero_pf_aux pr.1 pr.2 ce.2 ce.1) (iq, h')
| _ _ := fail "not enough args to mk_lt_zero_pf"
meta def term_of_ineq_prf (prf : expr) : tactic expr :=
do (lhs, _) ← infer_type prf >>= get_rel_sides,
return lhs
meta structure linarith_config :=
(discharger : tactic unit := `[ring])
(restrict_type : option Type := none)
(restrict_type_reflect : reflected restrict_type . apply_instance)
(exfalso : bool := tt)
meta def ineq_pf_tp (pf : expr) : tactic expr :=
do (_, z) ← infer_type pf >>= get_rel_sides,
infer_type z
meta def mk_neg_one_lt_zero_pf (tp : expr) : tactic expr :=
to_expr ``((neg_neg_of_pos zero_lt_one : -1 < (0 : %%tp)))
/--
Assumes e is a proof that t = 0. Creates a proof that -t = 0.
-/
meta def mk_neg_eq_zero_pf (e : expr) : tactic expr :=
to_expr ``(neg_eq_zero.mpr %%e)
meta def add_neg_eq_pfs : list expr → tactic (list expr)
| [] := return []
| (h::t) :=
do some (iq, tp) ← parse_into_comp_and_expr <$> infer_type h,
match iq with
| ineq.eq := do nep ← mk_neg_eq_zero_pf h, tl ← add_neg_eq_pfs t, return $ h::nep::tl
| _ := list.cons h <$> add_neg_eq_pfs t
end
/--
Takes a list of proofs of propositions of the form t {<, ≤, =} 0,
and tries to prove the goal `false`.
-/
meta def prove_false_by_linarith1 (cfg : linarith_config) : list expr → tactic unit
| [] := fail "no args to linarith"
| l@(h::t) :=
do extp ← match cfg.restrict_type with
| none := do (_, z) ← infer_type h >>= get_rel_sides, infer_type z
| some rtp := do
m ← mk_mvar,
unify `(some %%m : option Type) cfg.restrict_type_reflect,
return m
end,
hz ← mk_neg_one_lt_zero_pf extp,
l' ← if cfg.restrict_type.is_some then
l.mfilter (λ e, succeeds (ineq_pf_tp e >>= is_def_eq extp))
else return l,
l' ← add_neg_eq_pfs l',
(sum.inl contr, inputs) ← elim_all_vars.run (hz::l')
| fail "linarith failed to find a contradiction",
let coeffs := inputs.keys.map (λ k, (contr.src.flatten.ifind k)),
let pfs : list expr := inputs.keys.map (λ k, (inputs.ifind k).1),
let zip := (coeffs.zip pfs).filter (λ pr, pr.1 ≠ 0),
let (coeffs, pfs) := zip.unzip,
mls ← zip.mmap (λ pr, do e ← term_of_ineq_prf pr.2, return (mul_expr pr.1 e)),
sm ← to_expr $ add_exprs mls,
tgt ← to_expr ``(%%sm = 0),
(a, b) ← solve_aux tgt (cfg.discharger >> done),
pf ← mk_lt_zero_pf coeffs pfs,
pftp ← infer_type pf,
(_, nep, _) ← rewrite_core b pftp,
pf' ← mk_eq_mp nep pf,
mk_app `lt_irrefl [pf'] >>= exact
end prove
section normalize
open tactic
set_option eqn_compiler.max_steps 50000
meta def rem_neg (prf : expr) : expr → tactic expr
| `(_ ≤ _) := to_expr ``(lt_of_not_ge %%prf)
| `(_ < _) := to_expr ``(le_of_not_gt %%prf)
| `(_ > _) := to_expr ``(le_of_not_gt %%prf)
| `(_ ≥ _) := to_expr ``(lt_of_not_ge %%prf)
| e := failed
meta def rearr_comp : expr → expr → tactic expr
| prf `(%%a ≤ 0) := return prf
| prf `(%%a < 0) := return prf
| prf `(%%a = 0) := return prf
| prf `(%%a ≥ 0) := to_expr ``(neg_nonpos.mpr %%prf)
| prf `(%%a > 0) := to_expr ``(neg_neg_of_pos %%prf)
| prf `(0 ≥ %%a) := to_expr ``(show %%a ≤ 0, from %%prf)
| prf `(0 > %%a) := to_expr ``(show %%a < 0, from %%prf)
| prf `(0 = %%a) := to_expr ``(eq.symm %%prf)
| prf `(0 ≤ %%a) := to_expr ``(neg_nonpos.mpr %%prf)
| prf `(0 < %%a) := to_expr ``(neg_neg_of_pos %%prf)
| prf `(%%a ≤ %%b) := to_expr ``(sub_nonpos.mpr %%prf)
| prf `(%%a < %%b) := to_expr ``(sub_neg_of_lt %%prf)
| prf `(%%a = %%b) := to_expr ``(sub_eq_zero.mpr %%prf)
| prf `(%%a > %%b) := to_expr ``(sub_neg_of_lt %%prf)
| prf `(%%a ≥ %%b) := to_expr ``(sub_nonpos.mpr %%prf)
| prf `(¬ %%t) := do nprf ← rem_neg prf t, tp ← infer_type nprf, rearr_comp nprf tp
| prf _ := fail "couldn't rearrange comp"
meta def is_numeric : expr → option ℚ
| `(%%e1 + %%e2) := (+) <$> is_numeric e1 <*> is_numeric e2
| `(%%e1 - %%e2) := has_sub.sub <$> is_numeric e1 <*> is_numeric e2
| `(%%e1 * %%e2) := (*) <$> is_numeric e1 <*> is_numeric e2
| `(%%e1 / %%e2) := (/) <$> is_numeric e1 <*> is_numeric e2
| `(-%%e) := rat.neg <$> is_numeric e
| e := e.to_rat
inductive {u} tree (α : Type u) : Type u
| nil {} : tree
| node : α → tree → tree → tree
def tree.repr {α} [has_repr α] : tree α → string
| tree.nil := "nil"
| (tree.node a t1 t2) := "tree.node " ++ repr a ++ " (" ++ tree.repr t1 ++ ") (" ++ tree.repr t2 ++ ")"
instance {α} [has_repr α] : has_repr (tree α) := ⟨tree.repr⟩
meta def find_cancel_factor : expr → ℕ × tree ℕ
| `(%%e1 + %%e2) :=
let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, lcm := v1.lcm v2 in
(lcm, tree.node lcm t1 t2)
| `(%%e1 - %%e2) :=
let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, lcm := v1.lcm v2 in
(lcm, tree.node lcm t1 t2)
| `(%%e1 * %%e2) :=
let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, pd := v1*v2 in
(pd, tree.node pd t1 t2)
| `(%%e1 / %%e2) := --do q ← is_numeric e2, return q.num.nat_abs
match is_numeric e2 with
| some q := let (v1, t1) := find_cancel_factor e1, n := v1.lcm q.num.nat_abs in
(n, tree.node n t1 (tree.node q.num.nat_abs tree.nil tree.nil))
| none := (1, tree.node 1 tree.nil tree.nil)
end
| `(-%%e) := find_cancel_factor e
| _ := (1, tree.node 1 tree.nil tree.nil)
open tree
meta def mk_prod_prf : ℕ → tree ℕ → expr → tactic expr
| v (node _ lhs rhs) `(%%e1 + %%e2) :=
do v1 ← mk_prod_prf v lhs e1, v2 ← mk_prod_prf v rhs e2, mk_app ``add_subst [v1, v2]
| v (node _ lhs rhs) `(%%e1 - %%e2) :=
do v1 ← mk_prod_prf v lhs e1, v2 ← mk_prod_prf v rhs e2, mk_app ``sub_subst [v1, v2]
| v (node n lhs@(node ln _ _) rhs) `(%%e1 * %%e2) :=
do tp ← infer_type e1, v1 ← mk_prod_prf ln lhs e1, v2 ← mk_prod_prf (v/ln) rhs e2,
ln' ← tp.of_nat ln, vln' ← tp.of_nat (v/ln), v' ← tp.of_nat v,
ntp ← to_expr ``(%%ln' * %%vln' = %%v'),
(_, npf) ← solve_aux ntp `[norm_num, done],
mk_app ``mul_subst [v1, v2, npf]
| v (node n lhs rhs@(node rn _ _)) `(%%e1 / %%e2) :=
do tp ← infer_type e1, v1 ← mk_prod_prf (v/rn) lhs e1,
rn' ← tp.of_nat rn, vrn' ← tp.of_nat (v/rn), n' ← tp.of_nat n, v' ← tp.of_nat v,
ntp ← to_expr ``(%%rn' / %%e2 = 1),
(_, npf) ← solve_aux ntp `[norm_num, done],
ntp2 ← to_expr ``(%%vrn' * %%n' = %%v'),
(_, npf2) ← solve_aux ntp2 `[norm_num, done],
mk_app ``div_subst [v1, npf, npf2]
| v t `(-%%e) := do v' ← mk_prod_prf v t e, mk_app ``neg_subst [v']
| v _ e :=
do tp ← infer_type e,
v' ← tp.of_nat v,
e' ← to_expr ``(%%v' * %%e),
mk_app `eq.refl [e']
/--
e is a term with rational division. produces a natural number n and a proof that n*e = e',
where e' has no division.
-/
meta def kill_factors (e : expr) : tactic (ℕ × expr) :=
let (n, t) := find_cancel_factor e in
do e' ← mk_prod_prf n t e, return (n, e')
open expr
meta def expr_contains (n : name) : expr → bool
| (const nm _) := nm = n
| (lam _ _ _ bd) := expr_contains bd
| (pi _ _ _ bd) := expr_contains bd
| (app e1 e2) := expr_contains e1 || expr_contains e2
| _ := ff
lemma sub_into_lt {α} [ordered_semiring α] {a b : α} (he : a = b) (hl : a ≤ 0) : b ≤ 0 :=
by rwa he at hl
meta def norm_hyp_aux (h' lhs : expr) : tactic expr :=
do (v, lhs') ← kill_factors lhs,
(ih, h'') ← mk_single_comp_zero_pf v h',
(_, nep, _) ← infer_type h'' >>= rewrite_core lhs',
mk_eq_mp nep h''
meta def norm_hyp (h : expr) : tactic expr :=
do htp ← infer_type h,
h' ← rearr_comp h htp,
some (c, lhs) ← parse_into_comp_and_expr <$> infer_type h',
if expr_contains `has_div.div lhs then
norm_hyp_aux h' lhs
else return h'
meta def get_contr_lemma_name : expr → option name
| `(%%a < %%b) := return `lt_of_not_ge
| `(%%a ≤ %%b) := return `le_of_not_gt
| `(%%a = %%b) := return ``eq_of_not_lt_of_not_gt
| `(%%a ≥ %%b) := return `le_of_not_gt
| `(%%a > %%b) := return `lt_of_not_ge
| `(¬ %%a < %%b) := return `not.intro
| `(¬ %%a ≤ %%b) := return `not.intro
| `(¬ %%a = %%b) := return `not.intro
| `(¬ %%a ≥ %%b) := return `not.intro
| `(¬ %%a > %%b) := return `not.intro
| _ := none
-- assumes the input t is of type ℕ. Produces t' of type ℤ such that ↑t = t' and a proof of equality
meta def cast_expr (e : expr) : tactic (expr × expr) :=
do s ← [`int.coe_nat_add, `int.coe_nat_zero, `int.coe_nat_one,
``int.coe_nat_bit0_mul, ``int.coe_nat_bit1_mul, ``int.coe_nat_zero_mul, ``int.coe_nat_one_mul,
``int.coe_nat_mul_bit0, ``int.coe_nat_mul_bit1, ``int.coe_nat_mul_zero, ``int.coe_nat_mul_one,
``int.coe_nat_bit0, ``int.coe_nat_bit1].mfoldl simp_lemmas.add_simp simp_lemmas.mk,
ce ← to_expr ``(↑%%e : ℤ),
simplify s [] ce {fail_if_unchanged := ff}
meta def is_nat_int_coe : expr → option expr
| `((↑(%%n : ℕ) : ℤ)) := some n
| _ := none
meta def mk_coe_nat_nonneg_prf (e : expr) : tactic expr :=
mk_app `int.coe_nat_nonneg [e]
meta def get_nat_comps : expr → list expr
| `(%%a + %%b) := (get_nat_comps a).append (get_nat_comps b)
| `(%%a * %%b) := (get_nat_comps a).append (get_nat_comps b)
| e := match is_nat_int_coe e with
| some e' := [e']
| none := []
end
meta def mk_coe_nat_nonneg_prfs (e : expr) : tactic (list expr) :=
(get_nat_comps e).mmap mk_coe_nat_nonneg_prf
meta def mk_cast_eq_and_nonneg_prfs (pf a b : expr) (ln : name) : tactic (list expr) :=
do (a', prfa) ← cast_expr a,
(b', prfb) ← cast_expr b,
la ← mk_coe_nat_nonneg_prfs a',
lb ← mk_coe_nat_nonneg_prfs b',
pf' ← mk_app ln [pf, prfa, prfb],
return $ pf'::(la.append lb)
meta def mk_int_pfs_of_nat_pf (pf : expr) : tactic (list expr) :=
do tp ← infer_type pf,
match tp with
| `(%%a = %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_eq_subst
| `(%%a ≤ %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_le_subst
| `(%%a < %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_lt_subst
| `(%%a ≥ %%b) := mk_cast_eq_and_nonneg_prfs pf b a ``nat_le_subst
| `(%%a > %%b) := mk_cast_eq_and_nonneg_prfs pf b a ``nat_lt_subst
| `(¬ %%a ≤ %%b) := do pf' ← mk_app ``lt_of_not_ge [pf], mk_cast_eq_and_nonneg_prfs pf' b a ``nat_lt_subst
| `(¬ %%a < %%b) := do pf' ← mk_app ``le_of_not_gt [pf], mk_cast_eq_and_nonneg_prfs pf' b a ``nat_le_subst
| `(¬ %%a ≥ %%b) := do pf' ← mk_app ``lt_of_not_ge [pf], mk_cast_eq_and_nonneg_prfs pf' a b ``nat_lt_subst
| `(¬ %%a > %%b) := do pf' ← mk_app ``le_of_not_gt [pf], mk_cast_eq_and_nonneg_prfs pf' a b ``nat_le_subst
| _ := fail "mk_coe_comp_prf failed: proof is not an inequality"
end
meta def guard_is_nat_prop : expr → tactic unit
| `(%%a = _) := infer_type a >>= unify `(ℕ)
| `(%%a ≤ _) := infer_type a >>= unify `(ℕ)
| `(%%a < _) := infer_type a >>= unify `(ℕ)
| `(%%a ≥ _) := infer_type a >>= unify `(ℕ)
| `(%%a > _) := infer_type a >>= unify `(ℕ)
| `(¬ %%p) := guard_is_nat_prop p
| _ := failed
meta def replace_nat_pfs : list expr → tactic (list expr)
| [] := return []
| (h::t) :=
(do infer_type h >>= guard_is_nat_prop,
ls ← mk_int_pfs_of_nat_pf h,
list.append ls <$> replace_nat_pfs t) <|> list.cons h <$> replace_nat_pfs t
/--
Takes a list of proofs of propositions.
Filters out the proofs of linear (in)equalities,
and tries to use them to prove `false`.
-/
meta def prove_false_by_linarith (cfg : linarith_config) (l : list expr) : tactic unit :=
do l' ← replace_nat_pfs l,
ls ← l'.mmap (λ h, (do s ← norm_hyp h, return (some s)) <|> return none),
prove_false_by_linarith1 cfg ls.reduce_option
end normalize
end linarith
section
open tactic linarith
open lean lean.parser interactive tactic interactive.types
local postfix `?`:9001 := optional
local postfix *:9001 := many
meta def linarith.interactive_aux (cfg : linarith_config) :
parse ident* → (parse (tk "using" *> pexpr_list)?) → tactic unit
| l (some pe) := pe.mmap (λ p, i_to_expr p >>= note_anon) >> linarith.interactive_aux l none
| [] none :=
do t ← target,
if t = `(false) then local_context >>= prove_false_by_linarith cfg
else match get_contr_lemma_name t with
| some nm := seq (applyc nm) (intro1 >> linarith.interactive_aux [] none)
| none := if cfg.exfalso then exfalso >> linarith.interactive_aux [] none
else fail "linarith failed: target type is not an inequality."
end
| ls none := (ls.mmap get_local) >>= prove_false_by_linarith cfg
/--
Tries to prove a goal of `false` by linear arithmetic on hypotheses.
If the goal is a linear (in)equality, tries to prove it by contradiction.
If the goal is not `false` or an inequality, applies `exfalso` and tries linarith on the
hypotheses.
`linarith` will use all relevant hypotheses in the local context.
`linarith h1 h2 h3` will only use hypotheses h1, h2, h3.
`linarith using [t1, t2, t3]` will add proof terms t1, t2, t3 to the local context.
Config options:
`linarith {exfalso := ff}` will fail on a goal that is neither an inequality nor `false`
`linarith {restrict_type := T}` will run only on hypotheses that are inequalities over `T`
`linarith {discharger := tac}` will use `tac` instead of `ring` for normalization.
Options: `ring2`, `ring SOP`, `simp`
-/
meta def tactic.interactive.linarith (ids : parse (many ident))
(using_hyps : parse (tk "using" *> pexpr_list)?) (cfg : linarith_config := {}) : tactic unit :=
linarith.interactive_aux cfg ids using_hyps
end |
7f277842e0cac7ffd1fba5195a5f3edb0ea5a3b7 | 75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2 | /tests/lean/run/type_equations.lean | d8f28c008d6f0ee7db75f2e83e5b740fd10fc703 | [
"Apache-2.0"
] | permissive | jroesch/lean | 30ef0860fa905d35b9ad6f76de1a4f65c9af6871 | 3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2 | refs/heads/master | 1,586,090,835,348 | 1,455,142,203,000 | 1,455,142,277,000 | 51,536,958 | 1 | 0 | null | 1,455,215,811,000 | 1,455,215,811,000 | null | UTF-8 | Lean | false | false | 841 | lean | open nat
inductive expr :=
| zero : expr
| one : expr
| add : expr → expr → expr
namespace expr
inductive direct_subterm : expr → expr → Prop :=
| add_1 : ∀ e₁ e₂ : expr, direct_subterm e₁ (add e₁ e₂)
| add_2 : ∀ e₁ e₂ : expr, direct_subterm e₂ (add e₁ e₂)
theorem direct_subterm_wf : well_founded direct_subterm :=
begin
constructor, intro e, induction e,
repeat (constructor; intro y hlt; cases hlt; repeat assumption)
end
definition subterm := tc direct_subterm
theorem subterm_wf [instance] : well_founded subterm :=
tc.wf direct_subterm_wf
infix `+` := expr.add
set_option pp.notation false
definition ev : expr → nat
| zero := 0
| one := 1
| ((a : expr) + b) := ev a + ev b
definition foo : expr := add zero (add one one)
example : ev foo = 2 :=
rfl
end expr
|
5862e7b53e05820fd1b28524860bcd9eaac58a57 | 77c5b91fae1b966ddd1db969ba37b6f0e4901e88 | /src/topology/G_delta.lean | 47b5f993cefa18d82fbbe60bdae669cb252767c9 | [
"Apache-2.0"
] | permissive | dexmagic/mathlib | ff48eefc56e2412429b31d4fddd41a976eb287ce | 7a5d15a955a92a90e1d398b2281916b9c41270b2 | refs/heads/master | 1,693,481,322,046 | 1,633,360,193,000 | 1,633,360,193,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,024 | 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, Yury Kudryashov
-/
import topology.metric_space.emetric_space
/-!
# `Gδ` sets
In this file we define `Gδ` sets and prove their basic properties.
## Main definitions
* `is_Gδ`: a set `s` is a `Gδ` set if it can be represented as an intersection
of countably many open sets;
* `residual`: the filter of residual sets. A set `s` is called *residual* if it includes a dense
`Gδ` set. In a Baire space (e.g., in a complete (e)metric space), residual sets form a filter.
For technical reasons, we define `residual` in any topological space but the definition agrees
with the description above only in Baire spaces.
## Main results
We prove that finite or countable intersections of Gδ sets is a Gδ set. We also prove that the
continuity set of a function from a topological space to an (e)metric space is a Gδ set.
## Tags
Gδ set, residual set
-/
noncomputable theory
open_locale classical topological_space filter
open filter encodable set
variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*}
section is_Gδ
variable [topological_space α]
/-- A Gδ set is a countable intersection of open sets. -/
def is_Gδ (s : set α) : Prop :=
∃T : set (set α), (∀t ∈ T, is_open t) ∧ countable T ∧ s = (⋂₀ T)
/-- An open set is a Gδ set. -/
lemma is_open.is_Gδ {s : set α} (h : is_open s) : is_Gδ s :=
⟨{s}, by simp [h], countable_singleton _, (set.sInter_singleton _).symm⟩
lemma is_Gδ_univ : is_Gδ (univ : set α) := is_open_univ.is_Gδ
lemma is_Gδ_bInter_of_open {I : set ι} (hI : countable I) {f : ι → set α}
(hf : ∀i ∈ I, is_open (f i)) : is_Gδ (⋂i∈I, f i) :=
⟨f '' I, by rwa ball_image_iff, hI.image _, by rw sInter_image⟩
lemma is_Gδ_Inter_of_open [encodable ι] {f : ι → set α}
(hf : ∀i, is_open (f i)) : is_Gδ (⋂i, f i) :=
⟨range f, by rwa forall_range_iff, countable_range _, by rw sInter_range⟩
/-- A countable intersection of Gδ sets is a Gδ set. -/
lemma is_Gδ_sInter {S : set (set α)} (h : ∀s∈S, is_Gδ s) (hS : countable S) : is_Gδ (⋂₀ S) :=
begin
choose T hT using h,
refine ⟨_, _, _, (sInter_bUnion (λ s hs, (hT s hs).2.2)).symm⟩,
{ simp only [mem_Union],
rintros t ⟨s, hs, tTs⟩,
exact (hT s hs).1 t tTs },
{ exact hS.bUnion (λs hs, (hT s hs).2.1) },
end
lemma is_Gδ_Inter [encodable ι] {s : ι → set α} (hs : ∀ i, is_Gδ (s i)) : is_Gδ (⋂ i, s i) :=
is_Gδ_sInter (forall_range_iff.2 hs) $ countable_range s
lemma is_Gδ_bInter {s : set ι} (hs : countable s) {t : Π i ∈ s, set α}
(ht : ∀ i ∈ s, is_Gδ (t i ‹_›)) : is_Gδ (⋂ i ∈ s, t i ‹_›) :=
begin
rw [bInter_eq_Inter],
haveI := hs.to_encodable,
exact is_Gδ_Inter (λ x, ht x x.2)
end
lemma is_Gδ.inter {s t : set α} (hs : is_Gδ s) (ht : is_Gδ t) : is_Gδ (s ∩ t) :=
by { rw inter_eq_Inter, exact is_Gδ_Inter (bool.forall_bool.2 ⟨ht, hs⟩) }
/-- The union of two Gδ sets is a Gδ set. -/
lemma is_Gδ.union {s t : set α} (hs : is_Gδ s) (ht : is_Gδ t) : is_Gδ (s ∪ t) :=
begin
rcases hs with ⟨S, Sopen, Scount, rfl⟩,
rcases ht with ⟨T, Topen, Tcount, rfl⟩,
rw [sInter_union_sInter],
apply is_Gδ_bInter_of_open (Scount.prod Tcount),
rintros ⟨a, b⟩ hab,
exact is_open.union (Sopen a hab.1) (Topen b hab.2)
end
end is_Gδ
section continuous_at
open topological_space
open_locale uniformity
variables [topological_space α]
lemma is_Gδ_set_of_continuous_at_of_countably_generated_uniformity
[uniform_space β] (hU : is_countably_generated (𝓤 β)) (f : α → β) :
is_Gδ {x | continuous_at f x} :=
begin
obtain ⟨U, hUo, hU⟩ := hU.exists_antitone_subbasis uniformity_has_basis_open_symmetric,
simp only [uniform.continuous_at_iff_prod, nhds_prod_eq],
simp only [(nhds_basis_opens _).prod_self.tendsto_iff hU.to_has_basis, forall_prop_of_true,
set_of_forall, id],
refine is_Gδ_Inter (λ k, is_open.is_Gδ $ is_open_iff_mem_nhds.2 $ λ x, _),
rintros ⟨s, ⟨hsx, hso⟩, hsU⟩,
filter_upwards [is_open.mem_nhds hso hsx],
intros y hy,
exact ⟨s, ⟨hy, hso⟩, hsU⟩
end
/-- The set of points where a function is continuous is a Gδ set. -/
lemma is_Gδ_set_of_continuous_at [emetric_space β] (f : α → β) :
is_Gδ {x | continuous_at f x} :=
is_Gδ_set_of_continuous_at_of_countably_generated_uniformity
emetric.uniformity_has_countable_basis _
end continuous_at
/-- A set `s` is called *residual* if it includes a dense `Gδ` set. If `α` is a Baire space
(e.g., a complete metric space), then residual sets form a filter, see `mem_residual`.
For technical reasons we define the filter `residual` in any topological space but in a non-Baire
space it is not useful because it may contain some non-residual sets. -/
def residual (α : Type*) [topological_space α] : filter α :=
⨅ t (ht : is_Gδ t) (ht' : dense t), 𝓟 t
|
f91536cd215893fbc184dbabbf39870eab006e06 | 02005f45e00c7ecf2c8ca5db60251bd1e9c860b5 | /src/order/bounds.lean | fa352a9a9e00e6b28cacc0aac58a10e7e36209b8 | [
"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 | 30,018 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Yury Kudryashov
-/
import data.set.intervals.basic
import algebra.ordered_group
/-!
# Upper / lower bounds
In this file we define:
* `upper_bounds`, `lower_bounds` : the set of upper bounds (resp., lower bounds) of a set;
* `bdd_above s`, `bdd_below s` : the set `s` is bounded above (resp., below), i.e., the set of upper
(resp., lower) bounds of `s` is nonempty;
* `is_least s a`, `is_greatest s a` : `a` is a least (resp., greatest) element of `s`;
for a partial order, it is unique if exists;
* `is_lub s a`, `is_glb s a` : `a` is a least upper bound (resp., a greatest lower bound)
of `s`; for a partial order, it is unique if exists.
We also prove various lemmas about monotonicity, behaviour under `∪`, `∩`, `insert`, and provide
formulas for `∅`, `univ`, and intervals.
-/
open set
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x}
section
variables [preorder α] [preorder β] {s t : set α} {a b : α}
/-!
### Definitions
-/
/-- The set of upper bounds of a set. -/
def upper_bounds (s : set α) : set α := { x | ∀ ⦃a⦄, a ∈ s → a ≤ x }
/-- The set of lower bounds of a set. -/
def lower_bounds (s : set α) : set α := { x | ∀ ⦃a⦄, a ∈ s → x ≤ a }
/-- A set is bounded above if there exists an upper bound. -/
def bdd_above (s : set α) := (upper_bounds s).nonempty
/-- A set is bounded below if there exists a lower bound. -/
def bdd_below (s : set α) := (lower_bounds s).nonempty
/-- `a` is a least element of a set `s`; for a partial order, it is unique if exists. -/
def is_least (s : set α) (a : α) : Prop := a ∈ s ∧ a ∈ lower_bounds s
/-- `a` is a greatest element of a set `s`; for a partial order, it is unique if exists -/
def is_greatest (s : set α) (a : α) : Prop := a ∈ s ∧ a ∈ upper_bounds s
/-- `a` is a least upper bound of a set `s`; for a partial order, it is unique if exists. -/
def is_lub (s : set α) : α → Prop := is_least (upper_bounds s)
/-- `a` is a greatest lower bound of a set `s`; for a partial order, it is unique if exists. -/
def is_glb (s : set α) : α → Prop := is_greatest (lower_bounds s)
lemma mem_upper_bounds : a ∈ upper_bounds s ↔ ∀ x ∈ s, x ≤ a := iff.rfl
lemma mem_lower_bounds : a ∈ lower_bounds s ↔ ∀ x ∈ s, a ≤ x := iff.rfl
/-- A set `s` is not bounded above if and only if for each `x` there exists `y ∈ s` such that `x`
is not greater than or equal to `y`. This version only assumes `preorder` structure and uses
`¬(y ≤ x)`. A version for linear orders is called `not_bdd_above_iff`. -/
lemma not_bdd_above_iff' : ¬bdd_above s ↔ ∀ x, ∃ y ∈ s, ¬(y ≤ x) :=
by simp [bdd_above, upper_bounds, set.nonempty]
/-- A set `s` is not bounded below if and only if for each `x` there exists `y ∈ s` such that `x`
is not less than or equal to `y`. This version only assumes `preorder` structure and uses
`¬(x ≤ y)`. A version for linear orders is called `not_bdd_below_iff`. -/
lemma not_bdd_below_iff' : ¬bdd_below s ↔ ∀ x, ∃ y ∈ s, ¬(x ≤ y) :=
@not_bdd_above_iff' (order_dual α) _ _
/-- A set `s` is not bounded above if and only if for each `x` there exists `y ∈ s` that is greater
than `x`. A version for preorders is called `not_bdd_above_iff'`. -/
lemma not_bdd_above_iff {α : Type*} [linear_order α] {s : set α} :
¬bdd_above s ↔ ∀ x, ∃ y ∈ s, x < y :=
by simp only [not_bdd_above_iff', not_le]
/-- A set `s` is not bounded below if and only if for each `x` there exists `y ∈ s` that is less
than `x`. A version for preorders is called `not_bdd_below_iff'`. -/
lemma not_bdd_below_iff {α : Type*} [linear_order α] {s : set α} :
¬bdd_below s ↔ ∀ x, ∃ y ∈ s, y < x :=
@not_bdd_above_iff (order_dual α) _ _
/-!
### Monotonicity
-/
lemma upper_bounds_mono_set ⦃s t : set α⦄ (hst : s ⊆ t) :
upper_bounds t ⊆ upper_bounds s :=
λ b hb x h, hb $ hst h
lemma lower_bounds_mono_set ⦃s t : set α⦄ (hst : s ⊆ t) :
lower_bounds t ⊆ lower_bounds s :=
λ b hb x h, hb $ hst h
lemma upper_bounds_mono_mem ⦃a b⦄ (hab : a ≤ b) : a ∈ upper_bounds s → b ∈ upper_bounds s :=
λ ha x h, le_trans (ha h) hab
lemma lower_bounds_mono_mem ⦃a b⦄ (hab : a ≤ b) : b ∈ lower_bounds s → a ∈ lower_bounds s :=
λ hb x h, le_trans hab (hb h)
lemma upper_bounds_mono ⦃s t : set α⦄ (hst : s ⊆ t) ⦃a b⦄ (hab : a ≤ b) :
a ∈ upper_bounds t → b ∈ upper_bounds s :=
λ ha, upper_bounds_mono_set hst $ upper_bounds_mono_mem hab ha
lemma lower_bounds_mono ⦃s t : set α⦄ (hst : s ⊆ t) ⦃a b⦄ (hab : a ≤ b) :
b ∈ lower_bounds t → a ∈ lower_bounds s :=
λ hb, lower_bounds_mono_set hst $ lower_bounds_mono_mem hab hb
/-- If `s ⊆ t` and `t` is bounded above, then so is `s`. -/
lemma bdd_above.mono ⦃s t : set α⦄ (h : s ⊆ t) : bdd_above t → bdd_above s :=
nonempty.mono $ upper_bounds_mono_set h
/-- If `s ⊆ t` and `t` is bounded below, then so is `s`. -/
lemma bdd_below.mono ⦃s t : set α⦄ (h : s ⊆ t) : bdd_below t → bdd_below s :=
nonempty.mono $ lower_bounds_mono_set h
/-- If `a` is a least upper bound for sets `s` and `p`, then it is a least upper bound for any
set `t`, `s ⊆ t ⊆ p`. -/
lemma is_lub.of_subset_of_superset {s t p : set α} (hs : is_lub s a) (hp : is_lub p a)
(hst : s ⊆ t) (htp : t ⊆ p) : is_lub t a :=
⟨upper_bounds_mono_set htp hp.1, lower_bounds_mono_set (upper_bounds_mono_set hst) hs.2⟩
/-- If `a` is a greatest lower bound for sets `s` and `p`, then it is a greater lower bound for any
set `t`, `s ⊆ t ⊆ p`. -/
lemma is_glb.of_subset_of_superset {s t p : set α} (hs : is_glb s a) (hp : is_glb p a)
(hst : s ⊆ t) (htp : t ⊆ p) : is_glb t a :=
@is_lub.of_subset_of_superset (order_dual α) _ a s t p hs hp hst htp
lemma is_least.mono (ha : is_least s a) (hb : is_least t b) (hst : s ⊆ t) : b ≤ a :=
hb.2 (hst ha.1)
lemma is_greatest.mono (ha : is_greatest s a) (hb : is_greatest t b) (hst : s ⊆ t) : a ≤ b :=
hb.2 (hst ha.1)
lemma is_lub.mono (ha : is_lub s a) (hb : is_lub t b) (hst : s ⊆ t) : a ≤ b :=
hb.mono ha $ upper_bounds_mono_set hst
lemma is_glb.mono (ha : is_glb s a) (hb : is_glb t b) (hst : s ⊆ t) : b ≤ a :=
hb.mono ha $ lower_bounds_mono_set hst
/-!
### Conversions
-/
lemma is_least.is_glb (h : is_least s a) : is_glb s a := ⟨h.2, λ b hb, hb h.1⟩
lemma is_greatest.is_lub (h : is_greatest s a) : is_lub s a := ⟨h.2, λ b hb, hb h.1⟩
lemma is_lub.upper_bounds_eq (h : is_lub s a) : upper_bounds s = Ici a :=
set.ext $ λ b, ⟨λ hb, h.2 hb, λ hb, upper_bounds_mono_mem hb h.1⟩
lemma is_glb.lower_bounds_eq (h : is_glb s a) : lower_bounds s = Iic a :=
@is_lub.upper_bounds_eq (order_dual α) _ _ _ h
lemma is_least.lower_bounds_eq (h : is_least s a) : lower_bounds s = Iic a :=
h.is_glb.lower_bounds_eq
lemma is_greatest.upper_bounds_eq (h : is_greatest s a) : upper_bounds s = Ici a :=
h.is_lub.upper_bounds_eq
lemma is_lub_le_iff (h : is_lub s a) : a ≤ b ↔ b ∈ upper_bounds s :=
by { rw h.upper_bounds_eq, refl }
lemma le_is_glb_iff (h : is_glb s a) : b ≤ a ↔ b ∈ lower_bounds s :=
by { rw h.lower_bounds_eq, refl }
/-- If `s` has a least upper bound, then it is bounded above. -/
lemma is_lub.bdd_above (h : is_lub s a) : bdd_above s := ⟨a, h.1⟩
/-- If `s` has a greatest lower bound, then it is bounded below. -/
lemma is_glb.bdd_below (h : is_glb s a) : bdd_below s := ⟨a, h.1⟩
/-- If `s` has a greatest element, then it is bounded above. -/
lemma is_greatest.bdd_above (h : is_greatest s a) : bdd_above s := ⟨a, h.2⟩
/-- If `s` has a least element, then it is bounded below. -/
lemma is_least.bdd_below (h : is_least s a) : bdd_below s := ⟨a, h.2⟩
lemma is_least.nonempty (h : is_least s a) : s.nonempty := ⟨a, h.1⟩
lemma is_greatest.nonempty (h : is_greatest s a) : s.nonempty := ⟨a, h.1⟩
/-!
### Union and intersection
-/
@[simp] lemma upper_bounds_union : upper_bounds (s ∪ t) = upper_bounds s ∩ upper_bounds t :=
subset.antisymm
(λ b hb, ⟨λ x hx, hb (or.inl hx), λ x hx, hb (or.inr hx)⟩)
(λ b hb x hx, hx.elim (λ hs, hb.1 hs) (λ ht, hb.2 ht))
@[simp] lemma lower_bounds_union : lower_bounds (s ∪ t) = lower_bounds s ∩ lower_bounds t :=
@upper_bounds_union (order_dual α) _ s t
lemma union_upper_bounds_subset_upper_bounds_inter :
upper_bounds s ∪ upper_bounds t ⊆ upper_bounds (s ∩ t) :=
union_subset
(upper_bounds_mono_set $ inter_subset_left _ _)
(upper_bounds_mono_set $ inter_subset_right _ _)
lemma union_lower_bounds_subset_lower_bounds_inter :
lower_bounds s ∪ lower_bounds t ⊆ lower_bounds (s ∩ t) :=
@union_upper_bounds_subset_upper_bounds_inter (order_dual α) _ s t
lemma is_least_union_iff {a : α} {s t : set α} :
is_least (s ∪ t) a ↔ (is_least s a ∧ a ∈ lower_bounds t ∨ a ∈ lower_bounds s ∧ is_least t a) :=
by simp [is_least, lower_bounds_union, or_and_distrib_right, and_comm (a ∈ t), and_assoc]
lemma is_greatest_union_iff :
is_greatest (s ∪ t) a ↔ (is_greatest s a ∧ a ∈ upper_bounds t ∨
a ∈ upper_bounds s ∧ is_greatest t a) :=
@is_least_union_iff (order_dual α) _ a s t
/-- If `s` is bounded, then so is `s ∩ t` -/
lemma bdd_above.inter_of_left (h : bdd_above s) : bdd_above (s ∩ t) :=
h.mono $ inter_subset_left s t
/-- If `t` is bounded, then so is `s ∩ t` -/
lemma bdd_above.inter_of_right (h : bdd_above t) : bdd_above (s ∩ t) :=
h.mono $ inter_subset_right s t
/-- If `s` is bounded, then so is `s ∩ t` -/
lemma bdd_below.inter_of_left (h : bdd_below s) : bdd_below (s ∩ t) :=
h.mono $ inter_subset_left s t
/-- If `t` is bounded, then so is `s ∩ t` -/
lemma bdd_below.inter_of_right (h : bdd_below t) : bdd_below (s ∩ t) :=
h.mono $ inter_subset_right s t
/-- If `s` and `t` are bounded above sets in a `semilattice_sup`, then so is `s ∪ t`. -/
lemma bdd_above.union [semilattice_sup γ] {s t : set γ} :
bdd_above s → bdd_above t → bdd_above (s ∪ t) :=
begin
rintros ⟨bs, hs⟩ ⟨bt, ht⟩,
use bs ⊔ bt,
rw upper_bounds_union,
exact ⟨upper_bounds_mono_mem le_sup_left hs,
upper_bounds_mono_mem le_sup_right ht⟩
end
/-- The union of two sets is bounded above if and only if each of the sets is. -/
lemma bdd_above_union [semilattice_sup γ] {s t : set γ} :
bdd_above (s ∪ t) ↔ bdd_above s ∧ bdd_above t :=
⟨λ h, ⟨h.mono $ subset_union_left s t, h.mono $ subset_union_right s t⟩,
λ h, h.1.union h.2⟩
lemma bdd_below.union [semilattice_inf γ] {s t : set γ} :
bdd_below s → bdd_below t → bdd_below (s ∪ t) :=
@bdd_above.union (order_dual γ) _ s t
/--The union of two sets is bounded above if and only if each of the sets is.-/
lemma bdd_below_union [semilattice_inf γ] {s t : set γ} :
bdd_below (s ∪ t) ↔ bdd_below s ∧ bdd_below t :=
@bdd_above_union (order_dual γ) _ s t
/-- If `a` is the least upper bound of `s` and `b` is the least upper bound of `t`,
then `a ⊔ b` is the least upper bound of `s ∪ t`. -/
lemma is_lub.union [semilattice_sup γ] {a b : γ} {s t : set γ}
(hs : is_lub s a) (ht : is_lub t b) :
is_lub (s ∪ t) (a ⊔ b) :=
⟨assume c h, h.cases_on (λ h, le_sup_left_of_le $ hs.left h) (λ h, le_sup_right_of_le $ ht.left h),
assume c hc, sup_le
(hs.right $ assume d hd, hc $ or.inl hd) (ht.right $ assume d hd, hc $ or.inr hd)⟩
/-- If `a` is the greatest lower bound of `s` and `b` is the greatest lower bound of `t`,
then `a ⊓ b` is the greatest lower bound of `s ∪ t`. -/
lemma is_glb.union [semilattice_inf γ] {a₁ a₂ : γ} {s t : set γ}
(hs : is_glb s a₁) (ht : is_glb t a₂) :
is_glb (s ∪ t) (a₁ ⊓ a₂) :=
@is_lub.union (order_dual γ) _ _ _ _ _ hs ht
/-- If `a` is the least element of `s` and `b` is the least element of `t`,
then `min a b` is the least element of `s ∪ t`. -/
lemma is_least.union [linear_order γ] {a b : γ} {s t : set γ}
(ha : is_least s a) (hb : is_least t b) : is_least (s ∪ t) (min a b) :=
⟨by cases (le_total a b) with h h; simp [h, ha.1, hb.1],
(ha.is_glb.union hb.is_glb).1⟩
/-- If `a` is the greatest element of `s` and `b` is the greatest element of `t`,
then `max a b` is the greatest element of `s ∪ t`. -/
lemma is_greatest.union [linear_order γ] {a b : γ} {s t : set γ}
(ha : is_greatest s a) (hb : is_greatest t b) : is_greatest (s ∪ t) (max a b) :=
⟨by cases (le_total a b) with h h; simp [h, ha.1, hb.1],
(ha.is_lub.union hb.is_lub).1⟩
/-!
### Specific sets
#### Unbounded intervals
-/
lemma is_least_Ici : is_least (Ici a) a := ⟨left_mem_Ici, λ x, id⟩
lemma is_greatest_Iic : is_greatest (Iic a) a := ⟨right_mem_Iic, λ x, id⟩
lemma is_lub_Iic : is_lub (Iic a) a := is_greatest_Iic.is_lub
lemma is_glb_Ici : is_glb (Ici a) a := is_least_Ici.is_glb
lemma upper_bounds_Iic : upper_bounds (Iic a) = Ici a := is_lub_Iic.upper_bounds_eq
lemma lower_bounds_Ici : lower_bounds (Ici a) = Iic a := is_glb_Ici.lower_bounds_eq
lemma bdd_above_Iic : bdd_above (Iic a) := is_lub_Iic.bdd_above
lemma bdd_below_Ici : bdd_below (Ici a) := is_glb_Ici.bdd_below
lemma bdd_above_Iio : bdd_above (Iio a) := ⟨a, λ x hx, le_of_lt hx⟩
lemma bdd_below_Ioi : bdd_below (Ioi a) := ⟨a, λ x hx, le_of_lt hx⟩
section
variables [linear_order γ] [densely_ordered γ]
lemma is_lub_Iio {a : γ} : is_lub (Iio a) a :=
⟨λ x hx, le_of_lt hx, λ y hy, le_of_forall_ge_of_dense hy⟩
lemma is_glb_Ioi {a : γ} : is_glb (Ioi a) a := @is_lub_Iio (order_dual γ) _ _ a
lemma upper_bounds_Iio {a : γ} : upper_bounds (Iio a) = Ici a := is_lub_Iio.upper_bounds_eq
lemma lower_bounds_Ioi {a : γ} : lower_bounds (Ioi a) = Iic a := is_glb_Ioi.lower_bounds_eq
end
/-!
#### Singleton
-/
lemma is_greatest_singleton : is_greatest {a} a :=
⟨mem_singleton a, λ x hx, le_of_eq $ eq_of_mem_singleton hx⟩
lemma is_least_singleton : is_least {a} a :=
@is_greatest_singleton (order_dual α) _ a
lemma is_lub_singleton : is_lub {a} a := is_greatest_singleton.is_lub
lemma is_glb_singleton : is_glb {a} a := is_least_singleton.is_glb
lemma bdd_above_singleton : bdd_above ({a} : set α) := is_lub_singleton.bdd_above
lemma bdd_below_singleton : bdd_below ({a} : set α) := is_glb_singleton.bdd_below
@[simp] lemma upper_bounds_singleton : upper_bounds {a} = Ici a := is_lub_singleton.upper_bounds_eq
@[simp] lemma lower_bounds_singleton : lower_bounds {a} = Iic a := is_glb_singleton.lower_bounds_eq
/-!
#### Bounded intervals
-/
lemma bdd_above_Icc : bdd_above (Icc a b) := ⟨b, λ _, and.right⟩
lemma bdd_below_Icc : bdd_below (Icc a b) := ⟨a, λ _, and.left⟩
lemma bdd_above_Ico : bdd_above (Ico a b) := bdd_above_Icc.mono Ico_subset_Icc_self
lemma bdd_below_Ico : bdd_below (Ico a b) := bdd_below_Icc.mono Ico_subset_Icc_self
lemma bdd_above_Ioc : bdd_above (Ioc a b) := bdd_above_Icc.mono Ioc_subset_Icc_self
lemma bdd_below_Ioc : bdd_below (Ioc a b) := bdd_below_Icc.mono Ioc_subset_Icc_self
lemma bdd_above_Ioo : bdd_above (Ioo a b) := bdd_above_Icc.mono Ioo_subset_Icc_self
lemma bdd_below_Ioo : bdd_below (Ioo a b) := bdd_below_Icc.mono Ioo_subset_Icc_self
lemma is_greatest_Icc (h : a ≤ b) : is_greatest (Icc a b) b :=
⟨right_mem_Icc.2 h, λ x, and.right⟩
lemma is_lub_Icc (h : a ≤ b) : is_lub (Icc a b) b := (is_greatest_Icc h).is_lub
lemma upper_bounds_Icc (h : a ≤ b) : upper_bounds (Icc a b) = Ici b :=
(is_lub_Icc h).upper_bounds_eq
lemma is_least_Icc (h : a ≤ b) : is_least (Icc a b) a :=
⟨left_mem_Icc.2 h, λ x, and.left⟩
lemma is_glb_Icc (h : a ≤ b) : is_glb (Icc a b) a := (is_least_Icc h).is_glb
lemma lower_bounds_Icc (h : a ≤ b) : lower_bounds (Icc a b) = Iic a :=
(is_glb_Icc h).lower_bounds_eq
lemma is_greatest_Ioc (h : a < b) : is_greatest (Ioc a b) b :=
⟨right_mem_Ioc.2 h, λ x, and.right⟩
lemma is_lub_Ioc (h : a < b) : is_lub (Ioc a b) b :=
(is_greatest_Ioc h).is_lub
lemma upper_bounds_Ioc (h : a < b) : upper_bounds (Ioc a b) = Ici b :=
(is_lub_Ioc h).upper_bounds_eq
lemma is_least_Ico (h : a < b) : is_least (Ico a b) a :=
⟨left_mem_Ico.2 h, λ x, and.left⟩
lemma is_glb_Ico (h : a < b) : is_glb (Ico a b) a :=
(is_least_Ico h).is_glb
lemma lower_bounds_Ico (h : a < b) : lower_bounds (Ico a b) = Iic a :=
(is_glb_Ico h).lower_bounds_eq
section
variables [linear_order γ] [densely_ordered γ]
lemma is_glb_Ioo {a b : γ} (hab : a < b) : is_glb (Ioo a b) a :=
begin
refine ⟨λx hx, le_of_lt hx.1, λy hy, le_of_not_lt $ λ h, _⟩,
have : a < min b y, by { rw lt_min_iff, exact ⟨hab, h⟩ },
rcases exists_between this with ⟨z, az, zy⟩,
rw lt_min_iff at zy,
exact lt_irrefl _ (lt_of_le_of_lt (hy ⟨az, zy.1⟩) zy.2)
end
lemma lower_bounds_Ioo {a b : γ} (hab : a < b) : lower_bounds (Ioo a b) = Iic a :=
(is_glb_Ioo hab).lower_bounds_eq
lemma is_glb_Ioc {a b : γ} (hab : a < b) : is_glb (Ioc a b) a :=
(is_glb_Ioo hab).of_subset_of_superset (is_glb_Icc $ le_of_lt hab)
Ioo_subset_Ioc_self Ioc_subset_Icc_self
lemma lower_bound_Ioc {a b : γ} (hab : a < b) : lower_bounds (Ioc a b) = Iic a :=
(is_glb_Ioc hab).lower_bounds_eq
lemma is_lub_Ioo {a b : γ} (hab : a < b) : is_lub (Ioo a b) b :=
by simpa only [dual_Ioo] using @is_glb_Ioo (order_dual γ) _ _ b a hab
lemma upper_bounds_Ioo {a b : γ} (hab : a < b) : upper_bounds (Ioo a b) = Ici b :=
(is_lub_Ioo hab).upper_bounds_eq
lemma is_lub_Ico {a b : γ} (hab : a < b) : is_lub (Ico a b) b :=
by simpa only [dual_Ioc] using @is_glb_Ioc (order_dual γ) _ _ b a hab
lemma upper_bounds_Ico {a b : γ} (hab : a < b) : upper_bounds (Ico a b) = Ici b :=
(is_lub_Ico hab).upper_bounds_eq
end
lemma bdd_below_iff_subset_Ici : bdd_below s ↔ ∃ a, s ⊆ Ici a := iff.rfl
lemma bdd_above_iff_subset_Iic : bdd_above s ↔ ∃ a, s ⊆ Iic a := iff.rfl
lemma bdd_below_bdd_above_iff_subset_Icc : bdd_below s ∧ bdd_above s ↔ ∃ a b, s ⊆ Icc a b :=
by simp only [Ici_inter_Iic.symm, subset_inter_iff, bdd_below_iff_subset_Ici,
bdd_above_iff_subset_Iic, exists_and_distrib_left, exists_and_distrib_right]
/-!
### Univ
-/
lemma order_top.upper_bounds_univ [order_top γ] : upper_bounds (univ : set γ) = {⊤} :=
set.ext $ λ b, iff.trans ⟨λ hb, top_unique $ hb trivial, λ hb x hx, hb.symm ▸ le_top⟩
mem_singleton_iff.symm
lemma is_greatest_univ [order_top γ] : is_greatest (univ : set γ) ⊤ :=
by simp only [is_greatest, order_top.upper_bounds_univ, mem_univ, mem_singleton, true_and]
lemma is_lub_univ [order_top γ] : is_lub (univ : set γ) ⊤ :=
is_greatest_univ.is_lub
lemma order_bot.lower_bounds_univ [order_bot γ] : lower_bounds (univ : set γ) = {⊥} :=
@order_top.upper_bounds_univ (order_dual γ) _
lemma is_least_univ [order_bot γ] : is_least (univ : set γ) ⊥ :=
@is_greatest_univ (order_dual γ) _
lemma is_glb_univ [order_bot γ] : is_glb (univ : set γ) ⊥ :=
is_least_univ.is_glb
lemma no_top_order.upper_bounds_univ [no_top_order α] : upper_bounds (univ : set α) = ∅ :=
eq_empty_of_subset_empty $ λ b hb, let ⟨x, hx⟩ := no_top b in
not_le_of_lt hx (hb trivial)
lemma no_bot_order.lower_bounds_univ [no_bot_order α] : lower_bounds (univ : set α) = ∅ :=
@no_top_order.upper_bounds_univ (order_dual α) _ _
/-!
### Empty set
-/
@[simp] lemma upper_bounds_empty : upper_bounds (∅ : set α) = univ :=
by simp only [upper_bounds, eq_univ_iff_forall, mem_set_of_eq, ball_empty_iff, forall_true_iff]
@[simp] lemma lower_bounds_empty : lower_bounds (∅ : set α) = univ :=
@upper_bounds_empty (order_dual α) _
@[simp] lemma bdd_above_empty [nonempty α] : bdd_above (∅ : set α) :=
by simp only [bdd_above, upper_bounds_empty, univ_nonempty]
@[simp] lemma bdd_below_empty [nonempty α] : bdd_below (∅ : set α) :=
by simp only [bdd_below, lower_bounds_empty, univ_nonempty]
lemma is_glb_empty [order_top γ] : is_glb ∅ (⊤:γ) :=
by simp only [is_glb, lower_bounds_empty, is_greatest_univ]
lemma is_lub_empty [order_bot γ] : is_lub ∅ (⊥:γ) :=
@is_glb_empty (order_dual γ) _
lemma is_lub.nonempty [no_bot_order α] (hs : is_lub s a) : s.nonempty :=
let ⟨a', ha'⟩ := no_bot a in
ne_empty_iff_nonempty.1 $ assume h,
have a ≤ a', from hs.right $ by simp only [h, upper_bounds_empty],
not_le_of_lt ha' this
lemma is_glb.nonempty [no_top_order α] (hs : is_glb s a) : s.nonempty :=
@is_lub.nonempty (order_dual α) _ _ _ _ hs
lemma nonempty_of_not_bdd_above [ha : nonempty α] (h : ¬bdd_above s) : s.nonempty :=
nonempty.elim ha $ λ x, (not_bdd_above_iff'.1 h x).imp $ λ a ha, ha.fst
lemma nonempty_of_not_bdd_below [ha : nonempty α] (h : ¬bdd_below s) : s.nonempty :=
@nonempty_of_not_bdd_above (order_dual α) _ _ _ h
/-!
### insert
-/
/-- Adding a point to a set preserves its boundedness above. -/
@[simp] lemma bdd_above_insert [semilattice_sup γ] (a : γ) {s : set γ} :
bdd_above (insert a s) ↔ bdd_above s :=
by simp only [insert_eq, bdd_above_union, bdd_above_singleton, true_and]
lemma bdd_above.insert [semilattice_sup γ] (a : γ) {s : set γ} (hs : bdd_above s) :
bdd_above (insert a s) :=
(bdd_above_insert a).2 hs
/--Adding a point to a set preserves its boundedness below.-/
@[simp] lemma bdd_below_insert [semilattice_inf γ] (a : γ) {s : set γ} :
bdd_below (insert a s) ↔ bdd_below s :=
by simp only [insert_eq, bdd_below_union, bdd_below_singleton, true_and]
lemma bdd_below.insert [semilattice_inf γ] (a : γ) {s : set γ} (hs : bdd_below s) :
bdd_below (insert a s) :=
(bdd_below_insert a).2 hs
lemma is_lub.insert [semilattice_sup γ] (a) {b} {s : set γ} (hs : is_lub s b) :
is_lub (insert a s) (a ⊔ b) :=
by { rw insert_eq, exact is_lub_singleton.union hs }
lemma is_glb.insert [semilattice_inf γ] (a) {b} {s : set γ} (hs : is_glb s b) :
is_glb (insert a s) (a ⊓ b) :=
by { rw insert_eq, exact is_glb_singleton.union hs }
lemma is_greatest.insert [linear_order γ] (a) {b} {s : set γ} (hs : is_greatest s b) :
is_greatest (insert a s) (max a b) :=
by { rw insert_eq, exact is_greatest_singleton.union hs }
lemma is_least.insert [linear_order γ] (a) {b} {s : set γ} (hs : is_least s b) :
is_least (insert a s) (min a b) :=
by { rw insert_eq, exact is_least_singleton.union hs }
@[simp] lemma upper_bounds_insert (a : α) (s : set α) :
upper_bounds (insert a s) = Ici a ∩ upper_bounds s :=
by rw [insert_eq, upper_bounds_union, upper_bounds_singleton]
@[simp] lemma lower_bounds_insert (a : α) (s : set α) :
lower_bounds (insert a s) = Iic a ∩ lower_bounds s :=
by rw [insert_eq, lower_bounds_union, lower_bounds_singleton]
/-- When there is a global maximum, every set is bounded above. -/
@[simp] protected lemma order_top.bdd_above [order_top γ] (s : set γ) : bdd_above s :=
⟨⊤, assume a ha, order_top.le_top a⟩
/-- When there is a global minimum, every set is bounded below. -/
@[simp] protected lemma order_bot.bdd_below [order_bot γ] (s : set γ) : bdd_below s :=
⟨⊥, assume a ha, order_bot.bot_le a⟩
/-!
### Pair
-/
lemma is_lub_pair [semilattice_sup γ] {a b : γ} : is_lub {a, b} (a ⊔ b) :=
is_lub_singleton.insert _
lemma is_glb_pair [semilattice_inf γ] {a b : γ} : is_glb {a, b} (a ⊓ b) :=
is_glb_singleton.insert _
lemma is_least_pair [linear_order γ] {a b : γ} : is_least {a, b} (min a b) :=
is_least_singleton.insert _
lemma is_greatest_pair [linear_order γ] {a b : γ} : is_greatest {a, b} (max a b) :=
is_greatest_singleton.insert _
end
/-!
### (In)equalities with the least upper bound and the greatest lower bound
-/
section preorder
variables [preorder α] {s : set α} {a b : α}
lemma lower_bounds_le_upper_bounds (ha : a ∈ lower_bounds s) (hb : b ∈ upper_bounds s) :
s.nonempty → a ≤ b
| ⟨c, hc⟩ := le_trans (ha hc) (hb hc)
lemma is_glb_le_is_lub (ha : is_glb s a) (hb : is_lub s b) (hs : s.nonempty) : a ≤ b :=
lower_bounds_le_upper_bounds ha.1 hb.1 hs
lemma is_lub_lt_iff (ha : is_lub s a) : a < b ↔ ∃ c ∈ upper_bounds s, c < b :=
⟨λ hb, ⟨a, ha.1, hb⟩, λ ⟨c, hcs, hcb⟩, lt_of_le_of_lt (ha.2 hcs) hcb⟩
lemma lt_is_glb_iff (ha : is_glb s a) : b < a ↔ ∃ c ∈ lower_bounds s, b < c :=
@is_lub_lt_iff (order_dual α) _ s _ _ ha
lemma le_of_is_lub_le_is_glb {x y} (ha : is_glb s a) (hb : is_lub s b) (hab : b ≤ a)
(hx : x ∈ s) (hy : y ∈ s) : x ≤ y :=
calc x ≤ b : hb.1 hx
... ≤ a : hab
... ≤ y : ha.1 hy
end preorder
section partial_order
variables [partial_order α] {s : set α} {a b : α}
lemma is_least.unique (Ha : is_least s a) (Hb : is_least s b) : a = b :=
le_antisymm (Ha.right Hb.left) (Hb.right Ha.left)
lemma is_least.is_least_iff_eq (Ha : is_least s a) : is_least s b ↔ a = b :=
iff.intro Ha.unique (assume h, h ▸ Ha)
lemma is_greatest.unique (Ha : is_greatest s a) (Hb : is_greatest s b) : a = b :=
le_antisymm (Hb.right Ha.left) (Ha.right Hb.left)
lemma is_greatest.is_greatest_iff_eq (Ha : is_greatest s a) : is_greatest s b ↔ a = b :=
iff.intro Ha.unique (assume h, h ▸ Ha)
lemma is_lub.unique (Ha : is_lub s a) (Hb : is_lub s b) : a = b :=
Ha.unique Hb
lemma is_glb.unique (Ha : is_glb s a) (Hb : is_glb s b) : a = b :=
Ha.unique Hb
lemma set.subsingleton_of_is_lub_le_is_glb (Ha : is_glb s a) (Hb : is_lub s b) (hab : b ≤ a) :
s.subsingleton :=
λ x hx y hy, le_antisymm (le_of_is_lub_le_is_glb Ha Hb hab hx hy)
(le_of_is_lub_le_is_glb Ha Hb hab hy hx)
lemma is_glb_lt_is_lub_of_ne (Ha : is_glb s a) (Hb : is_lub s b)
{x y} (Hx : x ∈ s) (Hy : y ∈ s) (Hxy : x ≠ y) :
a < b :=
lt_iff_le_not_le.2
⟨lower_bounds_le_upper_bounds Ha.1 Hb.1 ⟨x, Hx⟩,
λ hab, Hxy $ set.subsingleton_of_is_lub_le_is_glb Ha Hb hab Hx Hy⟩
end partial_order
section linear_order
variables [linear_order α] {s : set α} {a b : α}
lemma lt_is_lub_iff (h : is_lub s a) : b < a ↔ ∃ c ∈ s, b < c :=
by simp only [← not_le, is_lub_le_iff h, mem_upper_bounds, not_forall]
lemma is_glb_lt_iff (h : is_glb s a) : a < b ↔ ∃ c ∈ s, c < b :=
@lt_is_lub_iff (order_dual α) _ _ _ _ h
lemma is_lub.exists_between (h : is_lub s a) (hb : b < a) :
∃ c ∈ s, b < c ∧ c ≤ a :=
let ⟨c, hcs, hbc⟩ := (lt_is_lub_iff h).1 hb in ⟨c, hcs, hbc, h.1 hcs⟩
lemma is_lub.exists_between' (h : is_lub s a) (h' : a ∉ s) (hb : b < a) :
∃ c ∈ s, b < c ∧ c < a :=
let ⟨c, hcs, hbc, hca⟩ := h.exists_between hb
in ⟨c, hcs, hbc, hca.lt_of_ne $ λ hac, h' $ hac ▸ hcs⟩
lemma is_glb.exists_between (h : is_glb s a) (hb : a < b) :
∃ c ∈ s, a ≤ c ∧ c < b :=
let ⟨c, hcs, hbc⟩ := (is_glb_lt_iff h).1 hb in ⟨c, hcs, h.1 hcs, hbc⟩
lemma is_glb.exists_between' (h : is_glb s a) (h' : a ∉ s) (hb : a < b) :
∃ c ∈ s, a < c ∧ c < b :=
let ⟨c, hcs, hac, hcb⟩ := h.exists_between hb
in ⟨c, hcs, hac.lt_of_ne $ λ hac, h' $ hac.symm ▸ hcs, hcb⟩
end linear_order
/-!
### Least upper bound and the greatest lower bound in linear ordered additive commutative groups
-/
section linear_ordered_add_comm_group
variables [linear_ordered_add_comm_group α] {s : set α} {a ε : α}
lemma is_glb.exists_between_self_add (h : is_glb s a) (hε : 0 < ε) :
∃ b ∈ s, a ≤ b ∧ b < a + ε :=
h.exists_between $ lt_add_of_pos_right _ hε
lemma is_glb.exists_between_self_add' (h : is_glb s a) (h₂ : a ∉ s) (hε : 0 < ε) :
∃ b ∈ s, a < b ∧ b < a + ε :=
h.exists_between' h₂ $ lt_add_of_pos_right _ hε
lemma is_lub.exists_between_sub_self (h : is_lub s a) (hε : 0 < ε) : ∃ b ∈ s, a - ε < b ∧ b ≤ a :=
h.exists_between $ sub_lt_self _ hε
lemma is_lub.exists_between_sub_self' (h : is_lub s a) (h₂ : a ∉ s) (hε : 0 < ε) :
∃ b ∈ s, a - ε < b ∧ b < a :=
h.exists_between' h₂ $ sub_lt_self _ hε
end linear_ordered_add_comm_group
/-!
### Images of upper/lower bounds under monotone functions
-/
namespace monotone
variables [preorder α] [preorder β] {f : α → β} (Hf : monotone f) {a : α} {s : set α}
lemma mem_upper_bounds_image (Ha : a ∈ upper_bounds s) :
f a ∈ upper_bounds (f '' s) :=
ball_image_of_ball (assume x H, Hf (Ha ‹x ∈ s›))
lemma mem_lower_bounds_image (Ha : a ∈ lower_bounds s) :
f a ∈ lower_bounds (f '' s) :=
ball_image_of_ball (assume x H, Hf (Ha ‹x ∈ s›))
/-- The image under a monotone function of a set which is bounded above is bounded above. -/
lemma map_bdd_above (hf : monotone f) : bdd_above s → bdd_above (f '' s)
| ⟨C, hC⟩ := ⟨f C, hf.mem_upper_bounds_image hC⟩
/-- The image under a monotone function of a set which is bounded below is bounded below. -/
lemma map_bdd_below (hf : monotone f) : bdd_below s → bdd_below (f '' s)
| ⟨C, hC⟩ := ⟨f C, hf.mem_lower_bounds_image hC⟩
/-- A monotone map sends a least element of a set to a least element of its image. -/
lemma map_is_least (Ha : is_least s a) : is_least (f '' s) (f a) :=
⟨mem_image_of_mem _ Ha.1, Hf.mem_lower_bounds_image Ha.2⟩
/-- A monotone map sends a greatest element of a set to a greatest element of its image. -/
lemma map_is_greatest (Ha : is_greatest s a) : is_greatest (f '' s) (f a) :=
⟨mem_image_of_mem _ Ha.1, Hf.mem_upper_bounds_image Ha.2⟩
lemma is_lub_image_le (Ha : is_lub s a) {b : β} (Hb : is_lub (f '' s) b) :
b ≤ f a :=
Hb.2 (Hf.mem_upper_bounds_image Ha.1)
lemma le_is_glb_image (Ha : is_glb s a) {b : β} (Hb : is_glb (f '' s) b) :
f a ≤ b :=
Hb.2 (Hf.mem_lower_bounds_image Ha.1)
end monotone
lemma is_glb.of_image [preorder α] [preorder β] {f : α → β} (hf : ∀ {x y}, f x ≤ f y ↔ x ≤ y)
{s : set α} {x : α} (hx : is_glb (f '' s) (f x)) :
is_glb s x :=
⟨λ y hy, hf.1 $ hx.1 $ mem_image_of_mem _ hy,
λ y hy, hf.1 $ hx.2 $ monotone.mem_lower_bounds_image (λ x y, hf.2) hy⟩
lemma is_lub.of_image [preorder α] [preorder β] {f : α → β} (hf : ∀ {x y}, f x ≤ f y ↔ x ≤ y)
{s : set α} {x : α} (hx : is_lub (f '' s) (f x)) :
is_lub s x :=
@is_glb.of_image (order_dual α) (order_dual β) _ _ f (λ x y, hf) _ _ hx
|
f5689920422506bd93d1058462662d801cc97d49 | 1abd1ed12aa68b375cdef28959f39531c6e95b84 | /src/ring_theory/norm.lean | 9a3a4f56e6df4019b0b797be5cc26a0a675084ca | [
"Apache-2.0"
] | permissive | jumpy4/mathlib | d3829e75173012833e9f15ac16e481e17596de0f | af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13 | refs/heads/master | 1,693,508,842,818 | 1,636,203,271,000 | 1,636,203,271,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,017 | lean | /-
Copyright (c) 2021 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen
-/
import linear_algebra.matrix.charpoly.coeff
import linear_algebra.determinant
import ring_theory.power_basis
/-!
# Norm for (finite) ring extensions
Suppose we have an `R`-algebra `S` with a finite basis. For each `s : S`,
the determinant of the linear map given by multiplying by `s` gives information
about the roots of the minimal polynomial of `s` over `R`.
## Implementation notes
Typically, the norm is defined specifically for finite field extensions.
The current definition is as general as possible and the assumption that we have
fields or that the extension is finite is added to the lemmas as needed.
We only define the norm for left multiplication (`algebra.left_mul_matrix`,
i.e. `algebra.lmul_left`).
For now, the definitions assume `S` is commutative, so the choice doesn't
matter anyway.
See also `algebra.trace`, which is defined similarly as the trace of
`algebra.left_mul_matrix`.
## References
* https://en.wikipedia.org/wiki/Field_norm
-/
universes u v w
variables {R S T : Type*} [comm_ring R] [is_domain R] [comm_ring S]
variables [algebra R S]
variables {K L F : Type*} [field K] [field L] [field F]
variables [algebra K L] [algebra L F] [algebra K F]
variables {ι : Type w} [fintype ι]
open finite_dimensional
open linear_map
open matrix
open_locale big_operators
open_locale matrix
namespace algebra
variables (R)
/-- The norm of an element `s` of an `R`-algebra is the determinant of `(*) s`. -/
noncomputable def norm : S →* R :=
linear_map.det.comp (lmul R S).to_ring_hom.to_monoid_hom
lemma norm_apply (x : S) : norm R x = linear_map.det (lmul R S x) := rfl
lemma norm_eq_one_of_not_exists_basis
(h : ¬ ∃ (s : finset S), nonempty (basis s R S)) (x : S) : norm R x = 1 :=
by { rw [norm_apply, linear_map.det], split_ifs with h, refl }
variables {R}
-- Can't be a `simp` lemma because it depends on a choice of basis
lemma norm_eq_matrix_det [decidable_eq ι] (b : basis ι R S) (s : S) :
norm R s = matrix.det (algebra.left_mul_matrix b s) :=
by rw [norm_apply, ← linear_map.det_to_matrix b, to_matrix_lmul_eq]
/-- If `x` is in the base field `K`, then the norm is `x ^ [L : K]`. -/
lemma norm_algebra_map_of_basis (b : basis ι R S) (x : R) :
norm R (algebra_map R S x) = x ^ fintype.card ι :=
begin
haveI := classical.dec_eq ι,
rw [norm_apply, ← det_to_matrix b, lmul_algebra_map],
convert @det_diagonal _ _ _ _ _ (λ (i : ι), x),
{ ext i j, rw [to_matrix_lsmul, matrix.diagonal] },
{ rw [finset.prod_const, finset.card_univ] }
end
/-- If `x` is in the base field `K`, then the norm is `x ^ [L : K]`.
(If `L` is not finite-dimensional over `K`, then `norm = 1 = x ^ 0 = x ^ (finrank L K)`.)
-/
@[simp]
lemma norm_algebra_map (x : K) : norm K (algebra_map K L x) = x ^ finrank K L :=
begin
by_cases H : ∃ (s : finset L), nonempty (basis s K L),
{ rw [norm_algebra_map_of_basis H.some_spec.some, finrank_eq_card_basis H.some_spec.some] },
{ rw [norm_eq_one_of_not_exists_basis K H, finrank_eq_zero_of_not_exists_basis, pow_zero],
rintros ⟨s, ⟨b⟩⟩,
exact H ⟨s, ⟨b⟩⟩ },
end
section eq_prod_roots
lemma norm_gen_eq_prod_roots [algebra K S] (pb : power_basis K S)
(hf : (minpoly K pb.gen).splits (algebra_map K F)) :
algebra_map K F (norm K pb.gen) =
((minpoly K pb.gen).map (algebra_map K F)).roots.prod :=
begin
-- Write the LHS as the 0'th coefficient of `minpoly K pb.gen`
rw [norm_eq_matrix_det pb.basis, det_eq_sign_charpoly_coeff, charpoly_left_mul_matrix,
ring_hom.map_mul, ring_hom.map_pow, ring_hom.map_neg, ring_hom.map_one,
← polynomial.coeff_map, fintype.card_fin],
-- Rewrite `minpoly K pb.gen` as a product over the roots.
conv_lhs { rw polynomial.eq_prod_roots_of_splits hf },
rw [polynomial.coeff_C_mul, polynomial.coeff_zero_multiset_prod, multiset.map_map,
(minpoly.monic pb.is_integral_gen).leading_coeff, ring_hom.map_one, one_mul],
-- Incorporate the `-1` from the `charpoly` back into the product.
rw [← multiset.prod_repeat (-1 : F), ← pb.nat_degree_minpoly,
polynomial.nat_degree_eq_card_roots hf, ← multiset.map_const, ← multiset.prod_map_mul],
-- And conclude that both sides are the same.
congr, convert multiset.map_id _, ext f, simp
end
end eq_prod_roots
section eq_zero_iff
lemma norm_eq_zero_iff_of_basis [is_domain S] (b : basis ι R S) {x : S} :
algebra.norm R x = 0 ↔ x = 0 :=
begin
have hι : nonempty ι := b.index_nonempty,
letI := classical.dec_eq ι,
rw algebra.norm_eq_matrix_det b,
split,
{ rw ← matrix.exists_mul_vec_eq_zero_iff,
rintros ⟨v, v_ne, hv⟩,
rw [← b.equiv_fun.apply_symm_apply v, b.equiv_fun_symm_apply, b.equiv_fun_apply,
algebra.left_mul_matrix_mul_vec_repr] at hv,
refine (mul_eq_zero.mp (b.ext_elem $ λ i, _)).resolve_right (show ∑ i, v i • b i ≠ 0, from _),
{ simpa only [linear_equiv.map_zero, pi.zero_apply] using congr_fun hv i },
{ contrapose! v_ne with sum_eq,
apply b.equiv_fun.symm.injective,
rw [b.equiv_fun_symm_apply, sum_eq, linear_equiv.map_zero] } },
{ rintro rfl,
rw [alg_hom.map_zero, matrix.det_zero hι] },
end
lemma norm_ne_zero_iff_of_basis [is_domain S] (b : basis ι R S) {x : S} :
algebra.norm R x ≠ 0 ↔ x ≠ 0 :=
not_iff_not.mpr (algebra.norm_eq_zero_iff_of_basis b)
/-- See also `algebra.norm_eq_zero_iff'` if you already have rewritten with `algebra.norm_apply`. -/
@[simp]
lemma norm_eq_zero_iff [finite_dimensional K L] {x : L} :
algebra.norm K x = 0 ↔ x = 0 :=
algebra.norm_eq_zero_iff_of_basis (basis.of_vector_space K L)
/-- This is `algebra.norm_eq_zero_iff` composed with `algebra.norm_apply`. -/
@[simp]
lemma norm_eq_zero_iff' [finite_dimensional K L] {x : L} :
linear_map.det (algebra.lmul K L x) = 0 ↔ x = 0 :=
algebra.norm_eq_zero_iff_of_basis (basis.of_vector_space K L)
end eq_zero_iff
end algebra
|
858b7e1659428eb13fffd5acae9c38e81676992c | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/measure_theory/arithmetic.lean | e6645ab74e848b457a83ca211a3be6057e803636 | [
"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 | 25,523 | lean | /-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import measure_theory.measure_space
/-!
# Typeclasses for measurability of operations
In this file we define classes `has_measurable_mul` etc and prove dot-style lemmas
(`measurable.mul`, `ae_measurable.mul` etc). For binary operations we define two typeclasses:
- `has_measurable_mul` says that both left and right multiplication are measurable;
- `has_measurable_mul₂` says that `λ p : α × α, p.1 * p.2` is measurable,
and similarly for other binary operations. The reason for introducing these classes is that in case
of topological space `α` equipped with the Borel `σ`-algebra, instances for `has_measurable_mul₂`
etc require `α` to have a second countable topology.
We define separate classes for `has_measurable_div`/`has_measurable_sub`
because on some types (e.g., `ℕ`, `ℝ≥0∞`) division and/or subtraction are not defined as `a * b⁻¹` /
`a + (-b)`.
For instances relating, e.g., `has_continuous_mul` to `has_measurable_mul` see file
`measure_theory.borel_space`.
## Implementation notes
For the heuristics of `@[to_additive]` it is important that the type with a multiplication
(or another multiplicative operations) is the first (implicit) argument of all declarations.
## Tags
measurable function, arithmetic operator
## Todo
* Uniformize the treatment of `pow` and `smul`.
* Use `@[to_additive]` to send `has_measurable_pow` to `has_measurable_smul₂`.
* This might require changing the definition (swapping the arguments in the function that is
in the conclusion of `measurable_smul`.)
-/
universes u v
open_locale big_operators
open measure_theory
/-!
### Binary operations: `(+)`, `(*)`, `(-)`, `(/)`
-/
/-- We say that a type `has_measurable_add` if `((+) c)` and `(+ c)` are measurable functions.
For a typeclass assuming measurability of `uncurry (+)` see `has_measurable_add₂`. -/
class has_measurable_add (M : Type*) [measurable_space M] [has_add M] : Prop :=
(measurable_const_add : ∀ c : M, measurable ((+) c))
(measurable_add_const : ∀ c : M, measurable (+ c))
/-- We say that a type `has_measurable_add` if `uncurry (+)` is a measurable functions.
For a typeclass assuming measurability of `((+) c)` and `(+ c)` see `has_measurable_add`. -/
class has_measurable_add₂ (M : Type*) [measurable_space M] [has_add M] : Prop :=
(measurable_add : measurable (λ p : M × M, p.1 + p.2))
export has_measurable_add₂ (measurable_add)
has_measurable_add (measurable_const_add measurable_add_const)
/-- We say that a type `has_measurable_mul` if `((*) c)` and `(* c)` are measurable functions.
For a typeclass assuming measurability of `uncurry (*)` see `has_measurable_mul₂`. -/
@[to_additive]
class has_measurable_mul (M : Type*) [measurable_space M] [has_mul M] : Prop :=
(measurable_const_mul : ∀ c : M, measurable ((*) c))
(measurable_mul_const : ∀ c : M, measurable (* c))
/-- We say that a type `has_measurable_mul` if `uncurry (*)` is a measurable functions.
For a typeclass assuming measurability of `((*) c)` and `(* c)` see `has_measurable_mul`. -/
@[to_additive has_measurable_add₂]
class has_measurable_mul₂ (M : Type*) [measurable_space M] [has_mul M] : Prop :=
(measurable_mul : measurable (λ p : M × M, p.1 * p.2))
export has_measurable_mul₂ (measurable_mul)
has_measurable_mul (measurable_const_mul measurable_mul_const)
section mul
variables {M α : Type*} [measurable_space M] [has_mul M] [measurable_space α]
@[to_additive, measurability]
lemma measurable.const_mul [has_measurable_mul M] {f : α → M} (hf : measurable f) (c : M) :
measurable (λ x, c * f x) :=
(measurable_const_mul c).comp hf
@[to_additive, measurability]
lemma ae_measurable.const_mul [has_measurable_mul M] {f : α → M} {μ : measure α}
(hf : ae_measurable f μ) (c : M) :
ae_measurable (λ x, c * f x) μ :=
(has_measurable_mul.measurable_const_mul c).comp_ae_measurable hf
@[to_additive, measurability]
lemma measurable.mul_const [has_measurable_mul M] {f : α → M} (hf : measurable f) (c : M) :
measurable (λ x, f x * c) :=
(measurable_mul_const c).comp hf
@[to_additive, measurability]
lemma ae_measurable.mul_const [has_measurable_mul M] {f : α → M} {μ : measure α}
(hf : ae_measurable f μ) (c : M) :
ae_measurable (λ x, f x * c) μ :=
(measurable_mul_const c).comp_ae_measurable hf
@[to_additive, measurability]
lemma measurable.mul' [has_measurable_mul₂ M] {f g : α → M} (hf : measurable f)
(hg : measurable g) :
measurable (f * g) :=
measurable_mul.comp (hf.prod_mk hg)
@[to_additive, measurability]
lemma measurable.mul [has_measurable_mul₂ M] {f g : α → M} (hf : measurable f) (hg : measurable g) :
measurable (λ a, f a * g a) :=
measurable_mul.comp (hf.prod_mk hg)
@[to_additive, measurability]
lemma ae_measurable.mul' [has_measurable_mul₂ M] {μ : measure α} {f g : α → M}
(hf : ae_measurable f μ) (hg : ae_measurable g μ) :
ae_measurable (f * g) μ :=
measurable_mul.comp_ae_measurable (hf.prod_mk hg)
@[to_additive, measurability]
lemma ae_measurable.mul [has_measurable_mul₂ M] {μ : measure α} {f g : α → M}
(hf : ae_measurable f μ) (hg : ae_measurable g μ) :
ae_measurable (λ a, f a * g a) μ :=
measurable_mul.comp_ae_measurable (hf.prod_mk hg)
@[priority 100, to_additive]
instance has_measurable_mul₂.to_has_measurable_mul [has_measurable_mul₂ M] :
has_measurable_mul M :=
⟨λ c, measurable_const.mul measurable_id, λ c, measurable_id.mul measurable_const⟩
attribute [measurability] measurable.add' measurable.add ae_measurable.add ae_measurable.add'
measurable.const_add ae_measurable.const_add measurable.add_const ae_measurable.add_const
end mul
/-- This class assumes that the map `β × γ → β` given by `(x, y) ↦ x ^ y` is measurable. -/
class has_measurable_pow (β γ : Type*) [measurable_space β] [measurable_space γ] [has_pow β γ] :=
(measurable_pow : measurable (λ p : β × γ, p.1 ^ p.2))
export has_measurable_pow (measurable_pow)
instance has_measurable_mul.has_measurable_pow (M : Type*) [monoid M] [measurable_space M]
[has_measurable_mul₂ M] : has_measurable_pow M ℕ :=
⟨begin
haveI : measurable_singleton_class ℕ := ⟨λ _, trivial⟩,
refine measurable_from_prod_encodable (λ n, _),
induction n with n ih,
{ simp [pow_zero, measurable_one] },
{ simp only [pow_succ], exact measurable_id.mul ih }
end⟩
section pow
variables {β γ α : Type*} [measurable_space β] [measurable_space γ] [has_pow β γ]
[has_measurable_pow β γ] [measurable_space α]
@[measurability]
lemma measurable.pow {f : α → β} {g : α → γ} (hf : measurable f) (hg : measurable g) :
measurable (λ x, f x ^ g x) :=
measurable_pow.comp (hf.prod_mk hg)
@[measurability]
lemma ae_measurable.pow {μ : measure α} {f : α → β} {g : α → γ} (hf : ae_measurable f μ)
(hg : ae_measurable g μ) :
ae_measurable (λ x, f x ^ g x) μ :=
measurable_pow.comp_ae_measurable (hf.prod_mk hg)
@[measurability]
lemma measurable.pow_const {f : α → β} (hf : measurable f) (c : γ) :
measurable (λ x, f x ^ c) :=
hf.pow measurable_const
@[measurability]
lemma ae_measurable.pow_const {μ : measure α} {f : α → β} (hf : ae_measurable f μ) (c : γ) :
ae_measurable (λ x, f x ^ c) μ :=
hf.pow ae_measurable_const
@[measurability]
lemma measurable.const_pow {f : α → γ} (hf : measurable f) (c : β) :
measurable (λ x, c ^ f x) :=
measurable_const.pow hf
@[measurability]
lemma ae_measurable.const_pow {μ : measure α} {f : α → γ} (hf : ae_measurable f μ) (c : β) :
ae_measurable (λ x, c ^ f x) μ :=
ae_measurable_const.pow hf
end pow
/-- We say that a type `has_measurable_sub` if `(λ x, c - x)` and `(λ x, x - c)` are measurable
functions. For a typeclass assuming measurability of `uncurry (-)` see `has_measurable_sub₂`. -/
class has_measurable_sub (G : Type*) [measurable_space G] [has_sub G] : Prop :=
(measurable_const_sub : ∀ c : G, measurable (λ x, c - x))
(measurable_sub_const : ∀ c : G, measurable (λ x, x - c))
/-- We say that a type `has_measurable_sub` if `uncurry (-)` is a measurable functions.
For a typeclass assuming measurability of `((-) c)` and `(- c)` see `has_measurable_sub`. -/
class has_measurable_sub₂ (G : Type*) [measurable_space G] [has_sub G] : Prop :=
(measurable_sub : measurable (λ p : G × G, p.1 - p.2))
export has_measurable_sub₂ (measurable_sub)
/-- We say that a type `has_measurable_div` if `((/) c)` and `(/ c)` are measurable functions.
For a typeclass assuming measurability of `uncurry (/)` see `has_measurable_div₂`. -/
@[to_additive] class has_measurable_div (G₀: Type*) [measurable_space G₀] [has_div G₀] : Prop :=
(measurable_const_div : ∀ c : G₀, measurable ((/) c))
(measurable_div_const : ∀ c : G₀, measurable (/ c))
/-- We say that a type `has_measurable_div` if `uncurry (/)` is a measurable functions.
For a typeclass assuming measurability of `((/) c)` and `(/ c)` see `has_measurable_div`. -/
@[to_additive has_measurable_sub₂]
class has_measurable_div₂ (G₀: Type*) [measurable_space G₀] [has_div G₀] : Prop :=
(measurable_div : measurable (λ p : G₀× G₀, p.1 / p.2))
export has_measurable_div₂ (measurable_div)
section div
variables {G α : Type*} [measurable_space G] [has_div G] [measurable_space α]
@[to_additive, measurability]
lemma measurable.const_div [has_measurable_div G] {f : α → G} (hf : measurable f) (c : G) :
measurable (λ x, c / f x) :=
(has_measurable_div.measurable_const_div c).comp hf
@[to_additive, measurability]
lemma ae_measurable.const_div [has_measurable_div G] {f : α → G} {μ : measure α}
(hf : ae_measurable f μ) (c : G) :
ae_measurable (λ x, c / f x) μ :=
(has_measurable_div.measurable_const_div c).comp_ae_measurable hf
@[to_additive, measurability]
lemma measurable.div_const [has_measurable_div G] {f : α → G} (hf : measurable f) (c : G) :
measurable (λ x, f x / c) :=
(has_measurable_div.measurable_div_const c).comp hf
@[to_additive, measurability]
lemma ae_measurable.div_const [has_measurable_div G] {f : α → G} {μ : measure α}
(hf : ae_measurable f μ) (c : G) :
ae_measurable (λ x, f x / c) μ :=
(has_measurable_div.measurable_div_const c).comp_ae_measurable hf
@[to_additive, measurability]
lemma measurable.div' [has_measurable_div₂ G] {f g : α → G} (hf : measurable f)
(hg : measurable g) :
measurable (f / g) :=
measurable_div.comp (hf.prod_mk hg)
@[to_additive, measurability]
lemma measurable.div [has_measurable_div₂ G] {f g : α → G} (hf : measurable f) (hg : measurable g) :
measurable (λ a, f a / g a) :=
measurable_div.comp (hf.prod_mk hg)
@[to_additive, measurability]
lemma ae_measurable.div' [has_measurable_div₂ G] {f g : α → G} {μ : measure α}
(hf : ae_measurable f μ) (hg : ae_measurable g μ) :
ae_measurable (f / g) μ :=
measurable_div.comp_ae_measurable (hf.prod_mk hg)
@[to_additive, measurability]
lemma ae_measurable.div [has_measurable_div₂ G] {f g : α → G} {μ : measure α}
(hf : ae_measurable f μ) (hg : ae_measurable g μ) :
ae_measurable (λ a, f a / g a) μ :=
measurable_div.comp_ae_measurable (hf.prod_mk hg)
@[priority 100, to_additive]
instance has_measurable_div₂.to_has_measurable_div [has_measurable_div₂ G] :
has_measurable_div G :=
⟨λ c, measurable_const.div measurable_id, λ c, measurable_id.div measurable_const⟩
attribute [measurability] measurable.sub measurable.sub' ae_measurable.sub ae_measurable.sub'
measurable.const_sub ae_measurable.const_sub measurable.sub_const ae_measurable.sub_const
lemma measurable_set_eq_fun {E} [measurable_space E] [add_group E] [measurable_singleton_class E]
[has_measurable_sub₂ E] {f g : α → E} (hf : measurable f) (hg : measurable g) :
measurable_set {x | f x = g x} :=
begin
suffices h_set_eq : {x : α | f x = g x} = {x | (f-g) x = (0 : E)},
{ rw h_set_eq,
exact (hf.sub hg) measurable_set_eq, },
ext,
simp_rw [set.mem_set_of_eq, pi.sub_apply, sub_eq_zero],
end
lemma ae_eq_trim_of_measurable {α E} {m m0 : measurable_space α} {μ : measure α}
[measurable_space E] [add_group E] [measurable_singleton_class E] [has_measurable_sub₂ E]
(hm : m ≤ m0) {f g : α → E} (hf : @measurable _ _ m _ f) (hg : @measurable _ _ m _ g)
(hfg : f =ᵐ[μ] g) :
f =ᶠ[@measure.ae α m (μ.trim hm)] g :=
begin
rwa [filter.eventually_eq, ae_iff, trim_measurable_set_eq hm _],
exact (@measurable_set.compl α _ m (@measurable_set_eq_fun α m E _ _ _ _ _ _ hf hg)),
end
end div
/-- We say that a type `has_measurable_neg` if `x ↦ -x` is a measurable function. -/
class has_measurable_neg (G : Type*) [has_neg G] [measurable_space G] : Prop :=
(measurable_neg : measurable (has_neg.neg : G → G))
/-- We say that a type `has_measurable_inv` if `x ↦ x⁻¹` is a measurable function. -/
@[to_additive]
class has_measurable_inv (G : Type*) [has_inv G] [measurable_space G] : Prop :=
(measurable_inv : measurable (has_inv.inv : G → G))
export has_measurable_inv (measurable_inv) has_measurable_neg (measurable_neg)
@[priority 100, to_additive]
instance has_measurable_div_of_mul_inv (G : Type*) [measurable_space G]
[div_inv_monoid G] [has_measurable_mul G] [has_measurable_inv G] :
has_measurable_div G :=
{ measurable_const_div := λ c,
by { convert (measurable_inv.const_mul c), ext1, apply div_eq_mul_inv },
measurable_div_const := λ c,
by { convert (measurable_id.mul_const c⁻¹), ext1, apply div_eq_mul_inv } }
section inv
variables {G α : Type*} [has_inv G] [measurable_space G] [has_measurable_inv G] [measurable_space α]
@[to_additive, measurability]
lemma measurable.inv {f : α → G} (hf : measurable f) :
measurable (λ x, (f x)⁻¹) :=
measurable_inv.comp hf
@[to_additive, measurability]
lemma ae_measurable.inv {f : α → G} {μ : measure α} (hf : ae_measurable f μ) :
ae_measurable (λ x, (f x)⁻¹) μ :=
measurable_inv.comp_ae_measurable hf
attribute [measurability] measurable.neg ae_measurable.neg
@[simp, to_additive] lemma measurable_inv_iff {G : Type*} [group G] [measurable_space G]
[has_measurable_inv G] {f : α → G} : measurable (λ x, (f x)⁻¹) ↔ measurable f :=
⟨λ h, by simpa only [inv_inv] using h.inv, λ h, h.inv⟩
@[simp, to_additive] lemma ae_measurable_inv_iff {G : Type*} [group G] [measurable_space G]
[has_measurable_inv G] {f : α → G} {μ : measure α} :
ae_measurable (λ x, (f x)⁻¹) μ ↔ ae_measurable f μ :=
⟨λ h, by simpa only [inv_inv] using h.inv, λ h, h.inv⟩
@[simp] lemma measurable_inv_iff' {G₀ : Type*} [group_with_zero G₀]
[measurable_space G₀] [has_measurable_inv G₀] {f : α → G₀} :
measurable (λ x, (f x)⁻¹) ↔ measurable f :=
⟨λ h, by simpa only [inv_inv'] using h.inv, λ h, h.inv⟩
@[simp] lemma ae_measurable_inv_iff' {G₀ : Type*} [group_with_zero G₀]
[measurable_space G₀] [has_measurable_inv G₀] {f : α → G₀} {μ : measure α} :
ae_measurable (λ x, (f x)⁻¹) μ ↔ ae_measurable f μ :=
⟨λ h, by simpa only [inv_inv'] using h.inv, λ h, h.inv⟩
end inv
/- There is something extremely strange here: copy-pasting the proof of this lemma in the proof
of `has_measurable_gpow` fails, while `pp.all` does not show any difference in the goal.
Keep it as a separate lemmas as a workaround. -/
private lemma has_measurable_gpow_aux (G : Type u) [div_inv_monoid G] [measurable_space G]
[has_measurable_mul₂ G] [has_measurable_inv G] (k : ℕ) :
measurable (λ (x : G), x ^(-[1+ k])) :=
begin
simp_rw [gpow_neg_succ_of_nat],
exact (measurable_id.pow_const (k + 1)).inv
end
instance has_measurable_gpow (G : Type u) [div_inv_monoid G] [measurable_space G]
[has_measurable_mul₂ G] [has_measurable_inv G] :
has_measurable_pow G ℤ :=
begin
letI : measurable_singleton_class ℤ := ⟨λ _, trivial⟩,
constructor,
refine measurable_from_prod_encodable (λ n, _),
dsimp,
apply int.cases_on n,
{ simpa using measurable_id.pow_const },
{ exact has_measurable_gpow_aux G }
end
@[priority 100, to_additive]
instance has_measurable_div₂_of_mul_inv (G : Type*) [measurable_space G]
[div_inv_monoid G] [has_measurable_mul₂ G] [has_measurable_inv G] :
has_measurable_div₂ G :=
⟨by { simp only [div_eq_mul_inv], exact measurable_fst.mul measurable_snd.inv }⟩
/-- We say that the action of `M` on `α` `has_measurable_smul` if for each `c` the map `x ↦ c • x`
is a measurable function and for each `x` the map `c ↦ c • x` is a measurable function. -/
class has_measurable_smul (M α : Type*) [has_scalar M α] [measurable_space M] [measurable_space α] :
Prop :=
(measurable_const_smul : ∀ c : M, measurable ((•) c : α → α))
(measurable_smul_const : ∀ x : α, measurable (λ c : M, c • x))
/-- We say that the action of `M` on `α` `has_measurable_smul` if the map
`(c, x) ↦ c • x` is a measurable function. -/
class has_measurable_smul₂ (M α : Type*) [has_scalar M α] [measurable_space M]
[measurable_space α] : Prop :=
(measurable_smul : measurable (function.uncurry (•) : M × α → α))
export has_measurable_smul (measurable_const_smul measurable_smul_const)
has_measurable_smul₂ (measurable_smul)
instance has_measurable_smul_of_mul (M : Type*) [monoid M] [measurable_space M]
[has_measurable_mul M] :
has_measurable_smul M M :=
⟨measurable_id.const_mul, measurable_id.mul_const⟩
instance has_measurable_smul₂_of_mul (M : Type*) [monoid M] [measurable_space M]
[has_measurable_mul₂ M] :
has_measurable_smul₂ M M :=
⟨measurable_mul⟩
section smul
variables {M β α : Type*} [measurable_space M] [measurable_space β] [has_scalar M β]
[measurable_space α]
@[measurability]
lemma measurable.smul [has_measurable_smul₂ M β]
{f : α → M} {g : α → β} (hf : measurable f) (hg : measurable g) :
measurable (λ x, f x • g x) :=
measurable_smul.comp (hf.prod_mk hg)
@[measurability]
lemma ae_measurable.smul [has_measurable_smul₂ M β]
{f : α → M} {g : α → β} {μ : measure α} (hf : ae_measurable f μ) (hg : ae_measurable g μ) :
ae_measurable (λ x, f x • g x) μ :=
has_measurable_smul₂.measurable_smul.comp_ae_measurable (hf.prod_mk hg)
@[priority 100]
instance has_measurable_smul₂.to_has_measurable_smul [has_measurable_smul₂ M β] :
has_measurable_smul M β :=
⟨λ c, measurable_const.smul measurable_id, λ y, measurable_id.smul measurable_const⟩
variables [has_measurable_smul M β] {μ : measure α}
@[measurability]
lemma measurable.smul_const {f : α → M} (hf : measurable f) (y : β) : measurable (λ x, f x • y) :=
(has_measurable_smul.measurable_smul_const y).comp hf
@[measurability]
lemma ae_measurable.smul_const {f : α → M} (hf : ae_measurable f μ) (y : β) :
ae_measurable (λ x, f x • y) μ :=
(has_measurable_smul.measurable_smul_const y).comp_ae_measurable hf
@[measurability]
lemma measurable.const_smul' {f : α → β} (hf : measurable f) (c : M) :
measurable (λ x, c • f x) :=
(has_measurable_smul.measurable_const_smul c).comp hf
@[measurability]
lemma measurable.const_smul {f : α → β} (hf : measurable f) (c : M) :
measurable (c • f) :=
hf.const_smul' c
@[measurability]
lemma ae_measurable.const_smul' {f : α → β} (hf : ae_measurable f μ) (c : M) :
ae_measurable (λ x, c • f x) μ :=
(has_measurable_smul.measurable_const_smul c).comp_ae_measurable hf
@[measurability]
lemma ae_measurable.const_smul {f : α → β} (hf : ae_measurable f μ) (c : M) :
ae_measurable (c • f) μ :=
hf.const_smul' c
end smul
section mul_action
variables {M β α : Type*} [measurable_space M] [measurable_space β] [monoid M] [mul_action M β]
[has_measurable_smul M β] [measurable_space α] {f : α → β} {μ : measure α}
variables {G : Type*} [group G] [measurable_space G] [mul_action G β]
[has_measurable_smul G β]
lemma measurable_const_smul_iff (c : G) :
measurable (λ x, c • f x) ↔ measurable f :=
⟨λ h, by simpa only [inv_smul_smul] using h.const_smul' c⁻¹, λ h, h.const_smul c⟩
lemma ae_measurable_const_smul_iff (c : G) :
ae_measurable (λ x, c • f x) μ ↔ ae_measurable f μ :=
⟨λ h, by simpa only [inv_smul_smul] using h.const_smul' c⁻¹, λ h, h.const_smul c⟩
instance : measurable_space (units M) := measurable_space.comap (coe : units M → M) ‹_›
instance units.has_measurable_smul : has_measurable_smul (units M) β :=
{ measurable_const_smul := λ c, (measurable_const_smul (c : M) : _),
measurable_smul_const := λ x,
(measurable_smul_const x : measurable (λ c : M, c • x)).comp measurable_space.le_map_comap, }
lemma is_unit.measurable_const_smul_iff {c : M} (hc : is_unit c) :
measurable (λ x, c • f x) ↔ measurable f :=
let ⟨u, hu⟩ := hc in hu ▸ measurable_const_smul_iff u
lemma is_unit.ae_measurable_const_smul_iff {c : M} (hc : is_unit c) :
ae_measurable (λ x, c • f x) μ ↔ ae_measurable f μ :=
let ⟨u, hu⟩ := hc in hu ▸ ae_measurable_const_smul_iff u
variables {G₀ : Type*} [group_with_zero G₀] [measurable_space G₀] [mul_action G₀ β]
[has_measurable_smul G₀ β]
lemma measurable_const_smul_iff' {c : G₀} (hc : c ≠ 0) :
measurable (λ x, c • f x) ↔ measurable f :=
(is_unit.mk0 c hc).measurable_const_smul_iff
lemma ae_measurable_const_smul_iff' {c : G₀} (hc : c ≠ 0) :
ae_measurable (λ x, c • f x) μ ↔ ae_measurable f μ :=
(is_unit.mk0 c hc).ae_measurable_const_smul_iff
end mul_action
/-!
### Big operators: `∏` and `∑`
-/
section monoid
variables {M α : Type*} [monoid M] [measurable_space M] [has_measurable_mul₂ M] [measurable_space α]
@[to_additive, measurability]
lemma list.measurable_prod' (l : list (α → M)) (hl : ∀ f ∈ l, measurable f) :
measurable l.prod :=
begin
induction l with f l ihl, { exact measurable_one },
rw [list.forall_mem_cons] at hl,
rw [list.prod_cons],
exact hl.1.mul (ihl hl.2)
end
@[to_additive, measurability]
lemma list.ae_measurable_prod' {μ : measure α} (l : list (α → M))
(hl : ∀ f ∈ l, ae_measurable f μ) : ae_measurable l.prod μ :=
begin
induction l with f l ihl, { exact ae_measurable_one },
rw [list.forall_mem_cons] at hl,
rw [list.prod_cons],
exact hl.1.mul (ihl hl.2)
end
@[to_additive, measurability]
lemma list.measurable_prod (l : list (α → M)) (hl : ∀ f ∈ l, measurable f) :
measurable (λ x, (l.map (λ f : α → M, f x)).prod) :=
by simpa only [← pi.list_prod_apply] using l.measurable_prod' hl
@[to_additive, measurability]
lemma list.ae_measurable_prod {μ : measure α} (l : list (α → M)) (hl : ∀ f ∈ l, ae_measurable f μ) :
ae_measurable (λ x, (l.map (λ f : α → M, f x)).prod) μ :=
by simpa only [← pi.list_prod_apply] using l.ae_measurable_prod' hl
end monoid
section comm_monoid
variables {M ι α : Type*} [comm_monoid M] [measurable_space M] [has_measurable_mul₂ M]
[measurable_space α]
@[to_additive, measurability]
lemma multiset.measurable_prod' (l : multiset (α → M)) (hl : ∀ f ∈ l, measurable f) :
measurable l.prod :=
by { rcases l with ⟨l⟩, simpa using l.measurable_prod' (by simpa using hl) }
@[to_additive, measurability]
lemma multiset.ae_measurable_prod' {μ : measure α} (l : multiset (α → M))
(hl : ∀ f ∈ l, ae_measurable f μ) : ae_measurable l.prod μ :=
by { rcases l with ⟨l⟩, simpa using l.ae_measurable_prod' (by simpa using hl) }
@[to_additive, measurability]
lemma multiset.measurable_prod (s : multiset (α → M)) (hs : ∀ f ∈ s, measurable f) :
measurable (λ x, (s.map (λ f : α → M, f x)).prod) :=
by simpa only [← pi.multiset_prod_apply] using s.measurable_prod' hs
@[to_additive, measurability]
lemma multiset.ae_measurable_prod {μ : measure α} (s : multiset (α → M))
(hs : ∀ f ∈ s, ae_measurable f μ) : ae_measurable (λ x, (s.map (λ f : α → M, f x)).prod) μ :=
by simpa only [← pi.multiset_prod_apply] using s.ae_measurable_prod' hs
@[to_additive, measurability]
lemma finset.measurable_prod' {f : ι → α → M} (s : finset ι) (hf : ∀i ∈ s, measurable (f i)) :
measurable (∏ i in s, f i) :=
finset.prod_induction _ _ (λ _ _, measurable.mul) (@measurable_one M _ _ _ _) hf
@[to_additive, measurability]
lemma finset.measurable_prod {f : ι → α → M} (s : finset ι) (hf : ∀i ∈ s, measurable (f i)) :
measurable (λ a, ∏ i in s, f i a) :=
by simpa only [← finset.prod_apply] using s.measurable_prod' hf
@[to_additive, measurability]
lemma finset.ae_measurable_prod' {μ : measure α} {f : ι → α → M} (s : finset ι)
(hf : ∀i ∈ s, ae_measurable (f i) μ) :
ae_measurable (∏ i in s, f i) μ :=
multiset.ae_measurable_prod' _ $
λ g hg, let ⟨i, hi, hg⟩ := multiset.mem_map.1 hg in (hg ▸ hf _ hi)
@[to_additive, measurability]
lemma finset.ae_measurable_prod {f : ι → α → M} {μ : measure α} (s : finset ι)
(hf : ∀i ∈ s, ae_measurable (f i) μ) :
ae_measurable (λ a, ∏ i in s, f i a) μ :=
by simpa only [← finset.prod_apply] using s.ae_measurable_prod' hf
end comm_monoid
attribute [measurability] list.measurable_sum' list.ae_measurable_sum' list.measurable_sum
list.ae_measurable_sum multiset.measurable_sum' multiset.ae_measurable_sum'
multiset.measurable_sum multiset.ae_measurable_sum finset.measurable_sum'
finset.ae_measurable_sum' finset.measurable_sum finset.ae_measurable_sum
|
47f40e50bc7a39a31ec82724ad2014d83c5aba11 | abd677583c7e4d55daf9487b82da11b7c5498d8d | /src/list.lean | 7bec6b0f1a42d64dc56f895a752410a24e4a0393 | [
"Apache-2.0"
] | permissive | jesse-michael-han/embed | e9c346918ad58e03933bdaa057a571c0cc4a7641 | c2fc188328e871e18e0dcb8258c6d0462c70a8c9 | refs/heads/master | 1,584,677,705,005 | 1,528,451,877,000 | 1,528,451,877,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 745 | lean | import data.list.perm
universe variables uu vv
variables {α : Type uu} {β : Type vv}
namespace list
def rotate : nat → list α → list α
| n [] := []
| 0 (h::t) := (h::t)
| (n+1) (h::t) := (rotate n t) ++ [h]
lemma perm_rotate : ∀ (n) (as : list α), rotate n as ~ as
| 0 [] := list.perm.refl _
| (n+1) [] := list.perm.refl _
| 0 (a::as) := list.perm.refl _
| (n+1) (a::as) :=
begin
simp [rotate],
apply perm.trans,
apply perm_cons_app,
rewrite perm_cons,
apply perm_rotate
end
theorem forall_mem_singleton {p : α → Prop} {a : α} :
(∀ x ∈ [a] , p x) ↔ p a :=
begin
rewrite forall_mem_cons, apply iff.intro; intro h,
apply h.elim_left, apply and.intro h (forall_mem_nil _)
end
end list |
29ccd5f16f7259b6d531db5c79cf236fc579e454 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/fintype/parity.lean | 9efe5b21bc594f1d4c89c79a76b50da266e8c6e9 | [
"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 | 870 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.fintype.card
import algebra.parity
/-!
# The cardinality of `fin (bit0 n)` is even.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
-/
variables {α : Type*}
namespace fintype
instance is_square.decidable_pred [has_mul α] [fintype α] [decidable_eq α] :
decidable_pred (is_square : α → Prop) :=
λ a, fintype.decidable_exists_fintype
end fintype
/-- The cardinality of `fin (bit0 n)` is even, `fact` version.
This `fact` is needed as an instance by `matrix.special_linear_group.has_neg`. -/
lemma fintype.card_fin_even {n : ℕ} : fact (even (fintype.card (fin (bit0 n)))) :=
⟨by { rw fintype.card_fin, exact even_bit0 _ }⟩
|
dd8027f1a882e27eff12305df8fb7bf87c191d02 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/rat/star.lean | 3d999719221c88cfd340a779c81e2816d672acb3 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 2,273 | lean | /-
Copyright (c) 2023 Jireh Loreaux. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jireh Loreaux
-/
import algebra.star.order
import data.rat.lemmas
import group_theory.submonoid.membership
/-! # Star order structure on ℚ
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Here we put the trivial `star` operation on `ℚ` for convenience and show that it is a
`star_ordered_ring`. In particular, this means that every element of `ℚ` is a sum of squares.
-/
namespace rat
instance : star_ring ℚ :=
{ star := id,
star_involutive := λ _, rfl,
star_mul := λ _ _, mul_comm _ _,
star_add := λ _ _, rfl }
instance : has_trivial_star ℚ :=
{ star_trivial := λ _, rfl }
instance : star_ordered_ring ℚ :=
star_ordered_ring.of_nonneg_iff (λ _ _, add_le_add_left) $ λ x,
begin
refine ⟨λ hx, _, λ hx, add_submonoid.closure_induction hx
(by { rintro - ⟨s, rfl⟩, exact mul_self_nonneg s }) le_rfl (λ _ _, add_nonneg)⟩,
/- If `x = p / q`, then, since `0 ≤ x`, we have `p q : ℕ`, and `p / q` is the sum of `p * q`
copies of `(1 / q) ^ 2`, and so `x` lies in the `add_submonoid` generated by square elements.
Note: it's possible to rephrase this argument as `x = (p * q) • (1 / q) ^ 2`, but this would
be somewhat challenging without increasing import requirements. -/
suffices : (finset.range (x.num.nat_abs * x.denom)).sum
(function.const ℕ (rat.mk_pnat 1 ⟨x.denom, x.pos⟩ * rat.mk_pnat 1 ⟨x.denom, x.pos⟩)) = x,
{ exact this ▸ sum_mem (λ n hn, add_submonoid.subset_closure ⟨_, rfl⟩) },
simp only [function.const_apply, finset.sum_const, finset.card_range, nsmul_eq_mul, mk_pnat_eq],
rw [←int.cast_coe_nat, int.coe_nat_mul, int.coe_nat_abs,
abs_of_nonneg (num_nonneg_iff_zero_le.mpr hx), int.cast_mul, int.cast_coe_nat],
simp only [int.cast_mul, int.cast_coe_nat, coe_int_eq_mk, coe_nat_eq_mk],
rw [mul_assoc, ←mul_assoc (mk (x.denom : ℤ) 1), mk_mul_mk_cancel one_ne_zero,
←one_mul (x.denom : ℤ), div_mk_div_cancel_left (by simpa using x.pos.ne' : (x.denom : ℤ) ≠ 0),
one_mul, mk_one_one, one_mul, mk_mul_mk_cancel one_ne_zero, rat.num_denom],
end
end rat
|
1ddfcc6147718e934c64a2b919ee5dd0a599a8ef | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/bad_structures2.lean | 5d53736c3112a82637c64882666a8a686397858f | [
"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 | 452 | lean | structure foo :=
(x : bool)
structure boo :=
(x : nat)
structure bla extends foo, boo
structure boo2 :=
{x : bool}
structure bla extends foo, boo2
structure bla extends foo :=
(x : num)
structure bla extends foo :=
( : num)
structure bla extends foo :=
mk :: y z : num
structure bla2 extends foo renaming y → z
structure bla2 extends nat
structure bla2 extends Type
structure bla2 : Prop :=
(x : Prop)
structure bla3 : Prop :=
(x : nat)
|
645a160602d35f9441bb89bcf11abcdb409d7225 | 8cb37a089cdb4af3af9d8bf1002b417e407a8e9e | /library/init/core.lean | 1f1188dd097576e6f3c8b80045c28c5f710893a3 | [
"Apache-2.0"
] | permissive | kbuzzard/lean | ae3c3db4bb462d750dbf7419b28bafb3ec983ef7 | ed1788fd674bb8991acffc8fca585ec746711928 | refs/heads/master | 1,620,983,366,617 | 1,618,937,600,000 | 1,618,937,600,000 | 359,886,396 | 1 | 0 | Apache-2.0 | 1,618,936,987,000 | 1,618,936,987,000 | null | UTF-8 | Lean | false | false | 20,623 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
notation, basic datatypes and type classes
-/
prelude
notation `Prop` := Sort 0
notation f ` $ `:1 a:0 := f a
/- Reserving notation. We do this so that the precedence of all of the operators
can be seen in one place and to prevent core notation being accidentally overloaded later. -/
/- Notation for logical operations and relations -/
reserve prefix `¬`:40
reserve prefix `~`:40 -- not used
reserve infixr ` ∧ `:35
reserve infixr ` /\ `:35
reserve infixr ` \/ `:30
reserve infixr ` ∨ `:30
reserve infix ` <-> `:20
reserve infix ` ↔ `:20
reserve infix ` = `:50 -- eq
reserve infix ` == `:50 -- heq
reserve infix ` ≠ `:50
reserve infix ` ≈ `:50 -- has_equiv.equiv
reserve infix ` ~ `:50 -- used as local notation for relations
reserve infix ` ≡ `:50 -- not used
reserve infixl ` ⬝ `:75 -- not used
reserve infixr ` ▸ `:75 -- eq.subst
reserve infixr ` ▹ `:75 -- not used
/- types and type constructors -/
reserve infixr ` ⊕ `:30 -- sum (defined in init/data/sum/basic.lean)
reserve infixr ` × `:35
/- arithmetic operations -/
reserve infixl ` + `:65
reserve infixl ` - `:65
reserve infixl ` * `:70
reserve infixl ` / `:70
reserve infixl ` % `:70
reserve prefix `-`:75
reserve infixr ` ^ `:80
reserve infixr ` ∘ `:90 -- function composition
reserve infix ` <= `:50
reserve infix ` ≤ `:50
reserve infix ` < `:50
reserve infix ` >= `:50
reserve infix ` ≥ `:50
reserve infix ` > `:50
/- boolean operations -/
reserve infixl ` && `:70
reserve infixl ` || `:65
/- set operations -/
reserve infix ` ∈ `:50
reserve infix ` ∉ `:50
reserve infixl ` ∩ `:70
reserve infixl ` ∪ `:65
reserve infix ` ⊆ `:50
reserve infix ` ⊇ `:50
reserve infix ` ⊂ `:50
reserve infix ` ⊃ `:50
reserve infix ` \ `:70 -- symmetric difference
/- other symbols -/
reserve infix ` ∣ `:50 -- has_dvd.dvd. Note this is different to `|`.
reserve infixl ` ++ `:65 -- has_append.append
reserve infixr ` :: `:67 -- list.cons
reserve infixl `; `:1 -- has_andthen.andthen
universes u v w
/--
The kernel definitional equality test (t =?= s) has special support for id_delta applications.
It implements the following rules
1) (id_delta t) =?= t
2) t =?= (id_delta t)
3) (id_delta t) =?= s IF (unfold_of t) =?= s
4) t =?= id_delta s IF t =?= (unfold_of s)
This is mechanism for controlling the delta reduction (aka unfolding) used in the kernel.
We use id_delta applications to address performance problems when type checking
lemmas generated by the equation compiler.
-/
@[inline] def id_delta {α : Sort u} (a : α) : α :=
a
/-- Gadget for optional parameter support. -/
@[reducible] def opt_param (α : Sort u) (default : α) : Sort u :=
α
/-- Gadget for marking output parameters in type classes. -/
@[reducible] def out_param (α : Sort u) : Sort u := α
/-
id_rhs is an auxiliary declaration used in the equation compiler to address performance
issues when proving equational lemmas. The equation compiler uses it as a marker.
-/
abbreviation id_rhs (α : Sort u) (a : α) : α := a
inductive punit : Sort u
| star : punit
/-- An abbreviation for `punit.{0}`, its most common instantiation.
This type should be preferred over `punit` where possible to avoid
unnecessary universe parameters. -/
abbreviation unit : Type := punit
@[pattern] abbreviation unit.star : unit := punit.star
/--
Gadget for defining thunks, thunk parameters have special treatment.
Example: given
def f (s : string) (t : thunk nat) : nat
an application
f "hello" 10
is converted into
f "hello" (λ _, 10)
-/
@[reducible] def thunk (α : Type u) : Type u :=
unit → α
inductive true : Prop
| intro : true
inductive false : Prop
inductive empty : Type
/--
Logical not.
`not P`, with notation `¬ P`, is the `Prop` which is true if and only if `P` is false. It is
internally represented as `P → false`, so one way to prove a goal `⊢ ¬ P` is to use `intro h`,
which gives you a new hypothesis `h : P` and the goal `⊢ false`.
A hypothesis `h : ¬ P` can be used in term mode as a function, so if `w : P` then `h w : false`.
Related mathlib tactic: `contrapose`.
-/
def not (a : Prop) := a → false
prefix `¬` := not
inductive eq {α : Sort u} (a : α) : α → Prop
| refl [] : eq a
/-
Initialize the quotient module, which effectively adds the following definitions:
constant quot {α : Sort u} (r : α → α → Prop) : Sort u
constant quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : quot r
constant quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) :
(∀ a b : α, r a b → eq (f a) (f b)) → quot r → β
constant quot.ind {α : Sort u} {r : α → α → Prop} {β : quot r → Prop} :
(∀ a : α, β (quot.mk r a)) → ∀ q : quot r, β q
Also the reduction rule:
quot.lift f _ (quot.mk a) ~~> f a
-/
init_quotient
/--
Heterogeneous equality.
Its purpose is to write down equalities between terms whose types are not definitionally equal.
For example, given `x : vector α n` and `y : vector α (0+n)`, `x = y` doesn't typecheck but `x == y` does.
If you have a goal `⊢ x == y`,
your first instinct should be to ask (either yourself, or on [zulip](https://leanprover.zulipchat.com/))
if something has gone wrong already.
If you really do need to follow this route,
you may find the lemmas `eq_rec_heq` and `eq_mpr_heq` useful.
-/
inductive heq {α : Sort u} (a : α) : Π {β : Sort u}, β → Prop
| refl [] : heq a
structure prod (α : Type u) (β : Type v) :=
(fst : α) (snd : β)
/-- Similar to `prod`, but α and β can be propositions.
We use this type internally to automatically generate the brec_on recursor. -/
structure pprod (α : Sort u) (β : Sort v) :=
(fst : α) (snd : β)
/--
Logical and.
`and P Q`, with notation `P ∧ Q`, is the `Prop` which is true precisely when `P` and `Q` are
both true.
To prove a goal `⊢ P ∧ Q`, you can use the tactic `split`,
which gives two separate goals `⊢ P` and `⊢ Q`.
Given a hypothesis `h : P ∧ Q`, you can use the tactic `cases h with hP hQ`
to obtain two new hypotheses `hP : P` and `hQ : Q`. See also the `obtain` or `rcases` tactics in
mathlib.
-/
structure and (a b : Prop) : Prop :=
intro :: (left : a) (right : b)
lemma and.elim_left {a b : Prop} (h : and a b) : a := h.1
lemma and.elim_right {a b : Prop} (h : and a b) : b := h.2
/- eq basic support -/
infix = := eq
attribute [refl] eq.refl
/- This is a `def`, so that it can be used as pattern in the equation compiler. -/
@[pattern] def rfl {α : Sort u} {a : α} : a = a := eq.refl a
@[elab_as_eliminator, subst]
lemma eq.subst {α : Sort u} {P : α → Prop} {a b : α} (h₁ : a = b) (h₂ : P a) : P b :=
eq.rec h₂ h₁
notation h1 ▸ h2 := eq.subst h1 h2
@[trans] lemma eq.trans {α : Sort u} {a b c : α} (h₁ : a = b) (h₂ : b = c) : a = c :=
h₂ ▸ h₁
@[symm] lemma eq.symm {α : Sort u} {a b : α} (h : a = b) : b = a :=
h ▸ rfl
infix == := heq
/- This is a `def`, so that it can be used as pattern in the equation compiler. -/
@[pattern] def heq.rfl {α : Sort u} {a : α} : a == a := heq.refl a
lemma eq_of_heq {α : Sort u} {a a' : α} (h : a == a') : a = a' :=
have ∀ (α' : Sort u) (a' : α') (h₁ : @heq α a α' a') (h₂ : α = α'), (eq.rec_on h₂ a : α') = a', from
λ (α' : Sort u) (a' : α') (h₁ : @heq α a α' a'), heq.rec_on h₁ (λ h₂ : α = α, rfl),
show (eq.rec_on (eq.refl α) a : α) = a', from
this α a' h (eq.refl α)
/- The following four lemmas could not be automatically generated when the
structures were declared, so we prove them manually here. -/
lemma prod.mk.inj {α : Type u} {β : Type v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β}
: (x₁, y₁) = (x₂, y₂) → and (x₁ = x₂) (y₁ = y₂) :=
λ h, prod.no_confusion h (λ h₁ h₂, ⟨h₁, h₂⟩)
lemma prod.mk.inj_arrow {α : Type u} {β : Type v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β}
: (x₁, y₁) = (x₂, y₂) → Π ⦃P : Sort w⦄, (x₁ = x₂ → y₁ = y₂ → P) → P :=
λ h₁ _ h₂, prod.no_confusion h₁ h₂
lemma pprod.mk.inj {α : Sort u} {β : Sort v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β}
: pprod.mk x₁ y₁ = pprod.mk x₂ y₂ → and (x₁ = x₂) (y₁ = y₂) :=
λ h, pprod.no_confusion h (λ h₁ h₂, ⟨h₁, h₂⟩)
lemma pprod.mk.inj_arrow {α : Type u} {β : Type v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β}
: (x₁, y₁) = (x₂, y₂) → Π ⦃P : Sort w⦄, (x₁ = x₂ → y₁ = y₂ → P) → P :=
λ h₁ _ h₂, prod.no_confusion h₁ h₂
inductive sum (α : Type u) (β : Type v)
| inl (val : α) : sum
| inr (val : β) : sum
inductive psum (α : Sort u) (β : Sort v)
| inl (val : α) : psum
| inr (val : β) : psum
/--
Logical or.
`or P Q`, with notation `P ∨ Q`, is the proposition which is true if and only if `P` or `Q` is
true.
To prove a goal `⊢ P ∨ Q`, if you know which alternative you want to prove,
you can use the tactics `left` (which gives the goal `⊢ P`)
or `right` (which gives the goal `⊢ Q`).
Given a hypothesis `h : P ∨ Q` and goal `⊢ R`,
the tactic `cases h` will give you two copies of the goal `⊢ R`,
with the hypothesis `h : P` in the first, and the hypothesis `h : Q` in the second.
-/
inductive or (a b : Prop) : Prop
| inl (h : a) : or
| inr (h : b) : or
lemma or.intro_left {a : Prop} (b : Prop) (ha : a) : or a b :=
or.inl ha
lemma or.intro_right (a : Prop) {b : Prop} (hb : b) : or a b :=
or.inr hb
structure sigma {α : Type u} (β : α → Type v) :=
mk :: (fst : α) (snd : β fst)
structure psigma {α : Sort u} (β : α → Sort v) :=
mk :: (fst : α) (snd : β fst)
inductive bool : Type
| ff : bool
| tt : bool
/- Remark: subtype must take a Sort instead of Type because of the axiom strong_indefinite_description. -/
structure subtype {α : Sort u} (p : α → Prop) :=
(val : α) (property : p val)
attribute [pp_using_anonymous_constructor] sigma psigma subtype pprod and
class inductive decidable (p : Prop)
| is_false (h : ¬p) : decidable
| is_true (h : p) : decidable
@[reducible]
def decidable_pred {α : Sort u} (r : α → Prop) :=
Π (a : α), decidable (r a)
@[reducible]
def decidable_rel {α : Sort u} (r : α → α → Prop) :=
Π (a b : α), decidable (r a b)
@[reducible]
def decidable_eq (α : Sort u) :=
decidable_rel (@eq α)
inductive option (α : Type u)
| none : option
| some (val : α) : option
export option (none some)
export bool (ff tt)
inductive list (T : Type u)
| nil : list
| cons (hd : T) (tl : list) : list
notation h :: t := list.cons h t
notation `[` l:(foldr `, ` (h t, list.cons h t) list.nil `]`) := l
inductive nat
| zero : nat
| succ (n : nat) : nat
structure unification_constraint :=
{α : Type u} (lhs : α) (rhs : α)
infix ` ≟ `:50 := unification_constraint.mk
infix ` =?= `:50 := unification_constraint.mk
structure unification_hint :=
(pattern : unification_constraint)
(constraints : list unification_constraint)
/- Declare builtin and reserved notation -/
class has_zero (α : Type u) := (zero : α)
class has_one (α : Type u) := (one : α)
class has_add (α : Type u) := (add : α → α → α)
class has_mul (α : Type u) := (mul : α → α → α)
class has_inv (α : Type u) := (inv : α → α)
class has_neg (α : Type u) := (neg : α → α)
class has_sub (α : Type u) := (sub : α → α → α)
class has_div (α : Type u) := (div : α → α → α)
class has_dvd (α : Type u) := (dvd : α → α → Prop)
class has_mod (α : Type u) := (mod : α → α → α)
class has_le (α : Type u) := (le : α → α → Prop)
class has_lt (α : Type u) := (lt : α → α → Prop)
class has_append (α : Type u) := (append : α → α → α)
class has_andthen (α : Type u) (β : Type v) (σ : out_param $ Type w) := (andthen : α → β → σ)
class has_union (α : Type u) := (union : α → α → α)
class has_inter (α : Type u) := (inter : α → α → α)
class has_sdiff (α : Type u) := (sdiff : α → α → α)
class has_equiv (α : Sort u) := (equiv : α → α → Prop)
class has_subset (α : Type u) := (subset : α → α → Prop)
class has_ssubset (α : Type u) := (ssubset : α → α → Prop)
/- Type classes has_emptyc and has_insert are
used to implement polymorphic notation for collections.
Example: {a, b, c}. -/
class has_emptyc (α : Type u) := (emptyc : α)
class has_insert (α : out_param $ Type u) (γ : Type v) := (insert : α → γ → γ)
class has_singleton (α : out_param $ Type u) (β : Type v) := (singleton : α → β)
/- Type class used to implement the notation { a ∈ c | p a } -/
class has_sep (α : out_param $ Type u) (γ : Type v) :=
(sep : (α → Prop) → γ → γ)
/- Type class for set-like membership -/
class has_mem (α : out_param $ Type u) (γ : Type v) := (mem : α → γ → Prop)
class has_pow (α : Type u) (β : Type v) :=
(pow : α → β → α)
export has_andthen (andthen)
export has_pow (pow)
infix ∈ := has_mem.mem
notation a ∉ s := ¬ has_mem.mem a s
infix + := has_add.add
infix * := has_mul.mul
infix - := has_sub.sub
infix / := has_div.div
infix ∣ := has_dvd.dvd
infix % := has_mod.mod
prefix - := has_neg.neg
infix <= := has_le.le
infix ≤ := has_le.le
infix < := has_lt.lt
infix ++ := has_append.append
infix ; := andthen
notation `∅` := has_emptyc.emptyc
infix ∪ := has_union.union
infix ∩ := has_inter.inter
infix ⊆ := has_subset.subset
infix ⊂ := has_ssubset.ssubset
infix \ := has_sdiff.sdiff
infix ≈ := has_equiv.equiv
infixr ^ := has_pow.pow
export has_append (append)
@[reducible] def ge {α : Type u} [has_le α] (a b : α) : Prop := has_le.le b a
@[reducible] def gt {α : Type u} [has_lt α] (a b : α) : Prop := has_lt.lt b a
infix >= := ge
infix ≥ := ge
infix > := gt
@[reducible] def superset {α : Type u} [has_subset α] (a b : α) : Prop := has_subset.subset b a
@[reducible] def ssuperset {α : Type u} [has_ssubset α] (a b : α) : Prop := has_ssubset.ssubset b a
infix ⊇ := superset
infix ⊃ := ssuperset
def bit0 {α : Type u} [s : has_add α] (a : α) : α := a + a
def bit1 {α : Type u} [s₁ : has_one α] [s₂ : has_add α] (a : α) : α := (bit0 a) + 1
attribute [pattern] has_zero.zero has_one.one bit0 bit1 has_add.add has_neg.neg has_mul.mul
export has_insert (insert)
class is_lawful_singleton (α : Type u) (β : Type v) [has_emptyc β] [has_insert α β]
[has_singleton α β] : Prop :=
(insert_emptyc_eq : ∀ (x : α), (insert x ∅ : β) = {x})
export has_singleton (singleton)
export is_lawful_singleton (insert_emptyc_eq)
attribute [simp] insert_emptyc_eq
/- nat basic instances -/
namespace nat
protected def add : nat → nat → nat
| a zero := a
| a (succ b) := succ (add a b)
/- We mark the following definitions as pattern to make sure they can be used in recursive equations,
and reduced by the equation compiler. -/
attribute [pattern] nat.add nat.add._main
end nat
instance : has_zero nat := ⟨nat.zero⟩
instance : has_one nat := ⟨nat.succ (nat.zero)⟩
instance : has_add nat := ⟨nat.add⟩
def std.priority.default : nat := 1000
def std.priority.max : nat := 0xFFFFFFFF
namespace nat
protected def prio := std.priority.default + 100
end nat
/-
Global declarations of right binding strength
If a module reassigns these, it will be incompatible with other modules that adhere to these
conventions.
When hovering over a symbol, use "C-c C-k" to see how to input it.
-/
def std.prec.max : nat := 1024 -- the strength of application, identifiers, (, [, etc.
def std.prec.arrow : nat := 25
/-
The next def is "max + 10". It can be used e.g. for postfix operations that should
be stronger than application.
-/
def std.prec.max_plus : nat := std.prec.max + 10
reserve postfix `⁻¹`:std.prec.max_plus -- input with \sy or \-1 or \inv
postfix ⁻¹ := has_inv.inv
notation α × β := prod α β
-- notation for n-ary tuples
/- sizeof -/
class has_sizeof (α : Sort u) :=
(sizeof : α → nat)
def sizeof {α : Sort u} [s : has_sizeof α] : α → nat :=
has_sizeof.sizeof
/-
Declare sizeof instances and lemmas for types declared before has_sizeof.
From now on, the inductive compiler will automatically generate sizeof instances and lemmas.
-/
/- Every type `α` has a default has_sizeof instance that just returns 0 for every element of `α` -/
protected def default.sizeof (α : Sort u) : α → nat
| a := 0
instance default_has_sizeof (α : Sort u) : has_sizeof α :=
⟨default.sizeof α⟩
protected def nat.sizeof : nat → nat
| n := n
instance : has_sizeof nat :=
⟨nat.sizeof⟩
protected def prod.sizeof {α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] : (prod α β) → nat
| ⟨a, b⟩ := 1 + sizeof a + sizeof b
instance (α : Type u) (β : Type v) [has_sizeof α] [has_sizeof β] : has_sizeof (prod α β) :=
⟨prod.sizeof⟩
protected def sum.sizeof {α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] : (sum α β) → nat
| (sum.inl a) := 1 + sizeof a
| (sum.inr b) := 1 + sizeof b
instance (α : Type u) (β : Type v) [has_sizeof α] [has_sizeof β] : has_sizeof (sum α β) :=
⟨sum.sizeof⟩
protected def psum.sizeof {α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] : (psum α β) → nat
| (psum.inl a) := 1 + sizeof a
| (psum.inr b) := 1 + sizeof b
instance (α : Type u) (β : Type v) [has_sizeof α] [has_sizeof β] : has_sizeof (psum α β) :=
⟨psum.sizeof⟩
protected def sigma.sizeof {α : Type u} {β : α → Type v} [has_sizeof α] [∀ a, has_sizeof (β a)] : sigma β → nat
| ⟨a, b⟩ := 1 + sizeof a + sizeof b
instance (α : Type u) (β : α → Type v) [has_sizeof α] [∀ a, has_sizeof (β a)] : has_sizeof (sigma β) :=
⟨sigma.sizeof⟩
protected def psigma.sizeof {α : Type u} {β : α → Type v} [has_sizeof α] [∀ a, has_sizeof (β a)] : psigma β → nat
| ⟨a, b⟩ := 1 + sizeof a + sizeof b
instance (α : Type u) (β : α → Type v) [has_sizeof α] [∀ a, has_sizeof (β a)] : has_sizeof (psigma β) :=
⟨psigma.sizeof⟩
protected def punit.sizeof : punit → nat
| u := 1
instance : has_sizeof punit := ⟨punit.sizeof⟩
protected def bool.sizeof : bool → nat
| b := 1
instance : has_sizeof bool := ⟨bool.sizeof⟩
protected def option.sizeof {α : Type u} [has_sizeof α] : option α → nat
| none := 1
| (some a) := 1 + sizeof a
instance (α : Type u) [has_sizeof α] : has_sizeof (option α) :=
⟨option.sizeof⟩
protected def list.sizeof {α : Type u} [has_sizeof α] : list α → nat
| list.nil := 1
| (list.cons a l) := 1 + sizeof a + list.sizeof l
instance (α : Type u) [has_sizeof α] : has_sizeof (list α) :=
⟨list.sizeof⟩
protected def subtype.sizeof {α : Type u} [has_sizeof α] {p : α → Prop} : subtype p → nat
| ⟨a, _⟩ := sizeof a
instance {α : Type u} [has_sizeof α] (p : α → Prop) : has_sizeof (subtype p) :=
⟨subtype.sizeof⟩
lemma nat_add_zero (n : nat) : n + 0 = n := rfl
/- Combinator calculus -/
namespace combinator
universes u₁ u₂ u₃
def I {α : Type u₁} (a : α) := a
def K {α : Type u₁} {β : Type u₂} (a : α) (b : β) := a
def S {α : Type u₁} {β : Type u₂} {γ : Type u₃} (x : α → β → γ) (y : α → β) (z : α) := x z (y z)
end combinator
/-- Auxiliary datatype for #[ ... ] notation.
#[1, 2, 3, 4] is notation for
bin_tree.node
(bin_tree.node (bin_tree.leaf 1) (bin_tree.leaf 2))
(bin_tree.node (bin_tree.leaf 3) (bin_tree.leaf 4))
We use this notation to input long sequences without exhausting the system stack space.
Later, we define a coercion from `bin_tree` into `list`.
-/
inductive bin_tree (α : Type u)
| empty : bin_tree
| leaf (val : α) : bin_tree
| node (left right : bin_tree) : bin_tree
attribute [elab_simple] bin_tree.node bin_tree.leaf
/- Basic unification hints -/
@[unify] def add_succ_defeq_succ_add_hint (x y z : nat) : unification_hint :=
{ pattern := x + nat.succ y ≟ nat.succ z,
constraints := [z ≟ x + y] }
/-- Like `by apply_instance`, but not dependent on the tactic framework. -/
@[reducible] def infer_instance {α : Sort u} [i : α] : α := i
|
bf8d4b699e83a4edd0af169c9961f8866b176a40 | 2bafba05c98c1107866b39609d15e849a4ca2bb8 | /src/week_8/ideas/Part_B_H0.lean | 57feae60232dbba2fca10108a51cb4639b96660b | [
"Apache-2.0"
] | permissive | ImperialCollegeLondon/formalising-mathematics | b54c83c94b5c315024ff09997fcd6b303892a749 | 7cf1d51c27e2038d2804561d63c74711924044a1 | refs/heads/master | 1,651,267,046,302 | 1,638,888,459,000 | 1,638,888,459,000 | 331,592,375 | 284 | 24 | Apache-2.0 | 1,669,593,705,000 | 1,611,224,849,000 | Lean | UTF-8 | Lean | false | false | 10,562 | lean | import week_8.ideas.Part_A_G_modules
/-
-- move this?
# Coercions
Something which will come up again and again in this workshop is
the concept of a coercion. We have seen things which computer scientists
call `φ : M →+[G] N` and we call "functions", but to Lean they are
functions with baggage, which in this case is all the axioms and theorems
attached to the theory of G-module homomorphisms (for example
a proof of the theorem that `φ 0 = 0`). This means that `φ` itself is a
pair consisting of a function and a whole bunch of extra stuff, and
in particular `φ` is not a function (it's a function and more).
The actual function `M → N` is called `⇑φ` by Lean, but we can just
call it `φ` most of the time.
The system that makes this happen is called a coercion -- we coercing
`φ` to a function `⇑φ`. We will see other examples of coercions later.
-/
/-
# Making the API for H⁰(G,M)
If `G` is a group and `M` is a G-module then H⁰(G,M), or `H0 G M`, is the abelian
group of G-invariant elements of `M`. We make the definition so we have
to make the interface too. We show that `H0 G M` is an abelian group,
define a coercion to `M` sending `m` to `↑m`, and define `m.spec` to be
the statement that `↑m` is G-invariant.
Let's start by giving a preliminary definition of H⁰ as an additive
subgroup of `M`.
-/
open set
/-- `H0 G M` is the type of G-invariant elements of M. -/
def H0_subgroup (G M : Type)
[monoid G] [add_comm_group M] [distrib_mul_action G M] : add_subgroup M :=
{ carrier := {m | ∀ g : G, g • m = m },
-- Need to check it's a subgroup.
-- Axiom 1: zero in ("closed under `0`")
zero_mem' := begin
-- you can start with this
rw mem_set_of_eq, -- says that `a ∈ { x | p x}` is the same as `p a`.
-- can you take it from there?
exact smul_zero,
end,
-- Axiom 2 : closed under `+`
add_mem' := begin
intros a b ha hb g,
rw mem_set_of_eq at *, -- that's how I'd start
rw [smul_add, ha, hb], -- then the sneaky refl closes the goal
end,
-- Axiom 3 : closed under `-`
neg_mem' := begin
simp *,
end }
/-
This makes `H0_subgroup G M`, a term (an additive subgroup of `M`, and
hence a term of type `add_subgroup M`). But this is no good -- we want
to consider functions `H⁰(G,M) → H⁰(G,N)` so we need a *type* `H0 G M`.
We need to promote the term to a type. We do this by using Lean's
theory of subtypes, with notation `{ x // P x }` (a type) as oppposed to
the set-theoretic `{ x | P x }` (a term)
-/
/-- Group cohomology `H⁰(G,M)` as a type. -/
def H0 (G M : Type)
[monoid G] [add_comm_group M] [distrib_mul_action G M] : Type :=
{m : M // ∀ g : G, g • m = m }
-- let's make an API and prove stuff about `H0 G M` in the `H0` namespace.
namespace H0
-- let `G` be a group (or a monoid) and let `M` be a `G`-module.
variables {G M : Type}
[monoid G] [add_comm_group M] [distrib_mul_action G M]
/-
We have defined `H0 G M` to be a type, a so-called subtype of `M`,
but a type in its own right. It has terms of its own (unlike `S : set M`
or `A : add_subgroup M`)
So how does this work? A term `m` of type `H0 G M` is a *package* consisting
of a term `m.1 : M` and a proof `m.2 : ∀ g, g • m.1 = m.1`. We do not
want to use these internal computer science terms for this package
of information, we want a nice interface. Below we use coercion, to turn
a term `m : H0 G M` into a term `↑m : M`.
-/
/-- set up coercion from `H⁰(G,M) to M`, sending `m` to `↑m` -/
instance : has_coe (H0 G M) M :=
-- this is the last time we see `m.1`
⟨λ m, m.1⟩
-- That's a definition, so we need to make a little API.
/-- If `a : M` then `↑⟨a, ha⟩ = a` -/
@[simp] lemma coe_def (a : M) (ha : ∀(g : G), g • a = a) :
((⟨a, ha⟩ : H0 G M) : M) = a := rfl
-- this is our nice interface
lemma spec (m : H0 G M) : ∀ (g : G), g • (m : M) = m :=
-- this is the last time we see `m.2`
m.2
/-
The idea now is that we should avoid `m.1` and `m.2` completely,
and use `m : M` or `↑m` for the element of the module, and `m.spec` for
the proof that it is `G`-invariant.
## Basic Infrastructure
We have made a new definition, `H0`, and now we need to make it easier
to use. Things we do here:
* We want to get (for free) that `H0 G M` is a group (so we need to put
this fact into the type class mechanism).
* We want to know that two terms of type `H0 G M` are equal if
and only if the corresponding terms of type `M` are equal (so we want to
prove an extensionality lemma).
* We want to know that things like 0 and addition coincide in `M`
and `H0 G M` (the coercion is a group homomorphism)
Let's start by making H⁰(G, M) a.k.a. `H0 G M` into a group. This is easy
because `H0 G M` is the type corresponding to the term `H0_subgroup G M`
which is a subgroup, hence a group.
-/
-- tell type class inference that `H0 G M` is a group
instance : add_comm_group (H0 G M) :=
add_subgroup.to_add_comm_group (H0_subgroup G M)
-- Let's now prove an ext_iff lemma (useful for rewriting)
lemma ext_iff (m₁ m₂ : H0 G M) : m₁ = m₂ ↔ (m₁ : M) = (m₂ : M) :=
begin
split,
{ rintro rfl, refl },
{ ext }
end
-- Let's tell the simplifier how the group structure (addition, 0, negation
-- and subtraction) works with respect to the coercion. All the proofs
-- are true by definition
@[simp] lemma coe_add (a b : H0 G M) :
((a + b : H0 G M) : M) = a + b := rfl
@[simp] lemma coe_zero : ((0 : H0 G M) : M) = 0 := rfl
@[simp] lemma coe_neg (a : H0 G M) :
((-a : H0 G M) : M) = -a := rfl
-- we'll never use it but what the heck, others might
@[simp] lemma coe_sub (a b : H0 G M) :
((a - b : H0 G M) : M) = a - b := rfl
-- try these
example (m₁ m₂ m₃ : H0 G M) : m₁ + (m₂ - m₁ + m₃) = m₃ + m₂ :=
begin
-- which tactic?
abel
end
example (g : G) (m : H0 G M) : g • (m + m : M) = m + m :=
begin
-- can you help the simplifier?
simp [m.spec g],
end
end H0
/-
## API for the interaction of G-module maps and our new definition `H⁰`
Now let's prove that a G-module map `φ : M →+[G] N` induces a natural
abelian group hom `φ.H0 : H⁰(G,M) →+ H⁰(G,N)`. I would rather do this in
`φ`'s namespace, which is `distrib_mul_action_hom`, because then
I can write `φ.H0` directly.
-/
namespace distrib_mul_action_hom
variables {G M N : Type}
[monoid G] [add_comm_group M] [add_comm_group N]
[distrib_mul_action G M] [distrib_mul_action G N]
(a : M) (b : N)
-- Let's first define the group homomorphism `H0 G M →+ H0 G N` induced by `φ`.
-- Recall that the constructor of `H0 G N` needs as input a pair consisting
-- of `b : N` and `hb : ∀ g, g • b = b`, and we make the element of `H0 G N`
-- using the `⟨b, hb⟩` notation.
/- The function underlying the group homomorphism `H⁰(G,M) → H⁰(G,N)`
induced by a `G`-equivariant group homomorphism `φ : M →+[G] N` -/
def H0_underlying_function (φ : M →+[G] N) (m : H0 G M) : H0 G N :=
⟨φ m, begin
-- use φ.map_smul and a.spec to prove that this map is well-defined.
-- Remember that `rw` doesn't work under binders, and ∀ is a binder, so start
-- with `intros`.
intros,
rw [←φ.map_smul, m.spec],
end⟩
/-- The group homomorphism `H⁰(G,M) →+ H⁰(G,N)`
induced by a `G`-equivariant group homomorphism `φ : M →+[G] N` -/
def H0 (φ : M →+[G] N) : H0 G M →+ H0 G N :=
-- to make a group homomorphism we need apply a constructor
add_monoid_hom.mk'
-- to the function we just made
(H0_underlying_function φ)
-- and then prove that this function preserves addition.
begin
intros a b,
simp only [H0_underlying_function],
ext,
simp,
end
end distrib_mul_action_hom
-- The API for `φ.H0` starts here
namespace H0
variables {G M N : Type}
[monoid G] [add_comm_group M] [add_comm_group N]
[distrib_mul_action G M] [distrib_mul_action G N]
(a : M) (b : N)
/-
## An API for `φ.H0`
So now if `φ : M →+[G] N` is a G-module homomorphism, we can talk
about `φ.H0 : H0 G M →+ H0 G N`, an abelian group homomorphism
from H⁰(G,M) to H⁰(G,N).
As ever, this is a definition so we need to make a little API.
We start with the following handy fact:
Given a G-module map `φ : M →+[G] N`, The following diagram commutes:
φ
M ----------------> N
/\ /\
| coercion ↑ | coercion ↑
| |
| |
H⁰(G,M) ---------> H⁰(G,N)
-/
@[simp] lemma coe_apply (m : H0 G M) (φ : M →+[G] N) :
((φ.H0 m) : N) = φ m :=
begin
-- Look at the goal the way I have written it.
-- Unfold the definitions. It's true by definition.
-- Look at the goal the way Lean is displaying it
-- right now. It's just coercions everywhere. Ignore them.
refl,
end
open distrib_mul_action_hom
-- If you're in to that sort of thing, you can prove that `φ.H0`
-- is functorial. That's it and comp.
def id_apply (m : H0 G M) :
(distrib_mul_action_hom.id G).H0 m = m :=
begin
-- remember extensionality.
ext,
refl,
end
variables {P : Type} [add_comm_group P] [distrib_mul_action G P]
def comp (φ : M →+[G] N) (ψ : N →+[G] P) :
(ψ ∘ᵍ φ).H0 = ψ.H0.comp φ.H0 :=
begin
refl,
end
end H0
/-
## First exactness result
If 0 → M → N → P → 0 is a short exact sequence, then there
is a long exact sequence
0 → H⁰(G,M) → H⁰(G,N) → H⁰(G,P)
and we can't go any further because we haven't defined H¹! This boils
down to two theorems; let's prove them.
-/
open function
open distrib_mul_action_hom
variables {G M N P : Type}
[monoid G] [add_comm_group M] [add_comm_group N] [add_comm_group P]
[distrib_mul_action G M] [distrib_mul_action G N] [distrib_mul_action G P]
(a : M) (b : N)
-- 0 → H⁰(G,M) → H⁰(G,N) is exact, i.e. φ.H0 is injective
theorem H0_hom.left_exact (φ : M →+[G] N) (hφ : injective φ) :
injective φ.H0 :=
begin
intros a b h,
ext,
apply hφ,
rw H0.ext_iff at h,
simpa using h,
end
-- H⁰(G,M) → H⁰(G,N) → H⁰(G,P) is exact, i.e. an image equals a kernel.
theorem H0_hom.middle_exact' (φ : M →+[G] N) (hφ : injective φ)
(ψ : N →+[G] P) (he : is_exact φ ψ) :
φ.H0.range = ψ.H0.ker :=
begin
ext n,
rw is_exact.def at he,
specialize he n,
rw add_monoid_hom.mem_ker,
rw [H0.ext_iff, n.coe_apply, H0.coe_zero, ← he],
split,
{ rintro ⟨y, rfl⟩,
exact ⟨y, rfl⟩ },
{ rintro ⟨y, hy⟩,
refine ⟨⟨y, _⟩, _⟩,
{ intro g,
apply hφ,
simpa [hy] using n.spec g },
{ ext,
exact hy } }
end
|
edc1ce98092ddcb3caff6f7e7d2980a5e6ce266f | 9060db28f6353f040da7481ea5ebcdac426589ff | /folklore/toposes.lean | 11460104d68ccccff5c9bec354d9ae4e0323cb9a | [] | no_license | picrin/formalabstracts | 9ccd859fb34a9194fa5ded77ab1bc734ababe194 | 8ebd529598cfc8b6bd02530dd21b7bf3156de174 | refs/heads/master | 1,609,476,202,073 | 1,500,070,922,000 | 1,500,070,922,000 | 97,234,461 | 0 | 0 | null | 1,500,037,389,000 | 1,500,037,389,000 | null | UTF-8 | Lean | false | false | 457 | lean | -- an incomplete definition of toposes
import .categories
structure natural_numbers (C : category) :=
(nno_object : C.obj)
(nno_structure : Type)
-- an incomplete definition of toposes
-- this should probably be done using type classes
structure topos :=
(underlying_category : category)
(nno : natural_numbers underlying_category)
(exponent : Π (A B : underlying_category.obj), exponential A B)
(other_structure_missing : Type)
|
002dfe5ac8137b05e785484098313cb2e4ed80f3 | f1a12d4db0f46eee317d703e3336d33950a2fe7e | /common/predicates.lean | 457bdf068c2b87d2109469a27638c4e4b1ce2447 | [
"Apache-2.0"
] | permissive | avigad/qelim | bce89b79c717b7649860d41a41a37e37c982624f | b7d22864f1f0a2d21adad0f4fb3fc7ba665f8e60 | refs/heads/master | 1,584,548,938,232 | 1,526,773,708,000 | 1,526,773,708,000 | 134,967,693 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 603 | lean | import .atom
variables {α β : Type}
def qfree_res_of_nqfree_arg (qe : fm α → fm α) :=
∀ (p : fm α), nqfree p → qfree (qe p)
def qfree_of_fnormal_of_nqfree (β) [atom_type α β] (qe : fm α → fm α) :=
∀ (p : fm α), nqfree p → fnormal β p → qfree (qe p)
def interp_prsv_ex (β) [atom_type α β] (qe : fm α → fm α) (p) :=
∀ (bs : list β), I (qe p) bs = ∃ b, (I p (b::bs))
def interp_prsv (β) [atom_type α β] (qe : fm α → fm α) (p) :=
∀ (bs : list β), I (qe p) bs = I p bs
def preserves (f : α → α) (r : α → Prop) : Prop :=
∀ a, r a → r (f a) |
9ed150f31451898adc4a8a8c17e6b933cc021bac | df7bb3acd9623e489e95e85d0bc55590ab0bc393 | /lean/love01_definitions_and_statements_exercise_solution.lean | 5e9bcc729d2520eda84371e3defdd7e095424329 | [] | no_license | MaschavanderMarel/logical_verification_2020 | a41c210b9237c56cb35f6cd399e3ac2fe42e775d | 7d562ef174cc6578ca6013f74db336480470b708 | refs/heads/master | 1,692,144,223,196 | 1,634,661,675,000 | 1,634,661,675,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,131 | lean | import .love01_definitions_and_statements_demo
/- # LoVe Exercise 1: Definitions and Statements
Replace the placeholders (e.g., `:= sorry`) with your solutions. -/
set_option pp.beta true
set_option pp.generalized_field_notation false
namespace LoVe
/- ## Question 1: Truncated Subtraction
1.1. Define the function `sub` that implements truncated subtraction on natural
numbers by recursion. "Truncated" means that results that mathematically would
be negative are represented by 0. For example:
`sub 7 2 = 5`
`sub 2 7 = 0` -/
def sub : ℕ → ℕ → ℕ
| m 0 := m
| 0 _ := 0
| (nat.succ m) (nat.succ n) := sub m n
/- 1.2. Check that your function works as expected. -/
#eval sub 0 0 -- expected: 0
#eval sub 0 1 -- expected: 0
#eval sub 0 7 -- expected: 0
#eval sub 1 0 -- expected: 1
#eval sub 1 1 -- expected: 0
#eval sub 3 0 -- expected: 3
#eval sub 2 7 -- expected: 0
#eval sub 3 1 -- expected: 2
#eval sub 3 3 -- expected: 0
#eval sub 3 7 -- expected: 0
#eval sub 7 2 -- expected: 5
/- ## Question 2: Arithmetic Expressions
Consider the type `aexp` from the lecture and the function `eval` that
computes the value of an expression. You will find the definitions in the file
`love01_definitions_and_statements_demo.lean`. One way to find them quickly is
to
1. hold the Control (on Linux and Windows) or Command (on macOS) key pressed;
2. move the cursor to the identifier `aexp` or `eval`;
3. click the identifier. -/
#check aexp
#check eval
/- 2.1. Test that `eval` behaves as expected. Make sure to exercise each
constructor at least once. You can use the following environment in your tests.
What happens if you divide by zero?
Make sure to use `#eval`. For technical reasons, `#reduce` does not work well
here. Note that `#eval` (Lean's evaluation command) and `eval` (our evaluation
function on `aexp`) are unrelated. -/
def some_env : string → ℤ
| "x" := 3
| "y" := 17
| _ := 201
#eval eval some_env (aexp.var "x") -- expected: 3
#eval eval some_env (aexp.num 12) -- expected: 12
#eval eval some_env (aexp.add (aexp.var "x") (aexp.var "y")) -- expected: 20
#eval eval some_env (aexp.sub (aexp.num 5) (aexp.var "y")) -- expected: -12
#eval eval some_env (aexp.mul (aexp.num 11) (aexp.var "z")) -- expected: 2211
#eval eval some_env (aexp.div (aexp.num 2) (aexp.num 0)) -- expected: 0
/- 2.2. The following function simplifies arithmetic expressions involving
addition. It simplifies `0 + e` and `e + 0` to `e`. Complete the definition so
that it also simplifies expressions involving the other three binary
operators. -/
def simplify : aexp → aexp
| (aexp.add (aexp.num 0) e₂) := simplify e₂
| (aexp.add e₁ (aexp.num 0)) := simplify e₁
| (aexp.sub e₁ (aexp.num 0)) := simplify e₁
| (aexp.mul (aexp.num 0) e₂) := aexp.num 0
| (aexp.mul e₁ (aexp.num 0)) := aexp.num 0
| (aexp.mul (aexp.num 1) e₂) := simplify e₂
| (aexp.mul e₁ (aexp.num 1)) := simplify e₁
| (aexp.div (aexp.num 0) e₂) := aexp.num 0
| (aexp.div e₁ (aexp.num 0)) := aexp.num 0
| (aexp.div e₁ (aexp.num 1)) := simplify e₁
-- catch-all cases below
| (aexp.num i) := aexp.num i
| (aexp.var x) := aexp.var x
| (aexp.add e₁ e₂) := aexp.add (simplify e₁) (simplify e₂)
| (aexp.sub e₁ e₂) := aexp.sub (simplify e₁) (simplify e₂)
| (aexp.mul e₁ e₂) := aexp.mul (simplify e₁) (simplify e₂)
| (aexp.div e₁ e₂) := aexp.div (simplify e₁) (simplify e₂)
/- 2.3. State (without proving it) the correctness lemma for `simplify`, namely
that the simplified expression should have the same semantics, with respect to
`eval`, as the original expression. -/
lemma simplify_correct (env : string → ℤ) (e : aexp) :
eval env (simplify e) = eval env e :=
sorry
/- ## Question 3: λ-Terms
3.1. Complete the following definitions, by replacing the `sorry` markers by
terms of the expected type.
Hint: A procedure for doing so systematically is described in Section 1.1.4 of
the Hitchhiker's Guide. As explained there, you can use `_` as a placeholder
while constructing a term. By hovering over `_`, you will see the current
logical context. -/
def I : α → α :=
λa, a
def K : α → β → α :=
λa b, a
def C : (α → β → γ) → β → α → γ :=
λg b a, g a b
def proj_1st : α → α → α :=
λx y, x
/- Please give a different answer than for `proj_1st`. -/
def proj_2nd : α → α → α :=
λx y, y
def some_nonsense : (α → β → γ) → α → (α → γ) → β → γ :=
λg a f b, g a b
/- 3.2. Show the typing derivation for your definition of `C` above, on paper
or using ASCII or Unicode art. You might find the characters `–` (to draw
horizontal bars) and `⊢` useful. -/
/- Let `D` := `g : α → β → γ, b : β, a : α`. We have
–––––––––––––––––– Var –––––––––– Var
D ⊢ g : α → β → γ D ⊢ a : α
–––––––––––––––––––––––––––––––––––– App –––––––––– Var
D ⊢ g a : β → γ D ⊢ b : β
–––––––––––––––––––––––––––––––––––––––––––––––––––––– App
D ⊢ g a b : γ
––––––––––––––––––––––––––––––––––––––––––– Lam
g : α → β → γ, b : β ⊢ (λa : α, g a b) : γ
–––––––––––––––––––––––––––––––––––––––––––––– Lam
g : α → β → γ ⊢ (λ(b : β) (a : α), g a b) : γ
––––––––––––––––––––––––––––––––––––––––––––––– Lam
⊢ (λ(g : α → β → γ) (b : β) (a : α), g a b) : γ -/
end LoVe
|
3e38cb4a83e66fe54cf960f8392a83b41857ced1 | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/algebra/group_ring_action.lean | 758c48fedeafb6b60ec2a38bd068e48c215c63c9 | [
"Apache-2.0"
] | permissive | hikari0108/mathlib | b7ea2b7350497ab1a0b87a09d093ecc025a50dfa | a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901 | refs/heads/master | 1,690,483,608,260 | 1,631,541,580,000 | 1,631,541,580,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,303 | 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 group_theory.group_action.group
import data.equiv.ring
import ring_theory.subring
import algebra.pointwise
/-!
# Group action on rings
This file defines the typeclass of monoid acting on semirings `mul_semiring_action M R`,
and the corresponding typeclass of invariant subrings.
Note that `algebra` does not satisfy the axioms of `mul_semiring_action`.
## Implementation notes
There is no separate typeclass for group acting on rings, group acting on fields, etc.
They are all grouped under `mul_semiring_action`.
## Tags
group action, invariant subring
-/
universes u v
open_locale big_operators
/-- Typeclass for multiplicative actions by monoids on semirings.
This combines `distrib_mul_action` with `mul_distrib_mul_action`. -/
class mul_semiring_action (M : Type u) (R : Type v) [monoid M] [semiring R]
extends distrib_mul_action M R :=
(smul_one : ∀ (g : M), (g • 1 : R) = 1)
(smul_mul : ∀ (g : M) (x y : R), g • (x * y) = (g • x) * (g • y))
section semiring
variables (M G : Type u) [monoid M] [group G]
variables (A R S F : Type v) [add_monoid A] [semiring R] [comm_semiring S] [division_ring F]
-- note we could not use `extends` since these typeclasses are made with `old_structure_cmd`
@[priority 100]
instance mul_semiring_action.to_mul_distrib_mul_action [h : mul_semiring_action M R] :
mul_distrib_mul_action M R :=
{ ..h }
/-- Each element of the group defines an additive monoid isomorphism. -/
@[simps]
def distrib_mul_action.to_add_equiv [distrib_mul_action G A] (x : G) : A ≃+ A :=
{ .. distrib_mul_action.to_add_monoid_hom A x,
.. mul_action.to_perm_hom G A x }
/-- Each element of the group defines a multiplicative monoid isomorphism. -/
@[simps]
def mul_distrib_mul_action.to_mul_equiv [mul_distrib_mul_action G M] (x : G) : M ≃* M :=
{ .. mul_distrib_mul_action.to_monoid_hom M x,
.. mul_action.to_perm_hom G M x }
/-- Each element of the monoid defines a semiring homomorphism. -/
@[simps]
def mul_semiring_action.to_ring_hom [mul_semiring_action M R] (x : M) : R →+* R :=
{ .. mul_distrib_mul_action.to_monoid_hom R x,
.. distrib_mul_action.to_add_monoid_hom R x }
theorem to_ring_hom_injective [mul_semiring_action M R] [has_faithful_scalar M R] :
function.injective (mul_semiring_action.to_ring_hom M R) :=
λ m₁ m₂ h, eq_of_smul_eq_smul $ λ r, ring_hom.ext_iff.1 h r
/-- Each element of the group defines a semiring isomorphism. -/
@[simps]
def mul_semiring_action.to_ring_equiv [mul_semiring_action G R] (x : G) : R ≃+* R :=
{ .. distrib_mul_action.to_add_equiv G R x,
.. mul_semiring_action.to_ring_hom G R x }
section
variables {M G R}
/-- A stronger version of `submonoid.distrib_mul_action`. -/
instance submonoid.mul_semiring_action [mul_semiring_action M R] (H : submonoid M) :
mul_semiring_action H R :=
{ smul := (•),
.. H.mul_distrib_mul_action,
.. H.distrib_mul_action }
/-- A stronger version of `subgroup.distrib_mul_action`. -/
instance subgroup.mul_semiring_action [mul_semiring_action G R] (H : subgroup G) :
mul_semiring_action H R :=
H.to_submonoid.mul_semiring_action
/-- A stronger version of `subsemiring.distrib_mul_action`. -/
instance subsemiring.mul_semiring_action {R'} [semiring R'] [mul_semiring_action R' R]
(H : subsemiring R') :
mul_semiring_action H R :=
H.to_submonoid.mul_semiring_action
/-- A stronger version of `subring.distrib_mul_action`. -/
instance subring.mul_semiring_action {R'} [ring R'] [mul_semiring_action R' R]
(H : subring R') :
mul_semiring_action H R :=
H.to_subsemiring.mul_semiring_action
end
section pointwise
namespace subsemiring
variables [mul_semiring_action M R]
/-- The action on a subsemiring corresponding to applying the action to every element.
This is available as an instance in the `pointwise` locale. -/
protected def pointwise_mul_action : mul_action M (subsemiring R) :=
{ smul := λ a S, S.map (mul_semiring_action.to_ring_hom _ _ a),
one_smul := λ S,
(congr_arg (λ f, S.map f) (ring_hom.ext $ by exact one_smul M)).trans S.map_id,
mul_smul := λ a₁ a₂ S,
(congr_arg (λ f, S.map f) (ring_hom.ext $ by exact mul_smul _ _)).trans (S.map_map _ _).symm }
localized "attribute [instance] subsemiring.pointwise_mul_action" in pointwise
open_locale pointwise
@[simp] lemma coe_pointwise_smul (m : M) (S : subsemiring R) : ↑(m • S) = m • (S : set R) := rfl
@[simp] lemma pointwise_smul_to_add_submonoid (m : M) (S : subsemiring R) :
(m • S).to_add_submonoid = m • S.to_add_submonoid := rfl
lemma smul_mem_pointwise_smul (m : M) (r : R) (S : subsemiring R) : r ∈ S → m • r ∈ m • S :=
(set.smul_mem_smul_set : _ → _ ∈ m • (S : set R))
end subsemiring
namespace subring
variables {R' : Type*} [ring R'] [mul_semiring_action M R']
/-- The action on a subring corresponding to applying the action to every element.
This is available as an instance in the `pointwise` locale. -/
protected def pointwise_mul_action : mul_action M (subring R') :=
{ smul := λ a S, S.map (mul_semiring_action.to_ring_hom _ _ a),
one_smul := λ S,
(congr_arg (λ f, S.map f) (ring_hom.ext $ by exact one_smul M)).trans S.map_id,
mul_smul := λ a₁ a₂ S,
(congr_arg (λ f, S.map f) (ring_hom.ext $ by exact mul_smul _ _)).trans (S.map_map _ _).symm }
localized "attribute [instance] subring.pointwise_mul_action" in pointwise
open_locale pointwise
@[simp] lemma coe_pointwise_smul (m : M) (S : subring R') : ↑(m • S) = m • (S : set R') := rfl
@[simp] lemma pointwise_smul_to_add_subgroup (m : M) (S : subring R') :
(m • S).to_add_subgroup = m • S.to_add_subgroup := rfl
@[simp] lemma pointwise_smul_to_subsemiring (m : M) (S : subring R') :
(m • S).to_subsemiring = m • S.to_subsemiring := rfl
lemma smul_mem_pointwise_smul (m : M) (r : R') (S : subring R') : r ∈ S → m • r ∈ m • S :=
(set.smul_mem_smul_set : _ → _ ∈ m • (S : set R'))
end subring
end pointwise
section simp_lemmas
variables {M G A R F}
attribute [simp] smul_one smul_mul' smul_zero smul_add
/-- Note that `smul_inv'` refers to the group case, and `smul_inv` has an additional inverse
on `x`. -/
@[simp] lemma smul_inv'' [mul_semiring_action M F] (x : M) (m : F) : x • m⁻¹ = (x • m)⁻¹ :=
(mul_semiring_action.to_ring_hom M F x).map_inv _
end simp_lemmas
end semiring
section ring
variables (M : Type u) [monoid M] {R : Type v} [ring R] [mul_semiring_action M R]
variables (S : subring R)
open mul_action
/-- A typeclass for subrings invariant under a `mul_semiring_action`. -/
class is_invariant_subring : Prop :=
(smul_mem : ∀ (m : M) {x : R}, x ∈ S → m • x ∈ S)
instance is_invariant_subring.to_mul_semiring_action [is_invariant_subring M S] :
mul_semiring_action M S :=
{ smul := λ m x, ⟨m • x, is_invariant_subring.smul_mem m x.2⟩,
one_smul := λ s, subtype.eq $ one_smul M s,
mul_smul := λ m₁ m₂ s, subtype.eq $ mul_smul m₁ m₂ s,
smul_add := λ m s₁ s₂, subtype.eq $ smul_add m s₁ s₂,
smul_zero := λ m, subtype.eq $ smul_zero m,
smul_one := λ m, subtype.eq $ smul_one m,
smul_mul := λ m s₁ s₂, subtype.eq $ smul_mul' m s₁ s₂ }
end ring
|
c82686863fceda8bc0e64bdfe237b24c0012e24c | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Elab/BuiltinNotation.lean | e2ff3e907da6b0913630d7e98b843b4c0a2c66a6 | [
"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 | 19,041 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Compiler.BorrowedAnnotation
import Lean.Meta.KAbstract
import Lean.Meta.MatchUtil
import Lean.Elab.SyntheticMVars
namespace Lean.Elab.Term
open Meta
@[builtin_term_elab coeNotation] def elabCoe : TermElab := fun stx expectedType? => do
let stx := stx[1]
tryPostponeIfNoneOrMVar expectedType?
let e ← elabTerm stx none
if expectedType?.isNone then
throwError "invalid coercion notation, expected type is not known"
ensureHasType expectedType? e
@[builtin_term_elab anonymousCtor] def elabAnonymousCtor : TermElab := fun stx expectedType? =>
match stx with
| `(⟨$args,*⟩) => do
tryPostponeIfNoneOrMVar expectedType?
match expectedType? with
| some expectedType =>
let expectedType ← whnf expectedType
matchConstInduct expectedType.getAppFn
(fun _ => throwError "invalid constructor ⟨...⟩, expected type must be an inductive type {indentExpr expectedType}")
(fun ival _ => do
match ival.ctors with
| [ctor] =>
if isPrivateNameFromImportedModule (← getEnv) ctor then
throwError "invalid ⟨...⟩ notation, constructor for `{ival.name}` is marked as private"
let cinfo ← getConstInfoCtor ctor
let numExplicitFields ← forallTelescopeReducing cinfo.type fun xs _ => do
let mut n := 0
for i in [cinfo.numParams:xs.size] do
if (← getFVarLocalDecl xs[i]!).binderInfo.isExplicit then
n := n + 1
return n
let args := args.getElems
if args.size < numExplicitFields then
throwError "invalid constructor ⟨...⟩, insufficient number of arguments, constructs '{ctor}' has #{numExplicitFields} explicit fields, but only #{args.size} provided"
let newStx ← if args.size == numExplicitFields then
`($(mkCIdentFrom stx ctor (canonical := true)) $(args)*)
else if numExplicitFields == 0 then
throwError "invalid constructor ⟨...⟩, insufficient number of arguments, constructs '{ctor}' does not have explicit fields, but #{args.size} provided"
else
let extra := args[numExplicitFields-1:args.size]
let newLast ← `(⟨$[$extra],*⟩)
let newArgs := args[0:numExplicitFields-1].toArray.push newLast
`($(mkCIdentFrom stx ctor (canonical := true)) $(newArgs)*)
withMacroExpansion stx newStx $ elabTerm newStx expectedType?
| _ => throwError "invalid constructor ⟨...⟩, expected type must be an inductive type with only one constructor {indentExpr expectedType}")
| none => throwError "invalid constructor ⟨...⟩, expected type must be known"
| _ => throwUnsupportedSyntax
@[builtin_term_elab borrowed] def elabBorrowed : TermElab := fun stx expectedType? =>
match stx with
| `(@& $e) => return markBorrowed (← elabTerm e expectedType?)
| _ => throwUnsupportedSyntax
@[builtin_macro Lean.Parser.Term.show] def expandShow : Macro := fun stx =>
match stx with
| `(show $type by%$b $tac) => `(show $type from by%$b $tac)
| _ => Macro.throwUnsupported
@[builtin_term_elab Lean.Parser.Term.show] def elabShow : TermElab := fun stx expectedType? => do
match stx with
| `(show $type from $val) =>
/-
We first elaborate the type and try to unify it with the expected type if available.
Note that, we should not throw an error if the types do not unify. Recall that we have coercions and
the following is supported in Lean 3 and 4.
```
example : Int :=
show Nat from 0
```
-/
let type ← withSynthesize (mayPostpone := true) do
let type ← elabType type
if let some expectedType := expectedType? then
-- Recall that a similiar approach is used when elaborating applications
discard <| isDefEq expectedType type
return type
/-
Recall that we do not use the same approach used to elaborate type ascriptions.
For the `($val : $type)` notation, we just elaborate `val` using `type` and
ensure it has type `type`. This approach only ensure the type resulting expression
is definitionally equal to `type`. For the `show` notation we use `let_fun` to ensure the type
of the resulting expression is *structurally equal* `type`. Structural equality is important,
for example, if the resulting expression is a `simp`/`rw` parameter. Here is an example:
```
example (x : Nat) : (x + 0) + y = x + y := by
rw [show x + 0 = x from rfl]
```
-/
let thisId := mkIdentFrom stx `this
let valNew ← `(let_fun $thisId : $(← exprToSyntax type) := $val; $thisId)
elabTerm valNew expectedType?
| _ => throwUnsupportedSyntax
@[builtin_macro Lean.Parser.Term.have] def expandHave : Macro := fun stx =>
match stx with
| `(have $hy:hygieneInfo $bs* $[: $type]? := $val; $body) =>
`(have $(HygieneInfo.mkIdent hy `this (canonical := true)) $bs* $[: $type]? := $val; $body)
| `(have $hy:hygieneInfo $bs* $[: $type]? $alts; $body) =>
`(have $(HygieneInfo.mkIdent hy `this (canonical := true)) $bs* $[: $type]? $alts; $body)
| `(have $x:ident $bs* $[: $type]? := $val; $body) => `(let_fun $x $bs* $[: $type]? := $val; $body)
| `(have $x:ident $bs* $[: $type]? $alts; $body) => `(let_fun $x $bs* $[: $type]? $alts; $body)
| `(have _%$x $bs* $[: $type]? := $val; $body) => `(let_fun _%$x $bs* $[: $type]? := $val; $body)
| `(have _%$x $bs* $[: $type]? $alts; $body) => `(let_fun _%$x $bs* $[: $type]? $alts; $body)
| `(have $pattern:term $[: $type]? := $val; $body) => `(let_fun $pattern:term $[: $type]? := $val; $body)
| _ => Macro.throwUnsupported
@[builtin_macro Lean.Parser.Term.suffices] def expandSuffices : Macro
| `(suffices%$tk $x:ident : $type from $val; $body) => `(have%$tk $x : $type := $body; $val)
| `(suffices%$tk _%$x : $type from $val; $body) => `(have%$tk _%$x : $type := $body; $val)
| `(suffices%$tk $hy:hygieneInfo $type from $val; $body) => `(have%$tk $hy:hygieneInfo : $type := $body; $val)
| `(suffices%$tk $x:ident : $type by%$b $tac:tacticSeq; $body) => `(have%$tk $x : $type := $body; by%$b $tac)
| `(suffices%$tk _%$x : $type by%$b $tac:tacticSeq; $body) => `(have%$tk _%$x : $type := $body; by%$b $tac)
| `(suffices%$tk $hy:hygieneInfo $type by%$b $tac:tacticSeq; $body) => `(have%$tk $hy:hygieneInfo : $type := $body; by%$b $tac)
| _ => Macro.throwUnsupported
open Lean.Parser in
private def elabParserMacroAux (prec e : Term) (withAnonymousAntiquot : Bool) : TermElabM Syntax := do
let (some declName) ← getDeclName?
| throwError "invalid `leading_parser` macro, it must be used in definitions"
match extractMacroScopes declName with
| { name := .str _ s, .. } =>
let kind := quote declName
let mut p ← ``(withAntiquot
(mkAntiquot $(quote s) $kind $(quote withAnonymousAntiquot))
(leadingNode $kind $prec $e))
-- cache only unparameterized parsers
if (← getLCtx).all (·.isAuxDecl) then
p ← ``(withCache $kind $p)
return p
| _ => throwError "invalid `leading_parser` macro, unexpected declaration name"
@[builtin_term_elab «leading_parser»] def elabLeadingParserMacro : TermElab :=
adaptExpander fun
| `(leading_parser $[: $prec?]? $[(withAnonymousAntiquot := $anon?)]? $e) =>
elabParserMacroAux (prec?.getD (quote Parser.maxPrec)) e (anon?.all (·.raw.isOfKind ``Parser.Term.trueVal))
| _ => throwUnsupportedSyntax
private def elabTParserMacroAux (prec lhsPrec e : Term) : TermElabM Syntax := do
let declName? ← getDeclName?
match declName? with
| some declName => let kind := quote declName; ``(Lean.Parser.trailingNode $kind $prec $lhsPrec $e)
| none => throwError "invalid `trailing_parser` macro, it must be used in definitions"
@[builtin_term_elab «trailing_parser»] def elabTrailingParserMacro : TermElab :=
adaptExpander fun stx => match stx with
| `(trailing_parser$[:$prec?]?$[:$lhsPrec?]? $e) =>
elabTParserMacroAux (prec?.getD <| quote Parser.maxPrec) (lhsPrec?.getD <| quote 0) e
| _ => throwUnsupportedSyntax
@[builtin_term_elab Lean.Parser.Term.panic] def elabPanic : TermElab := fun stx expectedType? => do
match stx with
| `(panic! $arg) =>
let pos ← getRefPosition
let env ← getEnv
let stxNew ← match (← getDeclName?) with
| some declName => `(panicWithPosWithDecl $(quote (toString env.mainModule)) $(quote (toString declName)) $(quote pos.line) $(quote pos.column) $arg)
| none => `(panicWithPos $(quote (toString env.mainModule)) $(quote pos.line) $(quote pos.column) $arg)
withMacroExpansion stx stxNew $ elabTerm stxNew expectedType?
| _ => throwUnsupportedSyntax
@[builtin_macro Lean.Parser.Term.unreachable] def expandUnreachable : Macro := fun _ =>
`(panic! "unreachable code has been reached")
@[builtin_macro Lean.Parser.Term.assert] def expandAssert : Macro
| `(assert! $cond; $body) =>
-- TODO: support for disabling runtime assertions
match cond.raw.reprint with
| some code => `(if $cond then $body else panic! ("assertion violation: " ++ $(quote code)))
| none => `(if $cond then $body else panic! ("assertion violation"))
| _ => Macro.throwUnsupported
@[builtin_macro Lean.Parser.Term.dbgTrace] def expandDbgTrace : Macro
| `(dbg_trace $arg:interpolatedStr; $body) => `(dbgTrace (s! $arg) fun _ => $body)
| `(dbg_trace $arg:term; $body) => `(dbgTrace (toString $arg) fun _ => $body)
| _ => Macro.throwUnsupported
@[builtin_term_elab «sorry»] def elabSorry : TermElab := fun stx expectedType? => do
let stxNew ← `(sorryAx _ false)
withMacroExpansion stx stxNew <| elabTerm stxNew expectedType?
/-- Return syntax `Prod.mk elems[0] (Prod.mk elems[1] ... (Prod.mk elems[elems.size - 2] elems[elems.size - 1])))` -/
partial def mkPairs (elems : Array Term) : MacroM Term :=
let rec loop (i : Nat) (acc : Term) := do
if i > 0 then
let i := i - 1
let elem := elems[i]!
let acc ← `(Prod.mk $elem $acc)
loop i acc
else
pure acc
loop (elems.size - 1) elems.back
open Parser in
partial def hasCDot : Syntax → Bool
| Syntax.node _ k args =>
if k == ``Term.paren || k == ``Term.typeAscription || k == ``Term.tuple then false
else if k == ``Term.cdot then true
else args.any hasCDot
| _ => false
/--
Return `some` if succeeded expanding `·` notation occurring in
the given syntax. Otherwise, return `none`.
Examples:
- `· + 1` => `fun _a_1 => _a_1 + 1`
- `f · · b` => `fun _a_1 _a_2 => f _a_1 _a_2 b` -/
partial def expandCDot? (stx : Term) : MacroM (Option Term) := do
if hasCDot stx then
let (newStx, binders) ← (go stx).run #[]
`(fun $binders* => $(⟨newStx⟩))
else
pure none
where
/--
Auxiliary function for expanding the `·` notation.
The extra state `Array Syntax` contains the new binder names.
If `stx` is a `·`, we create a fresh identifier, store in the
extra state, and return it. Otherwise, we just return `stx`. -/
go : Syntax → StateT (Array Ident) MacroM Syntax
| stx@`(($(_))) => pure stx
| stx@`(·) => withFreshMacroScope do
let id ← mkFreshIdent stx (canonical := true)
modify (·.push id)
pure id
| stx => match stx with
| .node _ k args => do
let args ← args.mapM go
return .node (.fromRef stx (canonical := true)) k args
| _ => pure stx
/--
Helper method for elaborating terms such as `(.+.)` where a constant name is expected.
This method is usually used to implement tactics that function names as arguments (e.g., `simp`).
-/
def elabCDotFunctionAlias? (stx : Term) : TermElabM (Option Expr) := do
let some stx ← liftMacroM <| expandCDotArg? stx | pure none
let stx ← liftMacroM <| expandMacros stx
match stx with
| `(fun $binders* => $f $args*) =>
if binders == args then
try Term.resolveId? f catch _ => return none
else
return none
| `(fun $binders* => binop% $f $a $b) =>
if binders == #[a, b] then
try Term.resolveId? f catch _ => return none
else
return none
| _ => return none
where
expandCDotArg? (stx : Term) : MacroM (Option Term) :=
match stx with
| `(($e)) => Term.expandCDot? e
| _ => Term.expandCDot? stx
@[builtin_macro Lean.Parser.Term.paren] def expandParen : Macro
| `(($e)) => return (← expandCDot? e).getD e
| _ => Macro.throwUnsupported
@[builtin_macro Lean.Parser.Term.tuple] def expandTuple : Macro
| `(()) => ``(Unit.unit)
| `(($e, $es,*)) => do
let pairs ← mkPairs (#[e] ++ es)
return (← expandCDot? pairs).getD pairs
| _ => Macro.throwUnsupported
@[builtin_macro Lean.Parser.Term.typeAscription] def expandTypeAscription : Macro
| `(($e : $(type)?)) => do
match (← expandCDot? e) with
| some e => `(($e : $(type)?))
| none => Macro.throwUnsupported
| _ => Macro.throwUnsupported
@[builtin_term_elab typeAscription] def elabTypeAscription : TermElab
| `(($e : $type)), _ => do
let type ← withSynthesize (mayPostpone := true) <| elabType type
let e ← elabTerm e type
ensureHasType type e
| `(($e :)), expectedType? => do
let e ← withSynthesize (mayPostpone := false) <| elabTerm e none
ensureHasType expectedType? e
| _, _ => throwUnsupportedSyntax
/-- Return `true` if `lhs` is a free variable and `rhs` does not depend on it. -/
private def isSubstCandidate (lhs rhs : Expr) : MetaM Bool :=
if lhs.isFVar then
return !(← dependsOn rhs lhs.fvarId!)
else
return false
/--
Given an expression `e` that is the elaboration of `stx`, if `e` is a free variable, then return `k stx`.
Otherwise, return `(fun x => k x) e`
-/
private def withLocalIdentFor (stx : Term) (e : Expr) (k : Term → TermElabM Expr) : TermElabM Expr := do
if e.isFVar then
k stx
else
let id ← mkFreshUserName `h
let aux ← withLocalDeclD id (← inferType e) fun x => do mkLambdaFVars #[x] (← k (mkIdentFrom stx id))
return mkApp aux e
@[builtin_term_elab subst] def elabSubst : TermElab := fun stx expectedType? => do
let expectedType? ← tryPostponeIfHasMVars? expectedType?
match stx with
| `($heqStx ▸ $hStx) => do
synthesizeSyntheticMVars
let mut heq ← withSynthesize <| elabTerm heqStx none
let heqType ← inferType heq
let heqType ← instantiateMVars heqType
match (← Meta.matchEq? heqType) with
| none => throwError "invalid `▸` notation, argument{indentExpr heq}\nhas type{indentExpr heqType}\nequality expected"
| some (α, lhs, rhs) =>
let mut lhs := lhs
let mut rhs := rhs
let mkMotive (lhs typeWithLooseBVar : Expr) := do
withLocalDeclD (← mkFreshUserName `x) α fun x => do
withLocalDeclD (← mkFreshUserName `h) (← mkEq lhs x) fun h => do
mkLambdaFVars #[x, h] $ typeWithLooseBVar.instantiate1 x
match expectedType? with
| some expectedType =>
let mut expectedAbst ← kabstract expectedType rhs
unless expectedAbst.hasLooseBVars do
expectedAbst ← kabstract expectedType lhs
unless expectedAbst.hasLooseBVars do
throwError "invalid `▸` notation, expected result type of cast is {indentExpr expectedType}\nhowever, the equality {indentExpr heq}\nof type {indentExpr heqType}\ndoes not contain the expected result type on either the left or the right hand side"
heq ← mkEqSymm heq
(lhs, rhs) := (rhs, lhs)
let hExpectedType := expectedAbst.instantiate1 lhs
let (h, badMotive?) ← withRef hStx do
let h ← elabTerm hStx hExpectedType
try
return (← ensureHasType hExpectedType h, none)
catch ex =>
-- if `rhs` occurs in `hType`, we try to apply `heq` to `h` too
let hType ← inferType h
let hTypeAbst ← kabstract hType rhs
unless hTypeAbst.hasLooseBVars do
throw ex
let hTypeNew := hTypeAbst.instantiate1 lhs
unless (← isDefEq hExpectedType hTypeNew) do
throw ex
let motive ← mkMotive rhs hTypeAbst
if !(← isTypeCorrect motive) then
return (h, some motive)
else
return (← mkEqRec motive h (← mkEqSymm heq), none)
let motive ← mkMotive lhs expectedAbst
if badMotive?.isSome || !(← isTypeCorrect motive) then
-- Before failing try tos use `subst`
if ← (isSubstCandidate lhs rhs <||> isSubstCandidate rhs lhs) then
withLocalIdentFor heqStx heq fun heqStx => do
let h ← instantiateMVars h
if h.hasMVar then
-- If `h` has metavariables, we try to elaborate `hStx` again after we substitute `heqStx`
-- Remark: re-elaborating `hStx` may be problematic if `hStx` contains the `lhs` of `heqStx` which will be eliminated by `subst`
let stxNew ← `(by subst $heqStx; exact $hStx)
withMacroExpansion stx stxNew (elabTerm stxNew expectedType)
else
withLocalIdentFor hStx h fun hStx => do
let stxNew ← `(by subst $heqStx; exact $hStx)
withMacroExpansion stx stxNew (elabTerm stxNew expectedType)
else
throwError "invalid `▸` notation, failed to compute motive for the substitution"
else
mkEqRec motive h heq
| none =>
let h ← elabTerm hStx none
let hType ← inferType h
let hTypeAbst ← kabstract hType lhs
let motive ← mkMotive lhs hTypeAbst
unless (← isTypeCorrect motive) do
throwError "invalid `▸` notation, failed to compute motive for the substitution"
mkEqRec motive h heq
| _ => throwUnsupportedSyntax
@[builtin_term_elab stateRefT] def elabStateRefT : TermElab := fun stx _ => do
let σ ← elabType stx[1]
let mut mStx := stx[2]
if mStx.getKind == ``Lean.Parser.Term.macroDollarArg then
mStx := mStx[1]
let m ← elabTerm mStx (← mkArrow (mkSort levelOne) (mkSort levelOne))
let ω ← mkFreshExprMVar (mkSort levelOne)
let stWorld ← mkAppM ``STWorld #[ω, m]
discard <| mkInstMVar stWorld
mkAppM ``StateRefT' #[ω, σ, m]
@[builtin_term_elab noindex] def elabNoindex : TermElab := fun stx expectedType? => do
let e ← elabTerm stx[1] expectedType?
return DiscrTree.mkNoindexAnnotation e
end Lean.Elab.Term
|
0a27aca85857d1dad9d35172b01022cb77617fc0 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Meta/Tactic/AuxLemma.lean | d95ac684de1ea118a7e9e49f8be7b96686efc8c4 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 1,558 | 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.Basic
namespace Lean.Meta
structure AuxLemmas where
idx : Nat := 1
lemmas : PHashMap Expr (Name × List Name) := {}
deriving Inhabited
builtin_initialize auxLemmasExt : EnvExtension AuxLemmas ← registerEnvExtension (pure {})
/--
Helper method for creating auxiliary lemmas in the environment.
It uses a cache that maps `type` to declaration name. The cache is not stored in `.olean` files.
It is useful to make sure the same auxiliary lemma is not created over and over again in the same file.
This method is useful for tactics (e.g., `simp`) that may perform preprocessing steps to lemmas provided by
users. For example, `simp` preprocessor may convert a lemma into multiple ones.
-/
def mkAuxLemma (levelParams : List Name) (type : Expr) (value : Expr) : MetaM Name := do
let env ← getEnv
let s := auxLemmasExt.getState env
let mkNewAuxLemma := do
let auxName := Name.mkNum (env.mainModule ++ `_auxLemma) s.idx
addDecl <| Declaration.thmDecl {
name := auxName
levelParams, type, value
}
modifyEnv fun env => auxLemmasExt.modifyState env fun ⟨idx, lemmas⟩ => ⟨idx + 1, lemmas.insert type (auxName, levelParams)⟩
return auxName
match s.lemmas.find? type with
| some (name, levelParams') => if levelParams == levelParams' then return name else mkNewAuxLemma
| none => mkNewAuxLemma
end Lean.Meta
|
2dff021e6408ae2547403175cb6b0ce4b4584a67 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /stage0/src/Lean/Meta/PPGoal.lean | ea9a8fcb827a25ea0a95d0856e6eefeb3b695bef | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | EdAyers/lean4 | 57ac632d6b0789cb91fab2170e8c9e40441221bd | 37ba0df5841bde51dbc2329da81ac23d4f6a4de4 | refs/heads/master | 1,676,463,245,298 | 1,660,619,433,000 | 1,660,619,433,000 | 183,433,437 | 1 | 0 | Apache-2.0 | 1,657,612,672,000 | 1,556,196,574,000 | Lean | UTF-8 | Lean | false | false | 11,679 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
import Lean.Meta.InferType
import Lean.Meta.MatchUtil
namespace Lean.Meta
register_builtin_option pp.auxDecls : Bool := {
defValue := false
group := "pp"
descr := "display auxiliary declarations used to compile recursive functions"
}
register_builtin_option pp.inaccessibleNames : Bool := {
defValue := false
group := "pp"
descr := "display inaccessible declarations in the local context"
}
register_builtin_option pp.showLetValues : Bool := {
defValue := false
group := "pp"
descr := "display let-declaration values in the info view"
}
def withPPInaccessibleNamesImp (flag : Bool) (x : MetaM α) : MetaM α :=
withTheReader Core.Context (fun ctx => { ctx with options := pp.inaccessibleNames.setIfNotSet ctx.options flag }) x
def withPPInaccessibleNames [MonadControlT MetaM m] [Monad m] (x : m α) (flag := true) : m α :=
mapMetaM (withPPInaccessibleNamesImp flag) x
def withPPShowLetValuesImp (flag : Bool) (x : MetaM α) : MetaM α :=
withTheReader Core.Context (fun ctx => { ctx with options := pp.showLetValues.setIfNotSet ctx.options flag }) x
def withPPShowLetValues [MonadControlT MetaM m] [Monad m] (x : m α) (flag := true) : m α :=
mapMetaM (withPPShowLetValuesImp flag) x
/--
Set pretty-printing options (`pp.showLetValues = true` and `pp.inaccessibleNames = true`) for visualizing goals.
-/
def withPPForTacticGoal [MonadControlT MetaM m] [Monad m] (x : m α) : m α :=
withPPShowLetValues <| withPPInaccessibleNames x
namespace ToHide
structure State where
/-- FVarIds of Propostions with inaccessible names but containing only visible names. We show only their types -/
hiddenInaccessibleProp : FVarIdSet := {}
/-- FVarIds with inaccessible names, but not in hiddenInaccessibleProp -/
hiddenInaccessible : FVarIdSet := {}
modified : Bool := false
structure Context where
/--
If true we make a declaration "visible" if it has visible backward dependencies.
Remark: recall that for the `Prop` case, the declaration is moved to `hiddenInaccessibleProp`
-/
backwardDeps : Bool
goalTarget : Expr
showLetValues : Bool
abbrev M := ReaderT Context $ StateRefT State MetaM
/-- Return true if `fvarId` is marked as an hidden inaccessible or inaccessible proposition -/
def isMarked (fvarId : FVarId) : M Bool := do
let s ← get
return s.hiddenInaccessible.contains fvarId || s.hiddenInaccessibleProp.contains fvarId
/-- If `fvarId` isMarked, then unmark it. -/
def unmark (fvarId : FVarId) : M Unit := do
modify fun s => {
hiddenInaccessible := s.hiddenInaccessible.erase fvarId
hiddenInaccessibleProp := s.hiddenInaccessibleProp.erase fvarId
modified := true
}
def moveToHiddeProp (fvarId : FVarId) : M Unit := do
modify fun s => {
hiddenInaccessible := s.hiddenInaccessible.erase fvarId
hiddenInaccessibleProp := s.hiddenInaccessibleProp.insert fvarId
modified := true
}
/-- Similar to `findLocalDeclDependsOn`, but it only considers `let`-values if `showLetValues = true` -/
private def findDeps (localDecl : LocalDecl) (f : FVarId → Bool) : M Bool := do
if (← read).showLetValues then
findLocalDeclDependsOn localDecl f
else
findExprDependsOn localDecl.type f
/-- Return true if the given local declaration has a "visible dependency", that is, it contains
a free variable that is `hiddenInaccessible`
Recall that hiddenInaccessibleProps are visible, only their names are hidden -/
def hasVisibleDep (localDecl : LocalDecl) : M Bool := do
let s ← get
findDeps localDecl (!s.hiddenInaccessible.contains ·)
/-- Return true if the given local declaration has a "nonvisible dependency", that is, it contains
a free variable that is `hiddenInaccessible` or `hiddenInaccessibleProp` -/
def hasInaccessibleNameDep (localDecl : LocalDecl) : M Bool := do
let s ← get
findDeps localDecl fun fvarId =>
s.hiddenInaccessible.contains fvarId || s.hiddenInaccessibleProp.contains fvarId
/-- If `e` is visible, then any inaccessible in `e` marked as hidden should be unmarked. -/
partial def visitVisibleExpr (e : Expr) : M Unit := do
visit (← instantiateMVars e) |>.run
where
visit (e : Expr) : MonadCacheT Expr Unit M Unit := do
if e.hasFVar then
checkCache e fun _ => do
match e with
| .forallE _ d b _ => visit d; visit b
| .lam _ d b _ => visit d; visit b
| .letE _ t v b _ => visit t; visit v; visit b
| .app f a => visit f; visit a
| .mdata _ b => visit b
| .proj _ _ b => visit b
| .fvar fvarId => if (← isMarked fvarId) then unmark fvarId
| _ => return ()
def fixpointStep : M Unit := do
visitVisibleExpr (← read).goalTarget -- The goal target is a visible forward dependency
(← getLCtx).forM fun localDecl => do
let fvarId := localDecl.fvarId
if (← get).hiddenInaccessible.contains fvarId then
if (← read).backwardDeps then
if (← hasVisibleDep localDecl) then
/- localDecl is marked to be hidden, but it has a (backward) visible dependency. -/
unmark fvarId
if (← isProp localDecl.type) then
unless (← hasInaccessibleNameDep localDecl) do
moveToHiddeProp fvarId
else
visitVisibleExpr localDecl.type
if (← read).showLetValues then
let some value := localDecl.value? | return ()
visitVisibleExpr value
partial def fixpoint : M Unit := do
modify fun s => { s with modified := false }
fixpointStep
if (← get).modified then
fixpoint
/--
Construct initial `FVarIdSet` containting free variables ids that have inaccessible user names.
-/
private def getInitialHiddenInaccessible (propOnly : Bool) : MetaM FVarIdSet := do
let mut r := {}
for localDecl in (← getLCtx) do
if localDecl.userName.isInaccessibleUserName then
if (← pure !propOnly <||> isProp localDecl.type) then
r := r.insert localDecl.fvarId
return r
/--
If `pp.inaccessibleNames == false`, then collect two sets of `FVarId`s : `hiddenInaccessible` and `hiddenInaccessibleProp`
1- `hiddenInaccessible` contains `FVarId`s of free variables with inaccessible names that
a) are not propositions or
b) are propositions containing "visible" names.
2- `hiddenInaccessibleProp` contains `FVarId`s of free variables with inaccessible names that are propositions
containing "visible" names.
Both sets do not contain `FVarId`s that contain visible backward or forward dependencies.
The `goalTarget` counts as a forward dependency.
We say a name is visible if it is a free variable with FVarId not in `hiddenInaccessible` nor `hiddenInaccessibleProp`
For propositions in `hiddenInaccessibleProp`, we show only their types when displaying a goal.
Remark: when `pp.inaccessibleNames == true`, we still compute `hiddenInaccessibleProp` to prevent the
goal from being littered with irrelevant names.
-/
def collect (goalTarget : Expr) : MetaM (FVarIdSet × FVarIdSet) := do
let showLetValues := pp.showLetValues.get (← getOptions)
if pp.inaccessibleNames.get (← getOptions) then
-- If `pp.inaccessibleNames == true`, we still must compute `hiddenInaccessibleProp`.
let hiddenInaccessible ← getInitialHiddenInaccessible (propOnly := true)
let (_, s) ← fixpoint.run { backwardDeps := false, goalTarget, showLetValues } |>.run { hiddenInaccessible }
return ({}, s.hiddenInaccessible)
else
let hiddenInaccessible ← getInitialHiddenInaccessible (propOnly := false)
let (_, s) ← fixpoint.run { backwardDeps := true, goalTarget, showLetValues } |>.run { hiddenInaccessible }
return (s.hiddenInaccessible, s.hiddenInaccessibleProp)
end ToHide
private def addLine (fmt : Format) : Format :=
if fmt.isNil then fmt else fmt ++ Format.line
def getGoalPrefix (mvarDecl : MetavarDecl) : String :=
if isLHSGoal? mvarDecl.type |>.isSome then
-- use special prefix for `conv` goals
"| "
else
"⊢ "
def ppGoal (mvarId : MVarId) : MetaM Format := do
match (← getMCtx).findDecl? mvarId with
| none => return "unknown goal"
| some mvarDecl =>
let indent := 2 -- Use option
let showLetValues := pp.showLetValues.get (← getOptions)
let ppAuxDecls := pp.auxDecls.get (← getOptions)
let lctx := mvarDecl.lctx
let lctx := lctx.sanitizeNames.run' { options := (← getOptions) }
withLCtx lctx mvarDecl.localInstances do
let (hidden, hiddenProp) ← ToHide.collect mvarDecl.type
-- The followint two `let rec`s are being used to control the generated code size.
-- Then should be remove after we rewrite the compiler in Lean
let rec pushPending (ids : List Name) (type? : Option Expr) (fmt : Format) : MetaM Format := do
if ids.isEmpty then
return fmt
else
let fmt := addLine fmt
match type? with
| none => return fmt
| some type =>
let typeFmt ← ppExpr type
return fmt ++ (Format.joinSep ids.reverse (format " ") ++ " :" ++ Format.nest indent (Format.line ++ typeFmt)).group
let rec ppVars (varNames : List Name) (prevType? : Option Expr) (fmt : Format) (localDecl : LocalDecl) : MetaM (List Name × Option Expr × Format) := do
if hiddenProp.contains localDecl.fvarId then
let fmt ← pushPending varNames prevType? fmt
let fmt := addLine fmt
let type ← instantiateMVars localDecl.type
let typeFmt ← ppExpr type
let fmt := fmt ++ ": " ++ typeFmt
return ([], none, fmt)
else
match localDecl with
| .cdecl _ _ varName type _ =>
let varName := varName.simpMacroScopes
let type ← instantiateMVars type
if prevType? == none || prevType? == some type then
return (varName :: varNames, some type, fmt)
else do
let fmt ← pushPending varNames prevType? fmt
return ([varName], some type, fmt)
| .ldecl _ _ varName type val _ => do
let varName := varName.simpMacroScopes
let fmt ← pushPending varNames prevType? fmt
let fmt := addLine fmt
let type ← instantiateMVars type
let typeFmt ← ppExpr type
let mut fmtElem := format varName ++ " : " ++ typeFmt
if showLetValues then
let val ← instantiateMVars val
let valFmt ← ppExpr val
fmtElem := fmtElem ++ " :=" ++ Format.nest indent (Format.line ++ valFmt)
let fmt := fmt ++ fmtElem.group
return ([], none, fmt)
let (varNames, type?, fmt) ← lctx.foldlM (init := ([], none, Format.nil)) fun (varNames, prevType?, fmt) (localDecl : LocalDecl) =>
if !ppAuxDecls && localDecl.isAuxDecl || hidden.contains localDecl.fvarId then
return (varNames, prevType?, fmt)
else
ppVars varNames prevType? fmt localDecl
let fmt ← pushPending varNames type? fmt
let fmt := addLine fmt
let typeFmt ← ppExpr (← instantiateMVars mvarDecl.type)
let fmt := fmt ++ getGoalPrefix mvarDecl ++ Format.nest indent typeFmt
match mvarDecl.userName with
| Name.anonymous => return fmt
| name => return "case " ++ format name.eraseMacroScopes ++ Format.line ++ fmt
end Lean.Meta
|
f3a3e8c445378fb637d467ef6a1c63686d89174a | d5ecf6c46a2f605470a4a7724909dc4b9e7350e0 | /linear_algebra/multivariate_polynomial.lean | f84c0ad84fdf5884aa7ef5d1e1f0eab247462d27 | [
"Apache-2.0"
] | permissive | MonoidMusician/mathlib | 41f79df478987a636b735c338396813d2e8e44c4 | 72234ef1a050eea3a2197c23aeb345fc13c08ff3 | refs/heads/master | 1,583,672,205,771 | 1,522,892,143,000 | 1,522,892,143,000 | 128,144,032 | 0 | 0 | Apache-2.0 | 1,522,892,144,000 | 1,522,890,892,000 | Lean | UTF-8 | Lean | false | false | 9,544 | 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
Multivariate Polynomial
-/
import data.finsupp linear_algebra.basic
noncomputable theory
open classical set function finsupp lattice
local attribute [instance] classical.prop_decidable
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
instance {α : Type u} [semilattice_sup α] : is_idempotent α (⊔) := ⟨assume a, sup_idem⟩
namespace finset
variables [semilattice_sup_bot α]
/-- Supremum of a finite set: `sup {a, b, c} f = f a ⊔ f b ⊔ f c` -/
def sup (s : finset β) (f : β → α) : α := s.fold (⊔) ⊥ f
variables {s s₁ s₂ : finset β} {f : β → α}
@[simp] lemma sup_empty : (∅ : finset β).sup f = ⊥ :=
fold_empty
@[simp] lemma sup_insert {b : β} : (insert b s : finset β).sup f = f b ⊔ s.sup f :=
fold_insert_idem
@[simp] lemma sup_singleton {b : β} : ({b} : finset β).sup f = f b :=
calc _ = f b ⊔ (∅:finset β).sup f : sup_insert
... = f b : by simp
lemma sup_union : (s₁ ∪ s₂).sup f = s₁.sup f ⊔ s₂.sup f :=
finset.induction_on s₁ (by simp) (by simp {contextual := tt}; cc)
lemma sup_mono_fun {g : β → α} : (∀b∈s, f b ≤ g b) → s.sup f ≤ s.sup g :=
finset.induction_on s (by simp) (by simp [-sup_le_iff, sup_le_sup] {contextual := tt})
lemma le_sup {b : β} (hb : b ∈ s) : f b ≤ s.sup f :=
calc f b ≤ f b ⊔ s.sup f : le_sup_left
... = (insert b s).sup f : by simp
... = s.sup f : by simp [hb]
lemma sup_le {a : α} : (∀b ∈ s, f b ≤ a) → s.sup f ≤ a :=
finset.induction_on s (by simp) (by simp {contextual := tt})
lemma sup_mono (h : s₁ ⊆ s₂) : s₁.sup f ≤ s₂.sup f :=
sup_le $ assume b hb, le_sup (subset_iff.mpr h hb)
end finset
instance nat.distrib_lattice : distrib_lattice ℕ :=
by apply_instance
instance nat.semilattice_sup_bot : semilattice_sup_bot ℕ :=
{ bot := 0, bot_le := nat.zero_le , .. nat.distrib_lattice }
@[simp] lemma finset.bind_singleton2 {a : α} {f : α → finset β} :
(finset.singleton a).bind f = f a :=
show (insert a ∅ : finset α).bind f = f a,
by simp
lemma finsupp.single_induction_on [add_monoid β] {p : (α →₀ β) → Prop} (f : α →₀ β)
(h_zero : p 0) (h_add : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (f + single a b)) :
p f :=
have ∀(s : finset α) (f : α →₀ β), s = f.support → p f,
from assume s, finset.induction_on s
(assume f eq,
have 0 = f, from finsupp.ext $ by simp [finset.ext, *] at * {contextual := tt},
this ▸ h_zero)
(assume a s has ih f eq,
have a ∈ f.support, by rw [← eq]; simp,
have f.filter (λa', a' ≠ a) + single a (f a) = f,
from finsupp.ext $ assume a', by_cases
(assume h : a' = a, by simp [h])
(assume h : a' ≠ a, by simp [h, h.symm]),
begin
rw ← this,
apply h_add,
{ simp },
{ have : a ∈ f.support, { rw [← eq], simp },
simpa using this },
apply ih,
{ rw finset.ext, intro a',
by_cases a' = a; simp [h, has, -finsupp.mem_support_iff, eq.symm, support_filter] }
end),
this _ _ rfl
/-- Multivariate polynomial, where `σ` is the index set of the variables and
`α` is the coefficient ring -/
def mv_polynomial (σ : Type*) (α : Type*) [comm_semiring α] := (σ →₀ ℕ) →₀ α
namespace mv_polynomial
variables {σ : Type*} {a a' a₁ a₂ : α} {e : ℕ} {n m : σ} {s : σ →₀ ℕ}
section comm_semiring
variables [comm_semiring α] {p q : mv_polynomial σ α}
instance : has_zero (mv_polynomial σ α) := finsupp.has_zero
instance : has_one (mv_polynomial σ α) := finsupp.has_one
instance : has_add (mv_polynomial σ α) := finsupp.has_add
instance : has_mul (mv_polynomial σ α) := finsupp.has_mul
instance : comm_semiring (mv_polynomial σ α) := finsupp.to_comm_semiring
/-- `monomial s a` is the monomial `a * X^s` -/
def monomial (s : σ →₀ ℕ) (a : α) : mv_polynomial σ α := single s a
/-- `C a` is the constant polynomial with value `a` -/
def C (a : α) : mv_polynomial σ α := monomial 0 a
/-- `X n` is the polynomial with value X_n -/
def X (n : σ) : mv_polynomial σ α := monomial (single n 1) 1
@[simp] lemma C_0 : C 0 = (0 : mv_polynomial σ α) := by simp [C, monomial]; refl
@[simp] lemma C_1 : C 1 = (1 : mv_polynomial σ α) := rfl
@[simp] lemma C_mul_monomial : C a * monomial s a' = monomial s (a * a') :=
by simp [C, monomial, single_mul_single]
lemma X_pow_eq_single : X n ^ e = monomial (single n e) (1 : α) :=
begin
induction e,
{ simp [X], refl },
{ simp [pow_succ, e_ih],
simp [X, monomial, single_mul_single, nat.succ_eq_add_one] }
end
lemma monomial_add_single : monomial (s + single n e) a = (monomial s a * X n ^ e):=
by rw [X_pow_eq_single, monomial, monomial, monomial, single_mul_single]; simp
lemma monomial_single_add : monomial (single n e + s) a = (X n ^ e * monomial s a):=
by rw [X_pow_eq_single, monomial, monomial, monomial, single_mul_single]; simp
lemma monomial_eq : monomial s a = C a * (s.prod $ λn e, X n ^ e : mv_polynomial σ α) :=
begin
apply @finsupp.single_induction_on σ ℕ _ _ s,
{ simp [C, prod_zero_index]; exact (mul_one _).symm },
{ assume n e s hns he ih,
simp [prod_add_index, prod_single_index, pow_zero, pow_add, (mul_assoc _ _ _).symm, ih.symm,
monomial_add_single] }
end
@[recursor 5]
lemma induction_on {M : mv_polynomial σ α → Prop} (p : mv_polynomial σ α)
(h_C : ∀a, M (C a)) (h_add : ∀p q, M p → M q → M (p + q)) (h_X : ∀p n, M p → M (p * X n)) :
M p :=
have ∀s a, M (monomial s a),
begin
assume s a,
apply @finsupp.single_induction_on σ ℕ _ _ s,
{ show M (monomial 0 a), from h_C a, },
{ assume n e p hpn he ih,
have : ∀e, M (monomial p a * X n ^ e),
{ intro e,
induction e,
{ simp [ih] },
{ simp [ih, pow_succ', (mul_assoc _ _ _).symm, h_X, e_ih] } },
simp [monomial_add_single, this] }
end,
finsupp.single_induction_on p
(by have : M (C 0) := h_C 0; rwa [C_0] at this)
(assume s a p hsp ha hp, h_add _ _ hp (this s a))
section eval
variables {f : σ → α}
/-- Evaluate a polynomial `p` given a valuation `f` of all the variables -/
def eval (p : mv_polynomial σ α) (f : σ → α) : α :=
p.sum (λs a, a * s.prod (λn e, f n ^ e))
@[simp] lemma eval_zero : (0 : mv_polynomial σ α).eval f = 0 :=
finsupp.sum_zero_index
lemma eval_add : (p + q).eval f = p.eval f + q.eval f :=
finsupp.sum_add_index (by simp) (by simp [add_mul])
lemma eval_monomial : (monomial s a).eval f = a * s.prod (λn e, f n ^ e) :=
finsupp.sum_single_index (zero_mul _)
@[simp] lemma eval_C : (C a).eval f = a :=
by simp [eval_monomial, C, prod_zero_index]
@[simp] lemma eval_X : (X n).eval f = f n :=
by simp [eval_monomial, X, prod_single_index, pow_one]
lemma eval_mul_monomial :
∀{s a}, (p * monomial s a).eval f = p.eval f * a * s.prod (λn e, f n ^ e) :=
begin
apply mv_polynomial.induction_on p,
{ assume a' s a, by simp [C_mul_monomial, eval_monomial] },
{ assume p q ih_p ih_q, simp [add_mul, eval_add, ih_p, ih_q] },
{ assume p n ih s a,
from calc eval (p * X n * monomial s a) f = eval (p * monomial (single n 1 + s) a) f :
by simp [monomial_single_add, -add_comm, pow_one, mul_assoc]
... = eval (p * monomial (single n 1) 1) f * a * s.prod (λn e, f n ^ e) :
by simp [ih, prod_single_index, prod_add_index, pow_one, pow_add, mul_assoc, mul_left_comm,
-add_comm] }
end
lemma eval_mul : ∀{p}, (p * q).eval f = p.eval f * q.eval f :=
begin
apply mv_polynomial.induction_on q,
{ simp [C, eval_monomial, eval_mul_monomial, prod_zero_index] },
{ simp [mul_add, eval_add] {contextual := tt} },
{ simp [X, eval_monomial, eval_mul_monomial, (mul_assoc _ _ _).symm] { contextual := tt} }
end
end eval
section vars
/-- `vars p` is the set of variables appearing in the polynomial `p` -/
def vars (p : mv_polynomial σ α) : finset σ := p.support.bind finsupp.support
@[simp] lemma vars_0 : (0 : mv_polynomial σ α).vars = ∅ :=
show (0 : (σ →₀ ℕ) →₀ α).support.bind finsupp.support = ∅, by simp
@[simp] lemma vars_monomial (h : a ≠ 0) : (monomial s a).vars = s.support :=
show (single s a : (σ →₀ ℕ) →₀ α).support.bind finsupp.support = s.support,
by simp [support_single_ne_zero, h]
@[simp] lemma vars_C : (C a : mv_polynomial σ α).vars = ∅ :=
by_cases
(assume h : a = 0, by simp [h])
(assume h : a ≠ 0, by simp [C, h])
@[simp] lemma vars_X (h : 0 ≠ (1 : α)) : (X n : mv_polynomial σ α).vars = {n} :=
calc (X n : mv_polynomial σ α).vars = (single n 1).support : vars_monomial h.symm
... = {n} : by rw [support_single_ne_zero nat.zero_ne_one.symm]
end vars
section degree_of
/-- `degree_of n p` gives the highest power of X_n that appears in `p` -/
def degree_of (n : σ) (p : mv_polynomial σ α) : ℕ := p.support.sup (λs, s n)
end degree_of
section total_degree
/-- `total_degree p` gives the maximum |s| over the monomials X^s in `p` -/
def total_degree (p : mv_polynomial σ α) : ℕ := p.support.sup (λs, s.sum $ λn e, e)
end total_degree
end comm_semiring
section comm_ring
variable [comm_ring α]
instance : ring (mv_polynomial σ α) := finsupp.to_ring
instance : has_scalar α (mv_polynomial σ α) := finsupp.to_has_scalar
instance : module α (mv_polynomial σ α) := finsupp.to_module
end comm_ring
end mv_polynomial
|
5223fd98dc4efa76bb8520fbadd1971bfeb8e16e | d7189ea2ef694124821b033e533f18905b5e87ef | /galois/list/fpow.lean | 38df8246835ba0d8beb80a11244c6977d641b47c | [
"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 | 3,939 | lean | -- Kuratowski-finite powerset
import .preds
galois.tactic
universes u
section
parameter {A : Type u}
def incl_elements (xs ys : list A) : Prop :=
∀ x : A, x ∈ xs → x ∈ ys
def same_elements (xs ys : list A) : Prop :=
∀ x : A, x ∈ xs ↔ x ∈ ys
def incl_same {xs ys : list A}
(H : incl_elements xs ys) (H' : incl_elements ys xs)
: same_elements xs ys
:= begin
intros z, split, apply H, apply H'
end
lemma incl_elements_refl (xs : list A) : incl_elements xs xs
:= begin
intros x H, apply H
end
lemma incl_elements_trans {xs ys zs : list A}
(H : incl_elements xs ys) (H' : incl_elements ys zs)
: incl_elements xs zs
:= begin
intros x H'', apply H', apply H, assumption,
end
lemma incl_elements_app {xs ys xs' ys' : list A}
(H : incl_elements xs xs') (H' : incl_elements ys ys')
: incl_elements (xs ++ ys) (xs' ++ ys')
:= begin
intros z X, rw list.mem_append, rw list.mem_append at X,
induction X with X X,
left, apply H, assumption,
right, apply H', assumption
end
lemma same_elements_app_comm {xs ys : list A}
: same_elements (xs ++ ys) (ys ++ xs)
:= begin
intros z, repeat {rw list.mem_append},
rw or_comm,
end
lemma same_elements_refl (xs : list A) : same_elements xs xs
:= begin
dsimp [same_elements], intros, trivial,
end
lemma same_elements_trans {xs ys zs : list A}
(H : same_elements xs ys) (H' : same_elements ys zs)
: same_elements xs zs
:= begin
dsimp [same_elements],
intros, rw H, rw H',
end
lemma same_elements_symm {xs ys : list A}
(H : same_elements xs ys)
: same_elements ys xs
:= begin
dsimp [same_elements] at *,
intros, rw H,
end
def same_incl1 {xs ys : list A}
(H : same_elements xs ys)
: incl_elements xs ys
:= begin
intros z,
destruct (H z), intros, apply mp, assumption
end
def same_incl2 {xs ys : list A}
(H : same_elements xs ys)
: incl_elements ys xs
:= begin
intros z,
destruct (H z), intros, apply mpr, assumption
end
def same_incl {xs ys : list A}
(H : same_elements xs ys)
: incl_elements xs ys ∧ incl_elements ys xs
:= begin
split, apply (same_incl1 H), apply (same_incl2 H)
end
lemma same_elements_app {xs ys xs' ys' : list A}
(H : same_elements xs xs') (H' : same_elements ys ys')
: same_elements (xs ++ ys) (xs' ++ ys')
:= begin
apply incl_same,
apply incl_elements_app; apply same_incl1; assumption,
apply incl_elements_app; apply same_incl2; assumption,
end
def cons_mono {x y : A} {xs ys : list A}
(Hhd : x = y)
(Htl : incl_elements xs ys)
: incl_elements (x :: xs) (y :: ys)
:= begin
induction Hhd,
intros z Hz, simp [has_mem.mem, list.mem] at Hz,
induction Hz, induction a, simp [has_mem.mem, list.mem],
simp [has_mem.mem, list.mem],
right, apply Htl, assumption
end
def cons_same {x y : A} {xs ys : list A}
(Hhd : x = y)
(Htl : same_elements xs ys)
: same_elements (x :: xs) (y :: ys)
:= begin
have Htl' := same_incl Htl, clear Htl,
induction Htl' with Htl1 Htl2,
apply incl_same; apply cons_mono, assumption,
apply Htl1, symmetry, assumption, apply Htl2,
end
end
def fpow (A : Type u) := quot (@same_elements A)
namespace fpow
section
parameter {A : Type u}
def from_list : list A → fpow A := quot.mk _
def nil : fpow A := quot.mk _ []
def cons (x : A) (xs : fpow A) : fpow A :=
begin
fapply (quot.lift_on xs); clear xs,
exact (λ xs, quot.mk _ (x :: xs)),
intros xs ys Heq, apply quot.sound,
unfold same_elements,
intros z, apply cons_same, reflexivity, assumption
end
instance mem : has_mem A (fpow A) :=
begin
constructor, intros x xs,
fapply (quot.lift_on xs); clear xs,
exact (λ xs, x ∈ xs),
intros xs ys H, apply propext, apply H
end
end
end fpow
lemma same_elements_fpow {A} {xs ys : list A}
: same_elements xs ys ↔ fpow.from_list xs = fpow.from_list ys
:= begin
split; intros H,
apply quot.sound, assumption,
have H' := quot.exact _ H,
clear H,
induction H', assumption,
apply same_elements_refl,
apply same_elements_symm; assumption,
apply same_elements_trans; assumption,
end |
f5ae32eeeb27a3a64e11696bb8e88931d760cd9a | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/order/monoid/with_zero/defs.lean | c0f6c4b9aa3b96d6fced72043d5dc5e422a5fb58 | [
"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 | 9,545 | 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.group.with_one.defs
import algebra.order.monoid.canonical.defs
/-!
# Adjoining a zero element to an ordered monoid.
-/
set_option old_structure_cmd true
open function
universe u
variables {α : Type u}
/-- Typeclass for expressing that the `0` of a type is less or equal to its `1`. -/
class zero_le_one_class (α : Type*) [has_zero α] [has_one α] [has_le α] :=
(zero_le_one : (0 : α) ≤ 1)
/-- A linearly ordered commutative monoid with a zero element. -/
class linear_ordered_comm_monoid_with_zero (α : Type*)
extends linear_ordered_comm_monoid α, comm_monoid_with_zero α :=
(zero_le_one : (0 : α) ≤ 1)
@[priority 100]
instance linear_ordered_comm_monoid_with_zero.to_zero_le_one_class
[linear_ordered_comm_monoid_with_zero α] : zero_le_one_class α :=
{ ..‹linear_ordered_comm_monoid_with_zero α› }
@[priority 100]
instance canonically_ordered_add_monoid.to_zero_le_one_class [canonically_ordered_add_monoid α]
[has_one α] : zero_le_one_class α :=
⟨zero_le 1⟩
/-- `zero_le_one` with the type argument implicit. -/
@[simp] lemma zero_le_one [has_zero α] [has_one α] [has_le α] [zero_le_one_class α] : (0 : α) ≤ 1 :=
zero_le_one_class.zero_le_one
/-- `zero_le_one` with the type argument explicit. -/
lemma zero_le_one' (α) [has_zero α] [has_one α] [has_le α] [zero_le_one_class α] : (0 : α) ≤ 1 :=
zero_le_one
lemma zero_le_two [preorder α] [has_one α] [add_zero_class α] [zero_le_one_class α]
[covariant_class α α (+) (≤)] : (0 : α) ≤ 2 :=
add_nonneg zero_le_one zero_le_one
lemma zero_le_three [preorder α] [has_one α] [add_zero_class α] [zero_le_one_class α]
[covariant_class α α (+) (≤)] : (0 : α) ≤ 3 :=
add_nonneg zero_le_two zero_le_one
lemma zero_le_four [preorder α] [has_one α] [add_zero_class α] [zero_le_one_class α]
[covariant_class α α (+) (≤)] : (0 : α) ≤ 4 :=
add_nonneg zero_le_two zero_le_two
lemma one_le_two [has_le α] [has_one α] [add_zero_class α] [zero_le_one_class α]
[covariant_class α α (+) (≤)] : (1 : α) ≤ 2 :=
calc 1 = 1 + 0 : (add_zero 1).symm
... ≤ 1 + 1 : add_le_add_left zero_le_one _
lemma one_le_two' [has_le α] [has_one α] [add_zero_class α] [zero_le_one_class α]
[covariant_class α α (swap (+)) (≤)] : (1 : α) ≤ 2 :=
calc 1 = 0 + 1 : (zero_add 1).symm
... ≤ 1 + 1 : add_le_add_right zero_le_one _
section
variables [has_zero α] [has_one α] [partial_order α] [zero_le_one_class α] [ne_zero (1 : α)]
/-- See `zero_lt_one'` for a version with the type explicit. -/
@[simp] lemma zero_lt_one : (0 : α) < 1 := zero_le_one.lt_of_ne (ne_zero.ne' 1)
variables (α)
/-- See `zero_lt_one` for a version with the type implicit. -/
lemma zero_lt_one' : (0 : α) < 1 := zero_lt_one
end
section
variables [has_one α] [add_zero_class α] [partial_order α] [zero_le_one_class α] [ne_zero (1 : α)]
section
variables [covariant_class α α (+) (≤)]
/-- See `zero_lt_two'` for a version with the type explicit. -/
@[simp] lemma zero_lt_two : (0 : α) < 2 := zero_lt_one.trans_le one_le_two
/-- See `zero_lt_three'` for a version with the type explicit. -/
@[simp] lemma zero_lt_three : (0 : α) < 3 := lt_add_of_lt_of_nonneg zero_lt_two zero_le_one
/-- See `zero_lt_four'` for a version with the type explicit. -/
@[simp] lemma zero_lt_four : (0 : α) < 4 := lt_add_of_lt_of_nonneg zero_lt_two zero_le_two
variables (α)
/-- See `zero_lt_two` for a version with the type implicit. -/
lemma zero_lt_two' : (0 : α) < 2 := zero_lt_two
/-- See `zero_lt_three` for a version with the type implicit. -/
lemma zero_lt_three' : (0 : α) < 3 := zero_lt_three
/-- See `zero_lt_four` for a version with the type implicit. -/
lemma zero_lt_four' : (0 : α) < 4 := zero_lt_four
instance zero_le_one_class.ne_zero.two : ne_zero (2 : α) := ⟨zero_lt_two.ne'⟩
instance zero_le_one_class.ne_zero.three : ne_zero (3 : α) := ⟨zero_lt_three.ne'⟩
instance zero_le_one_class.ne_zero.four : ne_zero (4 : α) := ⟨zero_lt_four.ne'⟩
end
lemma lt_add_one [covariant_class α α (+) (<)] (a : α) : a < a + 1 :=
lt_add_of_pos_right _ zero_lt_one
lemma lt_one_add [covariant_class α α (swap (+)) (<)] (a : α) : a < 1 + a :=
lt_add_of_pos_left _ zero_lt_one
lemma one_lt_two [covariant_class α α (+) (<)] : (1 : α) < 2 := lt_add_one _
end
alias zero_lt_one ← one_pos
alias zero_lt_two ← two_pos
alias zero_lt_three ← three_pos
alias zero_lt_four ← four_pos
namespace with_zero
local attribute [semireducible] with_zero
instance [preorder α] : preorder (with_zero α) := with_bot.preorder
instance [partial_order α] : partial_order (with_zero α) := with_bot.partial_order
instance [preorder α] : order_bot (with_zero α) := with_bot.order_bot
lemma zero_le [preorder α] (a : with_zero α) : 0 ≤ a := bot_le
lemma zero_lt_coe [preorder α] (a : α) : (0 : with_zero α) < a := with_bot.bot_lt_coe a
lemma zero_eq_bot [preorder α] : (0 : with_zero α) = ⊥ := rfl
@[simp, norm_cast] lemma coe_lt_coe [preorder α] {a b : α} : (a : with_zero α) < b ↔ a < b :=
with_bot.coe_lt_coe
@[simp, norm_cast] lemma coe_le_coe [preorder α] {a b : α} : (a : with_zero α) ≤ b ↔ a ≤ b :=
with_bot.coe_le_coe
instance [lattice α] : lattice (with_zero α) := with_bot.lattice
instance [linear_order α] : linear_order (with_zero α) := with_bot.linear_order
instance covariant_class_mul_le {α : Type u} [has_mul α] [preorder α]
[covariant_class α α (*) (≤)] :
covariant_class (with_zero α) (with_zero α) (*) (≤) :=
begin
refine ⟨λ a b c hbc, _⟩,
induction a using with_zero.rec_zero_coe, { exact zero_le _ },
induction b using with_zero.rec_zero_coe, { exact zero_le _ },
rcases with_bot.coe_le_iff.1 hbc with ⟨c, rfl, hbc'⟩,
rw [← coe_mul, ← coe_mul, coe_le_coe],
exact mul_le_mul_left' hbc' a
end
@[simp] lemma le_max_iff [linear_order α] {a b c : α} :
(a : with_zero α) ≤ max b c ↔ a ≤ max b c :=
by simp only [with_zero.coe_le_coe, le_max_iff]
@[simp] lemma min_le_iff [linear_order α] {a b c : α} :
min (a : with_zero α) b ≤ c ↔ min a b ≤ c :=
by simp only [with_zero.coe_le_coe, min_le_iff]
instance [ordered_comm_monoid α] : ordered_comm_monoid (with_zero α) :=
{ mul_le_mul_left := λ _ _, mul_le_mul_left',
..with_zero.comm_monoid_with_zero,
..with_zero.partial_order }
protected lemma covariant_class_add_le [add_zero_class α] [preorder α]
[covariant_class α α (+) (≤)] (h : ∀ a : α, 0 ≤ a) :
covariant_class (with_zero α) (with_zero α) (+) (≤) :=
begin
refine ⟨λ a b c hbc, _⟩,
induction a using with_zero.rec_zero_coe,
{ rwa [zero_add, zero_add] },
induction b using with_zero.rec_zero_coe,
{ rw [add_zero],
induction c using with_zero.rec_zero_coe,
{ rw [add_zero], exact le_rfl },
{ rw [← coe_add, coe_le_coe],
exact le_add_of_nonneg_right (h _) } },
{ rcases with_bot.coe_le_iff.1 hbc with ⟨c, rfl, hbc'⟩,
rw [← coe_add, ← coe_add, coe_le_coe],
exact add_le_add_left hbc' a }
end
/-
Note 1 : the below is not an instance because it requires `zero_le`. It seems
like a rather pathological definition because α already has a zero.
Note 2 : there is no multiplicative analogue because it does not seem necessary.
Mathematicians might be more likely to use the order-dual version, where all
elements are ≤ 1 and then 1 is the top element.
-/
/--
If `0` is the least element in `α`, then `with_zero α` is an `ordered_add_comm_monoid`.
See note [reducible non-instances].
-/
@[reducible] protected def ordered_add_comm_monoid [ordered_add_comm_monoid α]
(zero_le : ∀ a : α, 0 ≤ a) : ordered_add_comm_monoid (with_zero α) :=
{ add_le_add_left := @add_le_add_left _ _ _ (with_zero.covariant_class_add_le zero_le),
..with_zero.partial_order,
..with_zero.add_comm_monoid, .. }
end with_zero
section canonically_ordered_monoid
instance with_zero.has_exists_add_of_le {α} [has_add α] [preorder α] [has_exists_add_of_le α] :
has_exists_add_of_le (with_zero α) :=
⟨λ a b, begin
apply with_zero.cases_on a,
{ exact λ _, ⟨b, (zero_add b).symm⟩ },
apply with_zero.cases_on b,
{ exact λ b' h, (with_bot.not_coe_le_bot _ h).elim },
rintro a' b' h,
obtain ⟨c, rfl⟩ := exists_add_of_le (with_zero.coe_le_coe.1 h),
exact ⟨c, rfl⟩,
end⟩
-- This instance looks absurd: a monoid already has a zero
/-- Adding a new zero to a canonically ordered additive monoid produces another one. -/
instance with_zero.canonically_ordered_add_monoid {α : Type u} [canonically_ordered_add_monoid α] :
canonically_ordered_add_monoid (with_zero α) :=
{ le_self_add := λ a b, begin
apply with_zero.cases_on a,
{ exact bot_le },
apply with_zero.cases_on b,
{ exact λ b', le_rfl },
{ exact λ a' b', with_zero.coe_le_coe.2 le_self_add }
end,
.. with_zero.order_bot,
.. with_zero.ordered_add_comm_monoid zero_le, ..with_zero.has_exists_add_of_le }
end canonically_ordered_monoid
section canonically_linear_ordered_monoid
instance with_zero.canonically_linear_ordered_add_monoid
(α : Type*) [canonically_linear_ordered_add_monoid α] :
canonically_linear_ordered_add_monoid (with_zero α) :=
{ .. with_zero.canonically_ordered_add_monoid,
.. with_zero.linear_order }
end canonically_linear_ordered_monoid
|
8f795ddeef553b635315c540821b0da834900dec | e61a235b8468b03aee0120bf26ec615c045005d2 | /src/Std/Data/BinomialHeap.lean | 7444f4606728f99c4c0f2d64679275d68cf610a0 | [
"Apache-2.0"
] | permissive | SCKelemen/lean4 | 140dc63a80539f7c61c8e43e1c174d8500ec3230 | e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc | refs/heads/master | 1,660,973,595,917 | 1,590,278,033,000 | 1,590,278,033,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 199 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Std.Data.BinomialHeap.Basic
|
967d2cd8828b55ae5f8fe184a811fdb71c5d4380 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/data/set/finite.lean | bdccf5f25669d6a843b2f2fe717d6d8f08a94ab0 | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 24,204 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import data.fintype.basic
/-!
# Finite sets
This file defines predicates `finite : set α → Prop` and `infinite : set α → Prop` and proves some
basic facts about finite sets.
-/
open set function
universes u v w x
variables {α : Type u} {β : Type v} {ι : Sort w} {γ : Type x}
namespace set
/-- A set is finite if the subtype is a fintype, i.e. there is a
list that enumerates its members. -/
def finite (s : set α) : Prop := nonempty (fintype s)
/-- A set is infinite if it is not finite. -/
def infinite (s : set α) : Prop := ¬ finite s
/-- The subtype corresponding to a finite set is a finite type. Note
that because `finite` isn't a typeclass, this will not fire if it
is made into an instance -/
noncomputable def finite.fintype {s : set α} (h : finite s) : fintype s :=
classical.choice h
/-- Get a finset from a finite set -/
noncomputable def finite.to_finset {s : set α} (h : finite s) : finset α :=
@set.to_finset _ _ h.fintype
@[simp] theorem finite.mem_to_finset {s : set α} {h : finite s} {a : α} : a ∈ h.to_finset ↔ a ∈ s :=
@mem_to_finset _ _ h.fintype _
@[simp] lemma finite.coe_to_finset {α} {s : set α} (h : finite s) : ↑h.to_finset = s :=
@set.coe_to_finset _ s h.fintype
theorem finite.exists_finset {s : set α} : finite s →
∃ s' : finset α, ∀ a : α, a ∈ s' ↔ a ∈ s
| ⟨h⟩ := by exactI ⟨to_finset s, λ _, mem_to_finset⟩
theorem finite.exists_finset_coe {s : set α} (hs : finite s) :
∃ s' : finset α, ↑s' = s :=
⟨hs.to_finset, hs.coe_to_finset⟩
/-- Finite sets can be lifted to finsets. -/
instance : can_lift (set α) (finset α) :=
{ coe := coe,
cond := finite,
prf := λ s hs, hs.exists_finset_coe }
theorem finite_mem_finset (s : finset α) : finite {a | a ∈ s} :=
⟨fintype.of_finset s (λ _, iff.rfl)⟩
theorem finite.of_fintype [fintype α] (s : set α) : finite s :=
by classical; exact ⟨set_fintype s⟩
theorem exists_finite_iff_finset {p : set α → Prop} :
(∃ s, finite s ∧ p s) ↔ ∃ s : finset α, p ↑s :=
⟨λ ⟨s, hs, hps⟩, ⟨hs.to_finset, hs.coe_to_finset.symm ▸ hps⟩,
λ ⟨s, hs⟩, ⟨↑s, finite_mem_finset s, hs⟩⟩
/-- Membership of a subset of a finite type is decidable.
Using this as an instance leads to potential loops with `subtype.fintype` under certain decidability
assumptions, so it should only be declared a local instance. -/
def decidable_mem_of_fintype [decidable_eq α] (s : set α) [fintype s] (a) : decidable (a ∈ s) :=
decidable_of_iff _ mem_to_finset
instance fintype_empty : fintype (∅ : set α) :=
fintype.of_finset ∅ $ by simp
theorem empty_card : fintype.card (∅ : set α) = 0 := rfl
@[simp] theorem empty_card' {h : fintype.{u} (∅ : set α)} :
@fintype.card (∅ : set α) h = 0 :=
eq.trans (by congr) empty_card
@[simp] theorem finite_empty : @finite α ∅ := ⟨set.fintype_empty⟩
instance finite.inhabited : inhabited {s : set α // finite s} := ⟨⟨∅, finite_empty⟩⟩
/-- A `fintype` structure on `insert a s`. -/
def fintype_insert' {a : α} (s : set α) [fintype s] (h : a ∉ s) : fintype (insert a s : set α) :=
fintype.of_finset ⟨a :: s.to_finset.1,
multiset.nodup_cons_of_nodup (by simp [h]) s.to_finset.2⟩ $ by simp
theorem card_fintype_insert' {a : α} (s : set α) [fintype s] (h : a ∉ s) :
@fintype.card _ (fintype_insert' s h) = fintype.card s + 1 :=
by rw [fintype_insert', fintype.card_of_finset];
simp [finset.card, to_finset]; refl
@[simp] theorem card_insert {a : α} (s : set α)
[fintype s] (h : a ∉ s) {d : fintype.{u} (insert a s : set α)} :
@fintype.card _ d = fintype.card s + 1 :=
by rw ← card_fintype_insert' s h; congr
lemma card_image_of_inj_on {s : set α} [fintype s]
{f : α → β} [fintype (f '' s)] (H : ∀x∈s, ∀y∈s, f x = f y → x = y) :
fintype.card (f '' s) = fintype.card s :=
by haveI := classical.prop_decidable; exact
calc fintype.card (f '' s) = (s.to_finset.image f).card : fintype.card_of_finset' _ (by simp)
... = s.to_finset.card : finset.card_image_of_inj_on
(λ x hx y hy hxy, H x (mem_to_finset.1 hx) y (mem_to_finset.1 hy) hxy)
... = fintype.card s : (fintype.card_of_finset' _ (λ a, mem_to_finset)).symm
lemma card_image_of_injective (s : set α) [fintype s]
{f : α → β} [fintype (f '' s)] (H : function.injective f) :
fintype.card (f '' s) = fintype.card s :=
card_image_of_inj_on $ λ _ _ _ _ h, H h
section
local attribute [instance] decidable_mem_of_fintype
instance fintype_insert [decidable_eq α] (a : α) (s : set α) [fintype s] : fintype (insert a s : set α) :=
if h : a ∈ s then by rwa [insert_eq, union_eq_self_of_subset_left (singleton_subset_iff.2 h)]
else fintype_insert' _ h
end
@[simp] theorem finite.insert (a : α) {s : set α} : finite s → finite (insert a s)
| ⟨h⟩ := ⟨@set.fintype_insert _ (classical.dec_eq α) _ _ h⟩
lemma to_finset_insert [decidable_eq α] {a : α} {s : set α} (hs : finite s) :
(hs.insert a).to_finset = insert a hs.to_finset :=
finset.ext $ by simp
@[elab_as_eliminator]
theorem finite.induction_on {C : set α → Prop} {s : set α} (h : finite s)
(H0 : C ∅) (H1 : ∀ {a s}, a ∉ s → finite s → C s → C (insert a s)) : C s :=
let ⟨t⟩ := h in by exactI
match s.to_finset, @mem_to_finset _ s _ with
| ⟨l, nd⟩, al := begin
change ∀ a, a ∈ l ↔ a ∈ s at al,
clear _let_match _match t h, revert s nd al,
refine multiset.induction_on l _ (λ a l IH, _); intros s nd al,
{ rw show s = ∅, from eq_empty_iff_forall_not_mem.2 (by simpa using al),
exact H0 },
{ rw ← show insert a {x | x ∈ l} = s, from set.ext (by simpa using al),
cases multiset.nodup_cons.1 nd with m nd',
refine H1 _ ⟨finset.subtype.fintype ⟨l, nd'⟩⟩ (IH nd' (λ _, iff.rfl)),
exact m }
end
end
@[elab_as_eliminator]
theorem finite.dinduction_on {C : ∀s:set α, finite s → Prop} {s : set α} (h : finite s)
(H0 : C ∅ finite_empty)
(H1 : ∀ {a s}, a ∉ s → ∀h:finite s, C s h → C (insert a s) (h.insert a)) :
C s h :=
have ∀h:finite s, C s h,
from finite.induction_on h (assume h, H0) (assume a s has hs ih h, H1 has hs (ih _)),
this h
instance fintype_singleton (a : α) : fintype ({a} : set α) :=
unique.fintype
@[simp] theorem card_singleton (a : α) :
fintype.card ({a} : set α) = 1 :=
fintype.card_of_subsingleton _
@[simp] theorem finite_singleton (a : α) : finite ({a} : set α) :=
⟨set.fintype_singleton _⟩
instance fintype_pure : ∀ a : α, fintype (pure a : set α) :=
set.fintype_singleton
theorem finite_pure (a : α) : finite (pure a : set α) :=
⟨set.fintype_pure a⟩
instance fintype_univ [fintype α] : fintype (@univ α) :=
fintype.of_equiv α $ (equiv.set.univ α).symm
theorem finite_univ [fintype α] : finite (@univ α) := ⟨set.fintype_univ⟩
theorem infinite_univ_iff : (@univ α).infinite ↔ _root_.infinite α :=
⟨λ h₁, ⟨λ h₂, h₁ $ @finite_univ α h₂⟩,
λ ⟨h₁⟩ ⟨h₂⟩, h₁ $ @fintype.of_equiv _ _ h₂ $ equiv.set.univ _⟩
theorem infinite_univ [h : _root_.infinite α] : infinite (@univ α) :=
infinite_univ_iff.2 h
theorem infinite_coe_iff {s : set α} : _root_.infinite s ↔ infinite s :=
⟨λ ⟨h₁⟩ h₂, h₁ h₂.some, λ h₁, ⟨λ h₂, h₁ ⟨h₂⟩⟩⟩
theorem infinite.to_subtype {s : set α} (h : infinite s) : _root_.infinite s :=
infinite_coe_iff.2 h
/-- Embedding of `ℕ` into an infinite set. -/
noncomputable def infinite.nat_embedding (s : set α) (h : infinite s) : ℕ ↪ s :=
by { haveI := h.to_subtype, exact infinite.nat_embedding s }
lemma infinite.exists_subset_card_eq {s : set α} (hs : infinite s) (n : ℕ) :
∃ t : finset α, ↑t ⊆ s ∧ t.card = n :=
⟨((finset.range n).map (hs.nat_embedding _)).map (embedding.subtype _), by simp⟩
instance fintype_union [decidable_eq α] (s t : set α) [fintype s] [fintype t] : fintype (s ∪ t : set α) :=
fintype.of_finset (s.to_finset ∪ t.to_finset) $ by simp
theorem finite.union {s t : set α} : finite s → finite t → finite (s ∪ t)
| ⟨hs⟩ ⟨ht⟩ := ⟨@set.fintype_union _ (classical.dec_eq α) _ _ hs ht⟩
instance fintype_sep (s : set α) (p : α → Prop) [fintype s] [decidable_pred p] : fintype ({a ∈ s | p a} : set α) :=
fintype.of_finset (s.to_finset.filter p) $ by simp
instance fintype_inter (s t : set α) [fintype s] [decidable_pred t] : fintype (s ∩ t : set α) :=
set.fintype_sep s t
/-- A `fintype` structure on a set defines a `fintype` structure on its subset. -/
def fintype_subset (s : set α) {t : set α} [fintype s] [decidable_pred t] (h : t ⊆ s) : fintype t :=
by rw ← inter_eq_self_of_subset_right h; apply_instance
theorem finite.subset {s : set α} : finite s → ∀ {t : set α}, t ⊆ s → finite t
| ⟨hs⟩ t h := ⟨@set.fintype_subset _ _ _ hs (classical.dec_pred t) h⟩
instance fintype_image [decidable_eq β] (s : set α) (f : α → β) [fintype s] : fintype (f '' s) :=
fintype.of_finset (s.to_finset.image f) $ by simp
instance fintype_range [decidable_eq β] (f : α → β) [fintype α] : fintype (range f) :=
fintype.of_finset (finset.univ.image f) $ by simp [range]
theorem finite_range (f : α → β) [fintype α] : finite (range f) :=
by haveI := classical.dec_eq β; exact ⟨by apply_instance⟩
theorem finite.image {s : set α} (f : α → β) : finite s → finite (f '' s)
| ⟨h⟩ := ⟨@set.fintype_image _ _ (classical.dec_eq β) _ _ h⟩
lemma finite.dependent_image {s : set α} (hs : finite s) {F : Π i ∈ s, β} {t : set β}
(H : ∀ y ∈ t, ∃ x (hx : x ∈ s), y = F x hx) : set.finite t :=
begin
let G : s → β := λ x, F x.1 x.2,
have A : t ⊆ set.range G,
{ assume y hy,
rcases H y hy with ⟨x, hx, xy⟩,
refine ⟨⟨x, hx⟩, xy.symm⟩ },
letI : fintype s := finite.fintype hs,
exact (finite_range G).subset A
end
instance fintype_map {α β} [decidable_eq β] :
∀ (s : set α) (f : α → β) [fintype s], fintype (f <$> s) := set.fintype_image
theorem finite.map {α β} {s : set α} :
∀ (f : α → β), finite s → finite (f <$> s) := finite.image
/-- If a function `f` has a partial inverse and sends a set `s` to a set with `[fintype]` instance,
then `s` has a `fintype` structure as well. -/
def fintype_of_fintype_image (s : set α)
{f : α → β} {g} (I : is_partial_inv f g) [fintype (f '' s)] : fintype s :=
fintype.of_finset ⟨_, @multiset.nodup_filter_map β α g _
(@injective_of_partial_inv_right _ _ f g I) (f '' s).to_finset.2⟩ $ λ a,
begin
suffices : (∃ b x, f x = b ∧ g b = some a ∧ x ∈ s) ↔ a ∈ s,
by simpa [exists_and_distrib_left.symm, and.comm, and.left_comm, and.assoc],
rw exists_swap,
suffices : (∃ x, x ∈ s ∧ g (f x) = some a) ↔ a ∈ s, {simpa [and.comm, and.left_comm, and.assoc]},
simp [I _, (injective_of_partial_inv I).eq_iff]
end
theorem finite_of_finite_image {s : set α} {f : α → β} (hi : set.inj_on f s) :
finite (f '' s) → finite s | ⟨h⟩ :=
⟨@fintype.of_injective _ _ h (λa:s, ⟨f a.1, mem_image_of_mem f a.2⟩) $
assume a b eq, subtype.eq $ hi a.2 b.2 $ subtype.ext_iff_val.1 eq⟩
theorem finite_image_iff {s : set α} {f : α → β} (hi : inj_on f s) :
finite (f '' s) ↔ finite s :=
⟨finite_of_finite_image hi, finite.image _⟩
theorem finite.preimage {s : set β} {f : α → β}
(I : set.inj_on f (f⁻¹' s)) (h : finite s) : finite (f ⁻¹' s) :=
finite_of_finite_image I (h.subset (image_preimage_subset f s))
instance fintype_Union [decidable_eq α] {ι : Type*} [fintype ι]
(f : ι → set α) [∀ i, fintype (f i)] : fintype (⋃ i, f i) :=
fintype.of_finset (finset.univ.bind (λ i, (f i).to_finset)) $ by simp
theorem finite_Union {ι : Type*} [fintype ι] {f : ι → set α} (H : ∀i, finite (f i)) : finite (⋃ i, f i) :=
⟨@set.fintype_Union _ (classical.dec_eq α) _ _ _ (λ i, finite.fintype (H i))⟩
/-- A union of sets with `fintype` structure over a set with `fintype` structure has a `fintype`
structure. -/
def fintype_bUnion [decidable_eq α] {ι : Type*} {s : set ι} [fintype s]
(f : ι → set α) (H : ∀ i ∈ s, fintype (f i)) : fintype (⋃ i ∈ s, f i) :=
by rw bUnion_eq_Union; exact
@set.fintype_Union _ _ _ _ _ (by rintro ⟨i, hi⟩; exact H i hi)
instance fintype_bUnion' [decidable_eq α] {ι : Type*} {s : set ι} [fintype s]
(f : ι → set α) [H : ∀ i, fintype (f i)] : fintype (⋃ i ∈ s, f i) :=
fintype_bUnion _ (λ i _, H i)
theorem finite.sUnion {s : set (set α)} (h : finite s) (H : ∀t∈s, finite t) : finite (⋃₀ s) :=
by rw sUnion_eq_Union; haveI := finite.fintype h;
apply finite_Union; simpa using H
theorem finite.bUnion {α} {ι : Type*} {s : set ι} {f : Π i ∈ s, set α} :
finite s → (∀ i ∈ s, finite (f i ‹_›)) → finite (⋃ i∈s, f i ‹_›)
| ⟨hs⟩ h := by rw [bUnion_eq_Union]; exactI finite_Union (λ i, h _ _)
instance fintype_lt_nat (n : ℕ) : fintype {i | i < n} :=
fintype.of_finset (finset.range n) $ by simp
instance fintype_le_nat (n : ℕ) : fintype {i | i ≤ n} :=
by simpa [nat.lt_succ_iff] using set.fintype_lt_nat (n+1)
lemma finite_le_nat (n : ℕ) : finite {i | i ≤ n} := ⟨set.fintype_le_nat _⟩
lemma finite_lt_nat (n : ℕ) : finite {i | i < n} := ⟨set.fintype_lt_nat _⟩
instance fintype_prod (s : set α) (t : set β) [fintype s] [fintype t] : fintype (set.prod s t) :=
fintype.of_finset (s.to_finset.product t.to_finset) $ by simp
lemma finite.prod {s : set α} {t : set β} : finite s → finite t → finite (set.prod s t)
| ⟨hs⟩ ⟨ht⟩ := by exactI ⟨set.fintype_prod s t⟩
/-- `image2 f s t` is finitype if `s` and `t` are. -/
instance fintype_image2 [decidable_eq γ] (f : α → β → γ) (s : set α) (t : set β)
[hs : fintype s] [ht : fintype t] : fintype (image2 f s t : set γ) :=
by { rw ← image_prod, apply set.fintype_image }
lemma finite.image2 (f : α → β → γ) {s : set α} {t : set β} (hs : finite s) (ht : finite t) :
finite (image2 f s t) :=
by { rw ← image_prod, exact (hs.prod ht).image _ }
/-- If `s : set α` is a set with `fintype` instance and `f : α → set β` is a function such that
each `f a`, `a ∈ s`, has a `fintype` structure, then `s >>= f` has a `fintype` structure. -/
def fintype_bind {α β} [decidable_eq β] (s : set α) [fintype s]
(f : α → set β) (H : ∀ a ∈ s, fintype (f a)) : fintype (s >>= f) :=
set.fintype_bUnion _ H
instance fintype_bind' {α β} [decidable_eq β] (s : set α) [fintype s]
(f : α → set β) [H : ∀ a, fintype (f a)] : fintype (s >>= f) :=
fintype_bind _ _ (λ i _, H i)
theorem finite_bind {α β} {s : set α} {f : α → set β} :
finite s → (∀ a ∈ s, finite (f a)) → finite (s >>= f)
| ⟨hs⟩ H := ⟨@fintype_bind _ _ (classical.dec_eq β) _ hs _ (λ a ha, (H a ha).fintype)⟩
instance fintype_seq {α β : Type u} [decidable_eq β]
(f : set (α → β)) (s : set α) [fintype f] [fintype s] :
fintype (f <*> s) :=
by rw seq_eq_bind_map; apply set.fintype_bind'
theorem finite.seq {α β : Type u} {f : set (α → β)} {s : set α} :
finite f → finite s → finite (f <*> s)
| ⟨hf⟩ ⟨hs⟩ := by { haveI := classical.dec_eq β, exactI ⟨set.fintype_seq _ _⟩ }
/-- There are finitely many subsets of a given finite set -/
lemma finite.finite_subsets {α : Type u} {a : set α} (h : finite a) : finite {b | b ⊆ a} :=
begin
-- we just need to translate the result, already known for finsets,
-- to the language of finite sets
let s : set (set α) := coe '' (↑(finset.powerset (finite.to_finset h)) : set (finset α)),
have : finite s := (finite_mem_finset _).image _,
apply this.subset,
refine λ b hb, ⟨(h.subset hb).to_finset, _, finite.coe_to_finset _⟩,
simpa [finset.subset_iff]
end
lemma exists_min_image [linear_order β] (s : set α) (f : α → β) (h1 : finite s) :
s.nonempty → ∃ a ∈ s, ∀ b ∈ s, f a ≤ f b
| ⟨x, hx⟩ := by simpa only [exists_prop, finite.mem_to_finset]
using (finite.to_finset h1).exists_min_image f ⟨x, finite.mem_to_finset.2 hx⟩
lemma exists_max_image [linear_order β] (s : set α) (f : α → β) (h1 : finite s) :
s.nonempty → ∃ a ∈ s, ∀ b ∈ s, f b ≤ f a
| ⟨x, hx⟩ := by simpa only [exists_prop, finite.mem_to_finset]
using (finite.to_finset h1).exists_max_image f ⟨x, finite.mem_to_finset.2 hx⟩
end set
namespace finset
variables [decidable_eq β]
variables {s : finset α}
lemma finite_to_set (s : finset α) : set.finite (↑s : set α) :=
set.finite_mem_finset s
@[simp] lemma coe_bind {f : α → finset β} : ↑(s.bind f) = (⋃x ∈ (↑s : set α), ↑(f x) : set β) :=
by simp [set.ext_iff]
@[simp] lemma finite_to_set_to_finset {α : Type*} (s : finset α) :
(finite_to_set s).to_finset = s :=
by { ext, rw [set.finite.mem_to_finset, mem_coe] }
end finset
namespace set
lemma finite_subset_Union {s : set α} (hs : finite s)
{ι} {t : ι → set α} (h : s ⊆ ⋃ i, t i) : ∃ I : set ι, finite I ∧ s ⊆ ⋃ i ∈ I, t i :=
begin
casesI hs,
choose f hf using show ∀ x : s, ∃ i, x.1 ∈ t i, {simpa [subset_def] using h},
refine ⟨range f, finite_range f, _⟩,
rintro x hx,
simp,
exact ⟨x, ⟨hx, hf _⟩⟩,
end
lemma eq_finite_Union_of_finite_subset_Union {ι} {s : ι → set α} {t : set α} (tfin : finite t) (h : t ⊆ ⋃ i, s i) :
∃ I : set ι, (finite I) ∧ ∃ σ : {i | i ∈ I} → set α,
(∀ i, finite (σ i)) ∧ (∀ i, σ i ⊆ s i) ∧ t = ⋃ i, σ i :=
let ⟨I, Ifin, hI⟩ := finite_subset_Union tfin h in
⟨I, Ifin, λ x, s x ∩ t,
λ i, tfin.subset (inter_subset_right _ _),
λ i, inter_subset_left _ _,
begin
ext x,
rw mem_Union,
split,
{ intro x_in,
rcases mem_Union.mp (hI x_in) with ⟨i, _, ⟨hi, rfl⟩, H⟩,
use [i, hi, H, x_in] },
{ rintros ⟨i, hi, H⟩,
exact H }
end⟩
instance nat.fintype_Iio (n : ℕ) : fintype (Iio n) :=
fintype.of_finset (finset.range n) $ by simp
/--
If `P` is some relation between terms of `γ` and sets in `γ`,
such that every finite set `t : set γ` has some `c : γ` related to it,
then there is a recursively defined sequence `u` in `γ`
so `u n` is related to the image of `{0, 1, ..., n-1}` under `u`.
(We use this later to show sequentially compact sets
are totally bounded.)
-/
lemma seq_of_forall_finite_exists {γ : Type*}
{P : γ → set γ → Prop} (h : ∀ t, finite t → ∃ c, P c t) :
∃ u : ℕ → γ, ∀ n, P (u n) (u '' Iio n) :=
⟨λ n, @nat.strong_rec_on' (λ _, γ) n $ λ n ih, classical.some $ h
(range $ λ m : Iio n, ih m.1 m.2)
(finite_range _),
λ n, begin
classical,
refine nat.strong_rec_on' n (λ n ih, _),
rw nat.strong_rec_on_beta', convert classical.some_spec (h _ _),
ext x, split,
{ rintros ⟨m, hmn, rfl⟩, exact ⟨⟨m, hmn⟩, rfl⟩ },
{ rintros ⟨⟨m, hmn⟩, rfl⟩, exact ⟨m, hmn, rfl⟩ }
end⟩
lemma finite_range_ite {p : α → Prop} [decidable_pred p] {f g : α → β} (hf : finite (range f))
(hg : finite (range g)) : finite (range (λ x, if p x then f x else g x)) :=
(hf.union hg).subset range_ite_subset
lemma finite_range_const {c : β} : finite (range (λ x : α, c)) :=
(finite_singleton c).subset range_const_subset
lemma range_find_greatest_subset {P : α → ℕ → Prop} [∀ x, decidable_pred (P x)] {b : ℕ}:
range (λ x, nat.find_greatest (P x) b) ⊆ ↑(finset.range (b + 1)) :=
by { rw range_subset_iff, assume x, simp [nat.lt_succ_iff, nat.find_greatest_le] }
lemma finite_range_find_greatest {P : α → ℕ → Prop} [∀ x, decidable_pred (P x)] {b : ℕ} :
finite (range (λ x, nat.find_greatest (P x) b)) :=
(finset.range (b + 1)).finite_to_set.subset range_find_greatest_subset
lemma card_lt_card {s t : set α} [fintype s] [fintype t] (h : s ⊂ t) :
fintype.card s < fintype.card t :=
begin
rw [← s.coe_to_finset, ← t.coe_to_finset, finset.coe_ssubset] at h,
rw [fintype.card_of_finset' _ (λ x, mem_to_finset),
fintype.card_of_finset' _ (λ x, mem_to_finset)],
exact finset.card_lt_card h,
end
lemma card_le_of_subset {s t : set α} [fintype s] [fintype t] (hsub : s ⊆ t) :
fintype.card s ≤ fintype.card t :=
calc fintype.card s = s.to_finset.card : fintype.card_of_finset' _ (by simp)
... ≤ t.to_finset.card : finset.card_le_of_subset (λ x hx, by simp [set.subset_def, *] at *)
... = fintype.card t : eq.symm (fintype.card_of_finset' _ (by simp))
lemma eq_of_subset_of_card_le {s t : set α} [fintype s] [fintype t]
(hsub : s ⊆ t) (hcard : fintype.card t ≤ fintype.card s) : s = t :=
(eq_or_ssubset_of_subset hsub).elim id
(λ h, absurd hcard $ not_le_of_lt $ card_lt_card h)
lemma card_range_of_injective [fintype α] {f : α → β} (hf : injective f)
[fintype (range f)] : fintype.card (range f) = fintype.card α :=
eq.symm $ fintype.card_congr $ equiv.set.range f hf
lemma finite.exists_maximal_wrt [partial_order β] (f : α → β) (s : set α) (h : set.finite s) :
s.nonempty → ∃a∈s, ∀a'∈s, f a ≤ f a' → f a = f a' :=
begin
classical,
refine h.induction_on _ _,
{ assume h, exact absurd h empty_not_nonempty },
assume a s his _ ih _,
cases s.eq_empty_or_nonempty with h h,
{ use a, simp [h] },
rcases ih h with ⟨b, hb, ih⟩,
by_cases f b ≤ f a,
{ refine ⟨a, set.mem_insert _ _, assume c hc hac, le_antisymm hac _⟩,
rcases set.mem_insert_iff.1 hc with rfl | hcs,
{ refl },
{ rwa [← ih c hcs (le_trans h hac)] } },
{ refine ⟨b, set.mem_insert_of_mem _ hb, assume c hc hbc, _⟩,
rcases set.mem_insert_iff.1 hc with rfl | hcs,
{ exact (h hbc).elim },
{ exact ih c hcs hbc } }
end
lemma finite.card_to_finset {s : set α} [fintype s] (h : s.finite) :
h.to_finset.card = fintype.card s :=
by { rw [← finset.card_attach, finset.attach_eq_univ, ← fintype.card], congr' 2, funext,
rw set.finite.mem_to_finset }
section
local attribute [instance, priority 1] classical.prop_decidable
lemma to_finset_inter {α : Type*} [fintype α] (s t : set α) :
(s ∩ t).to_finset = s.to_finset ∩ t.to_finset :=
by ext; simp
end
section
variables [semilattice_sup α] [nonempty α] {s : set α}
/--A finite set is bounded above.-/
protected lemma finite.bdd_above (hs : finite s) : bdd_above s :=
finite.induction_on hs bdd_above_empty $ λ a s _ _ h, h.insert a
/--A finite union of sets which are all bounded above is still bounded above.-/
lemma finite.bdd_above_bUnion {I : set β} {S : β → set α} (H : finite I) :
(bdd_above (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_above (S i)) :=
finite.induction_on H
(by simp only [bUnion_empty, bdd_above_empty, ball_empty_iff])
(λ a s ha _ hs, by simp only [bUnion_insert, ball_insert_iff, bdd_above_union, hs])
end
section
variables [semilattice_inf α] [nonempty α] {s : set α}
/--A finite set is bounded below.-/
protected lemma finite.bdd_below (hs : finite s) : bdd_below s :=
@finite.bdd_above (order_dual α) _ _ _ hs
/--A finite union of sets which are all bounded below is still bounded below.-/
lemma finite.bdd_below_bUnion {I : set β} {S : β → set α} (H : finite I) :
(bdd_below (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_below (S i)) :=
@finite.bdd_above_bUnion (order_dual α) _ _ _ _ _ H
end
end set
namespace finset
/-- A finset is bounded above. -/
protected lemma bdd_above [semilattice_sup α] [nonempty α] (s : finset α) :
bdd_above (↑s : set α) :=
s.finite_to_set.bdd_above
/-- A finset is bounded below. -/
protected lemma bdd_below [semilattice_inf α] [nonempty α] (s : finset α) :
bdd_below (↑s : set α) :=
s.finite_to_set.bdd_below
end finset
lemma fintype.exists_max [fintype α] [nonempty α]
{β : Type*} [linear_order β] (f : α → β) :
∃ x₀ : α, ∀ x, f x ≤ f x₀ :=
begin
rcases set.finite_univ.exists_maximal_wrt f _ univ_nonempty with ⟨x, _, hx⟩,
exact ⟨x, λ y, (le_total (f x) (f y)).elim (λ h, ge_of_eq $ hx _ trivial h) id⟩
end
|
ac89c4bb50f20674614255b9e8667480669818ae | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/category_theory/limits/colimit_limit.lean | 541209e307fabf65d28bf61cf52b76cadf5a95ee | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 4,433 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.limits.types
import category_theory.currying
import category_theory.limits.functor_category
/-!
# The morphism comparing a colimit of limits with the corresponding limit of colimits.
For `F : J × K ⥤ C` there is always a morphism $\colim_k \lim_j F(j,k) → \lim_j \colim_k F(j, k)$.
While it is not usually an isomorphism, with additional hypotheses on `J` and `K` it may be,
in which case we say that "colimits commute with limits".
The prototypical example, proved in `category_theory.limits.filtered_colimit_commutes_finite_limit`,
is that when `C = Type`, filtered colimits commute with finite limits.
## References
* Borceux, Handbook of categorical algebra 1, Section 2.13
* [Stacks: Filtered colimits](https://stacks.math.columbia.edu/tag/002W)
-/
universes v₂ v u
open category_theory
namespace category_theory.limits
variables {J K : Type v} [small_category J] [small_category K]
variables {C : Type u} [category.{v} C]
variables (F : J × K ⥤ C)
open category_theory.prod
lemma map_id_left_eq_curry_map {j : J} {k k' : K} {f : k ⟶ k'} :
F.map ((𝟙 j, f) : (j, k) ⟶ (j, k')) = ((curry.obj F).obj j).map f :=
rfl
lemma map_id_right_eq_curry_swap_map {j j' : J} {f : j ⟶ j'} {k : K} :
F.map ((f, 𝟙 k) : (j, k) ⟶ (j', k)) = ((curry.obj (swap K J ⋙ F)).obj k).map f :=
rfl
variables [has_limits_of_shape J C]
variables [has_colimits_of_shape K C]
/--
The universal morphism
$\colim_k \lim_j F(j,k) → \lim_j \colim_k F(j, k)$.
-/
noncomputable
def colimit_limit_to_limit_colimit :
colimit ((curry.obj (swap K J ⋙ F)) ⋙ lim) ⟶ limit ((curry.obj F) ⋙ colim) :=
limit.lift ((curry.obj F) ⋙ colim)
{ X := _,
π :=
{ app := λ j, colimit.desc ((curry.obj (swap K J ⋙ F)) ⋙ lim)
{ X := _,
ι :=
{ app := λ k,
limit.π ((curry.obj (swap K J ⋙ F)).obj k) j ≫ colimit.ι ((curry.obj F).obj j) k,
naturality' :=
begin
dsimp,
intros k k' f,
simp only [functor.comp_map, curry.obj_map_app, limits.lim_map_π_assoc, swap_map,
category.comp_id, map_id_left_eq_curry_map, colimit.w],
end }, },
naturality' :=
begin
dsimp,
intros j j' f,
ext k,
simp only [limits.colimit.ι_map, curry.obj_map_app, limits.colimit.ι_desc_assoc,
limits.colimit.ι_desc, category.id_comp, category.assoc, map_id_right_eq_curry_swap_map,
limit.w_assoc],
end } }
/--
Since `colimit_limit_to_limit_colimit` is a morphism from a colimit to a limit,
this lemma characterises it.
-/
@[simp, reassoc] lemma ι_colimit_limit_to_limit_colimit_π (j) (k) :
colimit.ι _ k ≫ colimit_limit_to_limit_colimit F ≫ limit.π _ j =
limit.π ((curry.obj (swap K J ⋙ F)).obj k) j ≫ colimit.ι ((curry.obj F).obj j) k :=
by { dsimp [colimit_limit_to_limit_colimit], simp, }
@[simp] lemma ι_colimit_limit_to_limit_colimit_π_apply (F : J × K ⥤ Type v) (j) (k) (f) :
limit.π ((curry.obj F) ⋙ colim) j
(colimit_limit_to_limit_colimit F (colimit.ι ((curry.obj (swap K J ⋙ F)) ⋙ lim) k f)) =
colimit.ι ((curry.obj F).obj j) k (limit.π ((curry.obj (swap K J ⋙ F)).obj k) j f) :=
by { dsimp [colimit_limit_to_limit_colimit], simp, }
/-- The map `colimit_limit_to_limit_colimit` realized as a map of cones. -/
@[simps] noncomputable def colimit_limit_to_limit_colimit_cone (G : J ⥤ K ⥤ C) [has_limit G] :
colim.map_cone (limit.cone G) ⟶ limit.cone (G ⋙ colim) :=
{ hom := colim.map (limit_iso_swap_comp_lim G).hom ≫
colimit_limit_to_limit_colimit (uncurry.obj G : _) ≫
lim.map (whisker_right (currying.unit_iso.app G).inv colim),
w' := λ j,
begin
ext1 k,
simp only [limit_obj_iso_limit_comp_evaluation_hom_π_assoc, iso.app_inv,
ι_colimit_limit_to_limit_colimit_π_assoc, whisker_right_app,
colimit.ι_map, functor.map_cone_π_app, category.id_comp,
eq_to_hom_refl, eq_to_hom_app, colimit.ι_map_assoc, limit.cone_π,
lim_map_π_assoc, lim_map_π, category.assoc, currying_unit_iso_inv_app_app_app,
limit_iso_swap_comp_lim_hom_app, lim_map_eq_lim_map],
dsimp,
simp only [category.id_comp],
erw limit_obj_iso_limit_comp_evaluation_hom_π_assoc,
end }
end category_theory.limits
|
adb173e9792d3e4bbcf58a992a2b6ca3f03d70df | 453dcd7c0d1ef170b0843a81d7d8caedc9741dce | /algebra/ordered_group.lean | 122f380124de6188e7a9eddf4b5d00e69f7b04ef | [
"Apache-2.0"
] | permissive | amswerdlow/mathlib | 9af77a1f08486d8fa059448ae2d97795bd12ec0c | 27f96e30b9c9bf518341705c99d641c38638dfd0 | refs/heads/master | 1,585,200,953,598 | 1,534,275,532,000 | 1,534,275,532,000 | 144,564,700 | 0 | 0 | null | 1,534,156,197,000 | 1,534,156,197,000 | null | UTF-8 | Lean | false | false | 21,815 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Johannes Hölzl
Ordered monoids and groups.
-/
import algebra.group order.bounded_lattice tactic.basic
universe u
variable {α : Type u}
section old_structure_cmd
set_option old_structure_cmd true
/-- An ordered (additive) commutative monoid is a commutative monoid
with a partial order such that addition is an order embedding, i.e.
`a + b ≤ a + c ↔ b ≤ c`. These monoids are automatically cancellative. -/
class ordered_comm_monoid (α : Type*) extends add_comm_monoid α, partial_order α :=
(add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b)
(lt_of_add_lt_add_left : ∀ a b c : α, a + b < a + c → b < c)
/-- A canonically ordered monoid is an ordered commutative monoid
in which the ordering coincides with the divisibility relation,
which is to say, `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_monoid (α : Type*) extends ordered_comm_monoid α :=
(le_iff_exists_add : ∀a b:α, a ≤ b ↔ ∃c, b = a + c)
end old_structure_cmd
section ordered_comm_monoid
variables [ordered_comm_monoid α] {a b c d : α}
lemma add_le_add_left' (h : a ≤ b) : c + a ≤ c + b :=
ordered_comm_monoid.add_le_add_left a b h c
lemma add_le_add_right' (h : a ≤ b) : a + c ≤ b + c :=
add_comm c a ▸ add_comm c b ▸ add_le_add_left' h
lemma lt_of_add_lt_add_left' : a + b < a + c → b < c :=
ordered_comm_monoid.lt_of_add_lt_add_left a b c
lemma add_le_add' (h₁ : a ≤ b) (h₂ : c ≤ d) : a + c ≤ b + d :=
le_trans (add_le_add_right' h₁) (add_le_add_left' h₂)
lemma le_add_of_nonneg_right' (h : b ≥ 0) : a ≤ a + b :=
have a + b ≥ a + 0, from add_le_add_left' h,
by rwa add_zero at this
lemma le_add_of_nonneg_left' (h : b ≥ 0) : a ≤ b + a :=
have 0 + a ≤ b + a, from add_le_add_right' h,
by rwa zero_add at this
lemma lt_of_add_lt_add_right' (h : a + b < c + b) : a < c :=
lt_of_add_lt_add_left'
(show b + a < b + c, begin rw [add_comm b a, add_comm b c], assumption end)
-- here we start using properties of zero.
lemma le_add_of_nonneg_of_le' (ha : 0 ≤ a) (hbc : b ≤ c) : b ≤ a + c :=
zero_add b ▸ add_le_add' ha hbc
lemma le_add_of_le_of_nonneg' (hbc : b ≤ c) (ha : 0 ≤ a) : b ≤ c + a :=
add_zero b ▸ add_le_add' hbc ha
lemma add_nonneg' (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a + b :=
le_add_of_nonneg_of_le' ha hb
lemma add_pos_of_pos_of_nonneg' (ha : 0 < a) (hb : 0 ≤ b) : 0 < a + b :=
lt_of_lt_of_le ha $ le_add_of_nonneg_right' hb
lemma add_pos' (ha : 0 < a) (hb : 0 < b) : 0 < a + b :=
add_pos_of_pos_of_nonneg' ha $ le_of_lt hb
lemma add_pos_of_nonneg_of_pos' (ha : 0 ≤ a) (hb : 0 < b) : 0 < a + b :=
lt_of_lt_of_le hb $ le_add_of_nonneg_left' ha
lemma add_nonpos' (ha : a ≤ 0) (hb : b ≤ 0) : a + b ≤ 0 :=
zero_add (0:α) ▸ (add_le_add' ha hb)
lemma add_le_of_nonpos_of_le' (ha : a ≤ 0) (hbc : b ≤ c) : a + b ≤ c :=
zero_add c ▸ add_le_add' ha hbc
lemma add_le_of_le_of_nonpos' (hbc : b ≤ c) (ha : a ≤ 0) : b + a ≤ c :=
add_zero c ▸ add_le_add' hbc ha
lemma add_neg_of_neg_of_nonpos' (ha : a < 0) (hb : b ≤ 0) : a + b < 0 :=
lt_of_le_of_lt (add_le_of_le_of_nonpos' (le_refl _) hb) ha
lemma add_neg_of_nonpos_of_neg' (ha : a ≤ 0) (hb : b < 0) : a + b < 0 :=
lt_of_le_of_lt (add_le_of_nonpos_of_le' ha (le_refl _)) hb
lemma add_neg' (ha : a < 0) (hb : b < 0) : a + b < 0 :=
add_neg_of_nonpos_of_neg' (le_of_lt ha) hb
lemma lt_add_of_nonneg_of_lt' (ha : 0 ≤ a) (hbc : b < c) : b < a + c :=
lt_of_lt_of_le hbc $ le_add_of_nonneg_left' ha
lemma lt_add_of_lt_of_nonneg' (hbc : b < c) (ha : 0 ≤ a) : b < c + a :=
lt_of_lt_of_le hbc $ le_add_of_nonneg_right' ha
lemma lt_add_of_pos_of_lt' (ha : 0 < a) (hbc : b < c) : b < a + c :=
lt_add_of_nonneg_of_lt' (le_of_lt ha) hbc
lemma lt_add_of_lt_of_pos' (hbc : b < c) (ha : 0 < a) : b < c + a :=
lt_add_of_lt_of_nonneg' hbc (le_of_lt ha)
lemma add_lt_of_nonpos_of_lt' (ha : a ≤ 0) (hbc : b < c) : a + b < c :=
lt_of_le_of_lt (add_le_of_nonpos_of_le' ha (le_refl _)) hbc
lemma add_lt_of_lt_of_nonpos' (hbc : b < c) (ha : a ≤ 0) : b + a < c :=
lt_of_le_of_lt (add_le_of_le_of_nonpos' (le_refl _) ha) hbc
lemma add_lt_of_neg_of_lt' (ha : a < 0) (hbc : b < c) : a + b < c :=
add_lt_of_nonpos_of_lt' (le_of_lt ha) hbc
lemma add_lt_of_lt_of_neg' (hbc : b < c) (ha : a < 0) : b + a < c :=
add_lt_of_lt_of_nonpos' hbc (le_of_lt ha)
lemma add_eq_zero_iff_eq_zero_and_eq_zero_of_nonneg_of_nonneg'
(ha : 0 ≤ a) (hb : 0 ≤ b) : a + b = 0 ↔ a = 0 ∧ b = 0 :=
iff.intro
(assume hab : a + b = 0,
have a ≤ 0, from hab ▸ le_add_of_le_of_nonneg' (le_refl _) hb,
have a = 0, from le_antisymm this ha,
have b ≤ 0, from hab ▸ le_add_of_nonneg_of_le' ha (le_refl _),
have b = 0, from le_antisymm this hb,
and.intro ‹a = 0› ‹b = 0›)
(assume ⟨ha', hb'⟩, by rw [ha', hb', add_zero])
lemma bit0_pos {a : α} (h : 0 < a) : 0 < bit0 a :=
add_pos' h h
end ordered_comm_monoid
namespace units
instance [monoid α] [preorder α] : preorder (units α) :=
{ le := λ a b, (a:α) ≤ b,
lt := λ a b, (a:α) < b,
le_refl := λ a, @le_refl α _ _,
le_trans := λ a b c, @le_trans α _ _ _ _,
lt_iff_le_not_le := λ a b, @lt_iff_le_not_le α _ _ _ }
@[simp] theorem coe_le_coe [monoid α] [preorder α] {a b : units α} :
(a : α) ≤ b ↔ a ≤ b := iff.rfl
@[simp] theorem coe_lt_coe [monoid α] [preorder α] {a b : units α} :
(a : α) < b ↔ a < b := iff.rfl
instance [monoid α] [partial_order α] : partial_order (units α) :=
{ le_antisymm := λ a b h₁ h₂, ext $ le_antisymm h₁ h₂, ..units.preorder }
instance [monoid α] [linear_order α] : linear_order (units α) :=
{ le_total := λ a b, @le_total α _ _ _, ..units.partial_order }
instance [monoid α] [decidable_linear_order α] : decidable_linear_order (units α) :=
{ decidable_le := by apply_instance,
decidable_lt := by apply_instance,
decidable_eq := by apply_instance,
..units.linear_order }
theorem max_coe [monoid α] [decidable_linear_order α] {a b : units α} :
(↑(max a b) : α) = max a b :=
by by_cases a ≤ b; simp [max, h]
theorem min_coe [monoid α] [decidable_linear_order α] {a b : units α} :
(↑(min a b) : α) = min a b :=
by by_cases a ≤ b; simp [min, h]
end units
namespace with_zero
open lattice
instance [partial_order α] : partial_order (with_zero α) := with_bot.partial_order
instance [partial_order α] : order_bot (with_zero α) := with_bot.order_bot
instance [lattice α] : lattice (with_zero α) := with_bot.lattice
instance [linear_order α] : linear_order (with_zero α) := with_bot.linear_order
instance [decidable_linear_order α] :
decidable_linear_order (with_zero α) := with_bot.decidable_linear_order
def ordered_comm_monoid [ordered_comm_monoid α]
(zero_le : ∀ a : α, 0 ≤ a) : ordered_comm_monoid (with_zero α) :=
begin
suffices, refine {
add_le_add_left := this,
..with_zero.partial_order,
..with_zero.add_comm_monoid, ..},
{ intros a b c h,
refine ⟨λ b h₂, _, λ h₂, h.2 $ this _ _ h₂ _⟩,
cases h₂, cases c with c,
{ cases h.2 (this _ _ bot_le a) },
{ refine ⟨_, rfl, _⟩,
cases a with a,
{ exact with_bot.some_le_some.1 h.1 },
{ exact le_of_lt (lt_of_add_lt_add_left' $
with_bot.some_lt_some.1 h), } } },
{ intros a b h c ca h₂,
cases b with b,
{ rw le_antisymm h bot_le at h₂,
exact ⟨_, h₂, le_refl _⟩ },
cases a with a,
{ change c + 0 = some ca at h₂,
simp at h₂, simp [h₂],
exact ⟨_, rfl, by simpa using add_le_add_left' (zero_le b)⟩ },
{ simp at h,
cases c with c; change some _ = _ at h₂;
simp [-add_comm] at h₂; subst ca; refine ⟨_, rfl, _⟩,
{ exact h },
{ exact add_le_add_left' h } } }
end
end with_zero
namespace with_top
open lattice
instance [add_semigroup α] : add_semigroup (with_top α) :=
{ add := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a + b)),
..@additive.add_semigroup _ $ @with_zero.semigroup (multiplicative α) _ }
instance [add_comm_semigroup α] : add_comm_semigroup (with_top α) :=
{ ..@additive.add_comm_semigroup _ $
@with_zero.comm_semigroup (multiplicative α) _ }
instance [add_monoid α] : add_monoid (with_top α) :=
{ zero := some 0,
..@additive.add_monoid _ $ @with_zero.monoid (multiplicative α) _ }
instance [add_comm_monoid α] : add_comm_monoid (with_top α) :=
{ ..@additive.add_comm_monoid _ $
@with_zero.comm_monoid (multiplicative α) _ }
instance [ordered_comm_monoid α] : ordered_comm_monoid (with_top α) :=
begin
suffices, refine {
add_le_add_left := this,
..with_top.partial_order,
..with_top.add_comm_monoid, ..},
{ intros a b c h,
refine ⟨λ c h₂, _, λ h₂, h.2 $ this _ _ h₂ _⟩,
cases h₂, cases a with a,
{ exact (not_le_of_lt h).elim le_top },
cases b with b,
{ exact (not_le_of_lt h).elim le_top },
{ exact ⟨_, rfl, le_of_lt (lt_of_add_lt_add_left' $
with_top.some_lt_some.1 h)⟩ } },
{ intros a b h c cb h₂,
cases c with c, {cases h₂},
cases b with b; cases h₂,
cases a with a, {cases le_antisymm h le_top},
simp at h,
exact ⟨_, rfl, add_le_add_left' h⟩, }
end
end with_top
namespace with_bot
open lattice
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_monoid α] : add_monoid (with_bot α) := with_top.add_monoid
instance [add_comm_monoid α] : add_comm_monoid (with_bot α) := with_top.add_comm_monoid
instance [ordered_comm_monoid α] : ordered_comm_monoid (with_bot α) :=
begin
suffices, refine {
add_le_add_left := this,
..with_bot.partial_order,
..with_bot.add_comm_monoid, ..},
{ intros a b c h,
refine ⟨λ b h₂, _, λ h₂, h.2 $ this _ _ h₂ _⟩,
cases h₂, cases a with a,
{ exact (not_le_of_lt h).elim bot_le },
cases c with c,
{ exact (not_le_of_lt h).elim bot_le },
{ exact ⟨_, rfl, le_of_lt (lt_of_add_lt_add_left' $
with_bot.some_lt_some.1 h)⟩ } },
{ intros a b h c ca h₂,
cases c with c, {cases h₂},
cases a with a; cases h₂,
cases b with b, {cases le_antisymm h bot_le},
simp at h,
exact ⟨_, rfl, add_le_add_left' h⟩, }
end
@[simp] lemma coe_add [add_semigroup α] (a b : α) : ((a + b : α) : with_bot α) = a + b := rfl
@[simp] lemma bot_add [ordered_comm_monoid α] (a : with_bot α) : ⊥ + a = ⊥ := rfl
@[simp] lemma add_bot [ordered_comm_monoid α] (a : with_bot α) : a + ⊥ = ⊥ := by cases a; refl
lemma coe_lt_coe {a b : ℕ} : (a : with_bot ℕ) < b ↔ a < b := with_bot.some_lt_some
lemma bot_lt_some (a : ℕ) : (⊥ : with_bot ℕ) < some a :=
lt_of_le_of_ne bot_le (λ h, option.no_confusion h)
instance has_one : has_one (with_bot ℕ) := ⟨(1 : ℕ)⟩
end with_bot
section canonically_ordered_monoid
variables [canonically_ordered_monoid α] {a b c d : α}
lemma le_iff_exists_add : a ≤ b ↔ ∃c, b = a + c :=
canonically_ordered_monoid.le_iff_exists_add a b
@[simp] lemma zero_le (a : α) : 0 ≤ a := le_iff_exists_add.mpr ⟨a, by simp⟩
@[simp] lemma add_eq_zero_iff : a + b = 0 ↔ a = 0 ∧ b = 0 :=
add_eq_zero_iff_eq_zero_and_eq_zero_of_nonneg_of_nonneg' (zero_le _) (zero_le _)
@[simp] lemma le_zero_iff_eq : a ≤ 0 ↔ a = 0 :=
iff.intro
(assume h, le_antisymm h (zero_le a))
(assume h, h ▸ le_refl a)
instance with_zero.canonically_ordered_monoid :
canonically_ordered_monoid (with_zero α) :=
{ le_iff_exists_add := λ a b, begin
cases a with a,
{ exact iff_of_true lattice.bot_le ⟨b, (zero_add b).symm⟩ },
cases b with b,
{ exact iff_of_false
(mt (le_antisymm lattice.bot_le) (by simp))
(λ ⟨c, h⟩, by cases c; cases h) },
{ simp [le_iff_exists_add, -add_comm],
split; intro h; rcases h with ⟨c, h⟩,
{ exact ⟨some c, congr_arg some h⟩ },
{ cases c; cases h,
{ exact ⟨_, (add_zero _).symm⟩ },
{ exact ⟨_, rfl⟩ } } }
end,
..with_zero.ordered_comm_monoid zero_le }
end canonically_ordered_monoid
instance ordered_cancel_comm_monoid.to_ordered_comm_monoid
[H : ordered_cancel_comm_monoid α] : ordered_comm_monoid α :=
{ lt_of_add_lt_add_left := @lt_of_add_lt_add_left _ _, ..H }
section ordered_cancel_comm_monoid
variables [ordered_cancel_comm_monoid α] {a b c : α}
@[simp] lemma add_le_add_iff_left (a : α) {b c : α} : a + b ≤ a + c ↔ b ≤ c :=
⟨le_of_add_le_add_left, λ h, add_le_add_left h _⟩
@[simp] lemma add_le_add_iff_right (c : α) : a + c ≤ b + c ↔ a ≤ b :=
add_comm c a ▸ add_comm c b ▸ add_le_add_iff_left c
@[simp] lemma add_lt_add_iff_left (a : α) {b c : α} : a + b < a + c ↔ b < c :=
⟨lt_of_add_lt_add_left, λ h, add_lt_add_left h _⟩
@[simp] lemma add_lt_add_iff_right (c : α) : a + c < b + c ↔ a < b :=
add_comm c a ▸ add_comm c b ▸ add_lt_add_iff_left c
@[simp] lemma le_add_iff_nonneg_right (a : α) {b : α} : a ≤ a + b ↔ 0 ≤ b :=
have a + 0 ≤ a + b ↔ 0 ≤ b, from add_le_add_iff_left a,
by rwa add_zero at this
@[simp] lemma le_add_iff_nonneg_left (a : α) {b : α} : a ≤ b + a ↔ 0 ≤ b :=
by rw [add_comm, le_add_iff_nonneg_right]
@[simp] lemma lt_add_iff_pos_right (a : α) {b : α} : a < a + b ↔ 0 < b :=
have a + 0 < a + b ↔ 0 < b, from add_lt_add_iff_left a,
by rwa add_zero at this
@[simp] lemma lt_add_iff_pos_left (a : α) {b : α} : a < b + a ↔ 0 < b :=
by rw [add_comm, lt_add_iff_pos_right]
lemma add_eq_zero_iff_eq_zero_of_nonneg
(ha : 0 ≤ a) (hb : 0 ≤ b) : a + b = 0 ↔ a = 0 ∧ b = 0 :=
⟨λ hab : a + b = 0,
by split; apply le_antisymm; try {assumption};
rw ← hab; simp [ha, hb],
λ ⟨ha', hb'⟩, by rw [ha', hb', add_zero]⟩
end ordered_cancel_comm_monoid
section ordered_comm_group
variables [ordered_comm_group α] {a b c : α}
@[simp] lemma neg_le_neg_iff : -a ≤ -b ↔ b ≤ a :=
have a + b + -a ≤ a + b + -b ↔ -a ≤ -b, from add_le_add_iff_left _,
by simp at this; simp [this]
lemma neg_le : -a ≤ b ↔ -b ≤ a :=
have -a ≤ -(-b) ↔ -b ≤ a, from neg_le_neg_iff,
by rwa neg_neg at this
lemma le_neg : a ≤ -b ↔ b ≤ -a :=
have -(-a) ≤ -b ↔ b ≤ -a, from neg_le_neg_iff,
by rwa neg_neg at this
@[simp] lemma neg_nonpos : -a ≤ 0 ↔ 0 ≤ a :=
have -a ≤ -0 ↔ 0 ≤ a, from neg_le_neg_iff,
by rwa neg_zero at this
@[simp] lemma neg_nonneg : 0 ≤ -a ↔ a ≤ 0 :=
have -0 ≤ -a ↔ a ≤ 0, from neg_le_neg_iff,
by rwa neg_zero at this
@[simp] lemma neg_lt_neg_iff : -a < -b ↔ b < a :=
have a + b + -a < a + b + -b ↔ -a < -b, from add_lt_add_iff_left _,
by simp at this; simp [this]
lemma neg_lt_zero : -a < 0 ↔ 0 < a :=
have -a < -0 ↔ 0 < a, from neg_lt_neg_iff,
by rwa neg_zero at this
lemma neg_pos : 0 < -a ↔ a < 0 :=
have -0 < -a ↔ a < 0, from neg_lt_neg_iff,
by rwa neg_zero at this
lemma neg_lt : -a < b ↔ -b < a :=
have -a < -(-b) ↔ -b < a, from neg_lt_neg_iff,
by rwa neg_neg at this
lemma lt_neg : a < -b ↔ b < -a :=
have -(-a) < -b ↔ b < -a, from neg_lt_neg_iff,
by rwa neg_neg at this
lemma sub_le_sub_iff_left (a : α) {b c : α} : a - b ≤ a - c ↔ c ≤ b :=
(add_le_add_iff_left _).trans neg_le_neg_iff
lemma sub_le_sub_iff_right (c : α) : a - c ≤ b - c ↔ a ≤ b :=
add_le_add_iff_right _
lemma sub_lt_sub_iff_left (a : α) {b c : α} : a - b < a - c ↔ c < b :=
(add_lt_add_iff_left _).trans neg_lt_neg_iff
lemma sub_lt_sub_iff_right (c : α) : a - c < b - c ↔ a < b :=
add_lt_add_iff_right _
@[simp] lemma sub_nonneg : 0 ≤ a - b ↔ b ≤ a :=
have a - a ≤ a - b ↔ b ≤ a, from sub_le_sub_iff_left a,
by rwa sub_self at this
@[simp] lemma sub_nonpos : a - b ≤ 0 ↔ a ≤ b :=
have a - b ≤ b - b ↔ a ≤ b, from sub_le_sub_iff_right b,
by rwa sub_self at this
@[simp] lemma sub_pos : 0 < a - b ↔ b < a :=
have a - a < a - b ↔ b < a, from sub_lt_sub_iff_left a,
by rwa sub_self at this
@[simp] lemma sub_lt_zero : a - b < 0 ↔ a < b :=
have a - b < b - b ↔ a < b, from sub_lt_sub_iff_right b,
by rwa sub_self at this
lemma le_neg_add_iff_add_le : b ≤ -a + c ↔ a + b ≤ c :=
have -a + (a + b) ≤ -a + c ↔ a + b ≤ c, from add_le_add_iff_left _,
by rwa neg_add_cancel_left at this
lemma le_sub_iff_add_le' : b ≤ c - a ↔ a + b ≤ c :=
by rw [sub_eq_add_neg, add_comm, le_neg_add_iff_add_le]
lemma le_sub_iff_add_le : a ≤ c - b ↔ a + b ≤ c :=
by rw [le_sub_iff_add_le', add_comm]
@[simp] lemma neg_add_le_iff_le_add : -b + a ≤ c ↔ a ≤ b + c :=
have -b + a ≤ -b + (b + c) ↔ a ≤ b + c, from add_le_add_iff_left _,
by rwa neg_add_cancel_left at this
lemma sub_le_iff_le_add' : a - b ≤ c ↔ a ≤ b + c :=
by rw [sub_eq_add_neg, add_comm, neg_add_le_iff_le_add]
lemma sub_le_iff_le_add : a - c ≤ b ↔ a ≤ b + c :=
by rw [sub_le_iff_le_add', add_comm]
@[simp] lemma add_neg_le_iff_le_add : a + -c ≤ b ↔ a ≤ b + c :=
sub_le_iff_le_add
@[simp] lemma add_neg_le_iff_le_add' : a + -b ≤ c ↔ a ≤ b + c :=
sub_le_iff_le_add'
lemma neg_add_le_iff_le_add' : -c + a ≤ b ↔ a ≤ b + c :=
by rw [neg_add_le_iff_le_add, add_comm]
@[simp] lemma neg_le_sub_iff_le_add : -b ≤ a - c ↔ c ≤ a + b :=
le_sub_iff_add_le.trans neg_add_le_iff_le_add'
lemma neg_le_sub_iff_le_add' : -a ≤ b - c ↔ c ≤ a + b :=
by rw [neg_le_sub_iff_le_add, add_comm]
lemma sub_le : a - b ≤ c ↔ a - c ≤ b :=
sub_le_iff_le_add'.trans sub_le_iff_le_add.symm
theorem le_sub : a ≤ b - c ↔ c ≤ b - a :=
le_sub_iff_add_le'.trans le_sub_iff_add_le.symm
@[simp] lemma lt_neg_add_iff_add_lt : b < -a + c ↔ a + b < c :=
have -a + (a + b) < -a + c ↔ a + b < c, from add_lt_add_iff_left _,
by rwa neg_add_cancel_left at this
lemma lt_sub_iff_add_lt' : b < c - a ↔ a + b < c :=
by rw [sub_eq_add_neg, add_comm, lt_neg_add_iff_add_lt]
lemma lt_sub_iff_add_lt : a < c - b ↔ a + b < c :=
by rw [lt_sub_iff_add_lt', add_comm]
@[simp] lemma neg_add_lt_iff_lt_add : -b + a < c ↔ a < b + c :=
have -b + a < -b + (b + c) ↔ a < b + c, from add_lt_add_iff_left _,
by rwa neg_add_cancel_left at this
lemma sub_lt_iff_lt_add' : a - b < c ↔ a < b + c :=
by rw [sub_eq_add_neg, add_comm, neg_add_lt_iff_lt_add]
lemma sub_lt_iff_lt_add : a - c < b ↔ a < b + c :=
by rw [sub_lt_iff_lt_add', add_comm]
lemma neg_add_lt_iff_lt_add_right : -c + a < b ↔ a < b + c :=
by rw [neg_add_lt_iff_lt_add, add_comm]
@[simp] lemma neg_lt_sub_iff_lt_add : -b < a - c ↔ c < a + b :=
lt_sub_iff_add_lt.trans neg_add_lt_iff_lt_add_right
lemma neg_lt_sub_iff_lt_add' : -a < b - c ↔ c < a + b :=
by rw [neg_lt_sub_iff_lt_add, add_comm]
lemma sub_lt : a - b < c ↔ a - c < b :=
sub_lt_iff_lt_add'.trans sub_lt_iff_lt_add.symm
theorem lt_sub : a < b - c ↔ c < b - a :=
lt_sub_iff_add_lt'.trans lt_sub_iff_add_lt.symm
lemma sub_le_self_iff (a : α) {b : α} : a - b ≤ a ↔ 0 ≤ b :=
sub_le_iff_le_add'.trans (le_add_iff_nonneg_left _)
lemma sub_lt_self_iff (a : α) {b : α} : a - b < a ↔ 0 < b :=
sub_lt_iff_lt_add'.trans (lt_add_iff_pos_left _)
end ordered_comm_group
set_option old_structure_cmd true
/-- This is not so much a new structure as a construction mechanism
for ordered groups, by specifying only the "positive cone" of the group. -/
class nonneg_comm_group (α : Type*) extends add_comm_group α :=
(nonneg : α → Prop)
(pos : α → Prop := λ a, nonneg a ∧ ¬ nonneg (neg a))
(pos_iff : ∀ a, pos a ↔ nonneg a ∧ ¬ nonneg (-a) . order_laws_tac)
(zero_nonneg : nonneg 0)
(add_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a + b))
(nonneg_antisymm : ∀ {a}, nonneg a → nonneg (-a) → a = 0)
namespace nonneg_comm_group
variable [s : nonneg_comm_group α]
include s
@[reducible] instance to_ordered_comm_group : ordered_comm_group α :=
{ le := λ a b, nonneg (b - a),
lt := λ a b, pos (b - a),
lt_iff_le_not_le := λ a b, by simp; rw [pos_iff]; simp,
le_refl := λ a, by simp [zero_nonneg],
le_trans := λ a b c nab nbc, by simp [-sub_eq_add_neg];
rw ← sub_add_sub_cancel; exact add_nonneg nbc nab,
le_antisymm := λ a b nab nba, eq_of_sub_eq_zero $
nonneg_antisymm nba (by rw neg_sub; exact nab),
add_le_add_left := λ a b nab c, by simpa [(≤), preorder.le] using nab,
add_lt_add_left := λ a b nab c, by simpa [(<), preorder.lt] using nab, ..s }
theorem nonneg_def {a : α} : nonneg a ↔ 0 ≤ a :=
show _ ↔ nonneg _, by simp
theorem pos_def {a : α} : pos a ↔ 0 < a :=
show _ ↔ pos _, by simp
theorem not_zero_pos : ¬ pos (0 : α) :=
mt pos_def.1 (lt_irrefl _)
theorem zero_lt_iff_nonneg_nonneg {a : α} :
0 < a ↔ nonneg a ∧ ¬ nonneg (-a) :=
pos_def.symm.trans (pos_iff α _)
theorem nonneg_total_iff :
(∀ a : α, nonneg a ∨ nonneg (-a)) ↔
(∀ a b : α, a ≤ b ∨ b ≤ a) :=
⟨λ h a b, by have := h (b - a); rwa [neg_sub] at this,
λ h a, by rw [nonneg_def, nonneg_def, neg_nonneg]; apply h⟩
def to_decidable_linear_ordered_comm_group
[decidable_pred (@nonneg α _)]
(nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a))
: decidable_linear_ordered_comm_group α :=
{ le := (≤),
lt := (<),
lt_iff_le_not_le := @lt_iff_le_not_le _ _,
le_refl := @le_refl _ _,
le_trans := @le_trans _ _,
le_antisymm := @le_antisymm _ _,
le_total := nonneg_total_iff.1 nonneg_total,
decidable_le := by apply_instance,
decidable_eq := by apply_instance,
decidable_lt := by apply_instance,
..@nonneg_comm_group.to_ordered_comm_group _ s }
end nonneg_comm_group
|
8da2c785bfe94d11f6d1902c517caeb7edb2758d | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/pfun.lean | 588dcd7a2adbb3054e04aa4784992f4db01e2844 | [
"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 | 22,742 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Jeremy Avigad, Simon Hudon
-/
import data.part
import data.rel
/-!
# Partial functions
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines partial functions. Partial functions are like functions, except they can also be
"undefined" on some inputs. We define them as functions `α → part β`.
## Definitions
* `pfun α β`: Type of partial functions from `α` to `β`. Defined as `α → part β` and denoted
`α →. β`.
* `pfun.dom`: Domain of a partial function. Set of values on which it is defined. Not to be confused
with the domain of a function `α → β`, which is a type (`α` presently).
* `pfun.fn`: Evaluation of a partial function. Takes in an element and a proof it belongs to the
partial function's `dom`.
* `pfun.as_subtype`: Returns a partial function as a function from its `dom`.
* `pfun.to_subtype`: Restricts the codomain of a function to a subtype.
* `pfun.eval_opt`: Returns a partial function with a decidable `dom` as a function `a → option β`.
* `pfun.lift`: Turns a function into a partial function.
* `pfun.id`: The identity as a partial function.
* `pfun.comp`: Composition of partial functions.
* `pfun.restrict`: Restriction of a partial function to a smaller `dom`.
* `pfun.res`: Turns a function into a partial function with a prescribed domain.
* `pfun.fix` : First return map of a partial function `f : α →. β ⊕ α`.
* `pfun.fix_induction`: A recursion principle for `pfun.fix`.
### Partial functions as relations
Partial functions can be considered as relations, so we specialize some `rel` definitions to `pfun`:
* `pfun.image`: Image of a set under a partial function.
* `pfun.ran`: Range of a partial function.
* `pfun.preimage`: Preimage of a set under a partial function.
* `pfun.core`: Core of a set under a partial function.
* `pfun.graph`: Graph of a partial function `a →. β`as a `set (α × β)`.
* `pfun.graph'`: Graph of a partial function `a →. β`as a `rel α β`.
### `pfun α` as a monad
Monad operations:
* `pfun.pure`: The monad `pure` function, the constant `x` function.
* `pfun.bind`: The monad `bind` function, pointwise `part.bind`
* `pfun.map`: The monad `map` function, pointwise `part.map`.
-/
open function
/-- `pfun α β`, or `α →. β`, is the type of partial functions from
`α` to `β`. It is defined as `α → part β`. -/
def pfun (α β : Type*) := α → part β
infixr ` →. `:25 := pfun
namespace pfun
variables {α β γ δ ε ι : Type*}
instance : inhabited (α →. β) := ⟨λ a, part.none⟩
/-- The domain of a partial function -/
def dom (f : α →. β) : set α := {a | (f a).dom}
@[simp] lemma mem_dom (f : α →. β) (x : α) : x ∈ dom f ↔ ∃ y, y ∈ f x :=
by simp [dom, part.dom_iff_mem]
@[simp] lemma dom_mk (p : α → Prop) (f : Π a, p a → β) : pfun.dom (λ x, ⟨p x, f x⟩) = {x | p x} :=
rfl
theorem dom_eq (f : α →. β) : dom f = {x | ∃ y, y ∈ f x} :=
set.ext (mem_dom f)
/-- Evaluate a partial function -/
def fn (f : α →. β) (a : α) : dom f a → β := (f a).get
@[simp] lemma fn_apply (f : α →. β) (a : α) : f.fn a = (f a).get := rfl
/-- Evaluate a partial function to return an `option` -/
def eval_opt (f : α →. β) [D : decidable_pred (∈ dom f)] (x : α) : option β :=
@part.to_option _ _ (D x)
/-- Partial function extensionality -/
theorem ext' {f g : α →. β}
(H1 : ∀ a, a ∈ dom f ↔ a ∈ dom g)
(H2 : ∀ a p q, f.fn a p = g.fn a q) : f = g :=
funext $ λ a, part.ext' (H1 a) (H2 a)
theorem ext {f g : α →. β} (H : ∀ a b, b ∈ f a ↔ b ∈ g a) : f = g :=
funext $ λ a, part.ext (H a)
/-- Turns a partial function into a function out of its domain. -/
def as_subtype (f : α →. β) (s : f.dom) : β := f.fn s s.2
/-- The type of partial functions `α →. β` is equivalent to
the type of pairs `(p : α → Prop, f : subtype p → β)`. -/
def equiv_subtype : (α →. β) ≃ (Σ p : α → Prop, subtype p → β) :=
⟨λ f, ⟨λ a, (f a).dom, as_subtype f⟩,
λ f x, ⟨f.1 x, λ h, f.2 ⟨x, h⟩⟩,
λ f, funext $ λ a, part.eta _,
λ ⟨p, f⟩, by dsimp; congr; funext a; cases a; refl⟩
theorem as_subtype_eq_of_mem {f : α →. β} {x : α} {y : β} (fxy : y ∈ f x) (domx : x ∈ f.dom) :
f.as_subtype ⟨x, domx⟩ = y :=
part.mem_unique (part.get_mem _) fxy
/-- Turn a total function into a partial function. -/
protected def lift (f : α → β) : α →. β := λ a, part.some (f a)
instance : has_coe (α → β) (α →. β) := ⟨pfun.lift⟩
@[simp] theorem lift_eq_coe (f : α → β) : pfun.lift f = f := rfl
@[simp] theorem coe_val (f : α → β) (a : α) :
(f : α →. β) a = part.some (f a) := rfl
@[simp] lemma dom_coe (f : α → β) : (f : α →. β).dom = set.univ := rfl
lemma coe_injective : injective (coe : (α → β) → α →. β) :=
λ f g h, funext $ λ a, part.some_injective $ congr_fun h a
/-- Graph of a partial function `f` as the set of pairs `(x, f x)` where `x` is in the domain of
`f`. -/
def graph (f : α →. β) : set (α × β) := {p | p.2 ∈ f p.1}
/-- Graph of a partial function as a relation. `x` and `y` are related iff `f x` is defined and
"equals" `y`. -/
def graph' (f : α →. β) : rel α β := λ x y, y ∈ f x
/-- The range of a partial function is the set of values
`f x` where `x` is in the domain of `f`. -/
def ran (f : α →. β) : set β := {b | ∃ a, b ∈ f a}
/-- Restrict a partial function to a smaller domain. -/
def restrict (f : α →. β) {p : set α} (H : p ⊆ f.dom) : α →. β :=
λ x, (f x).restrict (x ∈ p) (@H x)
@[simp]
theorem mem_restrict {f : α →. β} {s : set α} (h : s ⊆ f.dom) (a : α) (b : β) :
b ∈ f.restrict h a ↔ a ∈ s ∧ b ∈ f a :=
by simp [restrict]
/-- Turns a function into a partial function with a prescribed domain. -/
def res (f : α → β) (s : set α) : α →. β :=
(pfun.lift f).restrict s.subset_univ
theorem mem_res (f : α → β) (s : set α) (a : α) (b : β) :
b ∈ res f s a ↔ (a ∈ s ∧ f a = b) :=
by simp [res, @eq_comm _ b]
theorem res_univ (f : α → β) : pfun.res f set.univ = f :=
rfl
theorem dom_iff_graph (f : α →. β) (x : α) : x ∈ f.dom ↔ ∃ y, (x, y) ∈ f.graph :=
part.dom_iff_mem
theorem lift_graph {f : α → β} {a b} : (a, b) ∈ (f : α →. β).graph ↔ f a = b :=
show (∃ (h : true), f a = b) ↔ f a = b, by simp
/-- The monad `pure` function, the total constant `x` function -/
protected def pure (x : β) : α →. β := λ _, part.some x
/-- The monad `bind` function, pointwise `part.bind` -/
def bind (f : α →. β) (g : β → α →. γ) : α →. γ :=
λ a, (f a).bind (λ b, g b a)
@[simp] lemma bind_apply (f : α →. β) (g : β → α →. γ) (a : α) :
f.bind g a = (f a).bind (λ b, g b a) := rfl
/-- The monad `map` function, pointwise `part.map` -/
def map (f : β → γ) (g : α →. β) : α →. γ :=
λ a, (g a).map f
instance : monad (pfun α) :=
{ pure := @pfun.pure _,
bind := @pfun.bind _,
map := @pfun.map _ }
instance : is_lawful_monad (pfun α) :=
{ bind_pure_comp_eq_map := λ β γ f x, funext $ λ a, part.bind_some_eq_map _ _,
id_map := λ β f, by funext a; dsimp [functor.map, pfun.map]; cases f a; refl,
pure_bind := λ β γ x f, funext $ λ a, part.bind_some.{u_1 u_2} _ (f x),
bind_assoc := λ β γ δ f g k,
funext $ λ a, (f a).bind_assoc (λ b, g b a) (λ b, k b a) }
theorem pure_defined (p : set α) (x : β) : p ⊆ (@pfun.pure α _ x).dom := p.subset_univ
theorem bind_defined {α β γ} (p : set α) {f : α →. β} {g : β → α →. γ}
(H1 : p ⊆ f.dom) (H2 : ∀ x, p ⊆ (g x).dom) : p ⊆ (f >>= g).dom :=
λ a ha, (⟨H1 ha, H2 _ ha⟩ : (f >>= g).dom a)
/-- First return map. Transforms a partial function `f : α →. β ⊕ α` into the partial function
`α →. β` which sends `a : α` to the first value in `β` it hits by iterating `f`, if such a value
exists. By abusing notation to illustrate, either `f a` is in the `β` part of `β ⊕ α` (in which
case `f.fix a` returns `f a`), or it is undefined (in which case `f.fix a` is undefined as well), or
it is in the `α` part of `β ⊕ α` (in which case we repeat the procedure, so `f.fix a` will return
`f.fix (f a)`). -/
def fix (f : α →. β ⊕ α) : α →. β := λ a,
part.assert (acc (λ x y, sum.inr x ∈ f y) a) $ λ h,
@well_founded.fix_F _ (λ x y, sum.inr x ∈ f y) _
(λ a IH, part.assert (f a).dom $ λ hf,
by cases e : (f a).get hf with b a';
[exact part.some b, exact IH _ ⟨hf, e⟩])
a h
theorem dom_of_mem_fix {f : α →. β ⊕ α} {a : α} {b : β}
(h : b ∈ f.fix a) : (f a).dom :=
let ⟨h₁, h₂⟩ := part.mem_assert_iff.1 h in
by rw well_founded.fix_F_eq at h₂; exact h₂.fst.fst
theorem mem_fix_iff {f : α →. β ⊕ α} {a : α} {b : β} :
b ∈ f.fix a ↔ sum.inl b ∈ f a ∨ ∃ a', sum.inr a' ∈ f a ∧ b ∈ f.fix a' :=
⟨λ h, let ⟨h₁, h₂⟩ := part.mem_assert_iff.1 h in
begin
rw well_founded.fix_F_eq at h₂,
simp at h₂,
cases h₂ with h₂ h₃,
cases e : (f a).get h₂ with b' a'; simp [e] at h₃,
{ subst b', refine or.inl ⟨h₂, e⟩ },
{ exact or.inr ⟨a', ⟨_, e⟩, part.mem_assert _ h₃⟩ }
end,
λ h, begin
simp [fix],
rcases h with ⟨h₁, h₂⟩ | ⟨a', h, h₃⟩,
{ refine ⟨⟨_, λ y h', _⟩, _⟩,
{ injection part.mem_unique ⟨h₁, h₂⟩ h' },
{ rw well_founded.fix_F_eq, simp [h₁, h₂] } },
{ simp [fix] at h₃, cases h₃ with h₃ h₄,
refine ⟨⟨_, λ y h', _⟩, _⟩,
{ injection part.mem_unique h h' with e,
exact e ▸ h₃ },
{ cases h with h₁ h₂,
rw well_founded.fix_F_eq, simp [h₁, h₂, h₄] } }
end⟩
/-- If advancing one step from `a` leads to `b : β`, then `f.fix a = b` -/
theorem fix_stop {f : α →. β ⊕ α} {b : β} {a : α} (hb : sum.inl b ∈ f a) : b ∈ f.fix a :=
by { rw [pfun.mem_fix_iff], exact or.inl hb, }
/-- If advancing one step from `a` on `f` leads to `a' : α`, then `f.fix a = f.fix a'` -/
theorem fix_fwd_eq {f : α →. β ⊕ α} {a a' : α} (ha' : sum.inr a' ∈ f a) :
f.fix a = f.fix a' :=
begin
ext b, split,
{ intro h, obtain h' | ⟨a, h', e'⟩ := mem_fix_iff.1 h; cases part.mem_unique ha' h', exact e', },
{ intro h, rw pfun.mem_fix_iff, right, use a', exact ⟨ha', h⟩, }
end
theorem fix_fwd {f : α →. β ⊕ α} {b : β} {a a' : α} (hb : b ∈ f.fix a) (ha' : sum.inr a' ∈ f a) :
b ∈ f.fix a' :=
by rwa [← fix_fwd_eq ha']
/-- A recursion principle for `pfun.fix`. -/
@[elab_as_eliminator]
def fix_induction {C : α → Sort*} {f : α →. β ⊕ α} {b : β} {a : α} (h : b ∈ f.fix a)
(H : ∀ a', b ∈ f.fix a' → (∀ a'', sum.inr a'' ∈ f a' → C a'') → C a') : C a :=
begin
have h₂ := (part.mem_assert_iff.1 h).snd, generalize_proofs h₁ at h₂, clear h,
induction h₁ with a ha IH,
have h : b ∈ f.fix a := part.mem_assert_iff.2 ⟨⟨a, ha⟩, h₂⟩,
exact H a h (λ a' fa', IH a' fa' ((part.mem_assert_iff.1 (fix_fwd h fa')).snd)),
end
lemma fix_induction_spec {C : α → Sort*} {f : α →. β ⊕ α} {b : β} {a : α} (h : b ∈ f.fix a)
(H : ∀ a', b ∈ f.fix a' → (∀ a'', sum.inr a'' ∈ f a' → C a'') → C a') :
@fix_induction _ _ C _ _ _ h H = H a h (λ a' h', fix_induction (fix_fwd h h') H) :=
by { unfold fix_induction, generalize_proofs ha, induction ha, refl, }
/--
Another induction lemma for `b ∈ f.fix a` which allows one to prove a predicate `P` holds for
`a` given that `f a` inherits `P` from `a` and `P` holds for preimages of `b`.
-/
@[elab_as_eliminator]
def fix_induction' {C : α → Sort*} {f : α →. β ⊕ α} {b : β} {a : α} (h : b ∈ f.fix a)
(hbase : ∀ a_final : α, sum.inl b ∈ f a_final → C a_final)
(hind : ∀ a₀ a₁ : α, b ∈ f.fix a₁ → sum.inr a₁ ∈ f a₀ → C a₁ → C a₀) : C a :=
begin
refine fix_induction h (λ a' h ih, _),
cases e : (f a').get (dom_of_mem_fix h) with b' a''; replace e : _ ∈ f a' := ⟨_, e⟩,
{ apply hbase, convert e, exact part.mem_unique h (fix_stop e), },
{ exact hind _ _ (fix_fwd h e) e (ih _ e), },
end
lemma fix_induction'_stop {C : α → Sort*} {f : α →. β ⊕ α} {b : β} {a : α}
(h : b ∈ f.fix a) (fa : sum.inl b ∈ f a)
(hbase : ∀ a_final : α, sum.inl b ∈ f a_final → C a_final)
(hind : ∀ a₀ a₁ : α, b ∈ f.fix a₁ → sum.inr a₁ ∈ f a₀ → C a₁ → C a₀) :
@fix_induction' _ _ C _ _ _ h hbase hind = hbase a fa :=
by { unfold fix_induction', rw [fix_induction_spec], simp [part.get_eq_of_mem fa], }
lemma fix_induction'_fwd {C : α → Sort*} {f : α →. β ⊕ α} {b : β} {a a' : α}
(h : b ∈ f.fix a) (h' : b ∈ f.fix a') (fa : sum.inr a' ∈ f a)
(hbase : ∀ a_final : α, sum.inl b ∈ f a_final → C a_final)
(hind : ∀ a₀ a₁ : α, b ∈ f.fix a₁ → sum.inr a₁ ∈ f a₀ → C a₁ → C a₀) :
@fix_induction' _ _ C _ _ _ h hbase hind = hind a a' h' fa (fix_induction' h' hbase hind) :=
by { unfold fix_induction', rw [fix_induction_spec], simpa [part.get_eq_of_mem fa], }
variables (f : α →. β)
/-- Image of a set under a partial function. -/
def image (s : set α) : set β := f.graph'.image s
lemma image_def (s : set α) : f.image s = {y | ∃ x ∈ s, y ∈ f x} := rfl
lemma mem_image (y : β) (s : set α) : y ∈ f.image s ↔ ∃ x ∈ s, y ∈ f x :=
iff.rfl
lemma image_mono {s t : set α} (h : s ⊆ t) : f.image s ⊆ f.image t :=
rel.image_mono _ h
lemma image_inter (s t : set α) : f.image (s ∩ t) ⊆ f.image s ∩ f.image t :=
rel.image_inter _ s t
lemma image_union (s t : set α) : f.image (s ∪ t) = f.image s ∪ f.image t :=
rel.image_union _ s t
/-- Preimage of a set under a partial function. -/
def preimage (s : set β) : set α := rel.image (λ x y, x ∈ f y) s
lemma preimage_def (s : set β) : f.preimage s = {x | ∃ y ∈ s, y ∈ f x} := rfl
@[simp] lemma mem_preimage (s : set β) (x : α) : x ∈ f.preimage s ↔ ∃ y ∈ s, y ∈ f x := iff.rfl
lemma preimage_subset_dom (s : set β) : f.preimage s ⊆ f.dom :=
λ x ⟨y, ys, fxy⟩, part.dom_iff_mem.mpr ⟨y, fxy⟩
lemma preimage_mono {s t : set β} (h : s ⊆ t) : f.preimage s ⊆ f.preimage t :=
rel.preimage_mono _ h
lemma preimage_inter (s t : set β) : f.preimage (s ∩ t) ⊆ f.preimage s ∩ f.preimage t :=
rel.preimage_inter _ s t
lemma preimage_union (s t : set β) : f.preimage (s ∪ t) = f.preimage s ∪ f.preimage t :=
rel.preimage_union _ s t
lemma preimage_univ : f.preimage set.univ = f.dom :=
by ext; simp [mem_preimage, mem_dom]
lemma coe_preimage (f : α → β) (s : set β) : (f : α →. β).preimage s = f ⁻¹' s :=
by ext; simp
/-- Core of a set `s : set β` with respect to a partial function `f : α →. β`. Set of all `a : α`
such that `f a ∈ s`, if `f a` is defined. -/
def core (s : set β) : set α := f.graph'.core s
lemma core_def (s : set β) : f.core s = {x | ∀ y, y ∈ f x → y ∈ s} := rfl
@[simp] lemma mem_core (x : α) (s : set β) : x ∈ f.core s ↔ ∀ y, y ∈ f x → y ∈ s := iff.rfl
lemma compl_dom_subset_core (s : set β) : f.domᶜ ⊆ f.core s :=
λ x hx y fxy,
absurd ((mem_dom f x).mpr ⟨y, fxy⟩) hx
lemma core_mono {s t : set β} (h : s ⊆ t) : f.core s ⊆ f.core t :=
rel.core_mono _ h
lemma core_inter (s t : set β) : f.core (s ∩ t) = f.core s ∩ f.core t :=
rel.core_inter _ s t
lemma mem_core_res (f : α → β) (s : set α) (t : set β) (x : α) :
x ∈ (res f s).core t ↔ x ∈ s → f x ∈ t :=
by simp [mem_core, mem_res]
section
open_locale classical
lemma core_res (f : α → β) (s : set α) (t : set β) : (res f s).core t = sᶜ ∪ f ⁻¹' t :=
by { ext, rw mem_core_res, by_cases h : x ∈ s; simp [h] }
end
lemma core_restrict (f : α → β) (s : set β) : (f : α →. β).core s = s.preimage f :=
by ext x; simp [core_def]
lemma preimage_subset_core (f : α →. β) (s : set β) : f.preimage s ⊆ f.core s :=
λ x ⟨y, ys, fxy⟩ y' fxy',
have y = y', from part.mem_unique fxy fxy',
this ▸ ys
lemma preimage_eq (f : α →. β) (s : set β) : f.preimage s = f.core s ∩ f.dom :=
set.eq_of_subset_of_subset
(set.subset_inter (f.preimage_subset_core s) (f.preimage_subset_dom s))
(λ x ⟨xcore, xdom⟩,
let y := (f x).get xdom in
have ys : y ∈ s, from xcore _ (part.get_mem _),
show x ∈ f.preimage s, from ⟨(f x).get xdom, ys, part.get_mem _⟩)
lemma core_eq (f : α →. β) (s : set β) : f.core s = f.preimage s ∪ f.domᶜ :=
by rw [preimage_eq, set.union_distrib_right, set.union_comm (dom f), set.compl_union_self,
set.inter_univ, set.union_eq_self_of_subset_right (f.compl_dom_subset_core s)]
lemma preimage_as_subtype (f : α →. β) (s : set β) :
f.as_subtype ⁻¹' s = subtype.val ⁻¹' f.preimage s :=
begin
ext x,
simp only [set.mem_preimage, set.mem_set_of_eq, pfun.as_subtype, pfun.mem_preimage],
show f.fn (x.val) _ ∈ s ↔ ∃ y ∈ s, y ∈ f (x.val),
exact iff.intro
(λ h, ⟨_, h, part.get_mem _⟩)
(λ ⟨y, ys, fxy⟩,
have f.fn x.val x.property ∈ f x.val := part.get_mem _,
part.mem_unique fxy this ▸ ys)
end
/-- Turns a function into a partial function to a subtype. -/
def to_subtype (p : β → Prop) (f : α → β) : α →. subtype p := λ a, ⟨p (f a), subtype.mk _⟩
@[simp] lemma dom_to_subtype (p : β → Prop) (f : α → β) : (to_subtype p f).dom = {a | p (f a)} :=
rfl
@[simp] lemma to_subtype_apply (p : β → Prop) (f : α → β) (a : α) :
to_subtype p f a = ⟨p (f a), subtype.mk _⟩ := rfl
lemma dom_to_subtype_apply_iff {p : β → Prop} {f : α → β} {a : α} :
(to_subtype p f a).dom ↔ p (f a) := iff.rfl
lemma mem_to_subtype_iff {p : β → Prop} {f : α → β} {a : α} {b : subtype p} :
b ∈ to_subtype p f a ↔ ↑b = f a :=
by rw [to_subtype_apply, part.mem_mk_iff, exists_subtype_mk_eq_iff, eq_comm]
/-- The identity as a partial function -/
protected def id (α : Type*) : α →. α := part.some
@[simp] lemma coe_id (α : Type*) : ((id : α → α) : α →. α) = pfun.id α := rfl
@[simp] lemma id_apply (a : α) : pfun.id α a = part.some a := rfl
/-- Composition of partial functions as a partial function. -/
def comp (f : β →. γ) (g : α →. β) : α →. γ := λ a, (g a).bind f
@[simp] lemma comp_apply (f : β →. γ) (g : α →. β) (a : α) : f.comp g a = (g a).bind f := rfl
@[simp] lemma id_comp (f : α →. β) : (pfun.id β).comp f = f := ext $ λ _ _, by simp
@[simp] lemma comp_id (f : α →. β) : f.comp (pfun.id α) = f := ext $ λ _ _, by simp
@[simp] lemma dom_comp (f : β →. γ) (g : α →. β) : (f.comp g).dom = g.preimage f.dom :=
begin
ext,
simp_rw [mem_preimage, mem_dom, comp_apply, part.mem_bind_iff, exists_prop,
←exists_and_distrib_right],
rw exists_comm,
simp_rw and.comm,
end
@[simp] lemma preimage_comp (f : β →. γ) (g : α →. β) (s :set γ) :
(f.comp g).preimage s = g.preimage (f.preimage s) :=
begin
ext,
simp_rw [mem_preimage, comp_apply, part.mem_bind_iff, exists_prop, ←exists_and_distrib_right,
←exists_and_distrib_left],
rw exists_comm,
simp_rw [and_assoc, and.comm],
end
@[simp] lemma _root_.part.bind_comp (f : β →. γ) (g : α →. β) (a : part α) :
a.bind (f.comp g) = (a.bind g).bind f :=
begin
ext c,
simp_rw [part.mem_bind_iff, comp_apply, part.mem_bind_iff, exists_prop, ←exists_and_distrib_right,
←exists_and_distrib_left],
rw exists_comm,
simp_rw and_assoc,
end
@[simp] lemma comp_assoc (f : γ →. δ) (g : β →. γ) (h : α →. β) :
(f.comp g).comp h = f.comp (g.comp h) :=
ext $ λ _ _, by simp only [comp_apply, part.bind_comp]
-- This can't be `simp`
lemma coe_comp (g : β → γ) (f : α → β) : ((g ∘ f : α → γ) : α →. γ) = (g : β →. γ).comp f :=
ext $ λ _ _, by simp only [coe_val, comp_apply, part.bind_some]
/-- Product of partial functions. -/
def prod_lift (f : α →. β) (g : α →. γ) : α →. β × γ :=
λ x, ⟨(f x).dom ∧ (g x).dom, λ h, ((f x).get h.1, (g x).get h.2)⟩
@[simp] lemma dom_prod_lift (f : α →. β) (g : α →. γ) :
(f.prod_lift g).dom = {x | (f x).dom ∧ (g x).dom} := rfl
lemma get_prod_lift (f : α →. β) (g : α →. γ) (x : α) (h) :
(f.prod_lift g x).get h = ((f x).get h.1, (g x).get h.2) := rfl
@[simp] lemma prod_lift_apply (f : α →. β) (g : α →. γ) (x : α) :
f.prod_lift g x = ⟨(f x).dom ∧ (g x).dom, λ h, ((f x).get h.1, (g x).get h.2)⟩ := rfl
lemma mem_prod_lift {f : α →. β} {g : α →. γ} {x : α} {y : β × γ} :
y ∈ f.prod_lift g x ↔ y.1 ∈ f x ∧ y.2 ∈ g x :=
begin
transitivity ∃ hp hq, (f x).get hp = y.1 ∧ (g x).get hq = y.2,
{ simp only [prod_lift, part.mem_mk_iff, and.exists, prod.ext_iff] },
{ simpa only [exists_and_distrib_left, exists_and_distrib_right] }
end
/-- Product of partial functions. -/
def prod_map (f : α →. γ) (g : β →. δ) : α × β →. γ × δ :=
λ x, ⟨(f x.1).dom ∧ (g x.2).dom, λ h, ((f x.1).get h.1, (g x.2).get h.2)⟩
@[simp] lemma dom_prod_map (f : α →. γ) (g : β →. δ) :
(f.prod_map g).dom = {x | (f x.1).dom ∧ (g x.2).dom} := rfl
lemma get_prod_map (f : α →. γ) (g : β →. δ) (x : α × β) (h) :
(f.prod_map g x).get h = ((f x.1).get h.1, (g x.2).get h.2) := rfl
@[simp] lemma prod_map_apply (f : α →. γ) (g : β →. δ) (x : α × β) :
f.prod_map g x = ⟨(f x.1).dom ∧ (g x.2).dom, λ h, ((f x.1).get h.1, (g x.2).get h.2)⟩ := rfl
lemma mem_prod_map {f : α →. γ} {g : β →. δ} {x : α × β} {y : γ × δ} :
y ∈ f.prod_map g x ↔ y.1 ∈ f x.1 ∧ y.2 ∈ g x.2 :=
begin
transitivity ∃ hp hq, (f x.1).get hp = y.1 ∧ (g x.2).get hq = y.2,
{ simp only [prod_map, part.mem_mk_iff, and.exists, prod.ext_iff] },
{ simpa only [exists_and_distrib_left, exists_and_distrib_right] }
end
@[simp] lemma prod_lift_fst_comp_snd_comp (f : α →. γ) (g : β →. δ) :
prod_lift (f.comp ((prod.fst : α × β → α) : α × β →. α))
(g.comp ((prod.snd : α × β → β) : α × β →. β)) = prod_map f g :=
ext $ λ a, by simp
@[simp] lemma prod_map_id_id : (pfun.id α).prod_map (pfun.id β) = pfun.id _ :=
ext $ λ _ _, by simp [eq_comm]
@[simp] lemma prod_map_comp_comp (f₁ : α →. β) (f₂ : β →. γ) (g₁ : δ →. ε) (g₂ : ε →. ι) :
(f₂.comp f₁).prod_map (g₂.comp g₁) = (f₂.prod_map g₂).comp (f₁.prod_map g₁) :=
ext $ λ _ _, by tidy
end pfun
|
d19eefc34a93162284294d5b626bc5296344f542 | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/group_theory/subgroup.lean | 7706b153611dd588e95bae1c6cfbf8d5c02f657b | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 30,323 | lean | /-
Copyright (c) 2018 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mitchell Rowett, Scott Morrison, Johan Commelin, Mario Carneiro
-/
import group_theory.submonoid
open set function
variables {α : Type*} {β : Type*} {a a₁ a₂ b c: α}
section group
variables [group α] [add_group β]
@[to_additive injective_add]
lemma injective_mul {a : α} : injective ((*) a) :=
assume a₁ a₂ h,
have a⁻¹ * a * a₁ = a⁻¹ * a * a₂, by rw [mul_assoc, mul_assoc, h],
by rwa [inv_mul_self, one_mul, one_mul] at this
/-- `s` is a subgroup: a set containing 1 and closed under multiplication and inverse. -/
class is_subgroup (s : set α) extends is_submonoid s : Prop :=
(inv_mem {a} : a ∈ s → a⁻¹ ∈ s)
/-- `s` is an additive subgroup: a set containing 0 and closed under addition and negation. -/
class is_add_subgroup (s : set β) extends is_add_submonoid s : Prop :=
(neg_mem {a} : a ∈ s → -a ∈ s)
attribute [to_additive is_add_subgroup] is_subgroup
attribute [to_additive is_add_subgroup.to_is_add_submonoid] is_subgroup.to_is_submonoid
attribute [to_additive is_add_subgroup.neg_mem] is_subgroup.inv_mem
attribute [to_additive is_add_subgroup.mk] is_subgroup.mk
instance additive.is_add_subgroup
(s : set α) [is_subgroup s] : @is_add_subgroup (additive α) _ s :=
⟨@is_subgroup.inv_mem _ _ _ _⟩
theorem additive.is_add_subgroup_iff
{s : set α} : @is_add_subgroup (additive α) _ s ↔ is_subgroup s :=
⟨by rintro ⟨⟨h₁, h₂⟩, h₃⟩; exact @is_subgroup.mk α _ _ ⟨h₁, @h₂⟩ @h₃,
λ h, by resetI; apply_instance⟩
instance multiplicative.is_subgroup
(s : set β) [is_add_subgroup s] : @is_subgroup (multiplicative β) _ s :=
⟨@is_add_subgroup.neg_mem _ _ _ _⟩
theorem multiplicative.is_subgroup_iff
{s : set β} : @is_subgroup (multiplicative β) _ s ↔ is_add_subgroup s :=
⟨by rintro ⟨⟨h₁, h₂⟩, h₃⟩; exact @is_add_subgroup.mk β _ _ ⟨h₁, @h₂⟩ @h₃,
λ h, by resetI; apply_instance⟩
instance subtype.group {s : set α} [is_subgroup s] : group s :=
by subtype_instance
instance subtype.add_group {s : set β} [is_add_subgroup s] : add_group s :=
by subtype_instance
attribute [to_additive subtype.add_group] subtype.group
attribute [to_additive subtype.add_group._proof_1] subtype.group._proof_1
attribute [to_additive subtype.add_group._proof_2] subtype.group._proof_2
attribute [to_additive subtype.add_group._proof_3] subtype.group._proof_3
attribute [to_additive subtype.add_group._proof_4] subtype.group._proof_4
attribute [to_additive subtype.add_group._proof_5] subtype.group._proof_5
attribute [to_additive subtype.add_group.equations._eqn_1] subtype.group.equations._eqn_1
instance subtype.comm_group {α : Type*} [comm_group α] {s : set α} [is_subgroup s] : comm_group s :=
by subtype_instance
instance subtype.add_comm_group {α : Type*} [add_comm_group α] {s : set α} [is_add_subgroup s] :
add_comm_group s := by subtype_instance
attribute [to_additive subtype.add_comm_group] subtype.comm_group
@[simp, to_additive is_add_subgroup.coe_neg]
lemma is_subgroup.coe_inv {s : set α} [is_subgroup s] (a : s) : ((a⁻¹ : s) : α) = a⁻¹ := rfl
@[simp] lemma is_subgroup.coe_gpow {s : set α} [is_subgroup s] (a : s) (n : ℤ) : ((a ^ n : s) : α) = a ^ n :=
by induction n; simp [is_submonoid.coe_pow a]
@[simp] lemma is_add_subgroup.gsmul_coe {β : Type*} [add_group β] {s : set β} [is_add_subgroup s] (a : s) (n : ℤ) :
((gsmul n a : s) : β) = gsmul n a :=
by induction n; simp [is_add_submonoid.smul_coe a]
attribute [to_additive is_add_subgroup.gsmul_coe] is_subgroup.coe_gpow
theorem is_subgroup.of_div (s : set α)
(one_mem : (1:α) ∈ s) (div_mem : ∀{a b:α}, a ∈ s → b ∈ s → a * b⁻¹ ∈ s):
is_subgroup s :=
have inv_mem : ∀a, a ∈ s → a⁻¹ ∈ s, from
assume a ha,
have 1 * a⁻¹ ∈ s, from div_mem one_mem ha,
by simpa,
{ inv_mem := inv_mem,
mul_mem := assume a b ha hb,
have a * b⁻¹⁻¹ ∈ s, from div_mem ha (inv_mem b hb),
by simpa,
one_mem := one_mem }
theorem is_add_subgroup.of_sub (s : set β)
(zero_mem : (0:β) ∈ s) (sub_mem : ∀{a b:β}, a ∈ s → b ∈ s → a - b ∈ s):
is_add_subgroup s :=
multiplicative.is_subgroup_iff.1 $
@is_subgroup.of_div (multiplicative β) _ _ zero_mem @sub_mem
@[to_additive is_add_subgroup_Union_of_directed]
lemma is_subgroup_Union_of_directed {ι : Type*} [hι : nonempty ι]
(s : ι → set α) [∀ i, is_subgroup (s i)]
(directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) :
is_subgroup (⋃i, s i) :=
{ inv_mem := λ a ha,
let ⟨i, hi⟩ := set.mem_Union.1 ha in
set.mem_Union.2 ⟨i, is_subgroup.inv_mem hi⟩,
to_is_submonoid := is_submonoid_Union_of_directed s directed }
def gpowers (x : α) : set α := set.range ((^) x : ℤ → α)
def gmultiples (x : β) : set β := set.range (λ i, gsmul i x)
attribute [to_additive gmultiples] gpowers
instance gpowers.is_subgroup (x : α) : is_subgroup (gpowers x) :=
{ one_mem := ⟨(0:ℤ), by simp⟩,
mul_mem := assume x₁ x₂ ⟨i₁, h₁⟩ ⟨i₂, h₂⟩, ⟨i₁ + i₂, by simp [gpow_add, *]⟩,
inv_mem := assume x₀ ⟨i, h⟩, ⟨-i, by simp [h.symm]⟩ }
instance gmultiples.is_add_subgroup (x : β) : is_add_subgroup (gmultiples x) :=
multiplicative.is_subgroup_iff.1 $ gpowers.is_subgroup _
attribute [to_additive gmultiples.is_add_subgroup] gpowers.is_subgroup
lemma is_subgroup.gpow_mem {a : α} {s : set α} [is_subgroup s] (h : a ∈ s) : ∀{i:ℤ}, a ^ i ∈ s
| (n : ℕ) := is_submonoid.pow_mem h
| -[1+ n] := is_subgroup.inv_mem (is_submonoid.pow_mem h)
lemma is_add_subgroup.gsmul_mem {a : β} {s : set β} [is_add_subgroup s] : a ∈ s → ∀{i:ℤ}, gsmul i a ∈ s :=
@is_subgroup.gpow_mem (multiplicative β) _ _ _ _
lemma mem_gpowers {a : α} : a ∈ gpowers a := ⟨1, by simp⟩
lemma mem_gmultiples {a : β} : a ∈ gmultiples a := ⟨1, by simp⟩
attribute [to_additive mem_gmultiples] mem_gpowers
end group
namespace is_subgroup
open is_submonoid
variables [group α] (s : set α) [is_subgroup s]
@[to_additive is_add_subgroup.neg_mem_iff]
lemma inv_mem_iff : a⁻¹ ∈ s ↔ a ∈ s :=
⟨λ h, by simpa using inv_mem h, inv_mem⟩
@[to_additive is_add_subgroup.add_mem_cancel_left]
lemma mul_mem_cancel_left (h : a ∈ s) : b * a ∈ s ↔ b ∈ s :=
⟨λ hba, by simpa using mul_mem hba (inv_mem h), λ hb, mul_mem hb h⟩
@[to_additive is_add_subgroup.add_mem_cancel_right]
lemma mul_mem_cancel_right (h : a ∈ s) : a * b ∈ s ↔ b ∈ s :=
⟨λ hab, by simpa using mul_mem (inv_mem h) hab, mul_mem h⟩
end is_subgroup
theorem is_add_subgroup.sub_mem {α} [add_group α] (s : set α) [is_add_subgroup s] (a b : α)
(ha : a ∈ s) (hb : b ∈ s) : a - b ∈ s :=
is_add_submonoid.add_mem ha (is_add_subgroup.neg_mem hb)
namespace group
open is_submonoid is_subgroup
variables [group α] {s : set α}
inductive in_closure (s : set α) : α → Prop
| basic {a : α} : a ∈ s → in_closure a
| one : in_closure 1
| inv {a : α} : in_closure a → in_closure a⁻¹
| mul {a b : α} : in_closure a → in_closure b → in_closure (a * b)
/-- `group.closure s` is the subgroup closed over `s`, i.e. the smallest subgroup containg s. -/
def closure (s : set α) : set α := {a | in_closure s a }
lemma mem_closure {a : α} : a ∈ s → a ∈ closure s := in_closure.basic
instance closure.is_subgroup (s : set α) : is_subgroup (closure s) :=
{ one_mem := in_closure.one s, mul_mem := assume a b, in_closure.mul, inv_mem := assume a, in_closure.inv }
theorem subset_closure {s : set α} : s ⊆ closure s := λ a, mem_closure
theorem closure_subset {s t : set α} [is_subgroup t] (h : s ⊆ t) : closure s ⊆ t :=
assume a ha, by induction ha; simp [h _, *, one_mem, mul_mem, inv_mem_iff]
lemma closure_subset_iff (s t : set α) [is_subgroup t] : closure s ⊆ t ↔ s ⊆ t :=
⟨assume h b ha, h (mem_closure ha), assume h b ha, closure_subset h ha⟩
theorem closure_mono {s t : set α} (h : s ⊆ t) : closure s ⊆ closure t :=
closure_subset $ set.subset.trans h subset_closure
theorem exists_list_of_mem_closure {s : set α} {a : α} (h : a ∈ closure s) :
(∃l:list α, (∀x∈l, x ∈ s ∨ x⁻¹ ∈ s) ∧ l.prod = a) :=
in_closure.rec_on h
(λ x hxs, ⟨[x], list.forall_mem_singleton.2 $ or.inl hxs, one_mul _⟩)
⟨[], list.forall_mem_nil _, rfl⟩
(λ x _ ⟨L, HL1, HL2⟩, ⟨L.reverse.map has_inv.inv,
λ x hx, let ⟨y, hy1, hy2⟩ := list.exists_of_mem_map hx in
hy2 ▸ or.imp id (by rw [inv_inv]; exact id) (HL1 _ $ list.mem_reverse.1 hy1).symm,
HL2 ▸ list.rec_on L one_inv.symm (λ hd tl ih,
by rw [list.reverse_cons, list.map_append, list.prod_append, ih, list.map_singleton,
list.prod_cons, list.prod_nil, mul_one, list.prod_cons, mul_inv_rev])⟩)
(λ x y hx hy ⟨L1, HL1, HL2⟩ ⟨L2, HL3, HL4⟩, ⟨L1 ++ L2, list.forall_mem_append.2 ⟨HL1, HL3⟩,
by rw [list.prod_append, HL2, HL4]⟩)
theorem mclosure_subset {s : set α} : monoid.closure s ⊆ closure s :=
monoid.closure_subset $ subset_closure
theorem mclosure_inv_subset {s : set α} : monoid.closure (has_inv.inv ⁻¹' s) ⊆ closure s :=
monoid.closure_subset $ λ x hx, inv_inv x ▸ (is_subgroup.inv_mem $ subset_closure hx)
theorem closure_eq_mclosure {s : set α} : closure s = monoid.closure (s ∪ has_inv.inv ⁻¹' s) :=
set.subset.antisymm
(@closure_subset _ _ _ (monoid.closure (s ∪ has_inv.inv ⁻¹' s))
{ inv_mem := λ x hx, monoid.in_closure.rec_on hx
(λ x hx, or.cases_on hx (λ hx, monoid.subset_closure $ or.inr $ show x⁻¹⁻¹ ∈ s, from (inv_inv x).symm ▸ hx)
(λ hx, monoid.subset_closure $ or.inl hx))
((@one_inv α _).symm ▸ is_submonoid.one_mem _)
(λ x y hx hy ihx ihy, (mul_inv_rev x y).symm ▸ is_submonoid.mul_mem ihy ihx) }
(set.subset.trans (set.subset_union_left _ _) monoid.subset_closure))
(monoid.closure_subset $ set.union_subset subset_closure $ λ x hx, inv_inv x ▸ (is_subgroup.inv_mem $ subset_closure hx))
theorem mem_closure_union_iff {α : Type*} [comm_group α] {s t : set α} {x : α} :
x ∈ closure (s ∪ t) ↔ ∃ y ∈ closure s, ∃ z ∈ closure t, y * z = x :=
begin
simp only [closure_eq_mclosure, monoid.mem_closure_union_iff, exists_prop, preimage_union], split,
{ rintro ⟨_, ⟨ys, hys, yt, hyt, rfl⟩, _, ⟨zs, hzs, zt, hzt, rfl⟩, rfl⟩,
refine ⟨_, ⟨_, hys, _, hzs, rfl⟩, _, ⟨_, hyt, _, hzt, rfl⟩, _⟩,
rw [mul_assoc, mul_assoc, mul_left_comm zs], refl },
{ rintro ⟨_, ⟨ys, hys, zs, hzs, rfl⟩, _, ⟨yt, hyt, zt, hzt, rfl⟩, rfl⟩,
refine ⟨_, ⟨ys, hys, yt, hyt, rfl⟩, _, ⟨zs, hzs, zt, hzt, rfl⟩, _⟩,
rw [mul_assoc, mul_assoc, mul_left_comm yt], refl }
end
theorem gpowers_eq_closure {a : α} : gpowers a = closure {a} :=
subset.antisymm
(assume x h, match x, h with _, ⟨i, rfl⟩ := gpow_mem (mem_closure $ by simp) end)
(closure_subset $ by simp [mem_gpowers])
end group
namespace add_group
open is_add_submonoid is_add_subgroup
variables [add_group α] {s : set α}
/-- `add_group.closure s` is the additive subgroup closed over `s`, i.e. the smallest subgroup containg s. -/
def closure (s : set α) : set α := @group.closure (multiplicative α) _ s
attribute [to_additive add_group.closure] group.closure
lemma mem_closure {a : α} : a ∈ s → a ∈ closure s := group.mem_closure
attribute [to_additive add_group.mem_closure] group.mem_closure
instance closure.is_add_subgroup (s : set α) : is_add_subgroup (closure s) :=
multiplicative.is_subgroup_iff.1 $ group.closure.is_subgroup _
attribute [to_additive add_group.closure.is_add_subgroup] group.closure.is_subgroup
attribute [to_additive add_group.subset_closure] group.subset_closure
theorem closure_subset {s t : set α} [is_add_subgroup t] : s ⊆ t → closure s ⊆ t :=
group.closure_subset
attribute [to_additive add_group.closure_subset] group.closure_subset
attribute [to_additive add_group.closure_subset_iff] group.closure_subset_iff
theorem gmultiples_eq_closure {a : α} : gmultiples a = closure {a} :=
group.gpowers_eq_closure
attribute [to_additive add_group.gmultiples_eq_closure] group.gpowers_eq_closure
@[elab_as_eliminator]
theorem in_closure.rec_on {C : α → Prop}
{a : α} (H : a ∈ closure s)
(H1 : ∀ {a : α}, a ∈ s → C a) (H2 : C 0) (H3 : ∀ {a : α}, a ∈ closure s → C a → C (-a))
(H4 : ∀ {a b : α}, a ∈ closure s → b ∈ closure s → C a → C b → C (a + b)) :
C a :=
group.in_closure.rec_on H (λ _, H1) H2 (λ _, H3) (λ _ _, H4)
theorem closure_mono {s t : set α} (h : s ⊆ t) : closure s ⊆ closure t :=
closure_subset $ set.subset.trans h subset_closure
theorem exists_list_of_mem_closure {s : set α} {a : α} (h : a ∈ closure s) :
(∃l:list α, (∀x∈l, x ∈ s ∨ -x ∈ s) ∧ l.sum = a) :=
group.exists_list_of_mem_closure h
theorem mclosure_subset {s : set α} : add_monoid.closure s ⊆ closure s :=
group.mclosure_subset
theorem mclosure_inv_subset {s : set α} : add_monoid.closure (has_neg.neg ⁻¹' s) ⊆ closure s :=
group.mclosure_inv_subset
theorem closure_eq_mclosure {s : set α} : closure s = add_monoid.closure (s ∪ has_neg.neg ⁻¹' s) :=
group.closure_eq_mclosure
theorem mem_closure_union_iff {α : Type*} [add_comm_group α] {s t : set α} {x : α} :
x ∈ closure (s ∪ t) ↔ ∃ y ∈ closure s, ∃ z ∈ closure t, y + z = x :=
group.mem_closure_union_iff
end add_group
class normal_subgroup [group α] (s : set α) extends is_subgroup s : Prop :=
(normal : ∀ n ∈ s, ∀ g : α, g * n * g⁻¹ ∈ s)
class normal_add_subgroup [add_group α] (s : set α) extends is_add_subgroup s : Prop :=
(normal : ∀ n ∈ s, ∀ g : α, g + n - g ∈ s)
attribute [to_additive normal_add_subgroup] normal_subgroup
attribute [to_additive normal_add_subgroup.to_is_add_subgroup] normal_subgroup.to_is_subgroup
attribute [to_additive normal_add_subgroup.normal] normal_subgroup.normal
attribute [to_additive normal_add_subgroup.mk] normal_subgroup.mk
@[to_additive normal_add_subgroup_of_add_comm_group]
lemma normal_subgroup_of_comm_group [comm_group α] (s : set α) [hs : is_subgroup s] :
normal_subgroup s :=
{ normal := λ n hn g, by rwa [mul_right_comm, mul_right_inv, one_mul],
..hs }
instance additive.normal_add_subgroup [group α]
(s : set α) [normal_subgroup s] : @normal_add_subgroup (additive α) _ s :=
⟨@normal_subgroup.normal _ _ _ _⟩
theorem additive.normal_add_subgroup_iff [group α]
{s : set α} : @normal_add_subgroup (additive α) _ s ↔ normal_subgroup s :=
⟨by rintro ⟨h₁, h₂⟩; exact
@normal_subgroup.mk α _ _ (additive.is_add_subgroup_iff.1 h₁) @h₂,
λ h, by resetI; apply_instance⟩
instance multiplicative.normal_subgroup [add_group α]
(s : set α) [normal_add_subgroup s] : @normal_subgroup (multiplicative α) _ s :=
⟨@normal_add_subgroup.normal _ _ _ _⟩
theorem multiplicative.normal_subgroup_iff [add_group α]
{s : set α} : @normal_subgroup (multiplicative α) _ s ↔ normal_add_subgroup s :=
⟨by rintro ⟨h₁, h₂⟩; exact
@normal_add_subgroup.mk α _ _ (multiplicative.is_subgroup_iff.1 h₁) @h₂,
λ h, by resetI; apply_instance⟩
namespace is_subgroup
variable [group α]
-- Normal subgroup properties
lemma mem_norm_comm {s : set α} [normal_subgroup s] {a b : α} (hab : a * b ∈ s) : b * a ∈ s :=
have h : a⁻¹ * (a * b) * a⁻¹⁻¹ ∈ s, from normal_subgroup.normal (a * b) hab a⁻¹,
by simp at h; exact h
lemma mem_norm_comm_iff {s : set α} [normal_subgroup s] {a b : α} : a * b ∈ s ↔ b * a ∈ s :=
⟨mem_norm_comm, mem_norm_comm⟩
/-- The trivial subgroup -/
def trivial (α : Type*) [group α] : set α := {1}
@[simp] lemma mem_trivial [group α] {g : α} : g ∈ trivial α ↔ g = 1 :=
mem_singleton_iff
instance trivial_normal : normal_subgroup (trivial α) :=
by refine {..}; simp [trivial] {contextual := tt}
lemma trivial_eq_closure : trivial α = group.closure ∅ :=
subset.antisymm
(by simp [set.subset_def, is_submonoid.one_mem])
(group.closure_subset $ by simp)
lemma eq_trivial_iff {H : set α} [is_subgroup H] :
H = trivial α ↔ (∀ x ∈ H, x = (1 : α)) :=
by simp only [set.ext_iff, is_subgroup.mem_trivial];
exact ⟨λ h x, (h x).1, λ h x, ⟨h x, λ hx, hx.symm ▸ is_submonoid.one_mem H⟩⟩
instance univ_subgroup : normal_subgroup (@univ α) :=
by refine {..}; simp
def center (α : Type*) [group α] : set α := {z | ∀ g, g * z = z * g}
lemma mem_center {a : α} : a ∈ center α ↔ ∀g, g * a = a * g := iff.rfl
instance center_normal : normal_subgroup (center α) :=
{ one_mem := by simp [center],
mul_mem := assume a b ha hb g,
by rw [←mul_assoc, mem_center.2 ha g, mul_assoc, mem_center.2 hb g, ←mul_assoc],
inv_mem := assume a ha g,
calc
g * a⁻¹ = a⁻¹ * (g * a) * a⁻¹ : by simp [ha g]
... = a⁻¹ * g : by rw [←mul_assoc, mul_assoc]; simp,
normal := assume n ha g h,
calc
h * (g * n * g⁻¹) = h * n : by simp [ha g, mul_assoc]
... = g * g⁻¹ * n * h : by rw ha h; simp
... = g * n * g⁻¹ * h : by rw [mul_assoc g, ha g⁻¹, ←mul_assoc] }
def normalizer (s : set α) : set α :=
{g : α | ∀ n, n ∈ s ↔ g * n * g⁻¹ ∈ s}
instance (s : set α) [is_subgroup s] : is_subgroup (normalizer s) :=
{ one_mem := by simp [normalizer],
mul_mem := λ a b (ha : ∀ n, n ∈ s ↔ a * n * a⁻¹ ∈ s)
(hb : ∀ n, n ∈ s ↔ b * n * b⁻¹ ∈ s) n,
by rw [mul_inv_rev, ← mul_assoc, mul_assoc a, mul_assoc a, ← ha, ← hb],
inv_mem := λ a (ha : ∀ n, n ∈ s ↔ a * n * a⁻¹ ∈ s) n,
by rw [ha (a⁻¹ * n * a⁻¹⁻¹)];
simp [mul_assoc] }
lemma subset_normalizer (s : set α) [is_subgroup s] : s ⊆ normalizer s :=
λ g hg n, by rw [is_subgroup.mul_mem_cancel_left _ ((is_subgroup.inv_mem_iff _).2 hg),
is_subgroup.mul_mem_cancel_right _ hg]
instance (s : set α) [is_subgroup s] : normal_subgroup (subtype.val ⁻¹' s : set (normalizer s)) :=
{ one_mem := show (1 : α) ∈ s, from is_submonoid.one_mem _,
mul_mem := λ a b ha hb, show (a * b : α) ∈ s, from is_submonoid.mul_mem ha hb,
inv_mem := λ a ha, show (a⁻¹ : α) ∈ s, from is_subgroup.inv_mem ha,
normal := λ a ha ⟨m, hm⟩, (hm a).1 ha }
end is_subgroup
namespace is_add_subgroup
variable [add_group α]
attribute [to_additive is_add_subgroup.mem_norm_comm] is_subgroup.mem_norm_comm
attribute [to_additive is_add_subgroup.mem_norm_comm_iff] is_subgroup.mem_norm_comm_iff
/-- The trivial subgroup -/
def trivial (α : Type*) [add_group α] : set α := {0}
attribute [to_additive is_add_subgroup.trivial] is_subgroup.trivial
attribute [to_additive is_add_subgroup.trivial.equations._eqn_1] is_subgroup.trivial.equations._eqn_1
attribute [to_additive is_add_subgroup.mem_trivial] is_subgroup.mem_trivial
instance trivial_normal : normal_add_subgroup (trivial α) :=
multiplicative.normal_subgroup_iff.1 is_subgroup.trivial_normal
attribute [to_additive is_add_subgroup.trivial_normal] is_subgroup.trivial_normal
attribute [to_additive is_add_subgroup.trivial_eq_closure] is_subgroup.trivial_eq_closure
attribute [to_additive is_add_subgroup.eq_trivial_iff] is_subgroup.eq_trivial_iff
instance univ_add_subgroup : normal_add_subgroup (@univ α) :=
multiplicative.normal_subgroup_iff.1 is_subgroup.univ_subgroup
attribute [to_additive is_add_subgroup.univ_add_subgroup] is_subgroup.univ_subgroup
def center (α : Type*) [add_group α] : set α := {z | ∀ g, g + z = z + g}
attribute [to_additive is_add_subgroup.center] is_subgroup.center
attribute [to_additive is_add_subgroup.mem_center] is_subgroup.mem_center
instance center_normal : normal_add_subgroup (center α) :=
multiplicative.normal_subgroup_iff.1 is_subgroup.center_normal
end is_add_subgroup
-- Homomorphism subgroups
namespace is_group_hom
open is_submonoid is_subgroup
variables [group α] [group β]
@[to_additive is_add_group_hom.ker]
def ker (f : α → β) [is_group_hom f] : set α := preimage f (trivial β)
attribute [to_additive is_add_group_hom.ker.equations._eqn_1] ker.equations._eqn_1
@[to_additive is_add_group_hom.mem_ker]
lemma mem_ker (f : α → β) [is_group_hom f] {x : α} : x ∈ ker f ↔ f x = 1 :=
mem_trivial
@[to_additive is_add_group_hom.map_zero_ker_neg]
lemma one_ker_inv (f : α → β) [is_group_hom f] {a b : α} (h : f (a * b⁻¹) = 1) : f a = f b :=
begin
rw [map_mul f, map_inv f] at h,
rw [←inv_inv (f b), eq_inv_of_mul_eq_one h]
end
@[to_additive is_add_group_hom.map_zero_ker_neg']
lemma one_ker_inv' (f : α → β) [is_group_hom f] {a b : α} (h : f (a⁻¹ * b) = 1) : f a = f b :=
begin
rw [map_mul f, map_inv f] at h,
apply eq_of_inv_eq_inv,
rw eq_inv_of_mul_eq_one h
end
@[to_additive is_add_group_hom.map_neg_ker_zero]
lemma inv_ker_one (f : α → β) [is_group_hom f] {a b : α} (h : f a = f b) : f (a * b⁻¹) = 1 :=
have f a * (f b)⁻¹ = 1, by rw [h, mul_right_inv],
by rwa [←map_inv f, ←map_mul f] at this
@[to_additive is_add_group_hom.map_neg_ker_zero']
lemma inv_ker_one' (f : α → β) [is_group_hom f] {a b : α} (h : f a = f b) : f (a⁻¹ * b) = 1 :=
have (f a)⁻¹ * f b = 1, by rw [h, mul_left_inv],
by rwa [←map_inv f, ←map_mul f] at this
@[to_additive is_add_group_hom.map_zero_iff_ker_neg]
lemma one_iff_ker_inv (f : α → β) [is_group_hom f] (a b : α) : f a = f b ↔ f (a * b⁻¹) = 1 :=
⟨inv_ker_one f, one_ker_inv f⟩
@[to_additive is_add_group_hom.map_zero_iff_ker_neg']
lemma one_iff_ker_inv' (f : α → β) [is_group_hom f] (a b : α) : f a = f b ↔ f (a⁻¹ * b) = 1 :=
⟨inv_ker_one' f, one_ker_inv' f⟩
@[to_additive is_add_group_hom.map_neg_iff_ker]
lemma inv_iff_ker (f : α → β) [w : is_group_hom f] (a b : α) : f a = f b ↔ a * b⁻¹ ∈ ker f :=
by rw [mem_ker]; exact one_iff_ker_inv _ _ _
@[to_additive is_add_group_hom.map_neg_iff_ker']
lemma inv_iff_ker' (f : α → β) [w : is_group_hom f] (a b : α) : f a = f b ↔ a⁻¹ * b ∈ ker f :=
by rw [mem_ker]; exact one_iff_ker_inv' _ _ _
instance image_subgroup (f : α → β) [is_group_hom f] (s : set α) [is_subgroup s] :
is_subgroup (f '' s) :=
{ mul_mem := assume a₁ a₂ ⟨b₁, hb₁, eq₁⟩ ⟨b₂, hb₂, eq₂⟩,
⟨b₁ * b₂, mul_mem hb₁ hb₂, by simp [eq₁, eq₂, map_mul f]⟩,
one_mem := ⟨1, one_mem s, map_one f⟩,
inv_mem := assume a ⟨b, hb, eq⟩, ⟨b⁻¹, inv_mem hb, by rw map_inv f; simp *⟩ }
attribute [to_additive is_add_group_hom.image_add_subgroup._match_1] is_group_hom.image_subgroup._match_1
attribute [to_additive is_add_group_hom.image_add_subgroup._match_2] is_group_hom.image_subgroup._match_2
attribute [to_additive is_add_group_hom.image_add_subgroup._match_3] is_group_hom.image_subgroup._match_3
attribute [to_additive is_add_group_hom.image_add_subgroup] is_group_hom.image_subgroup
attribute [to_additive is_add_group_hom.image_add_subgroup._match_1.equations._eqn_1] is_group_hom.image_subgroup._match_1.equations._eqn_1
attribute [to_additive is_add_group_hom.image_add_subgroup._match_2.equations._eqn_1] is_group_hom.image_subgroup._match_2.equations._eqn_1
attribute [to_additive is_add_group_hom.image_add_subgroup._match_3.equations._eqn_1] is_group_hom.image_subgroup._match_3.equations._eqn_1
attribute [to_additive is_add_group_hom.image_add_subgroup.equations._eqn_1] is_group_hom.image_subgroup.equations._eqn_1
instance range_subgroup (f : α → β) [is_group_hom f] : is_subgroup (set.range f) :=
@set.image_univ _ _ f ▸ is_group_hom.image_subgroup f set.univ
attribute [to_additive is_add_group_hom.range_add_subgroup] is_group_hom.range_subgroup
attribute [to_additive is_add_group_hom.range_add_subgroup.equations._eqn_1] is_group_hom.range_subgroup.equations._eqn_1
local attribute [simp] one_mem inv_mem mul_mem normal_subgroup.normal
instance preimage (f : α → β) [is_group_hom f] (s : set β) [is_subgroup s] :
is_subgroup (f ⁻¹' s) :=
by refine {..}; simp [map_mul f, map_one f, map_inv f, @inv_mem β _ s] {contextual:=tt}
attribute [to_additive is_add_group_hom.preimage] is_group_hom.preimage
attribute [to_additive is_add_group_hom.preimage.equations._eqn_1] is_group_hom.preimage.equations._eqn_1
instance preimage_normal (f : α → β) [is_group_hom f] (s : set β) [normal_subgroup s] :
normal_subgroup (f ⁻¹' s) :=
⟨by simp [map_mul f, map_inv f] {contextual:=tt}⟩
attribute [to_additive is_add_group_hom.preimage_normal] is_group_hom.preimage_normal
attribute [to_additive is_add_group_hom.preimage_normal.equations._eqn_1] is_group_hom.preimage_normal.equations._eqn_1
instance normal_subgroup_ker (f : α → β) [is_group_hom f] : normal_subgroup (ker f) :=
is_group_hom.preimage_normal f (trivial β)
attribute [to_additive is_add_group_hom.normal_subgroup_ker] is_group_hom.normal_subgroup_ker
attribute [to_additive is_add_group_hom.normal_subgroup_ker.equations._eqn_1] is_group_hom.normal_subgroup_ker.equations._eqn_1
@[to_additive is_add_group_hom.inj_of_trivial_ker]
lemma inj_of_trivial_ker (f : α → β) [is_group_hom f] (h : ker f = trivial α) :
function.injective f :=
begin
intros a₁ a₂ hfa,
simp [ext_iff, ker, is_subgroup.trivial] at h,
have ha : a₁ * a₂⁻¹ = 1, by rw ←h; exact inv_ker_one f hfa,
rw [eq_inv_of_mul_eq_one ha, inv_inv a₂]
end
@[to_additive is_add_group_hom.trivial_ker_of_inj]
lemma trivial_ker_of_inj (f : α → β) [is_group_hom f] (h : function.injective f) :
ker f = trivial α :=
set.ext $ assume x, iff.intro
(assume hx,
suffices f x = f 1, by simpa using h this,
by simp [map_one f]; rwa [mem_ker] at hx)
(by simp [mem_ker, is_group_hom.map_one f] {contextual := tt})
@[to_additive is_add_group_hom.inj_iff_trivial_ker]
lemma inj_iff_trivial_ker (f : α → β) [is_group_hom f] :
function.injective f ↔ ker f = trivial α :=
⟨trivial_ker_of_inj f, inj_of_trivial_ker f⟩
end is_group_hom
instance subtype_val.is_group_hom [group α] {s : set α} [is_subgroup s] :
is_group_hom (subtype.val : s → α) := { ..subtype_val.is_monoid_hom }
instance subtype_val.is_add_group_hom [add_group α] {s : set α} [is_add_subgroup s] :
is_add_group_hom (subtype.val : s → α) := { ..subtype_val.is_add_monoid_hom }
attribute [to_additive subtype_val.is_group_hom] subtype_val.is_add_group_hom
instance coe.is_group_hom [group α] {s : set α} [is_subgroup s] :
is_group_hom (coe : s → α) := { ..subtype_val.is_monoid_hom }
instance coe.is_add_group_hom [add_group α] {s : set α} [is_add_subgroup s] :
is_add_group_hom (coe : s → α) :=
{ ..subtype_val.is_add_monoid_hom }
attribute [to_additive coe.is_group_hom] coe.is_add_group_hom
instance subtype_mk.is_group_hom [group α] [group β] {s : set α}
[is_subgroup s] (f : β → α) [is_group_hom f] (h : ∀ x, f x ∈ s) :
is_group_hom (λ x, (⟨f x, h x⟩ : s)) := { ..subtype_mk.is_monoid_hom f h }
instance subtype_mk.is_add_group_hom [add_group α] [add_group β] {s : set α}
[is_add_subgroup s] (f : β → α) [is_add_group_hom f] (h : ∀ x, f x ∈ s) :
is_add_group_hom (λ x, (⟨f x, h x⟩ : s)) :=
{ ..subtype_mk.is_add_monoid_hom f h }
attribute [to_additive subtype_mk.is_group_hom] subtype_mk.is_add_group_hom
instance set_inclusion.is_group_hom [group α] {s t : set α}
[is_subgroup s] [is_subgroup t] (h : s ⊆ t) : is_group_hom (set.inclusion h) :=
subtype_mk.is_group_hom _ _
instance set_inclusion.is_add_group_hom [add_group α] {s t : set α}
[is_add_subgroup s] [is_add_subgroup t] (h : s ⊆ t) : is_add_group_hom (set.inclusion h) :=
subtype_mk.is_add_group_hom _ _
attribute [to_additive set_inclusion.is_group_hom] set_inclusion.is_add_group_hom
section simple_group
class simple_group (α : Type*) [group α] : Prop :=
(simple : ∀ (N : set α) [normal_subgroup N], N = is_subgroup.trivial α ∨ N = set.univ)
class simple_add_group (α : Type*) [add_group α] : Prop :=
(simple : ∀ (N : set α) [normal_add_subgroup N], N = is_add_subgroup.trivial α ∨ N = set.univ)
attribute [to_additive simple_add_group] simple_group
theorem additive.simple_add_group_iff [group α] :
simple_add_group (additive α) ↔ simple_group α :=
⟨λ hs, ⟨λ N h, @simple_add_group.simple _ _ hs _ (by exactI additive.normal_add_subgroup_iff.2 h)⟩,
λ hs, ⟨λ N h, @simple_group.simple _ _ hs _ (by exactI additive.normal_add_subgroup_iff.1 h)⟩⟩
instance additive.simple_add_group [group α] [simple_group α] :
simple_add_group (additive α) := additive.simple_add_group_iff.2 (by apply_instance)
theorem multiplicative.simple_group_iff [add_group α] :
simple_group (multiplicative α) ↔ simple_add_group α :=
⟨λ hs, ⟨λ N h, @simple_group.simple _ _ hs _ (by exactI multiplicative.normal_subgroup_iff.2 h)⟩,
λ hs, ⟨λ N h, @simple_add_group.simple _ _ hs _ (by exactI multiplicative.normal_subgroup_iff.1 h)⟩⟩
instance multiplicative.simple_group [add_group α] [simple_add_group α] :
simple_group (multiplicative α) := multiplicative.simple_group_iff.2 (by apply_instance)
lemma simple_group_of_surjective [group α] [group β] [simple_group α] (f : α → β)
[is_group_hom f] (hf : function.surjective f) : simple_group β :=
⟨λ H iH, have normal_subgroup (f ⁻¹' H), by resetI; apply_instance,
begin
resetI,
cases simple_group.simple (f ⁻¹' H) with h h,
{ refine or.inl (is_subgroup.eq_trivial_iff.2 (λ x hx, _)),
cases hf x with y hy,
rw ← hy at hx,
rw [← hy, is_subgroup.eq_trivial_iff.1 h y hx, is_group_hom.map_one f] },
{ refine or.inr (set.eq_univ_of_forall (λ x, _)),
cases hf x with y hy,
rw set.eq_univ_iff_forall at h,
rw ← hy,
exact h y }
end⟩
lemma simple_add_group_of_surjective [add_group α] [add_group β] [simple_add_group α] (f : α → β)
[is_add_group_hom f] (hf : function.surjective f) : simple_add_group β :=
multiplicative.simple_group_iff.1 (@simple_group_of_surjective (multiplicative α) (multiplicative β) _ _ _ f _ hf)
attribute [to_additive simple_add_group_of_surjective] simple_group_of_surjective
end simple_group
|
c95ba10aa6eb95768bdc619d31f5828726981f80 | 7b66d83f3b69dae0a3dfb684d7ebe5e9e3f3c913 | /src/solutions/thursday/afternoon/category_theory/exercise2.lean | dcd44c04f8465f05a7242541b590c3903710508b | [] | permissive | dpochekutov/lftcm2020 | 58a09e10f0e638075b97884d3c2612eb90296adb | cdfbf1ac089f21058e523db73f2476c9c98ed16a | refs/heads/master | 1,669,226,265,076 | 1,594,629,725,000 | 1,594,629,725,000 | 279,213,346 | 1 | 0 | MIT | 1,594,622,757,000 | 1,594,615,843,000 | null | UTF-8 | Lean | false | false | 1,645 | lean | import category_theory.preadditive
import category_theory.limits.shapes.biproducts
/-!
We prove that biproducts (direct sums) are preserved by any preadditive functor.
This result is not in mathlib, so full marks for the exercise are only achievable if you
contribute to a pull request! :-)
-/
universes v₁ v₂ u₁ u₂
open category_theory
open category_theory.limits
namespace category_theory
variables {C : Type u₁} [category.{v₁} C] [preadditive C]
variables {D : Type u₂} [category.{v₂} D] [preadditive D]
/-!
In fact, no one has gotten around to defining preadditive functors,
so I'll help you out by doing that first.
-/
structure functor.preadditive (F : C ⥤ D) : Prop :=
(map_zero' : ∀ X Y, F.map (0 : X ⟶ Y) = 0)
(map_add' : ∀ {X Y} (f g : X ⟶ Y), F.map (f + g) = F.map f + F.map g)
variables [has_binary_biproducts C] [has_binary_biproducts D]
def functor.preadditive.preserves_biproducts (F : C ⥤ D) (P : F.preadditive) (X Y : C) :
F.obj (X ⊞ Y) ≅ F.obj X ⊞ F.obj Y :=
-- sorry
{ hom := biprod.lift (F.map biprod.fst) (F.map biprod.snd),
inv := biprod.desc (F.map biprod.inl) (F.map biprod.inr),
hom_inv_id' := begin simp, simp_rw [←F.map_comp, ←P.map_add'], simp, end,
inv_hom_id' := begin ext; simp; simp_rw [←F.map_comp]; simp [P.map_zero'], end, }
-- This proof is not okay as a mathlib proof, because it uses "nonterminal" `simp`s.
-- Can you fix it?
-- sorry
-- Challenge problem:
-- In fact one could prove a better result,
-- not requiring chosen biproducts in D,
-- just asserting that `F.obj (X ⊞ Y)` is a biproduct of `F.obj X` and `F.obj Y`.
end category_theory
|
cbdae4c7c4c97c859fee96bbb0533117740a8fe2 | d1a52c3f208fa42c41df8278c3d280f075eb020c | /src/Init/Data/Range.lean | 804cda9e788592e5f998c575b2443e391b43bdda | [
"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,932 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Meta
namespace Std
-- We put `Range` in `Init` because we want the notation `[i:j]` without importing `Std`
-- We don't put `Range` in the top-level namespace to avoid collisions with user defined types
structure Range where
start : Nat := 0
stop : Nat
step : Nat := 1
namespace Range
universe u v
@[inline] protected def forIn {β : Type u} {m : Type u → Type v} [Monad m] (range : Range) (init : β) (f : Nat → β → m (ForInStep β)) : m β :=
let rec @[specialize] loop (i : Nat) (j : Nat) (b : β) : m β := do
if j ≥ range.stop then
pure b
else match i with
| 0 => pure b
| i+1 => match (← f j b) with
| ForInStep.done b => pure b
| ForInStep.yield b => loop i (j + range.step) b
loop range.stop range.start init
instance : ForIn m Range Nat where
forIn := Range.forIn
@[inline] protected def forM {m : Type u → Type v} [Monad m] (range : Range) (f : Nat → m PUnit) : m PUnit :=
let rec @[specialize] loop (i : Nat) (j : Nat) : m PUnit := do
if j ≥ range.stop then
pure ⟨⟩
else match i with
| 0 => pure ⟨⟩
| i+1 => f j; loop i (j + range.step)
loop range.stop range.start
instance : ForM m Range Nat where
forM := Range.forM
syntax:max "[" ":" term "]" : term
syntax:max "[" term ":" term "]" : term
syntax:max "[" ":" term ":" term "]" : term
syntax:max "[" term ":" term ":" term "]" : term
macro_rules
| `([ : $stop]) => `({ stop := $stop : Range })
| `([ $start : $stop ]) => `({ start := $start, stop := $stop : Range })
| `([ $start : $stop : $step ]) => `({ start := $start, stop := $stop, step := $step : Range })
| `([ : $stop : $step ]) => `({ stop := $stop, step := $step : Range })
end Range
end Std
|
9bf2524aa7c33a39d5830f26b2d340255b896c3e | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/category_theory/sites/sheaf_of_types.lean | fd0b2296cd3ac4f54440fed3a29807e14f795b65 | [
"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 | 40,819 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import category_theory.sites.pretopology
import category_theory.limits.shapes.types
import category_theory.full_subcategory
/-!
# Sheaves of types on a Grothendieck topology
Defines the notion of a sheaf of types (usually called a sheaf of sets by mathematicians)
on a category equipped with a Grothendieck topology, as well as a range of equivalent
conditions useful in different situations.
First define what it means for a presheaf `P : Cᵒᵖ ⥤ Type v` to be a sheaf *for* a particular
presieve `R` on `X`:
* A *family of elements* `x` for `P` at `R` is an element `x_f` of `P Y` for every `f : Y ⟶ X` in
`R`. See `family_of_elements`.
* The family `x` is *compatible* if, for any `f₁ : Y₁ ⟶ X` and `f₂ : Y₂ ⟶ X` both in `R`,
and any `g₁ : Z ⟶ Y₁` and `g₂ : Z ⟶ Y₂` such that `g₁ ≫ f₁ = g₂ ≫ f₂`, the restriction of
`x_f₁` along `g₁` agrees with the restriction of `x_f₂` along `g₂`.
See `family_of_elements.compatible`.
* An *amalgamation* `t` for the family is an element of `P X` such that for every `f : Y ⟶ X` in
`R`, the restriction of `t` on `f` is `x_f`.
See `family_of_elements.is_amalgamation`.
We then say `P` is *separated* for `R` if every compatible family has at most one amalgamation,
and it is a *sheaf* for `R` if every compatible family has a unique amalgamation.
See `is_separated_for` and `is_sheaf_for`.
In the special case where `R` is a sieve, the compatibility condition can be simplified:
* The family `x` is *compatible* if, for any `f : Y ⟶ X` in `R` and `g : Z ⟶ Y`, the restriction of
`x_f` along `g` agrees with `x_(g ≫ f)` (which is well defined since `g ≫ f` is in `R`).
See `family_of_elements.sieve_compatible` and `compatible_iff_sieve_compatible`.
In the special case where `C` has pullbacks, the compatibility condition can be simplified:
* The family `x` is *compatible* if, for any `f : Y ⟶ X` and `g : Z ⟶ X` both in `R`,
the restriction of `x_f` along `π₁ : pullback f g ⟶ Y` agrees with the restriction of `x_g`
along `π₂ : pullback f g ⟶ Z`.
See `family_of_elements.pullback_compatible` and `pullback_compatible_iff`.
Now given a Grothendieck topology `J`, `P` is a sheaf if it is a sheaf for every sieve in the
topology. See `is_sheaf`.
In the case where the topology is generated by a basis, it suffices to check `P` is a sheaf for
every presieve in the pretopology. See `is_sheaf_pretopology`.
We also provide equivalent conditions to satisfy alternate definitions given in the literature.
* Stacks: In `equalizer.presieve.sheaf_condition`, the sheaf condition at a presieve is shown to be
equivalent to that of https://stacks.math.columbia.edu/tag/00VM (and combined with
`is_sheaf_pretopology`, this shows the notions of `is_sheaf` are exactly equivalent.)
The condition of https://stacks.math.columbia.edu/tag/00Z8 is virtually identical to the
statement of `yoneda_condition_iff_sheaf_condition` (since the bijection described there carries
the same information as the unique existence.)
* Maclane-Moerdijk [MM92]: Using `compatible_iff_sieve_compatible`, the definitions of `is_sheaf`
are equivalent. There are also alternate definitions given:
- Yoneda condition: Defined in `yoneda_sheaf_condition` and equivalence in
`yoneda_condition_iff_sheaf_condition`.
- Equalizer condition (Equation 3): Defined in the `equalizer.sieve` namespace, and equivalence
in `equalizer.sieve.sheaf_condition`.
- Matching family for presieves with pullback: `pullback_compatible_iff`.
- Sheaf for a pretopology (Prop 1): `is_sheaf_pretopology` combined with the previous.
- Sheaf for a pretopology as equalizer (Prop 1, bis): `equalizer.presieve.sheaf_condition`
combined with the previous.
## Implementation
The sheaf condition is given as a proposition, rather than a subsingleton in `Type (max u₁ v)`.
This doesn't seem to make a big difference, other than making a couple of definitions noncomputable,
but it means that equivalent conditions can be given as `↔` statements rather than `≃` statements,
which can be convenient.
## References
* [MM92]: *Sheaves in geometry and logic*, Saunders MacLane, and Ieke Moerdijk:
Chapter III, Section 4.
* [Elephant]: *Sketches of an Elephant*, P. T. Johnstone: C2.1.
* https://stacks.math.columbia.edu/tag/00VL (sheaves on a pretopology or site)
* https://stacks.math.columbia.edu/tag/00ZB (sheaves on a topology)
-/
universes w v₁ v₂ u₁ u₂
namespace category_theory
open opposite category_theory category limits sieve
namespace presieve
variables {C : Type u₁} [category.{v₁} C]
variables {P Q U : Cᵒᵖ ⥤ Type w}
variables {X Y : C} {S : sieve X} {R : presieve X}
variables (J J₂ : grothendieck_topology C)
/--
A family of elements for a presheaf `P` given a collection of arrows `R` with fixed codomain `X`
consists of an element of `P Y` for every `f : Y ⟶ X` in `R`.
A presheaf is a sheaf (resp, separated) if every *compatible* family of elements has exactly one
(resp, at most one) amalgamation.
This data is referred to as a `family` in [MM92], Chapter III, Section 4. It is also a concrete
version of the elements of the middle object in https://stacks.math.columbia.edu/tag/00VM which is
more useful for direct calculations. It is also used implicitly in Definition C2.1.2 in [Elephant].
-/
def family_of_elements (P : Cᵒᵖ ⥤ Type w) (R : presieve X) :=
Π ⦃Y : C⦄ (f : Y ⟶ X), R f → P.obj (op Y)
instance : inhabited (family_of_elements P (⊥ : presieve X)) := ⟨λ Y f, false.elim⟩
/--
A family of elements for a presheaf on the presieve `R₂` can be restricted to a smaller presieve
`R₁`.
-/
def family_of_elements.restrict {R₁ R₂ : presieve X} (h : R₁ ≤ R₂) :
family_of_elements P R₂ → family_of_elements P R₁ :=
λ x Y f hf, x f (h _ hf)
/--
A family of elements for the arrow set `R` is *compatible* if for any `f₁ : Y₁ ⟶ X` and
`f₂ : Y₂ ⟶ X` in `R`, and any `g₁ : Z ⟶ Y₁` and `g₂ : Z ⟶ Y₂`, if the square `g₁ ≫ f₁ = g₂ ≫ f₂`
commutes then the elements of `P Z` obtained by restricting the element of `P Y₁` along `g₁` and
restricting the element of `P Y₂` along `g₂` are the same.
In special cases, this condition can be simplified, see `pullback_compatible_iff` and
`compatible_iff_sieve_compatible`.
This is referred to as a "compatible family" in Definition C2.1.2 of [Elephant], and on nlab:
https://ncatlab.org/nlab/show/sheaf#GeneralDefinitionInComponents
-/
def family_of_elements.compatible (x : family_of_elements P R) : Prop :=
∀ ⦃Y₁ Y₂ Z⦄ (g₁ : Z ⟶ Y₁) (g₂ : Z ⟶ Y₂) ⦃f₁ : Y₁ ⟶ X⦄ ⦃f₂ : Y₂ ⟶ X⦄
(h₁ : R f₁) (h₂ : R f₂), g₁ ≫ f₁ = g₂ ≫ f₂ → P.map g₁.op (x f₁ h₁) = P.map g₂.op (x f₂ h₂)
/--
If the category `C` has pullbacks, this is an alternative condition for a family of elements to be
compatible: For any `f : Y ⟶ X` and `g : Z ⟶ X` in the presieve `R`, the restriction of the
given elements for `f` and `g` to the pullback agree.
This is equivalent to being compatible (provided `C` has pullbacks), shown in
`pullback_compatible_iff`.
This is the definition for a "matching" family given in [MM92], Chapter III, Section 4,
Equation (5). Viewing the type `family_of_elements` as the middle object of the fork in
https://stacks.math.columbia.edu/tag/00VM, this condition expresses that `pr₀* (x) = pr₁* (x)`,
using the notation defined there.
-/
def family_of_elements.pullback_compatible (x : family_of_elements P R) [has_pullbacks C] : Prop :=
∀ ⦃Y₁ Y₂⦄ ⦃f₁ : Y₁ ⟶ X⦄ ⦃f₂ : Y₂ ⟶ X⦄ (h₁ : R f₁) (h₂ : R f₂),
P.map (pullback.fst : pullback f₁ f₂ ⟶ _).op (x f₁ h₁) = P.map pullback.snd.op (x f₂ h₂)
lemma pullback_compatible_iff (x : family_of_elements P R) [has_pullbacks C] :
x.compatible ↔ x.pullback_compatible :=
begin
split,
{ intros t Y₁ Y₂ f₁ f₂ hf₁ hf₂,
apply t,
apply pullback.condition },
{ intros t Y₁ Y₂ Z g₁ g₂ f₁ f₂ hf₁ hf₂ comm,
rw [←pullback.lift_fst _ _ comm, op_comp, functor_to_types.map_comp_apply, t hf₁ hf₂,
←functor_to_types.map_comp_apply, ←op_comp, pullback.lift_snd] }
end
/-- The restriction of a compatible family is compatible. -/
lemma family_of_elements.compatible.restrict {R₁ R₂ : presieve X} (h : R₁ ≤ R₂)
{x : family_of_elements P R₂} : x.compatible → (x.restrict h).compatible :=
λ q Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ comm, q g₁ g₂ (h _ h₁) (h _ h₂) comm
/--
Extend a family of elements to the sieve generated by an arrow set.
This is the construction described as "easy" in Lemma C2.1.3 of [Elephant].
-/
noncomputable def family_of_elements.sieve_extend (x : family_of_elements P R) :
family_of_elements P (generate R) :=
λ Z f hf, P.map hf.some_spec.some.op (x _ hf.some_spec.some_spec.some_spec.1)
/-- The extension of a compatible family to the generated sieve is compatible. -/
lemma family_of_elements.compatible.sieve_extend {x : family_of_elements P R} (hx : x.compatible) :
x.sieve_extend.compatible :=
begin
intros _ _ _ _ _ _ _ h₁ h₂ comm,
iterate 2 { erw ← functor_to_types.map_comp_apply, rw ← op_comp }, apply hx,
simp [comm, h₁.some_spec.some_spec.some_spec.2, h₂.some_spec.some_spec.some_spec.2],
end
/-- The extension of a family agrees with the original family. -/
lemma extend_agrees {x : family_of_elements P R} (t : x.compatible) {f : Y ⟶ X} (hf : R f) :
x.sieve_extend f (le_generate R Y hf) = x f hf :=
begin
have h := (le_generate R Y hf).some_spec,
unfold family_of_elements.sieve_extend,
rw t h.some (𝟙 _) _ hf _,
{ simp }, { rw id_comp, exact h.some_spec.some_spec.2 },
end
/-- The restriction of an extension is the original. -/
@[simp]
lemma restrict_extend {x : family_of_elements P R} (t : x.compatible) :
x.sieve_extend.restrict (le_generate R) = x :=
begin
ext Y f hf,
exact extend_agrees t hf,
end
/--
If the arrow set for a family of elements is actually a sieve (i.e. it is downward closed) then the
consistency condition can be simplified.
This is an equivalent condition, see `compatible_iff_sieve_compatible`.
This is the notion of "matching" given for families on sieves given in [MM92], Chapter III,
Section 4, Equation 1, and nlab: https://ncatlab.org/nlab/show/matching+family.
See also the discussion before Lemma C2.1.4 of [Elephant].
-/
def family_of_elements.sieve_compatible (x : family_of_elements P S) : Prop :=
∀ ⦃Y Z⦄ (f : Y ⟶ X) (g : Z ⟶ Y) (hf), x (g ≫ f) (S.downward_closed hf g) = P.map g.op (x f hf)
lemma compatible_iff_sieve_compatible (x : family_of_elements P S) :
x.compatible ↔ x.sieve_compatible :=
begin
split,
{ intros h Y Z f g hf,
simpa using h (𝟙 _) g (S.downward_closed hf g) hf (id_comp _) },
{ intros h Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ k,
simp_rw [← h f₁ g₁ h₁, k, h f₂ g₂ h₂] }
end
lemma family_of_elements.compatible.to_sieve_compatible {x : family_of_elements P S}
(t : x.compatible) : x.sieve_compatible :=
(compatible_iff_sieve_compatible x).1 t
/--
Given a family of elements `x` for the sieve `S` generated by a presieve `R`, if `x` is restricted
to `R` and then extended back up to `S`, the resulting extension equals `x`.
-/
@[simp]
lemma extend_restrict {x : family_of_elements P (generate R)} (t : x.compatible) :
(x.restrict (le_generate R)).sieve_extend = x :=
begin
rw compatible_iff_sieve_compatible at t,
ext _ _ h, apply (t _ _ _).symm.trans, congr,
exact h.some_spec.some_spec.some_spec.2,
end
/--
Two compatible families on the sieve generated by a presieve `R` are equal if and only if they are
equal when restricted to `R`.
-/
lemma restrict_inj {x₁ x₂ : family_of_elements P (generate R)}
(t₁ : x₁.compatible) (t₂ : x₂.compatible) :
x₁.restrict (le_generate R) = x₂.restrict (le_generate R) → x₁ = x₂ :=
λ h, by { rw [←extend_restrict t₁, ←extend_restrict t₂], congr, exact h }
/-- Compatible families of elements for a presheaf of types `P` and a presieve `R`
are in 1-1 correspondence with compatible families for the same presheaf and
the sieve generated by `R`, through extension and restriction. -/
@[simps] noncomputable def compatible_equiv_generate_sieve_compatible :
{x : family_of_elements P R // x.compatible} ≃
{x : family_of_elements P (generate R) // x.compatible} :=
{ to_fun := λ x, ⟨x.1.sieve_extend, x.2.sieve_extend⟩,
inv_fun := λ x, ⟨x.1.restrict (le_generate R), x.2.restrict _⟩,
left_inv := λ x, subtype.ext (restrict_extend x.2),
right_inv := λ x, subtype.ext (extend_restrict x.2) }
lemma family_of_elements.comp_of_compatible (S : sieve X) {x : family_of_elements P S}
(t : x.compatible) {f : Y ⟶ X} (hf : S f) {Z} (g : Z ⟶ Y) :
x (g ≫ f) (S.downward_closed hf g) = P.map g.op (x f hf) :=
by simpa using t (𝟙 _) g (S.downward_closed hf g) hf (id_comp _)
section functor_pullback
variables {D : Type u₂} [category.{v₂} D] (F : D ⥤ C) {Z : D}
variables {T : presieve (F.obj Z)} {x : family_of_elements P T}
/--
Given a family of elements of a sieve `S` on `F(X)`, we can realize it as a family of elements of
`S.functor_pullback F`.
-/
def family_of_elements.functor_pullback (x : family_of_elements P T) :
family_of_elements (F.op ⋙ P) (T.functor_pullback F) := λ Y f hf, x (F.map f) hf
lemma family_of_elements.compatible.functor_pullback (h : x.compatible) :
(x.functor_pullback F).compatible :=
begin
intros Z₁ Z₂ W g₁ g₂ f₁ f₂ h₁ h₂ eq,
exact h (F.map g₁) (F.map g₂) h₁ h₂ (by simp only [← F.map_comp, eq])
end
end functor_pullback
/--
Given a family of elements of a sieve `S` on `X` whose values factors through `F`, we can
realize it as a family of elements of `S.functor_pushforward F`. Since the preimage is obtained by
choice, this is not well-defined generally.
-/
noncomputable
def family_of_elements.functor_pushforward {D : Type u₂} [category.{v₂} D] (F : D ⥤ C) {X : D}
{T : presieve X} (x : family_of_elements (F.op ⋙ P) T) :
family_of_elements P (T.functor_pushforward F) := λ Y f h,
by { obtain ⟨Z, g, h, h₁, _⟩ := get_functor_pushforward_structure h, exact P.map h.op (x g h₁) }
section pullback
/--
Given a family of elements of a sieve `S` on `X`, and a map `Y ⟶ X`, we can obtain a
family of elements of `S.pullback f` by taking the same elements.
-/
def family_of_elements.pullback (f : Y ⟶ X) (x : family_of_elements P S) :
family_of_elements P (S.pullback f) := λ _ g hg, x (g ≫ f) hg
lemma family_of_elements.compatible.pullback (f : Y ⟶ X) {x : family_of_elements P S}
(h : x.compatible) : (x.pullback f).compatible :=
begin
simp only [compatible_iff_sieve_compatible] at h ⊢,
intros W Z f₁ f₂ hf,
unfold family_of_elements.pullback,
rw ← (h (f₁ ≫ f) f₂ hf),
simp only [assoc],
end
end pullback
/--
Given a morphism of presheaves `f : P ⟶ Q`, we can take a family of elements valued in `P` to a
family of elements valued in `Q` by composing with `f`.
-/
def family_of_elements.comp_presheaf_map (f : P ⟶ Q) (x : family_of_elements P R) :
family_of_elements Q R := λ Y g hg, f.app (op Y) (x g hg)
@[simp]
lemma family_of_elements.comp_presheaf_map_id (x : family_of_elements P R) :
x.comp_presheaf_map (𝟙 P) = x := rfl
@[simp]
lemma family_of_elements.comp_prersheaf_map_comp (x : family_of_elements P R)
(f : P ⟶ Q) (g : Q ⟶ U) :
(x.comp_presheaf_map f).comp_presheaf_map g = x.comp_presheaf_map (f ≫ g) := rfl
lemma family_of_elements.compatible.comp_presheaf_map (f : P ⟶ Q) {x : family_of_elements P R}
(h : x.compatible) : (x.comp_presheaf_map f).compatible :=
begin
intros Z₁ Z₂ W g₁ g₂ f₁ f₂ h₁ h₂ eq,
unfold family_of_elements.comp_presheaf_map,
rwa [← functor_to_types.naturality, ← functor_to_types.naturality, h],
end
/--
The given element `t` of `P.obj (op X)` is an *amalgamation* for the family of elements `x` if every
restriction `P.map f.op t = x_f` for every arrow `f` in the presieve `R`.
This is the definition given in https://ncatlab.org/nlab/show/sheaf#GeneralDefinitionInComponents,
and https://ncatlab.org/nlab/show/matching+family, as well as [MM92], Chapter III, Section 4,
equation (2).
-/
def family_of_elements.is_amalgamation (x : family_of_elements P R)
(t : P.obj (op X)) : Prop :=
∀ ⦃Y : C⦄ (f : Y ⟶ X) (h : R f), P.map f.op t = x f h
lemma family_of_elements.is_amalgamation.comp_presheaf_map
{x : family_of_elements P R} {t} (f : P ⟶ Q) (h : x.is_amalgamation t) :
(x.comp_presheaf_map f).is_amalgamation (f.app (op X) t) :=
begin
intros Y g hg,
dsimp [family_of_elements.comp_presheaf_map],
change (f.app _ ≫ Q.map _) _ = _,
simp [← f.naturality, h g hg],
end
lemma is_compatible_of_exists_amalgamation (x : family_of_elements P R)
(h : ∃ t, x.is_amalgamation t) : x.compatible :=
begin
cases h with t ht,
intros Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ comm,
rw [←ht _ h₁, ←ht _ h₂, ←functor_to_types.map_comp_apply, ←op_comp, comm],
simp,
end
lemma is_amalgamation_restrict {R₁ R₂ : presieve X} (h : R₁ ≤ R₂)
(x : family_of_elements P R₂) (t : P.obj (op X)) (ht : x.is_amalgamation t) :
(x.restrict h).is_amalgamation t :=
λ Y f hf, ht f (h Y hf)
lemma is_amalgamation_sieve_extend {R : presieve X}
(x : family_of_elements P R) (t : P.obj (op X)) (ht : x.is_amalgamation t) :
x.sieve_extend.is_amalgamation t :=
begin
intros Y f hf,
dsimp [family_of_elements.sieve_extend],
rw [←ht _, ←functor_to_types.map_comp_apply, ←op_comp, hf.some_spec.some_spec.some_spec.2],
end
/-- A presheaf is separated for a presieve if there is at most one amalgamation. -/
def is_separated_for (P : Cᵒᵖ ⥤ Type w) (R : presieve X) : Prop :=
∀ (x : family_of_elements P R) (t₁ t₂),
x.is_amalgamation t₁ → x.is_amalgamation t₂ → t₁ = t₂
lemma is_separated_for.ext {R : presieve X} (hR : is_separated_for P R)
{t₁ t₂ : P.obj (op X)} (h : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄ (hf : R f), P.map f.op t₁ = P.map f.op t₂) :
t₁ = t₂ :=
hR (λ Y f hf, P.map f.op t₂) t₁ t₂ (λ Y f hf, h hf) (λ Y f hf, rfl)
lemma is_separated_for_iff_generate :
is_separated_for P R ↔ is_separated_for P (generate R) :=
begin
split,
{ intros h x t₁ t₂ ht₁ ht₂,
apply h (x.restrict (le_generate R)) t₁ t₂ _ _,
{ exact is_amalgamation_restrict _ x t₁ ht₁ },
{ exact is_amalgamation_restrict _ x t₂ ht₂ } },
{ intros h x t₁ t₂ ht₁ ht₂,
apply h (x.sieve_extend),
{ exact is_amalgamation_sieve_extend x t₁ ht₁ },
{ exact is_amalgamation_sieve_extend x t₂ ht₂ } }
end
lemma is_separated_for_top (P : Cᵒᵖ ⥤ Type w) : is_separated_for P (⊤ : presieve X) :=
λ x t₁ t₂ h₁ h₂,
begin
have q₁ := h₁ (𝟙 X) (by simp),
have q₂ := h₂ (𝟙 X) (by simp),
simp only [op_id, functor_to_types.map_id_apply] at q₁ q₂,
rw [q₁, q₂],
end
/--
We define `P` to be a sheaf for the presieve `R` if every compatible family has a unique
amalgamation.
This is the definition of a sheaf for the given presieve given in C2.1.2 of [Elephant], and
https://ncatlab.org/nlab/show/sheaf#GeneralDefinitionInComponents.
Using `compatible_iff_sieve_compatible`,
this is equivalent to the definition of a sheaf in [MM92], Chapter III, Section 4.
-/
def is_sheaf_for (P : Cᵒᵖ ⥤ Type w) (R : presieve X) : Prop :=
∀ (x : family_of_elements P R), x.compatible → ∃! t, x.is_amalgamation t
/--
This is an equivalent condition to be a sheaf, which is useful for the abstraction to local
operators on elementary toposes. However this definition is defined only for sieves, not presieves.
The equivalence between this and `is_sheaf_for` is given in `yoneda_condition_iff_sheaf_condition`.
This version is also useful to establish that being a sheaf is preserved under isomorphism of
presheaves.
See the discussion before Equation (3) of [MM92], Chapter III, Section 4. See also C2.1.4 of
[Elephant]. This is also a direct reformulation of <https://stacks.math.columbia.edu/tag/00Z8>.
-/
def yoneda_sheaf_condition (P : Cᵒᵖ ⥤ Type v₁) (S : sieve X) : Prop :=
∀ (f : S.functor ⟶ P), ∃! g, S.functor_inclusion ≫ g = f
-- TODO: We can generalize the universe parameter v₁ above by composing with
-- appropriate `ulift_functor`s.
/--
(Implementation). This is a (primarily internal) equivalence between natural transformations
and compatible families.
Cf the discussion after Lemma 7.47.10 in <https://stacks.math.columbia.edu/tag/00YW>. See also
the proof of C2.1.4 of [Elephant], and the discussion in [MM92], Chapter III, Section 4.
-/
def nat_trans_equiv_compatible_family {P : Cᵒᵖ ⥤ Type v₁} :
(S.functor ⟶ P) ≃ {x : family_of_elements P S // x.compatible} :=
{ to_fun := λ α,
begin
refine ⟨λ Y f hf, _, _⟩,
{ apply α.app (op Y) ⟨_, hf⟩ },
{ rw compatible_iff_sieve_compatible,
intros Y Z f g hf,
dsimp,
rw ← functor_to_types.naturality _ _ α g.op,
refl }
end,
inv_fun := λ t,
{ app := λ Y f, t.1 _ f.2,
naturality' := λ Y Z g,
begin
ext ⟨f, hf⟩,
apply t.2.to_sieve_compatible _,
end },
left_inv := λ α,
begin
ext X ⟨_, _⟩,
refl
end,
right_inv :=
begin
rintro ⟨x, hx⟩,
refl,
end }
/-- (Implementation). A lemma useful to prove `yoneda_condition_iff_sheaf_condition`. -/
lemma extension_iff_amalgamation {P : Cᵒᵖ ⥤ Type v₁} (x : S.functor ⟶ P) (g : yoneda.obj X ⟶ P) :
S.functor_inclusion ≫ g = x ↔
(nat_trans_equiv_compatible_family x).1.is_amalgamation (yoneda_equiv g) :=
begin
change _ ↔ ∀ ⦃Y : C⦄ (f : Y ⟶ X) (h : S f), P.map f.op (yoneda_equiv g) = x.app (op Y) ⟨f, h⟩,
split,
{ rintro rfl Y f hf,
rw yoneda_equiv_naturality,
dsimp,
simp }, -- See note [dsimp, simp].
{ intro h,
ext Y ⟨f, hf⟩,
have : _ = x.app Y _ := h f hf,
rw yoneda_equiv_naturality at this,
rw ← this,
dsimp,
simp }, -- See note [dsimp, simp].
end
/--
The yoneda version of the sheaf condition is equivalent to the sheaf condition.
C2.1.4 of [Elephant].
-/
lemma is_sheaf_for_iff_yoneda_sheaf_condition {P : Cᵒᵖ ⥤ Type v₁} :
is_sheaf_for P S ↔ yoneda_sheaf_condition P S :=
begin
rw [is_sheaf_for, yoneda_sheaf_condition],
simp_rw [extension_iff_amalgamation],
rw equiv.forall_congr_left' nat_trans_equiv_compatible_family,
rw subtype.forall,
apply ball_congr,
intros x hx,
rw equiv.exists_unique_congr_left _,
simp,
end
/--
If `P` is a sheaf for the sieve `S` on `X`, a natural transformation from `S` (viewed as a functor)
to `P` can be (uniquely) extended to all of `yoneda.obj X`.
f
S → P
↓ ↗
yX
-/
noncomputable def is_sheaf_for.extend {P : Cᵒᵖ ⥤ Type v₁} (h : is_sheaf_for P S)
(f : S.functor ⟶ P) : yoneda.obj X ⟶ P :=
(is_sheaf_for_iff_yoneda_sheaf_condition.1 h f).exists.some
/--
Show that the extension of `f : S.functor ⟶ P` to all of `yoneda.obj X` is in fact an extension, ie
that the triangle below commutes, provided `P` is a sheaf for `S`
f
S → P
↓ ↗
yX
-/
@[simp, reassoc]
lemma is_sheaf_for.functor_inclusion_comp_extend {P : Cᵒᵖ ⥤ Type v₁} (h : is_sheaf_for P S)
(f : S.functor ⟶ P) : S.functor_inclusion ≫ h.extend f = f :=
(is_sheaf_for_iff_yoneda_sheaf_condition.1 h f).exists.some_spec
/-- The extension of `f` to `yoneda.obj X` is unique. -/
lemma is_sheaf_for.unique_extend {P : Cᵒᵖ ⥤ Type v₁} (h : is_sheaf_for P S) {f : S.functor ⟶ P}
(t : yoneda.obj X ⟶ P) (ht : S.functor_inclusion ≫ t = f) :
t = h.extend f :=
((is_sheaf_for_iff_yoneda_sheaf_condition.1 h f).unique ht (h.functor_inclusion_comp_extend f))
/--
If `P` is a sheaf for the sieve `S` on `X`, then if two natural transformations from `yoneda.obj X`
to `P` agree when restricted to the subfunctor given by `S`, they are equal.
-/
lemma is_sheaf_for.hom_ext {P : Cᵒᵖ ⥤ Type v₁} (h : is_sheaf_for P S) (t₁ t₂ : yoneda.obj X ⟶ P)
(ht : S.functor_inclusion ≫ t₁ = S.functor_inclusion ≫ t₂) :
t₁ = t₂ :=
(h.unique_extend t₁ ht).trans (h.unique_extend t₂ rfl).symm
/-- `P` is a sheaf for `R` iff it is separated for `R` and there exists an amalgamation. -/
lemma is_separated_for_and_exists_is_amalgamation_iff_sheaf_for :
is_separated_for P R ∧ (∀ (x : family_of_elements P R), x.compatible → ∃ t, x.is_amalgamation t) ↔
is_sheaf_for P R :=
begin
rw [is_separated_for, ←forall_and_distrib],
apply forall_congr,
intro x,
split,
{ intros z hx, exact exists_unique_of_exists_of_unique (z.2 hx) z.1 },
{ intros h,
refine ⟨_, (exists_of_exists_unique ∘ h)⟩,
intros t₁ t₂ ht₁ ht₂,
apply (h _).unique ht₁ ht₂,
exact is_compatible_of_exists_amalgamation x ⟨_, ht₂⟩ }
end
/--
If `P` is separated for `R` and every family has an amalgamation, then `P` is a sheaf for `R`.
-/
lemma is_separated_for.is_sheaf_for (t : is_separated_for P R) :
(∀ (x : family_of_elements P R), x.compatible → ∃ t, x.is_amalgamation t) →
is_sheaf_for P R :=
begin
rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for,
exact and.intro t,
end
/-- If `P` is a sheaf for `R`, it is separated for `R`. -/
lemma is_sheaf_for.is_separated_for : is_sheaf_for P R → is_separated_for P R :=
λ q, (is_separated_for_and_exists_is_amalgamation_iff_sheaf_for.2 q).1
/-- Get the amalgamation of the given compatible family, provided we have a sheaf. -/
noncomputable def is_sheaf_for.amalgamate
(t : is_sheaf_for P R) (x : family_of_elements P R) (hx : x.compatible) :
P.obj (op X) :=
(t x hx).exists.some
lemma is_sheaf_for.is_amalgamation
(t : is_sheaf_for P R) {x : family_of_elements P R} (hx : x.compatible) :
x.is_amalgamation (t.amalgamate x hx) :=
(t x hx).exists.some_spec
@[simp]
lemma is_sheaf_for.valid_glue
(t : is_sheaf_for P R) {x : family_of_elements P R} (hx : x.compatible) (f : Y ⟶ X) (Hf : R f) :
P.map f.op (t.amalgamate x hx) = x f Hf :=
t.is_amalgamation hx f Hf
/-- C2.1.3 in [Elephant] -/
lemma is_sheaf_for_iff_generate (R : presieve X) :
is_sheaf_for P R ↔ is_sheaf_for P (generate R) :=
begin
rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for,
rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for,
rw ← is_separated_for_iff_generate,
apply and_congr (iff.refl _),
split,
{ intros q x hx,
apply exists_imp_exists _ (q _ (hx.restrict (le_generate R))),
intros t ht,
simpa [hx] using is_amalgamation_sieve_extend _ _ ht },
{ intros q x hx,
apply exists_imp_exists _ (q _ hx.sieve_extend),
intros t ht,
simpa [hx] using is_amalgamation_restrict (le_generate R) _ _ ht },
end
/--
Every presheaf is a sheaf for the family {𝟙 X}.
[Elephant] C2.1.5(i)
-/
lemma is_sheaf_for_singleton_iso (P : Cᵒᵖ ⥤ Type w) :
is_sheaf_for P (presieve.singleton (𝟙 X)) :=
begin
intros x hx,
refine ⟨x _ (presieve.singleton_self _), _, _⟩,
{ rintro _ _ ⟨rfl, rfl⟩,
simp },
{ intros t ht,
simpa using ht _ (presieve.singleton_self _) }
end
/--
Every presheaf is a sheaf for the maximal sieve.
[Elephant] C2.1.5(ii)
-/
lemma is_sheaf_for_top_sieve (P : Cᵒᵖ ⥤ Type w) :
is_sheaf_for P ((⊤ : sieve X) : presieve X) :=
begin
rw ← generate_of_singleton_is_split_epi (𝟙 X),
rw ← is_sheaf_for_iff_generate,
apply is_sheaf_for_singleton_iso,
end
/--
If `P` is a sheaf for `S`, and it is iso to `P'`, then `P'` is a sheaf for `S`. This shows that
"being a sheaf for a presieve" is a mathematical or hygenic property.
-/
lemma is_sheaf_for_iso {P' : Cᵒᵖ ⥤ Type w} (i : P ≅ P') : is_sheaf_for P R → is_sheaf_for P' R :=
begin
intros h x hx,
let x' := x.comp_presheaf_map i.inv,
have : x'.compatible := family_of_elements.compatible.comp_presheaf_map i.inv hx,
obtain ⟨t, ht1, ht2⟩ := h x' this,
use i.hom.app _ t,
fsplit,
{ convert family_of_elements.is_amalgamation.comp_presheaf_map i.hom ht1,
dsimp [x'],
simp },
{ intros y hy,
rw (show y = (i.inv.app (op X) ≫ i.hom.app (op X)) y, by simp),
simp [ ht2 (i.inv.app _ y) (family_of_elements.is_amalgamation.comp_presheaf_map i.inv hy)] }
end
/--
If a presieve `R` on `X` has a subsieve `S` such that:
* `P` is a sheaf for `S`.
* For every `f` in `R`, `P` is separated for the pullback of `S` along `f`,
then `P` is a sheaf for `R`.
This is closely related to [Elephant] C2.1.6(i).
-/
lemma is_sheaf_for_subsieve_aux (P : Cᵒᵖ ⥤ Type w) {S : sieve X} {R : presieve X}
(h : (S : presieve X) ≤ R)
(hS : is_sheaf_for P S)
(trans : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄, R f → is_separated_for P (S.pullback f)) :
is_sheaf_for P R :=
begin
rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for,
split,
{ intros x t₁ t₂ ht₁ ht₂,
exact hS.is_separated_for _ _ _ (is_amalgamation_restrict h x t₁ ht₁)
(is_amalgamation_restrict h x t₂ ht₂) },
{ intros x hx,
use hS.amalgamate _ (hx.restrict h),
intros W j hj,
apply (trans hj).ext,
intros Y f hf,
rw [←functor_to_types.map_comp_apply, ←op_comp,
hS.valid_glue (hx.restrict h) _ hf, family_of_elements.restrict,
←hx (𝟙 _) f _ _ (id_comp _)],
simp },
end
/--
If `P` is a sheaf for every pullback of the sieve `S`, then `P` is a sheaf for any presieve which
contains `S`.
This is closely related to [Elephant] C2.1.6.
-/
lemma is_sheaf_for_subsieve (P : Cᵒᵖ ⥤ Type w) {S : sieve X} {R : presieve X}
(h : (S : presieve X) ≤ R)
(trans : Π ⦃Y⦄ (f : Y ⟶ X), is_sheaf_for P (S.pullback f)) :
is_sheaf_for P R :=
is_sheaf_for_subsieve_aux P h (by simpa using trans (𝟙 _)) (λ Y f hf, (trans f).is_separated_for)
/-- A presheaf is separated for a topology if it is separated for every sieve in the topology. -/
def is_separated (P : Cᵒᵖ ⥤ Type w) : Prop :=
∀ {X} (S : sieve X), S ∈ J X → is_separated_for P S
/--
A presheaf is a sheaf for a topology if it is a sheaf for every sieve in the topology.
If the given topology is given by a pretopology, `is_sheaf_for_pretopology` shows it suffices to
check the sheaf condition at presieves in the pretopology.
-/
def is_sheaf (P : Cᵒᵖ ⥤ Type w) : Prop :=
∀ ⦃X⦄ (S : sieve X), S ∈ J X → is_sheaf_for P S
lemma is_sheaf.is_sheaf_for {P : Cᵒᵖ ⥤ Type w} (hp : is_sheaf J P)
(R : presieve X) (hr : generate R ∈ J X) : is_sheaf_for P R :=
(is_sheaf_for_iff_generate R).2 $ hp _ hr
lemma is_sheaf_of_le (P : Cᵒᵖ ⥤ Type w) {J₁ J₂ : grothendieck_topology C} :
J₁ ≤ J₂ → is_sheaf J₂ P → is_sheaf J₁ P :=
λ h t X S hS, t S (h _ hS)
lemma is_separated_of_is_sheaf (P : Cᵒᵖ ⥤ Type w) (h : is_sheaf J P) : is_separated J P :=
λ X S hS, (h S hS).is_separated_for
/-- The property of being a sheaf is preserved by isomorphism. -/
lemma is_sheaf_iso {P' : Cᵒᵖ ⥤ Type w} (i : P ≅ P') (h : is_sheaf J P) : is_sheaf J P' :=
λ X S hS, is_sheaf_for_iso i (h S hS)
lemma is_sheaf_of_yoneda {P : Cᵒᵖ ⥤ Type v₁}
(h : ∀ {X} (S : sieve X), S ∈ J X → yoneda_sheaf_condition P S) : is_sheaf J P :=
λ X S hS, is_sheaf_for_iff_yoneda_sheaf_condition.2 (h _ hS)
/--
For a topology generated by a basis, it suffices to check the sheaf condition on the basis
presieves only.
-/
lemma is_sheaf_pretopology [has_pullbacks C] (K : pretopology C) :
is_sheaf (K.to_grothendieck C) P ↔ (∀ {X : C} (R : presieve X), R ∈ K X → is_sheaf_for P R) :=
begin
split,
{ intros PJ X R hR,
rw is_sheaf_for_iff_generate,
apply PJ (sieve.generate R) ⟨_, hR, le_generate R⟩ },
{ rintro PK X S ⟨R, hR, RS⟩,
have gRS : ⇑(generate R) ≤ S,
{ apply gi_generate.gc.monotone_u,
rwa sets_iff_generate },
apply is_sheaf_for_subsieve P gRS _,
intros Y f,
rw [← pullback_arrows_comm, ← is_sheaf_for_iff_generate],
exact PK (pullback_arrows f R) (K.pullbacks f R hR) }
end
/-- Any presheaf is a sheaf for the bottom (trivial) grothendieck topology. -/
lemma is_sheaf_bot : is_sheaf (⊥ : grothendieck_topology C) P :=
λ X, by simp [is_sheaf_for_top_sieve]
end presieve
namespace equalizer
variables {C : Type u₁} [category.{v₁} C] (P : Cᵒᵖ ⥤ Type (max v₁ u₁))
{X : C} (R : presieve X) (S : sieve X)
noncomputable theory
/--
The middle object of the fork diagram given in Equation (3) of [MM92], as well as the fork diagram
of <https://stacks.math.columbia.edu/tag/00VM>.
-/
def first_obj : Type (max v₁ u₁) :=
∏ (λ (f : Σ Y, {f : Y ⟶ X // R f}), P.obj (op f.1))
/-- Show that `first_obj` is isomorphic to `family_of_elements`. -/
@[simps]
def first_obj_eq_family : first_obj P R ≅ R.family_of_elements P :=
{ hom := λ t Y f hf, pi.π (λ (f : Σ Y, {f : Y ⟶ X // R f}), P.obj (op f.1)) ⟨_, _, hf⟩ t,
inv := pi.lift (λ f x, x _ f.2.2),
hom_inv_id' :=
begin
ext ⟨Y, f, hf⟩ p,
simpa,
end,
inv_hom_id' :=
begin
ext x Y f hf,
apply limits.types.limit.lift_π_apply',
end }
instance : inhabited (first_obj P (⊥ : presieve X)) :=
((first_obj_eq_family P _).to_equiv).inhabited
/--
The left morphism of the fork diagram given in Equation (3) of [MM92], as well as the fork diagram
of <https://stacks.math.columbia.edu/tag/00VM>.
-/
def fork_map : P.obj (op X) ⟶ first_obj P R :=
pi.lift (λ f, P.map f.2.1.op)
/-!
This section establishes the equivalence between the sheaf condition of Equation (3) [MM92] and
the definition of `is_sheaf_for`.
-/
namespace sieve
/--
The rightmost object of the fork diagram of Equation (3) [MM92], which contains the data used
to check a family is compatible.
-/
def second_obj : Type (max v₁ u₁) :=
∏ (λ (f : Σ Y Z (g : Z ⟶ Y), {f' : Y ⟶ X // S f'}), P.obj (op f.2.1))
/-- The map `p` of Equations (3,4) [MM92]. -/
def first_map : first_obj P S ⟶ second_obj P S :=
pi.lift (λ fg, pi.π _ (⟨_, _, S.downward_closed fg.2.2.2.2 fg.2.2.1⟩ : Σ Y, {f : Y ⟶ X // S f}))
instance : inhabited (second_obj P (⊥ : sieve X)) := ⟨first_map _ _ default⟩
/-- The map `a` of Equations (3,4) [MM92]. -/
def second_map : first_obj P S ⟶ second_obj P S :=
pi.lift (λ fg, pi.π _ ⟨_, fg.2.2.2⟩ ≫ P.map fg.2.2.1.op)
lemma w : fork_map P S ≫ first_map P S = fork_map P S ≫ second_map P S :=
begin
apply limit.hom_ext,
rintro ⟨Y, Z, g, f, hf⟩,
simp [first_map, second_map, fork_map],
end
/--
The family of elements given by `x : first_obj P S` is compatible iff `first_map` and `second_map`
map it to the same point.
-/
lemma compatible_iff (x : first_obj P S) :
((first_obj_eq_family P S).hom x).compatible ↔ first_map P S x = second_map P S x :=
begin
rw presieve.compatible_iff_sieve_compatible,
split,
{ intro t,
ext ⟨Y, Z, g, f, hf⟩,
simpa [first_map, second_map] using t _ g hf },
{ intros t Y Z f g hf,
rw types.limit_ext_iff' at t,
simpa [first_map, second_map] using t ⟨⟨Y, Z, g, f, hf⟩⟩ }
end
/-- `P` is a sheaf for `S`, iff the fork given by `w` is an equalizer. -/
lemma equalizer_sheaf_condition :
presieve.is_sheaf_for P S ↔ nonempty (is_limit (fork.of_ι _ (w P S))) :=
begin
rw [types.type_equalizer_iff_unique,
← equiv.forall_congr_left (first_obj_eq_family P S).to_equiv.symm],
simp_rw ← compatible_iff,
simp only [inv_hom_id_apply, iso.to_equiv_symm_fun],
apply ball_congr,
intros x tx,
apply exists_unique_congr,
intro t,
rw ← iso.to_equiv_symm_fun,
rw equiv.eq_symm_apply,
split,
{ intros q,
ext Y f hf,
simpa [first_obj_eq_family, fork_map] using q _ _ },
{ intros q Y f hf,
rw ← q,
simp [first_obj_eq_family, fork_map] }
end
end sieve
/-!
This section establishes the equivalence between the sheaf condition of
https://stacks.math.columbia.edu/tag/00VM and the definition of `is_sheaf_for`.
-/
namespace presieve
variables [has_pullbacks C]
/--
The rightmost object of the fork diagram of https://stacks.math.columbia.edu/tag/00VM, which
contains the data used to check a family of elements for a presieve is compatible.
-/
def second_obj : Type (max v₁ u₁) :=
∏ (λ (fg : (Σ Y, {f : Y ⟶ X // R f}) × (Σ Z, {g : Z ⟶ X // R g})),
P.obj (op (pullback fg.1.2.1 fg.2.2.1)))
/-- The map `pr₀*` of <https://stacks.math.columbia.edu/tag/00VL>. -/
def first_map : first_obj P R ⟶ second_obj P R :=
pi.lift (λ fg, pi.π _ _ ≫ P.map pullback.fst.op)
instance : inhabited (second_obj P (⊥ : presieve X)) := ⟨first_map _ _ default⟩
/-- The map `pr₁*` of <https://stacks.math.columbia.edu/tag/00VL>. -/
def second_map : first_obj P R ⟶ second_obj P R :=
pi.lift (λ fg, pi.π _ _ ≫ P.map pullback.snd.op)
lemma w : fork_map P R ≫ first_map P R = fork_map P R ≫ second_map P R :=
begin
apply limit.hom_ext,
rintro ⟨⟨Y, f, hf⟩, ⟨Z, g, hg⟩⟩,
simp only [first_map, second_map, fork_map],
simp only [limit.lift_π, limit.lift_π_assoc, assoc, fan.mk_π_app, subtype.coe_mk,
subtype.val_eq_coe],
rw [← P.map_comp, ← op_comp, pullback.condition],
simp,
end
/--
The family of elements given by `x : first_obj P S` is compatible iff `first_map` and `second_map`
map it to the same point.
-/
lemma compatible_iff (x : first_obj P R) :
((first_obj_eq_family P R).hom x).compatible ↔ first_map P R x = second_map P R x :=
begin
rw presieve.pullback_compatible_iff,
split,
{ intro t,
ext ⟨⟨Y, f, hf⟩, Z, g, hg⟩,
simpa [first_map, second_map] using t hf hg },
{ intros t Y Z f g hf hg,
rw types.limit_ext_iff' at t,
simpa [first_map, second_map] using t ⟨⟨⟨Y, f, hf⟩, Z, g, hg⟩⟩ }
end
/--
`P` is a sheaf for `R`, iff the fork given by `w` is an equalizer.
See <https://stacks.math.columbia.edu/tag/00VM>.
-/
lemma sheaf_condition :
R.is_sheaf_for P ↔ nonempty (is_limit (fork.of_ι _ (w P R))) :=
begin
rw types.type_equalizer_iff_unique,
erw ← equiv.forall_congr_left (first_obj_eq_family P R).to_equiv.symm,
simp_rw [← compatible_iff, ← iso.to_equiv_fun, equiv.apply_symm_apply],
apply ball_congr,
intros x hx,
apply exists_unique_congr,
intros t,
rw equiv.eq_symm_apply,
split,
{ intros q,
ext Y f hf,
simpa [fork_map] using q _ _ },
{ intros q Y f hf,
rw ← q,
simp [fork_map] }
end
end presieve
end equalizer
variables {C : Type u₁} [category.{v₁} C]
variables (J : grothendieck_topology C)
/-- The category of sheaves on a grothendieck topology. -/
structure SheafOfTypes (J : grothendieck_topology C) : Type (max u₁ v₁ (w+1)) :=
(val : Cᵒᵖ ⥤ Type w)
(cond : presieve.is_sheaf J val)
namespace SheafOfTypes
variable {J}
/-- Morphisms between sheaves of types are just morphisms between the underlying presheaves. -/
@[ext]
structure hom (X Y : SheafOfTypes J) :=
(val : X.val ⟶ Y.val)
@[simps]
instance : category (SheafOfTypes J) :=
{ hom := hom,
id := λ X, ⟨𝟙 _⟩,
comp := λ X Y Z f g, ⟨f.val ≫ g.val⟩,
id_comp' := λ X Y f, hom.ext _ _ $ id_comp _,
comp_id' := λ X Y f, hom.ext _ _ $ comp_id _,
assoc' := λ X Y Z W f g h, hom.ext _ _ $ assoc _ _ _ }
-- Let's make the inhabited linter happy...
instance (X : SheafOfTypes J) : inhabited (hom X X) := ⟨𝟙 X⟩
end SheafOfTypes
/-- The inclusion functor from sheaves to presheaves. -/
@[simps]
def SheafOfTypes_to_presheaf : SheafOfTypes J ⥤ (Cᵒᵖ ⥤ Type w) :=
{ obj := SheafOfTypes.val,
map := λ X Y f, f.val,
map_id' := λ X, rfl,
map_comp' := λ X Y Z f g, rfl }
instance : full (SheafOfTypes_to_presheaf J) := { preimage := λ X Y f, ⟨f⟩ }
instance : faithful (SheafOfTypes_to_presheaf J) := {}
/--
The category of sheaves on the bottom (trivial) grothendieck topology is equivalent to the category
of presheaves.
-/
@[simps]
def SheafOfTypes_bot_equiv : SheafOfTypes (⊥ : grothendieck_topology C) ≌ (Cᵒᵖ ⥤ Type w) :=
{ functor := SheafOfTypes_to_presheaf _,
inverse :=
{ obj := λ P, ⟨P, presieve.is_sheaf_bot⟩,
map := λ P₁ P₂ f, (SheafOfTypes_to_presheaf _).preimage f },
unit_iso :=
{ hom := { app := λ _, ⟨𝟙 _⟩ },
inv := { app := λ _, ⟨𝟙 _⟩ } },
counit_iso := iso.refl _ }
instance : inhabited (SheafOfTypes (⊥ : grothendieck_topology C)) :=
⟨SheafOfTypes_bot_equiv.inverse.obj ((functor.const _).obj punit)⟩
end category_theory
|
c665e68ee2f545c2ab950d93afa58be99a9f4673 | 2c096fdfecf64e46ea7bc6ce5521f142b5926864 | /src/Lean/Meta/Tactic/Simp.lean | 30554e3d5cb8e5d4c16fa65c325dec51d605c741 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | Kha/lean4 | 1005785d2c8797ae266a303968848e5f6ce2fe87 | b99e11346948023cd6c29d248cd8f3e3fb3474cf | refs/heads/master | 1,693,355,498,027 | 1,669,080,461,000 | 1,669,113,138,000 | 184,748,176 | 0 | 0 | Apache-2.0 | 1,665,995,520,000 | 1,556,884,930,000 | Lean | UTF-8 | Lean | false | false | 963 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Tactic.Simp.SimpTheorems
import Lean.Meta.Tactic.Simp.SimpCongrTheorems
import Lean.Meta.Tactic.Simp.Types
import Lean.Meta.Tactic.Simp.Main
import Lean.Meta.Tactic.Simp.Rewrite
import Lean.Meta.Tactic.Simp.SimpAll
namespace Lean
builtin_initialize registerTraceClass `Meta.Tactic.simp
builtin_initialize registerTraceClass `Meta.Tactic.simp.congr (inherited := true)
builtin_initialize registerTraceClass `Meta.Tactic.simp.discharge (inherited := true)
builtin_initialize registerTraceClass `Meta.Tactic.simp.rewrite (inherited := true)
builtin_initialize registerTraceClass `Meta.Tactic.simp.unify (inherited := true)
builtin_initialize registerTraceClass `Debug.Meta.Tactic.simp
builtin_initialize registerTraceClass `Debug.Meta.Tactic.simp.congr (inherited := true)
end Lean
|
f8784303832fa034893c2f2a991d579ac7950a59 | 31f556cdeb9239ffc2fad8f905e33987ff4feab9 | /src/Lean/Meta/DiscrTree.lean | 99cf7107c02891b60586681891ab1f48034bd03c | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | tobiasgrosser/lean4 | ce0fd9cca0feba1100656679bf41f0bffdbabb71 | ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f | refs/heads/master | 1,673,103,412,948 | 1,664,930,501,000 | 1,664,930,501,000 | 186,870,185 | 0 | 0 | Apache-2.0 | 1,665,129,237,000 | 1,557,939,901,000 | Lean | UTF-8 | Lean | false | false | 22,858 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.WHNF
import Lean.Meta.DiscrTreeTypes
namespace Lean.Meta.DiscrTree
/-!
(Imperfect) discrimination trees.
We use a hybrid representation.
- A `PersistentHashMap` for the root node which usually contains many children.
- A sorted array of key/node pairs for inner nodes.
The edges are labeled by keys:
- Constant names (and arity). Universe levels are ignored.
- Free variables (and arity). Thus, an entry in the discrimination tree
may reference hypotheses from the local context.
- Literals
- Star/Wildcard. We use them to represent metavariables and terms
we want to ignore. We ignore implicit arguments and proofs.
- Other. We use to represent other kinds of terms (e.g., nested lambda, forall, sort, etc).
We reduce terms using `TransparencyMode.reducible`. Thus, all reducible
definitions in an expression `e` are unfolded before we insert it into the
discrimination tree.
Recall that projections from classes are **NOT** reducible.
For example, the expressions `Add.add α (ringAdd ?α ?s) ?x ?x`
and `Add.add Nat Nat.hasAdd a b` generates paths with the following keys
respctively
```
⟨Add.add, 4⟩, *, *, *, *
⟨Add.add, 4⟩, *, *, ⟨a,0⟩, ⟨b,0⟩
```
That is, we don't reduce `Add.add Nat inst a b` into `Nat.add a b`.
We say the `Add.add` applications are the de-facto canonical forms in
the metaprogramming framework.
Moreover, it is the metaprogrammer's responsibility to re-pack applications such as
`Nat.add a b` into `Add.add Nat inst a b`.
Remark: we store the arity in the keys
1- To be able to implement the "skip" operation when retrieving "candidate"
unifiers.
2- Distinguish partial applications `f a`, `f a b`, and `f a b c`.
-/
def Key.ctorIdx : Key → Nat
| Key.star => 0
| Key.other => 1
| Key.lit .. => 2
| Key.fvar .. => 3
| Key.const .. => 4
| Key.arrow => 5
| Key.proj .. => 6
def Key.lt : Key → Key → Bool
| Key.lit v₁, Key.lit v₂ => v₁ < v₂
| Key.fvar n₁ a₁, Key.fvar n₂ a₂ => Name.quickLt n₁.name n₂.name || (n₁ == n₂ && a₁ < a₂)
| Key.const n₁ a₁, Key.const n₂ a₂ => Name.quickLt n₁ n₂ || (n₁ == n₂ && a₁ < a₂)
| Key.proj s₁ i₁, Key.proj s₂ i₂ => Name.quickLt s₁ s₂ || (s₁ == s₂ && i₁ < i₂)
| k₁, k₂ => k₁.ctorIdx < k₂.ctorIdx
instance : LT Key := ⟨fun a b => Key.lt a b⟩
instance (a b : Key) : Decidable (a < b) := inferInstanceAs (Decidable (Key.lt a b))
def Key.format : Key → Format
| Key.star => "*"
| Key.other => "◾"
| Key.lit (Literal.natVal v) => Std.format v
| Key.lit (Literal.strVal v) => repr v
| Key.const k _ => Std.format k
| Key.proj s i => Std.format s ++ "." ++ Std.format i
| Key.fvar k _ => Std.format k.name
| Key.arrow => "→"
instance : ToFormat Key := ⟨Key.format⟩
def Key.arity : Key → Nat
| Key.const _ a => a
| Key.fvar _ a => a
| Key.arrow => 2
| Key.proj .. => 1
| _ => 0
instance : Inhabited (Trie α) := ⟨Trie.node #[] #[]⟩
def empty : DiscrTree α := { root := {} }
partial def Trie.format [ToFormat α] : Trie α → Format
| Trie.node vs cs => Format.group $ Format.paren $
"node" ++ (if vs.isEmpty then Format.nil else " " ++ Std.format vs)
++ Format.join (cs.toList.map fun ⟨k, c⟩ => Format.line ++ Format.paren (Std.format k ++ " => " ++ format c))
instance [ToFormat α] : ToFormat (Trie α) := ⟨Trie.format⟩
partial def format [ToFormat α] (d : DiscrTree α) : Format :=
let (_, r) := d.root.foldl
(fun (p : Bool × Format) k c =>
(false, p.2 ++ (if p.1 then Format.nil else Format.line) ++ Format.paren (Std.format k ++ " => " ++ Std.format c)))
(true, Format.nil)
Format.group r
instance [ToFormat α] : ToFormat (DiscrTree α) := ⟨format⟩
/-- The discrimination tree ignores implicit arguments and proofs.
We use the following auxiliary id as a "mark". -/
private def tmpMVarId : MVarId := { name := `_discr_tree_tmp }
private def tmpStar := mkMVar tmpMVarId
instance : Inhabited (DiscrTree α) where
default := {}
/--
Return true iff the argument should be treated as a "wildcard" by the discrimination tree.
- We ignore proofs because of proof irrelevance. It doesn't make sense to try to
index their structure.
- We ignore instance implicit arguments (e.g., `[Add α]`) because they are "morally" canonical.
Moreover, we may have many definitionally equal terms floating around.
Example: `Ring.hasAdd Int Int.isRing` and `Int.hasAdd`.
- We considered ignoring implicit arguments (e.g., `{α : Type}`) since users don't "see" them,
and may not even understand why some simplification rule is not firing.
However, in type class resolution, we have instance such as `Decidable (@Eq Nat x y)`,
where `Nat` is an implicit argument. Thus, we would add the path
```
Decidable -> Eq -> * -> * -> * -> [Nat.decEq]
```
to the discrimination tree IF we ignored the implict `Nat` argument.
This would be BAD since **ALL** decidable equality instances would be in the same path.
So, we index implicit arguments if they are types.
This setting seems sensible for simplification theorems such as:
```
forall (x y : Unit), (@Eq Unit x y) = true
```
If we ignore the implicit argument `Unit`, the `DiscrTree` will say it is a candidate
simplification theorem for any equality in our goal.
Remark: if users have problems with the solution above, we may provide a `noIndexing` annotation,
and `ignoreArg` would return true for any term of the form `noIndexing t`.
-/
private def ignoreArg (a : Expr) (i : Nat) (infos : Array ParamInfo) : MetaM Bool := do
if h : i < infos.size then
let info := infos.get ⟨i, h⟩
if info.isInstImplicit then
return true
else if info.isImplicit || info.isStrictImplicit then
return not (← isType a)
else
isProof a
else
isProof a
private partial def pushArgsAux (infos : Array ParamInfo) : Nat → Expr → Array Expr → MetaM (Array Expr)
| i, Expr.app f a, todo => do
if (← ignoreArg a i infos) then
pushArgsAux infos (i-1) f (todo.push tmpStar)
else
pushArgsAux infos (i-1) f (todo.push a)
| _, _, todo => return todo
/--
Return true if `e` is one of the following
- A nat literal (numeral)
- `Nat.zero`
- `Nat.succ x` where `isNumeral x`
- `OfNat.ofNat _ x _` where `isNumeral x` -/
private partial def isNumeral (e : Expr) : Bool :=
if e.isNatLit then true
else
let f := e.getAppFn
if !f.isConst then false
else
let fName := f.constName!
if fName == ``Nat.succ && e.getAppNumArgs == 1 then isNumeral e.appArg!
else if fName == ``OfNat.ofNat && e.getAppNumArgs == 3 then isNumeral (e.getArg! 1)
else if fName == ``Nat.zero && e.getAppNumArgs == 0 then true
else false
private def isNatType (e : Expr) : MetaM Bool :=
return (← whnf e).isConstOf ``Nat
/--
Return true if `e` is one of the following
- `Nat.add _ k` where `isNumeral k`
- `Add.add Nat _ _ k` where `isNumeral k`
- `HAdd.hAdd _ Nat _ _ k` where `isNumeral k`
- `Nat.succ _`
This function assumes `e.isAppOf fName`
-/
private def isOffset (fName : Name) (e : Expr) : MetaM Bool := do
if fName == ``Nat.add && e.getAppNumArgs == 2 then
return isNumeral e.appArg!
else if fName == ``Add.add && e.getAppNumArgs == 4 then
if (← isNatType (e.getArg! 0)) then return isNumeral e.appArg! else return false
else if fName == ``HAdd.hAdd && e.getAppNumArgs == 6 then
if (← isNatType (e.getArg! 1)) then return isNumeral e.appArg! else return false
else
return fName == ``Nat.succ && e.getAppNumArgs == 1
/--
TODO: add hook for users adding their own functions for controlling `shouldAddAsStar`
Different `DiscrTree` users may populate this set using, for example, attributes.
Remark: we currently tag `Nat.zero` and "offset" terms to avoid having to add special
support for `Expr.lit` and offset terms.
Example, suppose the discrimination tree contains the entry
`Nat.succ ?m |-> v`, and we are trying to retrieve the matches for `Expr.lit (Literal.natVal 1) _`.
In this scenario, we want to retrieve `Nat.succ ?m |-> v` -/
private def shouldAddAsStar (fName : Name) (e : Expr) : MetaM Bool := do
if fName == ``Nat.zero then
return true
else
isOffset fName e
def mkNoindexAnnotation (e : Expr) : Expr :=
mkAnnotation `noindex e
def hasNoindexAnnotation (e : Expr) : Bool :=
annotation? `noindex e |>.isSome
private partial def whnfEta (e : Expr) : MetaM Expr := do
let e ← whnf e
match e.etaExpandedStrict? with
| some e => whnfEta e
| none => return e
/--
Return `true` if `fn` is a "bad" key. That is, `pushArgs` would add `Key.other` or `Key.star`.
We use this function when processing "root terms, and will avoid unfolding terms.
Note that without this trick the pattern `List.map f ∘ List.map g` would be mapped into the key `Key.other`
since the function composition `∘` would be unfolded and we would get `fun x => List.map g (List.map f x)`
-/
private def isBadKey (fn : Expr) : Bool :=
match fn with
| Expr.lit .. => false
| Expr.const .. => false
| Expr.fvar .. => false
| Expr.proj .. => false
| Expr.forallE _ _ b _ => b.hasLooseBVars
| _ => true
/--
Reduce `e` until we get an irreducible term (modulo current reducibility setting) or the resulting term
is a bad key (see comment at `isBadKey`).
We use this method instead of `whnfEta` for root terms at `pushArgs`. -/
private partial def whnfUntilBadKey (e : Expr) : MetaM Expr := do
let e ← step e
match e.etaExpandedStrict? with
| some e => whnfUntilBadKey e
| none => return e
where
step (e : Expr) := do
let e ← whnfCore e
match (← unfoldDefinition? e) with
| some e' => if isBadKey e'.getAppFn then return e else step e'
| none => return e
/-- whnf for the discrimination tree module -/
def whnfDT (e : Expr) (root : Bool) : MetaM Expr :=
if root then whnfUntilBadKey e else whnfEta e
/- Remark: we use `shouldAddAsStar` only for nested terms, and `root == false` for nested terms -/
private def pushArgs (root : Bool) (todo : Array Expr) (e : Expr) : MetaM (Key × Array Expr) := do
if hasNoindexAnnotation e then
return (Key.star, todo)
else
let e ← whnfDT e root
let fn := e.getAppFn
let push (k : Key) (nargs : Nat) : MetaM (Key × Array Expr) := do
let info ← getFunInfoNArgs fn nargs
let todo ← pushArgsAux info.paramInfo (nargs-1) e todo
return (k, todo)
match fn with
| Expr.lit v => return (Key.lit v, todo)
| Expr.const c _ =>
unless root do
if (← shouldAddAsStar c e) then
return (Key.star, todo)
let nargs := e.getAppNumArgs
push (Key.const c nargs) nargs
| Expr.proj s i a .. =>
return (Key.proj s i, todo.push a)
| Expr.fvar fvarId =>
let nargs := e.getAppNumArgs
push (Key.fvar fvarId nargs) nargs
| Expr.mvar mvarId =>
if mvarId == tmpMVarId then
-- We use `tmp to mark implicit arguments and proofs
return (Key.star, todo)
else if (← mvarId.isReadOnlyOrSyntheticOpaque) then
return (Key.other, todo)
else
return (Key.star, todo)
| Expr.forallE _ d b _ =>
if b.hasLooseBVars then
return (Key.other, todo)
else
return (Key.arrow, todo.push d |>.push b)
| _ =>
return (Key.other, todo)
partial def mkPathAux (root : Bool) (todo : Array Expr) (keys : Array Key) : MetaM (Array Key) := do
if todo.isEmpty then
return keys
else
let e := todo.back
let todo := todo.pop
let (k, todo) ← pushArgs root todo e
mkPathAux false todo (keys.push k)
private def initCapacity := 8
def mkPath (e : Expr) : MetaM (Array Key) := do
withReducible do
let todo : Array Expr := Array.mkEmpty initCapacity
let keys : Array Key := Array.mkEmpty initCapacity
mkPathAux (root := true) (todo.push e) keys
private partial def createNodes (keys : Array Key) (v : α) (i : Nat) : Trie α :=
if h : i < keys.size then
let k := keys.get ⟨i, h⟩
let c := createNodes keys v (i+1)
Trie.node #[] #[(k, c)]
else
Trie.node #[v] #[]
private def insertVal [BEq α] (vs : Array α) (v : α) : Array α :=
if vs.contains v then vs else vs.push v
private partial def insertAux [BEq α] (keys : Array Key) (v : α) : Nat → Trie α → Trie α
| i, Trie.node vs cs =>
if h : i < keys.size then
let k := keys.get ⟨i, h⟩
let c := Id.run $ cs.binInsertM
(fun a b => a.1 < b.1)
(fun ⟨_, s⟩ => let c := insertAux keys v (i+1) s; (k, c)) -- merge with existing
(fun _ => let c := createNodes keys v (i+1); (k, c))
(k, default)
Trie.node vs c
else
Trie.node (insertVal vs v) cs
def insertCore [BEq α] (d : DiscrTree α) (keys : Array Key) (v : α) : DiscrTree α :=
if keys.isEmpty then panic! "invalid key sequence"
else
let k := keys[0]!
match d.root.find? k with
| none =>
let c := createNodes keys v 1
{ root := d.root.insert k c }
| some c =>
let c := insertAux keys v 1 c
{ root := d.root.insert k c }
def insert [BEq α] (d : DiscrTree α) (e : Expr) (v : α) : MetaM (DiscrTree α) := do
let keys ← mkPath e
return d.insertCore keys v
private def getKeyArgs (e : Expr) (isMatch root : Bool) : MetaM (Key × Array Expr) := do
let e ← whnfDT e root
match e.getAppFn with
| Expr.lit v => return (Key.lit v, #[])
| Expr.const c _ =>
if (← getConfig).isDefEqStuckEx && e.hasExprMVar then
if (← isReducible c) then
/- `e` is a term `c ...` s.t. `c` is reducible and `e` has metavariables, but it was not unfolded.
This can happen if the metavariables in `e` are "blocking" smart unfolding.
If `isDefEqStuckEx` is enabled, then we must throw the `isDefEqStuck` exception to postpone TC resolution.
Here is an example. Suppose we have
```
inductive Ty where
| bool | fn (a ty : Ty)
@[reducible] def Ty.interp : Ty → Type
| bool => Bool
| fn a b => a.interp → b.interp
```
and we are trying to synthesize `BEq (Ty.interp ?m)`
-/
Meta.throwIsDefEqStuck
else if let some matcherInfo := isMatcherAppCore? (← getEnv) e then
-- A matcher application is stuck is one of the discriminants has a metavariable
let args := e.getAppArgs
for arg in args[matcherInfo.getFirstDiscrPos: matcherInfo.getFirstDiscrPos + matcherInfo.numDiscrs] do
if arg.hasExprMVar then
Meta.throwIsDefEqStuck
else if (← isRec c) then
/- Similar to the previous case, but for `match` and recursor applications. It may be stuck (i.e., did not reduce)
because of metavariables. -/
Meta.throwIsDefEqStuck
let nargs := e.getAppNumArgs
return (Key.const c nargs, e.getAppRevArgs)
| Expr.fvar fvarId =>
let nargs := e.getAppNumArgs
return (Key.fvar fvarId nargs, e.getAppRevArgs)
| Expr.mvar mvarId =>
if isMatch then
return (Key.other, #[])
else do
let ctx ← read
if ctx.config.isDefEqStuckEx then
/-
When the configuration flag `isDefEqStuckEx` is set to true,
we want `isDefEq` to throw an exception whenever it tries to assign
a read-only metavariable.
This feature is useful for type class resolution where
we may want to notify the caller that the TC problem may be solveable
later after it assigns `?m`.
The method `DiscrTree.getUnify e` returns candidates `c` that may "unify" with `e`.
That is, `isDefEq c e` may return true. Now, consider `DiscrTree.getUnify d (Add ?m)`
where `?m` is a read-only metavariable, and the discrimination tree contains the keys
`HadAdd Nat` and `Add Int`. If `isDefEqStuckEx` is set to true, we must treat `?m` as
a regular metavariable here, otherwise we return the empty set of candidates.
This is incorrect because it is equivalent to saying that there is no solution even if
the caller assigns `?m` and try again. -/
return (Key.star, #[])
else if (← mvarId.isReadOnlyOrSyntheticOpaque) then
return (Key.other, #[])
else
return (Key.star, #[])
| Expr.proj s i a .. =>
return (Key.proj s i, #[a])
| Expr.forallE _ d b _ =>
if b.hasLooseBVars then
return (Key.other, #[])
else
return (Key.arrow, #[d, b])
| _ =>
return (Key.other, #[])
private abbrev getMatchKeyArgs (e : Expr) (root : Bool) : MetaM (Key × Array Expr) :=
getKeyArgs e (isMatch := true) (root := root)
private abbrev getUnifyKeyArgs (e : Expr) (root : Bool) : MetaM (Key × Array Expr) :=
getKeyArgs e (isMatch := false) (root := root)
private def getStarResult (d : DiscrTree α) : Array α :=
let result : Array α := Array.mkEmpty initCapacity
match d.root.find? Key.star with
| none => result
| some (Trie.node vs _) => result ++ vs
private abbrev findKey (cs : Array (Key × Trie α)) (k : Key) : Option (Key × Trie α) :=
cs.binSearch (k, default) (fun a b => a.1 < b.1)
private partial def getMatchLoop (todo : Array Expr) (c : Trie α) (result : Array α) : MetaM (Array α) := do
match c with
| Trie.node vs cs =>
if todo.isEmpty then
return result ++ vs
else if cs.isEmpty then
return result
else
let e := todo.back
let todo := todo.pop
let first := cs[0]! /- Recall that `Key.star` is the minimal key -/
let (k, args) ← getMatchKeyArgs e (root := false)
/- We must always visit `Key.star` edges since they are wildcards.
Thus, `todo` is not used linearly when there is `Key.star` edge
and there is an edge for `k` and `k != Key.star`. -/
let visitStar (result : Array α) : MetaM (Array α) :=
if first.1 == Key.star then
getMatchLoop todo first.2 result
else
return result
let visitNonStar (k : Key) (args : Array Expr) (result : Array α) : MetaM (Array α) :=
match findKey cs k with
| none => return result
| some c => getMatchLoop (todo ++ args) c.2 result
let result ← visitStar result
match k with
| Key.star => return result
/-
Recall that dependent arrows are `(Key.other, #[])`, and non-dependent arrows are `(Key.arrow, #[a, b])`.
A non-dependent arrow may be an instance of a dependent arrow (stored at `DiscrTree`). Thus, we also visit the `Key.other` child.
-/
| Key.arrow => visitNonStar Key.other #[] (← visitNonStar k args result)
| _ => visitNonStar k args result
private def getMatchRoot (d : DiscrTree α) (k : Key) (args : Array Expr) (result : Array α) : MetaM (Array α) :=
match d.root.find? k with
| none => return result
| some c => getMatchLoop args c result
private def getMatchCore (d : DiscrTree α) (e : Expr) : MetaM (Key × Array α) :=
withReducible do
let result := getStarResult d
let (k, args) ← getMatchKeyArgs e (root := true)
match k with
| Key.star => return (k, result)
| _ => return (k, ← getMatchRoot d k args result)
/--
Find values that match `e` in `d`.
-/
def getMatch (d : DiscrTree α) (e : Expr) : MetaM (Array α) :=
return (← getMatchCore d e).2
/--
Similar to `getMatch`, but returns solutions that are prefixes of `e`.
We store the number of ignored arguments in the result.-/
partial def getMatchWithExtra (d : DiscrTree α) (e : Expr) : MetaM (Array (α × Nat)) := do
let (k, result) ← getMatchCore d e
let result := result.map (·, 0)
if !e.isApp then
return result
else if !(← mayMatchPrefix k) then
return result
else
go e.appFn! 1 result
where
mayMatchPrefix (k : Key) : MetaM Bool :=
let cont (k : Key) : MetaM Bool :=
if d.root.find? k |>.isSome then
return true
else
mayMatchPrefix k
match k with
| Key.const f (n+1) => cont (Key.const f n)
| Key.fvar f (n+1) => cont (Key.fvar f n)
| _ => return false
go (e : Expr) (numExtra : Nat) (result : Array (α × Nat)) : MetaM (Array (α × Nat)) := do
let result := result ++ (← getMatch d e).map (., numExtra)
if e.isApp then
go e.appFn! (numExtra + 1) result
else
return result
partial def getUnify (d : DiscrTree α) (e : Expr) : MetaM (Array α) :=
withReducible do
let (k, args) ← getUnifyKeyArgs e (root := true)
match k with
| .star => d.root.foldlM (init := #[]) fun result k c => process k.arity #[] c result
| _ =>
let result := getStarResult d
match d.root.find? k with
| none => return result
| some c => process 0 args c result
where
process (skip : Nat) (todo : Array Expr) (c : Trie α) (result : Array α) : MetaM (Array α) := do
match skip, c with
| skip+1, Trie.node _ cs =>
if cs.isEmpty then
return result
else
cs.foldlM (init := result) fun result ⟨k, c⟩ => process (skip + k.arity) todo c result
| 0, Trie.node vs cs => do
if todo.isEmpty then
return result ++ vs
else if cs.isEmpty then
return result
else
let e := todo.back
let todo := todo.pop
let (k, args) ← getUnifyKeyArgs e (root := false)
let visitStar (result : Array α) : MetaM (Array α) :=
let first := cs[0]!
if first.1 == Key.star then
process 0 todo first.2 result
else
return result
let visitNonStar (k : Key) (args : Array Expr) (result : Array α) : MetaM (Array α) :=
match findKey cs k with
| none => return result
| some c => process 0 (todo ++ args) c.2 result
match k with
| .star => cs.foldlM (init := result) fun result ⟨k, c⟩ => process k.arity todo c result
-- See comment a `getMatch` regarding non-dependent arrows vs dependent arrows
| .arrow => visitNonStar Key.other #[] (← visitNonStar k args (← visitStar result))
| _ => visitNonStar k args (← visitStar result)
end Lean.Meta.DiscrTree
|
64dc031f3d7c948819d58ee61ca2e69bc50b39cb | 4727251e0cd73359b15b664c3170e5d754078599 | /src/category_theory/functor/currying.lean | 6285dff51ee5870d63ff40df89b86c213998c830 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 4,489 | 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.bifunctor
/-!
# Curry and uncurry, as functors.
We define `curry : ((C × D) ⥤ E) ⥤ (C ⥤ (D ⥤ E))` and `uncurry : (C ⥤ (D ⥤ E)) ⥤ ((C × D) ⥤ E)`,
and verify that they provide an equivalence of categories
`currying : (C ⥤ (D ⥤ E)) ≌ ((C × D) ⥤ E)`.
-/
namespace category_theory
universes v₁ v₂ v₃ u₁ u₂ u₃
variables {C : Type u₁} [category.{v₁} C]
{D : Type u₂} [category.{v₂} D]
{E : Type u₃} [category.{v₃} E]
/--
The uncurrying functor, taking a functor `C ⥤ (D ⥤ E)` and producing a functor `(C × D) ⥤ E`.
-/
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_comp' := λ X Y Z f g,
begin
simp only [prod_comp_fst, prod_comp_snd, functor.map_comp,
nat_trans.comp_app, category.assoc],
slice_lhs 2 3 { rw ← nat_trans.naturality },
rw category.assoc,
end },
map := λ F G T,
{ app := λ X, (T.app X.1).app X.2,
naturality' := λ X Y f,
begin
simp only [prod_comp_fst, prod_comp_snd, category.comp_id, category.assoc,
functor.map_id, functor.map_comp, nat_trans.id_app, nat_trans.comp_app],
slice_lhs 2 3 { rw nat_trans.naturality },
slice_lhs 1 2 { rw [←nat_trans.comp_app, nat_trans.naturality, nat_trans.comp_app] },
rw category.assoc,
end } }.
/--
The object level part of the currying functor. (See `curry` for the functorial version.)
-/
def curry_obj (F : (C × D) ⥤ E) : C ⥤ (D ⥤ E) :=
{ 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) } }
/--
The currying functor, taking a functor `(C × D) ⥤ E` and producing a functor `C ⥤ (D ⥤ E)`.
-/
def curry : ((C × D) ⥤ E) ⥤ (C ⥤ (D ⥤ E)) :=
{ obj := λ F, curry_obj F,
map := λ F G T,
{ app := λ X,
{ app := λ Y, T.app (X, Y),
naturality' := λ Y Y' g,
begin
dsimp [curry_obj],
rw nat_trans.naturality,
end },
naturality' := λ X X' f,
begin
ext, dsimp [curry_obj],
rw nat_trans.naturality,
end } }.
@[simp] lemma uncurry.obj_obj {F : C ⥤ (D ⥤ E)} {X : C × D} :
(uncurry.obj F).obj X = (F.obj X.1).obj X.2 := rfl
@[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 uncurry.map_app {F G : C ⥤ (D ⥤ E)} {α : F ⟶ G} {X : C × D} :
(uncurry.map α).app X = (α.app X.1).app X.2 := rfl
@[simp] lemma curry.obj_obj_obj
{F : (C × D) ⥤ E} {X : C} {Y : D} :
((curry.obj F).obj X).obj Y = F.obj (X, Y) := 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
@[simp] lemma curry.map_app_app {F G : (C × D) ⥤ E} {α : F ⟶ G} {X} {Y} :
((curry.map α).app X).app Y = α.app (X, Y) := rfl
/--
The equivalence of functor categories given by currying/uncurrying.
-/
@[simps] -- create projection simp lemmas even though this isn't a `{ .. }`.
def currying : (C ⥤ (D ⥤ E)) ≌ ((C × D) ⥤ E) :=
equivalence.mk uncurry curry
(nat_iso.of_components (λ F, nat_iso.of_components
(λ X, nat_iso.of_components (λ Y, iso.refl _) (by tidy)) (by tidy)) (by tidy))
(nat_iso.of_components (λ F, nat_iso.of_components
(λ X, eq_to_iso (by simp)) (by tidy)) (by tidy))
/-- `F.flip` is isomorphic to uncurrying `F`, swapping the variables, and currying. -/
@[simps]
def flip_iso_curry_swap_uncurry (F : C ⥤ D ⥤ E) :
F.flip ≅ curry.obj (prod.swap _ _ ⋙ uncurry.obj F) :=
nat_iso.of_components (λ d, nat_iso.of_components (λ c, iso.refl _) (by tidy)) (by tidy)
/-- The uncurrying of `F.flip` is isomorphic to
swapping the factors followed by the uncurrying of `F`. -/
@[simps]
def uncurry_obj_flip (F : C ⥤ D ⥤ E) : uncurry.obj F.flip ≅ prod.swap _ _ ⋙ uncurry.obj F :=
nat_iso.of_components (λ p, iso.refl _) (by tidy)
end category_theory
|
cf3adb2ea78a4137995a25269ef10dadf00c706b | 766b82465c89f7c306a9c07004605f5d564fd7f7 | /src/game/basic/level01.lean | 88a94310818d06e3ebb513954b0ad81114d2329d | [
"Apache-2.0"
] | permissive | stanescuUW/integer-number-game | ca4293a46c51db178f3bdb248118075caf87f582 | fced68b04a59ef0f4ea41b5beb2df87e0428c761 | refs/heads/master | 1,669,860,820,240 | 1,597,966,427,000 | 1,597,966,427,000 | 289,131,361 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,325 | lean | import data.nat.prime
import data.rat.basic
import data.real.basic
import tactic
namespace uwyo -- hide
/-
# Chapter 1 : Basic facts
## Level 1
In this level you need to prove that `sqrt 2` is irrational.
This is adapted from a similar proof from chapter 2 of "logic and Proof"
by J. Avigad, R. Y. Lewis and F. van Doorn, freely available online.
-/
/- Lemma
For any two arbitrary natural numbers $a$ and $b$, it is not true that
$$ a^2 = 2 b^2.$$
-/
theorem sqrt_two_irrational {a b : ℕ} (co : nat.gcd a b = 1) : a^2 ≠ 2 * b^2 :=
begin
intro h,
have h1 : 2 ∣ a^2, simp [h],
have h2 : 2 ∣ a, from nat.prime.dvd_of_dvd_pow nat.prime_two h1,
cases h2 with c aeq,
have h3 : 2 * ( 2 * c^2) = 2 * b^2,
by simp [eq.symm h, aeq];
simp [nat.pow_succ, mul_comm, mul_assoc, mul_left_comm],
have h4 : 2 * c^2 = b^2,
from nat.eq_of_mul_eq_mul_left dec_trivial h3,
have h5 : 2 ∣ b^2, by simp [eq.symm h4],
have hb : 2 ∣ b, from nat.prime.dvd_of_dvd_pow nat.prime_two h5,
have ha : 2 ∣ a, from nat.prime.dvd_of_dvd_pow nat.prime_two h1,
have h6 : 2 ∣ nat.gcd a b, from nat.dvd_gcd ha hb,
have habs : 2 ∣ (1 : ℕ), by
{rw co at h6, exact h6},
have h7 : ¬ 2 ∣ 1, exact dec_trivial,
exact h7 habs, done
end
end uwyo -- hide
|
b97d92c4df6d5d8429665c900a8ecb133b03b791 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /stage0/src/Lean/PrettyPrinter.lean | 808532b07a9231589f87749bd5bdbf57fa6e0f53 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | EdAyers/lean4 | 57ac632d6b0789cb91fab2170e8c9e40441221bd | 37ba0df5841bde51dbc2329da81ac23d4f6a4de4 | refs/heads/master | 1,676,463,245,298 | 1,660,619,433,000 | 1,660,619,433,000 | 183,433,437 | 1 | 0 | Apache-2.0 | 1,657,612,672,000 | 1,556,196,574,000 | Lean | UTF-8 | Lean | false | false | 4,305 | lean | /-
Copyright (c) 2020 Sebastian Ullrich. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
-/
import Lean.PrettyPrinter.Delaborator
import Lean.PrettyPrinter.Parenthesizer
import Lean.PrettyPrinter.Formatter
import Lean.Parser.Module
import Lean.ParserCompiler
namespace Lean
def PPContext.runCoreM {α : Type} (ppCtx : PPContext) (x : CoreM α) : IO α :=
Prod.fst <$> x.toIO { options := ppCtx.opts, currNamespace := ppCtx.currNamespace, openDecls := ppCtx.openDecls, fileName := "<PrettyPrinter>", fileMap := default }
{ env := ppCtx.env, ngen := { namePrefix := `_pp_uniq } }
def PPContext.runMetaM {α : Type} (ppCtx : PPContext) (x : MetaM α) : IO α :=
ppCtx.runCoreM <| x.run' { lctx := ppCtx.lctx } { mctx := ppCtx.mctx }
namespace PrettyPrinter
def ppCategory (cat : Name) (stx : Syntax) : CoreM Format := do
let opts ← getOptions
let stx := (sanitizeSyntax stx).run' { options := opts }
parenthesizeCategory cat stx >>= formatCategory cat
def ppTerm (stx : Term) : CoreM Format := ppCategory `term stx
def ppUsing (e : Expr) (delab : Expr → MetaM Term) : MetaM Format := do
let lctx := (← getLCtx).sanitizeNames.run' { options := (← getOptions) }
Meta.withLCtx lctx #[] do
ppTerm (← delab e)
def ppExpr (e : Expr) : MetaM Format := do
ppUsing e delab
/-- Return a `fmt` representing pretty-printed `e` together with a map from tags in `fmt`
to `Elab.Info` nodes produced by the delaborator at various subexpressions of `e`. -/
def ppExprWithInfos (e : Expr) (optsPerPos : Delaborator.OptionsPerPos := {})
: MetaM (Format × Std.RBMap Nat Elab.Info compare) := do
let lctx := (← getLCtx).sanitizeNames.run' { options := (← getOptions) }
Meta.withLCtx lctx #[] do
let (stx, infos) ← delabCore e optsPerPos
let fmt ← ppTerm stx
return (fmt, infos)
def ppConst (e : Expr) : MetaM Format := do
ppUsing e fun e => return (← delabCore e (delab := Delaborator.delabConst)).1
@[export lean_pp_expr]
def ppExprLegacy (env : Environment) (mctx : MetavarContext) (lctx : LocalContext) (opts : Options) (e : Expr) : IO Format :=
Prod.fst <$> ((ppExpr e).run' { lctx := lctx } { mctx := mctx }).toIO { options := opts, fileName := "<PrettyPrinter>", fileMap := default } { env := env }
def ppTactic (stx : TSyntax `tactic) : CoreM Format := ppCategory `tactic stx
def ppCommand (stx : Syntax.Command) : CoreM Format := ppCategory `command stx
def ppModule (stx : TSyntax ``Parser.Module.module) : CoreM Format := do
parenthesize Lean.Parser.Module.module.parenthesizer stx >>= format Lean.Parser.Module.module.formatter
private partial def noContext : MessageData → MessageData
| MessageData.withContext _ msg => noContext msg
| MessageData.withNamingContext ctx msg => MessageData.withNamingContext ctx (noContext msg)
| MessageData.nest n msg => MessageData.nest n (noContext msg)
| MessageData.group msg => MessageData.group (noContext msg)
| MessageData.compose msg₁ msg₂ => MessageData.compose (noContext msg₁) (noContext msg₂)
| MessageData.tagged tag msg => MessageData.tagged tag (noContext msg)
| MessageData.node msgs => MessageData.node (msgs.map noContext)
| msg => msg
-- strip context (including environments with registered pretty printers) to prevent infinite recursion when pretty printing pretty printer error
private def withoutContext {m} [MonadExcept Exception m] (x : m Format) : m Format :=
tryCatch x fun
| Exception.error ref msg => throw <| Exception.error ref (noContext msg)
| ex => throw ex
builtin_initialize
ppFnsRef.set {
ppExpr := fun ctx e => ctx.runMetaM <| withoutContext <| ppExpr e,
ppTerm := fun ctx stx => ctx.runCoreM <| withoutContext <| ppTerm stx,
ppGoal := fun ctx mvarId => ctx.runMetaM <| withoutContext <| Meta.ppGoal mvarId
}
builtin_initialize
registerTraceClass `PrettyPrinter
@[builtinInit]
unsafe def registerParserCompilers : IO Unit := do
ParserCompiler.registerParserCompiler ⟨`parenthesizer, parenthesizerAttribute, combinatorParenthesizerAttribute⟩
ParserCompiler.registerParserCompiler ⟨`formatter, formatterAttribute, combinatorFormatterAttribute⟩
end PrettyPrinter
end Lean
|
42086fc50333e38c6cd5bf04121964a4a2ecd312 | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/algebra/group_with_zero/basic.lean | 2809bff2df364adf82a19123ce4797d8a1b3094a | [
"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 | 42,017 | 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 logic.nontrivial
import algebra.group.units_hom
import algebra.group.inj_surj
import algebra.group_with_zero.defs
/-!
# Groups with an adjoined zero element
This file describes structures that are not usually studied on their own right in mathematics,
namely a special sort of monoid: apart from a distinguished “zero element” they form a group,
or in other words, they are groups with an adjoined zero element.
Examples are:
* division rings;
* the value monoid of a multiplicative valuation;
* in particular, the non-negative real numbers.
## Main definitions
Various lemmas about `group_with_zero` and `comm_group_with_zero`.
To reduce import dependencies, the type-classes themselves are in
`algebra.group_with_zero.defs`.
## Implementation details
As is usual in mathlib, we extend the inverse function to the zero element,
and require `0⁻¹ = 0`.
-/
set_option old_structure_cmd true
open_locale classical
open function
variables {M₀ G₀ M₀' G₀' : Type*}
mk_simp_attribute field_simps "The simpset `field_simps` is used by the tactic `field_simp` to
reduce an expression in a field to an expression of the form `n / d` where `n` and `d` are
division-free."
attribute [field_simps] mul_div_assoc'
section
section mul_zero_class
variables [mul_zero_class M₀] {a b : M₀}
/-- Pullback a `mul_zero_class` instance along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.mul_zero_class [has_mul M₀'] [has_zero M₀'] (f : M₀' → M₀)
(hf : injective f) (zero : f 0 = 0) (mul : ∀ a b, f (a * b) = f a * f b) :
mul_zero_class M₀' :=
{ mul := (*),
zero := 0,
zero_mul := λ a, hf $ by simp only [mul, zero, zero_mul],
mul_zero := λ a, hf $ by simp only [mul, zero, mul_zero] }
/-- Pushforward a `mul_zero_class` instance along an surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.mul_zero_class [has_mul M₀'] [has_zero M₀'] (f : M₀ → M₀')
(hf : surjective f) (zero : f 0 = 0) (mul : ∀ a b, f (a * b) = f a * f b) :
mul_zero_class M₀' :=
{ mul := (*),
zero := 0,
mul_zero := hf.forall.2 $ λ x, by simp only [← zero, ← mul, mul_zero],
zero_mul := hf.forall.2 $ λ x, by simp only [← zero, ← mul, zero_mul] }
lemma mul_eq_zero_of_left (h : a = 0) (b : M₀) : a * b = 0 := h.symm ▸ zero_mul b
lemma mul_eq_zero_of_right (a : M₀) (h : b = 0) : a * b = 0 := h.symm ▸ mul_zero a
lemma left_ne_zero_of_mul : a * b ≠ 0 → a ≠ 0 := mt (λ h, mul_eq_zero_of_left h b)
lemma right_ne_zero_of_mul : a * b ≠ 0 → b ≠ 0 := mt (mul_eq_zero_of_right a)
lemma ne_zero_and_ne_zero_of_mul (h : a * b ≠ 0) : a ≠ 0 ∧ b ≠ 0 :=
⟨left_ne_zero_of_mul h, right_ne_zero_of_mul h⟩
lemma mul_eq_zero_of_ne_zero_imp_eq_zero {a b : M₀} (h : a ≠ 0 → b = 0) :
a * b = 0 :=
if ha : a = 0 then by rw [ha, zero_mul] else by rw [h ha, mul_zero]
end mul_zero_class
/-- Pushforward a `no_zero_divisors` instance along an injective function. -/
protected lemma function.injective.no_zero_divisors [has_mul M₀] [has_zero M₀]
[has_mul M₀'] [has_zero M₀'] [no_zero_divisors M₀']
(f : M₀ → M₀') (hf : injective f) (zero : f 0 = 0) (mul : ∀ x y, f (x * y) = f x * f y) :
no_zero_divisors M₀ :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ x y H,
have f x * f y = 0, by rw [← mul, H, zero],
(eq_zero_or_eq_zero_of_mul_eq_zero this).imp (λ H, hf $ by rwa zero) (λ H, hf $ by rwa zero) }
lemma eq_zero_of_mul_self_eq_zero [has_mul M₀] [has_zero M₀] [no_zero_divisors M₀]
{a : M₀} (h : a * a = 0) :
a = 0 :=
(eq_zero_or_eq_zero_of_mul_eq_zero h).elim id id
section
variables [mul_zero_class M₀] [no_zero_divisors M₀] {a b : M₀}
/-- If `α` has no zero divisors, then the product of two elements equals zero iff one of them
equals zero. -/
@[simp] theorem mul_eq_zero : a * b = 0 ↔ a = 0 ∨ b = 0 :=
⟨eq_zero_or_eq_zero_of_mul_eq_zero,
λo, o.elim (λ h, mul_eq_zero_of_left h b) (mul_eq_zero_of_right a)⟩
/-- If `α` has no zero divisors, then the product of two elements equals zero iff one of them
equals zero. -/
@[simp] theorem zero_eq_mul : 0 = a * b ↔ a = 0 ∨ b = 0 :=
by rw [eq_comm, mul_eq_zero]
/-- If `α` has no zero divisors, then the product of two elements is nonzero iff both of them
are nonzero. -/
theorem mul_ne_zero_iff : a * b ≠ 0 ↔ a ≠ 0 ∧ b ≠ 0 :=
(not_congr mul_eq_zero).trans not_or_distrib
@[field_simps] theorem mul_ne_zero (ha : a ≠ 0) (hb : b ≠ 0) : a * b ≠ 0 :=
mul_ne_zero_iff.2 ⟨ha, hb⟩
/-- If `α` has no zero divisors, then for elements `a, b : α`, `a * b` equals zero iff so is
`b * a`. -/
theorem mul_eq_zero_comm : a * b = 0 ↔ b * a = 0 :=
mul_eq_zero.trans $ (or_comm _ _).trans mul_eq_zero.symm
/-- If `α` has no zero divisors, then for elements `a, b : α`, `a * b` is nonzero iff so is
`b * a`. -/
theorem mul_ne_zero_comm : a * b ≠ 0 ↔ b * a ≠ 0 :=
not_congr mul_eq_zero_comm
lemma mul_self_eq_zero : a * a = 0 ↔ a = 0 := by simp
lemma zero_eq_mul_self : 0 = a * a ↔ a = 0 := by simp
end
end
section
variables [mul_zero_one_class M₀]
/-- Pullback a `mul_zero_one_class` instance along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.mul_zero_one_class [has_mul M₀'] [has_zero M₀'] [has_one M₀']
(f : M₀' → M₀)
(hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ a b, f (a * b) = f a * f b) :
mul_zero_one_class M₀' :=
{ ..hf.mul_zero_class f zero mul, ..hf.mul_one_class f one mul }
/-- Pushforward a `mul_zero_one_class` instance along an surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.mul_zero_one_class [has_mul M₀'] [has_zero M₀'] [has_one M₀']
(f : M₀ → M₀')
(hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ a b, f (a * b) = f a * f b) :
mul_zero_one_class M₀' :=
{ ..hf.mul_zero_class f zero mul, ..hf.mul_one_class f one mul }
/-- In a monoid with zero, if zero equals one, then zero is the only element. -/
lemma eq_zero_of_zero_eq_one (h : (0 : M₀) = 1) (a : M₀) : a = 0 :=
by rw [← mul_one a, ← h, mul_zero]
/-- In a monoid with zero, if zero equals one, then zero is the unique element.
Somewhat arbitrarily, we define the default element to be `0`.
All other elements will be provably equal to it, but not necessarily definitionally equal. -/
def unique_of_zero_eq_one (h : (0 : M₀) = 1) : unique M₀ :=
{ default := 0, uniq := eq_zero_of_zero_eq_one h }
/-- In a monoid with zero, zero equals one if and only if all elements of that semiring
are equal. -/
theorem subsingleton_iff_zero_eq_one : (0 : M₀) = 1 ↔ subsingleton M₀ :=
⟨λ h, @unique.subsingleton _ (unique_of_zero_eq_one h), λ h, @subsingleton.elim _ h _ _⟩
alias subsingleton_iff_zero_eq_one ↔ subsingleton_of_zero_eq_one _
lemma eq_of_zero_eq_one (h : (0 : M₀) = 1) (a b : M₀) : a = b :=
@subsingleton.elim _ (subsingleton_of_zero_eq_one h) a b
/-- In a monoid with zero, either zero and one are nonequal, or zero is the only element. -/
lemma zero_ne_one_or_forall_eq_0 : (0 : M₀) ≠ 1 ∨ (∀a:M₀, a = 0) :=
not_or_of_imp eq_zero_of_zero_eq_one
end
section
variables [mul_zero_one_class M₀] [nontrivial M₀] {a b : M₀}
/-- In a nontrivial monoid with zero, zero and one are different. -/
@[simp] lemma zero_ne_one : 0 ≠ (1:M₀) :=
begin
assume h,
rcases exists_pair_ne M₀ with ⟨x, y, hx⟩,
apply hx,
calc x = 1 * x : by rw [one_mul]
... = 0 : by rw [← h, zero_mul]
... = 1 * y : by rw [← h, zero_mul]
... = y : by rw [one_mul]
end
@[simp] lemma one_ne_zero : (1:M₀) ≠ 0 :=
zero_ne_one.symm
lemma ne_zero_of_eq_one {a : M₀} (h : a = 1) : a ≠ 0 :=
calc a = 1 : h
... ≠ 0 : one_ne_zero
lemma left_ne_zero_of_mul_eq_one (h : a * b = 1) : a ≠ 0 :=
left_ne_zero_of_mul $ ne_zero_of_eq_one h
lemma right_ne_zero_of_mul_eq_one (h : a * b = 1) : b ≠ 0 :=
right_ne_zero_of_mul $ ne_zero_of_eq_one h
/-- Pullback a `nontrivial` instance along a function sending `0` to `0` and `1` to `1`. -/
protected lemma pullback_nonzero [has_zero M₀'] [has_one M₀']
(f : M₀' → M₀) (zero : f 0 = 0) (one : f 1 = 1) : nontrivial M₀' :=
⟨⟨0, 1, mt (congr_arg f) $ by { rw [zero, one], exact zero_ne_one }⟩⟩
end
section semigroup_with_zero
/-- Pullback a `semigroup_with_zero` class along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.semigroup_with_zero
[has_zero M₀'] [has_mul M₀'] [semigroup_with_zero M₀] (f : M₀' → M₀) (hf : injective f)
(zero : f 0 = 0) (mul : ∀ x y, f (x * y) = f x * f y) :
semigroup_with_zero M₀' :=
{ .. hf.mul_zero_class f zero mul,
.. ‹has_zero M₀'›,
.. hf.semigroup f mul }
/-- Pushforward a `semigroup_with_zero` class along an surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.semigroup_with_zero
[semigroup_with_zero M₀] [has_zero M₀'] [has_mul M₀'] (f : M₀ → M₀') (hf : surjective f)
(zero : f 0 = 0) (mul : ∀ x y, f (x * y) = f x * f y) :
semigroup_with_zero M₀' :=
{ .. hf.mul_zero_class f zero mul,
.. ‹has_zero M₀'›,
.. hf.semigroup f mul }
end semigroup_with_zero
section monoid_with_zero
/-- Pullback a `monoid_with_zero` class along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀']
[monoid_with_zero M₀]
(f : M₀' → M₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) :
monoid_with_zero M₀' :=
{ .. hf.monoid f one mul, .. hf.mul_zero_class f zero mul }
/-- Pushforward a `monoid_with_zero` class along a surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀']
[monoid_with_zero M₀]
(f : M₀ → M₀') (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) :
monoid_with_zero M₀' :=
{ .. hf.monoid f one mul, .. hf.mul_zero_class f zero mul }
/-- Pullback a `monoid_with_zero` class along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.comm_monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀']
[comm_monoid_with_zero M₀]
(f : M₀' → M₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) :
comm_monoid_with_zero M₀' :=
{ .. hf.comm_monoid f one mul, .. hf.mul_zero_class f zero mul }
/-- Pushforward a `monoid_with_zero` class along a surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.comm_monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀']
[comm_monoid_with_zero M₀]
(f : M₀ → M₀') (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) :
comm_monoid_with_zero M₀' :=
{ .. hf.comm_monoid f one mul, .. hf.mul_zero_class f zero mul }
variables [monoid_with_zero M₀]
namespace units
/-- An element of the unit group of a nonzero monoid with zero represented as an element
of the monoid is nonzero. -/
@[simp] lemma ne_zero [nontrivial M₀] (u : units M₀) :
(u : M₀) ≠ 0 :=
left_ne_zero_of_mul_eq_one u.mul_inv
-- We can't use `mul_eq_zero` + `units.ne_zero` in the next two lemmas because we don't assume
-- `nonzero M₀`.
@[simp] lemma mul_left_eq_zero (u : units M₀) {a : M₀} : a * u = 0 ↔ a = 0 :=
⟨λ h, by simpa using mul_eq_zero_of_left h ↑u⁻¹, λ h, mul_eq_zero_of_left h u⟩
@[simp] lemma mul_right_eq_zero (u : units M₀) {a : M₀} : ↑u * a = 0 ↔ a = 0 :=
⟨λ h, by simpa using mul_eq_zero_of_right ↑u⁻¹ h, mul_eq_zero_of_right u⟩
end units
namespace is_unit
lemma ne_zero [nontrivial M₀] {a : M₀} (ha : is_unit a) : a ≠ 0 := let ⟨u, hu⟩ :=
ha in hu ▸ u.ne_zero
lemma mul_right_eq_zero {a b : M₀} (ha : is_unit a) : a * b = 0 ↔ b = 0 :=
let ⟨u, hu⟩ := ha in hu ▸ u.mul_right_eq_zero
lemma mul_left_eq_zero {a b : M₀} (hb : is_unit b) : a * b = 0 ↔ a = 0 :=
let ⟨u, hu⟩ := hb in hu ▸ u.mul_left_eq_zero
end is_unit
@[simp] theorem is_unit_zero_iff : is_unit (0 : M₀) ↔ (0:M₀) = 1 :=
⟨λ ⟨⟨_, a, (a0 : 0 * a = 1), _⟩, rfl⟩, by rwa zero_mul at a0,
λ h, @is_unit_of_subsingleton _ _ (subsingleton_of_zero_eq_one h) 0⟩
@[simp] theorem not_is_unit_zero [nontrivial M₀] : ¬ is_unit (0 : M₀) :=
mt is_unit_zero_iff.1 zero_ne_one
variable (M₀)
end monoid_with_zero
section cancel_monoid_with_zero
variables [cancel_monoid_with_zero M₀] {a b c : M₀}
@[priority 10] -- see Note [lower instance priority]
instance cancel_monoid_with_zero.to_no_zero_divisors : no_zero_divisors M₀ :=
⟨λ a b ab0, by { by_cases a = 0, { left, exact h }, right,
apply cancel_monoid_with_zero.mul_left_cancel_of_ne_zero h, rw [ab0, mul_zero], }⟩
lemma mul_left_inj' (hc : c ≠ 0) : a * c = b * c ↔ a = b := ⟨mul_right_cancel₀ hc, λ h, h ▸ rfl⟩
lemma mul_right_inj' (ha : a ≠ 0) : a * b = a * c ↔ b = c := ⟨mul_left_cancel₀ ha, λ h, h ▸ rfl⟩
@[simp] lemma mul_eq_mul_right_iff : a * c = b * c ↔ a = b ∨ c = 0 :=
by by_cases hc : c = 0; [simp [hc], simp [mul_left_inj', hc]]
@[simp] lemma mul_eq_mul_left_iff : a * b = a * c ↔ b = c ∨ a = 0 :=
by by_cases ha : a = 0; [simp [ha], simp [mul_right_inj', ha]]
/-- Pullback a `monoid_with_zero` class along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.cancel_monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀']
(f : M₀' → M₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) :
cancel_monoid_with_zero M₀' :=
{ mul_left_cancel_of_ne_zero := λ x y z hx H, hf $ mul_left_cancel₀ ((hf.ne_iff' zero).2 hx) $
by erw [← mul, ← mul, H]; refl,
mul_right_cancel_of_ne_zero := λ x y z hx H, hf $ mul_right_cancel₀ ((hf.ne_iff' zero).2 hx) $
by erw [← mul, ← mul, H]; refl,
.. hf.monoid f one mul, .. hf.mul_zero_class f zero mul }
/-- An element of a `cancel_monoid_with_zero` fixed by right multiplication by an element other
than one must be zero. -/
theorem eq_zero_of_mul_eq_self_right (h₁ : b ≠ 1) (h₂ : a * b = a) : a = 0 :=
classical.by_contradiction $ λ ha, h₁ $ mul_left_cancel₀ ha $ h₂.symm ▸ (mul_one a).symm
/-- An element of a `cancel_monoid_with_zero` fixed by left multiplication by an element other
than one must be zero. -/
theorem eq_zero_of_mul_eq_self_left (h₁ : b ≠ 1) (h₂ : b * a = a) : a = 0 :=
classical.by_contradiction $ λ ha, h₁ $ mul_right_cancel₀ ha $ h₂.symm ▸ (one_mul a).symm
end cancel_monoid_with_zero
section comm_cancel_monoid_with_zero
variables [comm_cancel_monoid_with_zero M₀] {a b c : M₀}
/-- Pullback a `comm_cancel_monoid_with_zero` class along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.comm_cancel_monoid_with_zero
[has_zero M₀'] [has_mul M₀'] [has_one M₀']
(f : M₀' → M₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) :
comm_cancel_monoid_with_zero M₀' :=
{ .. hf.comm_monoid_with_zero f zero one mul,
.. hf.cancel_monoid_with_zero f zero one mul }
end comm_cancel_monoid_with_zero
section group_with_zero
variables [group_with_zero G₀] {a b c g h x : G₀}
alias div_eq_mul_inv ← division_def
/-- Pullback a `group_with_zero` class along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.group_with_zero [has_zero G₀'] [has_mul G₀'] [has_one G₀']
[has_inv G₀'] [has_div G₀'] (f : G₀' → G₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹)
(div : ∀ x y, f (x / y) = f x / f y) :
group_with_zero G₀' :=
{ inv_zero := hf $ by erw [inv, zero, inv_zero],
mul_inv_cancel := λ x hx, hf $ by erw [one, mul, inv, mul_inv_cancel ((hf.ne_iff' zero).2 hx)],
.. hf.monoid_with_zero f zero one mul,
.. hf.div_inv_monoid f one mul inv div,
.. pullback_nonzero f zero one, }
/-- Pushforward a `group_with_zero` class along an surjective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.surjective.group_with_zero [has_zero G₀'] [has_mul G₀'] [has_one G₀']
[has_inv G₀'] [has_div G₀'] (h01 : (0:G₀') ≠ 1) (f : G₀ → G₀') (hf : surjective f)
(zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y)
(inv : ∀ x, f x⁻¹ = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) :
group_with_zero G₀' :=
{ inv_zero := by erw [← zero, ← inv, inv_zero],
mul_inv_cancel := hf.forall.2 $ λ x hx,
by erw [← inv, ← mul, mul_inv_cancel (mt (congr_arg f) $ trans_rel_left ne hx zero.symm)];
exact one,
exists_pair_ne := ⟨0, 1, h01⟩,
.. hf.monoid_with_zero f zero one mul,
.. hf.div_inv_monoid f one mul inv div }
@[simp] lemma mul_inv_cancel_right₀ (h : b ≠ 0) (a : G₀) :
(a * b) * b⁻¹ = a :=
calc (a * b) * b⁻¹ = a * (b * b⁻¹) : mul_assoc _ _ _
... = a : by simp [h]
@[simp] lemma mul_inv_cancel_left₀ (h : a ≠ 0) (b : G₀) :
a * (a⁻¹ * b) = b :=
calc a * (a⁻¹ * b) = (a * a⁻¹) * b : (mul_assoc _ _ _).symm
... = b : by simp [h]
lemma inv_ne_zero (h : a ≠ 0) : a⁻¹ ≠ 0 :=
assume a_eq_0, by simpa [a_eq_0] using mul_inv_cancel h
@[simp] lemma inv_mul_cancel (h : a ≠ 0) : a⁻¹ * a = 1 :=
calc a⁻¹ * a = (a⁻¹ * a) * a⁻¹ * a⁻¹⁻¹ : by simp [inv_ne_zero h]
... = a⁻¹ * a⁻¹⁻¹ : by simp [h]
... = 1 : by simp [inv_ne_zero h]
lemma group_with_zero.mul_left_injective (h : x ≠ 0) :
function.injective (λ y, x * y) :=
λ y y' w, by simpa only [←mul_assoc, inv_mul_cancel h, one_mul] using congr_arg (λ y, x⁻¹ * y) w
lemma group_with_zero.mul_right_injective (h : x ≠ 0) :
function.injective (λ y, y * x) :=
λ y y' w, by simpa only [mul_assoc, mul_inv_cancel h, mul_one] using congr_arg (λ y, y * x⁻¹) w
@[simp] lemma inv_mul_cancel_right₀ (h : b ≠ 0) (a : G₀) :
(a * b⁻¹) * b = a :=
calc (a * b⁻¹) * b = a * (b⁻¹ * b) : mul_assoc _ _ _
... = a : by simp [h]
@[simp] lemma inv_mul_cancel_left₀ (h : a ≠ 0) (b : G₀) :
a⁻¹ * (a * b) = b :=
calc a⁻¹ * (a * b) = (a⁻¹ * a) * b : (mul_assoc _ _ _).symm
... = b : by simp [h]
@[simp] lemma inv_one : 1⁻¹ = (1:G₀) :=
calc 1⁻¹ = 1 * 1⁻¹ : by rw [one_mul]
... = (1:G₀) : by simp
@[simp] lemma inv_inv₀ (a : G₀) : a⁻¹⁻¹ = a :=
begin
by_cases h : a = 0, { simp [h] },
calc a⁻¹⁻¹ = a * (a⁻¹ * a⁻¹⁻¹) : by simp [h]
... = a : by simp [inv_ne_zero h]
end
/-- Multiplying `a` by itself and then by its inverse results in `a`
(whether or not `a` is zero). -/
@[simp] lemma mul_self_mul_inv (a : G₀) : a * a * a⁻¹ = a :=
begin
by_cases h : a = 0,
{ rw [h, inv_zero, mul_zero] },
{ rw [mul_assoc, mul_inv_cancel h, mul_one] }
end
/-- Multiplying `a` by its inverse and then by itself results in `a`
(whether or not `a` is zero). -/
@[simp] lemma mul_inv_mul_self (a : G₀) : a * a⁻¹ * a = a :=
begin
by_cases h : a = 0,
{ rw [h, inv_zero, mul_zero] },
{ rw [mul_inv_cancel h, one_mul] }
end
/-- Multiplying `a⁻¹` by `a` twice results in `a` (whether or not `a`
is zero). -/
@[simp] lemma inv_mul_mul_self (a : G₀) : a⁻¹ * a * a = a :=
begin
by_cases h : a = 0,
{ rw [h, inv_zero, mul_zero] },
{ rw [inv_mul_cancel h, one_mul] }
end
/-- Multiplying `a` by itself and then dividing by itself results in
`a` (whether or not `a` is zero). -/
@[simp] lemma mul_self_div_self (a : G₀) : a * a / a = a :=
by rw [div_eq_mul_inv, mul_self_mul_inv a]
/-- Dividing `a` by itself and then multiplying by itself results in
`a` (whether or not `a` is zero). -/
@[simp] lemma div_self_mul_self (a : G₀) : a / a * a = a :=
by rw [div_eq_mul_inv, mul_inv_mul_self a]
lemma inv_involutive₀ : function.involutive (has_inv.inv : G₀ → G₀) :=
inv_inv₀
lemma eq_inv_of_mul_right_eq_one (h : a * b = 1) :
b = a⁻¹ :=
by rw [← inv_mul_cancel_left₀ (left_ne_zero_of_mul_eq_one h) b, h, mul_one]
lemma eq_inv_of_mul_left_eq_one (h : a * b = 1) :
a = b⁻¹ :=
by rw [← mul_inv_cancel_right₀ (right_ne_zero_of_mul_eq_one h) a, h, one_mul]
lemma inv_injective₀ : function.injective (@has_inv.inv G₀ _) :=
inv_involutive₀.injective
@[simp] lemma inv_inj₀ : g⁻¹ = h⁻¹ ↔ g = h := inv_injective₀.eq_iff
/-- This is the analogue of `inv_eq_iff_inv_eq` for `group_with_zero`.
It could also be named `inv_eq_iff_inv_eq'`. -/
lemma inv_eq_iff : g⁻¹ = h ↔ h⁻¹ = g :=
by rw [← inv_inj₀, eq_comm, inv_inv₀]
/-- This is the analogue of `eq_inv_iff_eq_inv` for `group_with_zero`.
It could also be named `eq_inv_iff_eq_inv'`. -/
lemma eq_inv_iff : a = b⁻¹ ↔ b = a⁻¹ :=
by rw [eq_comm, inv_eq_iff, eq_comm]
@[simp] lemma inv_eq_one₀ : g⁻¹ = 1 ↔ g = 1 :=
by rw [inv_eq_iff, inv_one, eq_comm]
lemma eq_mul_inv_iff_mul_eq₀ (hc : c ≠ 0) : a = b * c⁻¹ ↔ a * c = b :=
by split; rintro rfl; [rw inv_mul_cancel_right₀ hc, rw mul_inv_cancel_right₀ hc]
lemma eq_inv_mul_iff_mul_eq₀ (hb : b ≠ 0) : a = b⁻¹ * c ↔ b * a = c :=
by split; rintro rfl; [rw mul_inv_cancel_left₀ hb, rw inv_mul_cancel_left₀ hb]
lemma inv_mul_eq_iff_eq_mul₀ (ha : a ≠ 0) : a⁻¹ * b = c ↔ b = a * c :=
by rw [eq_comm, eq_inv_mul_iff_mul_eq₀ ha, eq_comm]
lemma mul_inv_eq_iff_eq_mul₀ (hb : b ≠ 0) : a * b⁻¹ = c ↔ a = c * b :=
by rw [eq_comm, eq_mul_inv_iff_mul_eq₀ hb, eq_comm]
lemma mul_inv_eq_one₀ (hb : b ≠ 0) : a * b⁻¹ = 1 ↔ a = b :=
by rw [mul_inv_eq_iff_eq_mul₀ hb, one_mul]
lemma inv_mul_eq_one₀ (ha : a ≠ 0) : a⁻¹ * b = 1 ↔ a = b :=
by rw [inv_mul_eq_iff_eq_mul₀ ha, mul_one, eq_comm]
lemma mul_eq_one_iff_eq_inv₀ (hb : b ≠ 0) : a * b = 1 ↔ a = b⁻¹ :=
by { convert mul_inv_eq_one₀ (inv_ne_zero hb), rw [inv_inv₀] }
lemma mul_eq_one_iff_inv_eq₀ (ha : a ≠ 0) : a * b = 1 ↔ a⁻¹ = b :=
by { convert inv_mul_eq_one₀ (inv_ne_zero ha), rw [inv_inv₀] }
end group_with_zero
namespace units
variables [group_with_zero G₀]
variables {a b : G₀}
/-- Embed a non-zero element of a `group_with_zero` into the unit group.
By combining this function with the operations on units,
or the `/ₚ` operation, it is possible to write a division
as a partial function with three arguments. -/
def mk0 (a : G₀) (ha : a ≠ 0) : units G₀ :=
⟨a, a⁻¹, mul_inv_cancel ha, inv_mul_cancel ha⟩
@[simp] lemma mk0_one (h := one_ne_zero) :
mk0 (1 : G₀) h = 1 :=
by { ext, refl }
@[simp] lemma coe_mk0 {a : G₀} (h : a ≠ 0) : (mk0 a h : G₀) = a := rfl
@[simp] lemma mk0_coe (u : units G₀) (h : (u : G₀) ≠ 0) : mk0 (u : G₀) h = u :=
units.ext rfl
@[simp, norm_cast] lemma coe_inv' (u : units G₀) : ((u⁻¹ : units G₀) : G₀) = u⁻¹ :=
eq_inv_of_mul_left_eq_one u.inv_mul
@[simp] lemma mul_inv' (u : units G₀) : (u : G₀) * u⁻¹ = 1 := mul_inv_cancel u.ne_zero
@[simp] lemma inv_mul' (u : units G₀) : (u⁻¹ : G₀) * u = 1 := inv_mul_cancel u.ne_zero
@[simp] lemma mk0_inj {a b : G₀} (ha : a ≠ 0) (hb : b ≠ 0) :
units.mk0 a ha = units.mk0 b hb ↔ a = b :=
⟨λ h, by injection h, λ h, units.ext h⟩
@[simp] lemma exists_iff_ne_zero {x : G₀} : (∃ u : units G₀, ↑u = x) ↔ x ≠ 0 :=
⟨λ ⟨u, hu⟩, hu ▸ u.ne_zero, assume hx, ⟨mk0 x hx, rfl⟩⟩
lemma _root_.group_with_zero.eq_zero_or_unit (a : G₀) :
a = 0 ∨ ∃ u : units G₀, a = u :=
begin
by_cases h : a = 0,
{ left,
exact h },
{ right,
simpa only [eq_comm] using units.exists_iff_ne_zero.mpr h }
end
instance : can_lift G₀ (units G₀) :=
{ coe := coe,
cond := (≠ 0),
prf := λ x, exists_iff_ne_zero.mpr }
end units
section group_with_zero
variables [group_with_zero G₀]
lemma is_unit.mk0 (x : G₀) (hx : x ≠ 0) : is_unit x := (units.mk0 x hx).is_unit
lemma is_unit_iff_ne_zero {x : G₀} : is_unit x ↔ x ≠ 0 :=
units.exists_iff_ne_zero
@[priority 10] -- see Note [lower instance priority]
instance group_with_zero.no_zero_divisors : no_zero_divisors G₀ :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h,
begin
contrapose! h,
exact ((units.mk0 a h.1) * (units.mk0 b h.2)).ne_zero
end,
.. (‹_› : group_with_zero G₀) }
@[priority 10] -- see Note [lower instance priority]
instance group_with_zero.cancel_monoid_with_zero : cancel_monoid_with_zero G₀ :=
{ mul_left_cancel_of_ne_zero := λ x y z hx h,
by rw [← inv_mul_cancel_left₀ hx y, h, inv_mul_cancel_left₀ hx z],
mul_right_cancel_of_ne_zero := λ x y z hy h,
by rw [← mul_inv_cancel_right₀ hy x, h, mul_inv_cancel_right₀ hy z],
.. (‹_› : group_with_zero G₀) }
-- Can't be put next to the other `mk0` lemmas becuase it depends on the
-- `no_zero_divisors` instance, which depends on `mk0`.
@[simp] lemma units.mk0_mul (x y : G₀) (hxy) :
units.mk0 (x * y) hxy =
units.mk0 x (mul_ne_zero_iff.mp hxy).1 * units.mk0 y (mul_ne_zero_iff.mp hxy).2 :=
by { ext, refl }
lemma mul_inv_rev₀ (x y : G₀) : (x * y)⁻¹ = y⁻¹ * x⁻¹ :=
begin
by_cases hx : x = 0, { simp [hx] },
by_cases hy : y = 0, { simp [hy] },
symmetry,
apply eq_inv_of_mul_left_eq_one,
simp [mul_assoc, hx, hy]
end
@[simp] lemma div_self {a : G₀} (h : a ≠ 0) : a / a = 1 :=
by rw [div_eq_mul_inv, mul_inv_cancel h]
@[simp] lemma div_one (a : G₀) : a / 1 = a :=
by simp [div_eq_mul_inv a 1]
@[simp] lemma zero_div (a : G₀) : 0 / a = 0 :=
by rw [div_eq_mul_inv, zero_mul]
@[simp] lemma div_zero (a : G₀) : a / 0 = 0 :=
by rw [div_eq_mul_inv, inv_zero, mul_zero]
@[simp] lemma div_mul_cancel (a : G₀) {b : G₀} (h : b ≠ 0) : a / b * b = a :=
by rw [div_eq_mul_inv, inv_mul_cancel_right₀ h a]
lemma div_mul_cancel_of_imp {a b : G₀} (h : b = 0 → a = 0) : a / b * b = a :=
classical.by_cases (λ hb : b = 0, by simp [*]) (div_mul_cancel a)
@[simp] lemma mul_div_cancel (a : G₀) {b : G₀} (h : b ≠ 0) : a * b / b = a :=
by rw [div_eq_mul_inv, mul_inv_cancel_right₀ h a]
lemma mul_div_cancel_of_imp {a b : G₀} (h : b = 0 → a = 0) : a * b / b = a :=
classical.by_cases (λ hb : b = 0, by simp [*]) (mul_div_cancel a)
local attribute [simp] div_eq_mul_inv mul_comm mul_assoc mul_left_comm
@[simp] lemma div_self_mul_self' (a : G₀) : a / (a * a) = a⁻¹ :=
calc a / (a * a) = a⁻¹⁻¹ * a⁻¹ * a⁻¹ : by simp [mul_inv_rev₀]
... = a⁻¹ : inv_mul_mul_self _
lemma div_eq_mul_one_div (a b : G₀) : a / b = a * (1 / b) :=
by simp
lemma mul_one_div_cancel {a : G₀} (h : a ≠ 0) : a * (1 / a) = 1 :=
by simp [h]
lemma one_div_mul_cancel {a : G₀} (h : a ≠ 0) : (1 / a) * a = 1 :=
by simp [h]
lemma one_div_one : 1 / 1 = (1:G₀) :=
div_self (ne.symm zero_ne_one)
lemma one_div_ne_zero {a : G₀} (h : a ≠ 0) : 1 / a ≠ 0 :=
by simpa only [one_div] using inv_ne_zero h
lemma eq_one_div_of_mul_eq_one {a b : G₀} (h : a * b = 1) : b = 1 / a :=
by simpa only [one_div] using eq_inv_of_mul_right_eq_one h
lemma eq_one_div_of_mul_eq_one_left {a b : G₀} (h : b * a = 1) : b = 1 / a :=
by simpa only [one_div] using eq_inv_of_mul_left_eq_one h
@[simp] lemma one_div_div (a b : G₀) : 1 / (a / b) = b / a :=
by rw [one_div, div_eq_mul_inv, mul_inv_rev₀, inv_inv₀, div_eq_mul_inv]
lemma one_div_one_div (a : G₀) : 1 / (1 / a) = a :=
by simp
lemma eq_of_one_div_eq_one_div {a b : G₀} (h : 1 / a = 1 / b) : a = b :=
by rw [← one_div_one_div a, h, one_div_one_div]
variables {a b c : G₀}
@[simp] lemma inv_eq_zero {a : G₀} : a⁻¹ = 0 ↔ a = 0 :=
by rw [inv_eq_iff, inv_zero, eq_comm]
@[simp] lemma zero_eq_inv {a : G₀} : 0 = a⁻¹ ↔ 0 = a :=
eq_comm.trans $ inv_eq_zero.trans eq_comm
lemma one_div_mul_one_div_rev (a b : G₀) : (1 / a) * (1 / b) = 1 / (b * a) :=
by simp only [div_eq_mul_inv, one_mul, mul_inv_rev₀]
theorem divp_eq_div (a : G₀) (u : units G₀) : a /ₚ u = a / u :=
by simpa only [div_eq_mul_inv] using congr_arg ((*) a) u.coe_inv'
@[simp] theorem divp_mk0 (a : G₀) {b : G₀} (hb : b ≠ 0) :
a /ₚ units.mk0 b hb = a / b :=
divp_eq_div _ _
lemma inv_div : (a / b)⁻¹ = b / a :=
by rw [div_eq_mul_inv, mul_inv_rev₀, div_eq_mul_inv, inv_inv₀]
lemma inv_div_left : a⁻¹ / b = (b * a)⁻¹ :=
by rw [mul_inv_rev₀, div_eq_mul_inv]
lemma div_ne_zero (ha : a ≠ 0) (hb : b ≠ 0) : a / b ≠ 0 :=
by { rw div_eq_mul_inv, exact mul_ne_zero ha (inv_ne_zero hb) }
@[simp] lemma div_eq_zero_iff : a / b = 0 ↔ a = 0 ∨ b = 0:=
by simp [div_eq_mul_inv]
lemma div_ne_zero_iff : a / b ≠ 0 ↔ a ≠ 0 ∧ b ≠ 0 :=
(not_congr div_eq_zero_iff).trans not_or_distrib
lemma div_left_inj' (hc : c ≠ 0) : a / c = b / c ↔ a = b :=
by rw [← divp_mk0 _ hc, ← divp_mk0 _ hc, divp_left_inj]
lemma div_eq_iff_mul_eq (hb : b ≠ 0) : a / b = c ↔ c * b = a :=
⟨λ h, by rw [← h, div_mul_cancel _ hb],
λ h, by rw [← h, mul_div_cancel _ hb]⟩
lemma eq_div_iff_mul_eq (hc : c ≠ 0) : a = b / c ↔ a * c = b :=
by rw [eq_comm, div_eq_iff_mul_eq hc]
lemma div_eq_of_eq_mul {x : G₀} (hx : x ≠ 0) {y z : G₀} (h : y = z * x) : y / x = z :=
(div_eq_iff_mul_eq hx).2 h.symm
lemma eq_div_of_mul_eq {x : G₀} (hx : x ≠ 0) {y z : G₀} (h : z * x = y) : z = y / x :=
eq.symm $ div_eq_of_eq_mul hx h.symm
lemma eq_of_div_eq_one (h : a / b = 1) : a = b :=
begin
by_cases hb : b = 0,
{ rw [hb, div_zero] at h,
exact eq_of_zero_eq_one h a b },
{ rwa [div_eq_iff_mul_eq hb, one_mul, eq_comm] at h }
end
lemma div_eq_one_iff_eq (hb : b ≠ 0) : a / b = 1 ↔ a = b :=
⟨eq_of_div_eq_one, λ h, h.symm ▸ div_self hb⟩
lemma div_mul_left {a b : G₀} (hb : b ≠ 0) : b / (a * b) = 1 / a :=
by simp only [div_eq_mul_inv, mul_inv_rev₀, mul_inv_cancel_left₀ hb, one_mul]
lemma mul_div_mul_right (a b : G₀) {c : G₀} (hc : c ≠ 0) :
(a * c) / (b * c) = a / b :=
by simp only [div_eq_mul_inv, mul_inv_rev₀, mul_assoc, mul_inv_cancel_left₀ hc]
lemma mul_mul_div (a : G₀) {b : G₀} (hb : b ≠ 0) : a = a * b * (1 / b) :=
by simp [hb]
end group_with_zero
section comm_group_with_zero -- comm
variables [comm_group_with_zero G₀] {a b c : G₀}
@[priority 10] -- see Note [lower instance priority]
instance comm_group_with_zero.comm_cancel_monoid_with_zero : comm_cancel_monoid_with_zero G₀ :=
{ ..group_with_zero.cancel_monoid_with_zero, ..comm_group_with_zero.to_comm_monoid_with_zero G₀ }
/-- Pullback a `comm_group_with_zero` class along an injective function.
See note [reducible non-instances]. -/
@[reducible]
protected def function.injective.comm_group_with_zero [has_zero G₀'] [has_mul G₀'] [has_one G₀']
[has_inv G₀'] [has_div G₀'] (f : G₀' → G₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹)
(div : ∀ x y, f (x / y) = f x / f y) :
comm_group_with_zero G₀' :=
{ .. hf.group_with_zero f zero one mul inv div, .. hf.comm_semigroup f mul }
/-- Pushforward a `comm_group_with_zero` class along a surjective function. -/
protected def function.surjective.comm_group_with_zero [has_zero G₀'] [has_mul G₀']
[has_one G₀'] [has_inv G₀'] [has_div G₀'] (h01 : (0:G₀') ≠ 1) (f : G₀ → G₀') (hf : surjective f)
(zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹)
(div : ∀ x y, f (x / y) = f x / f y) :
comm_group_with_zero G₀' :=
{ .. hf.group_with_zero h01 f zero one mul inv div, .. hf.comm_semigroup f mul }
lemma mul_inv₀ : (a * b)⁻¹ = a⁻¹ * b⁻¹ :=
by rw [mul_inv_rev₀, mul_comm]
lemma one_div_mul_one_div (a b : G₀) : (1 / a) * (1 / b) = 1 / (a * b) :=
by rw [one_div_mul_one_div_rev, mul_comm b]
lemma div_mul_right {a : G₀} (b : G₀) (ha : a ≠ 0) : a / (a * b) = 1 / b :=
by rw [mul_comm, div_mul_left ha]
lemma mul_div_cancel_left_of_imp {a b : G₀} (h : a = 0 → b = 0) : a * b / a = b :=
by rw [mul_comm, mul_div_cancel_of_imp h]
lemma mul_div_cancel_left {a : G₀} (b : G₀) (ha : a ≠ 0) : a * b / a = b :=
mul_div_cancel_left_of_imp $ λ h, (ha h).elim
lemma mul_div_cancel_of_imp' {a b : G₀} (h : b = 0 → a = 0) : b * (a / b) = a :=
by rw [mul_comm, div_mul_cancel_of_imp h]
lemma mul_div_cancel' (a : G₀) {b : G₀} (hb : b ≠ 0) : b * (a / b) = a :=
by rw [mul_comm, (div_mul_cancel _ hb)]
local attribute [simp] mul_assoc mul_comm mul_left_comm
lemma div_mul_div (a b c d : G₀) :
(a / b) * (c / d) = (a * c) / (b * d) :=
by simp [div_eq_mul_inv, mul_inv₀]
lemma mul_div_mul_left (a b : G₀) {c : G₀} (hc : c ≠ 0) :
(c * a) / (c * b) = a / b :=
by rw [mul_comm c, mul_comm c, mul_div_mul_right _ _ hc]
@[field_simps] lemma div_mul_eq_mul_div (a b c : G₀) : (b / c) * a = (b * a) / c :=
by simp [div_eq_mul_inv]
lemma div_mul_eq_mul_div_comm (a b c : G₀) :
(b / c) * a = b * (a / c) :=
by rw [div_mul_eq_mul_div, ← one_mul c, ← div_mul_div, div_one, one_mul]
lemma mul_eq_mul_of_div_eq_div (a : G₀) {b : G₀} (c : G₀) {d : G₀} (hb : b ≠ 0)
(hd : d ≠ 0) (h : a / b = c / d) : a * d = c * b :=
by rw [← mul_one (a*d), mul_assoc, mul_comm d, ← mul_assoc, ← div_self hb,
← div_mul_eq_mul_div_comm, h, div_mul_eq_mul_div, div_mul_cancel _ hd]
@[field_simps] lemma div_div_eq_mul_div (a b c : G₀) :
a / (b / c) = (a * c) / b :=
by rw [div_eq_mul_one_div, one_div_div, ← mul_div_assoc]
@[field_simps] lemma div_div_eq_div_mul (a b c : G₀) :
(a / b) / c = a / (b * c) :=
by rw [div_eq_mul_one_div, div_mul_div, mul_one]
lemma div_div_div_div_eq (a : G₀) {b c d : G₀} :
(a / b) / (c / d) = (a * d) / (b * c) :=
by rw [div_div_eq_mul_div, div_mul_eq_mul_div, div_div_eq_div_mul]
lemma div_mul_eq_div_mul_one_div (a b c : G₀) :
a / (b * c) = (a / b) * (1 / c) :=
by rw [← div_div_eq_div_mul, ← div_eq_mul_one_div]
/-- Dividing `a` by the result of dividing `a` by itself results in
`a` (whether or not `a` is zero). -/
@[simp] lemma div_div_self (a : G₀) : a / (a / a) = a :=
begin
rw div_div_eq_mul_div,
exact mul_self_div_self a
end
lemma ne_zero_of_one_div_ne_zero {a : G₀} (h : 1 / a ≠ 0) : a ≠ 0 :=
assume ha : a = 0, begin rw [ha, div_zero] at h, contradiction end
lemma eq_zero_of_one_div_eq_zero {a : G₀} (h : 1 / a = 0) : a = 0 :=
classical.by_cases
(assume ha, ha)
(assume ha, ((one_div_ne_zero ha) h).elim)
lemma div_helper {a : G₀} (b : G₀) (h : a ≠ 0) : (1 / (a * b)) * a = 1 / b :=
by rw [div_mul_eq_mul_div, one_mul, div_mul_right _ h]
end comm_group_with_zero
section comm_group_with_zero
variables [comm_group_with_zero G₀] {a b c d : G₀}
lemma div_eq_inv_mul : a / b = b⁻¹ * a :=
by rw [div_eq_mul_inv, mul_comm]
lemma mul_div_right_comm (a b c : G₀) : (a * b) / c = (a / c) * b :=
by rw [div_eq_mul_inv, mul_assoc, mul_comm b, ← mul_assoc, div_eq_mul_inv]
lemma mul_comm_div' (a b c : G₀) : (a / b) * c = a * (c / b) :=
by rw [← mul_div_assoc, mul_div_right_comm]
lemma div_mul_comm' (a b c : G₀) : (a / b) * c = (c / b) * a :=
by rw [div_mul_eq_mul_div, mul_comm, mul_div_right_comm]
lemma mul_div_comm (a b c : G₀) : a * (b / c) = b * (a / c) :=
by rw [← mul_div_assoc, mul_comm, mul_div_assoc]
lemma div_right_comm (a : G₀) : (a / b) / c = (a / c) / b :=
by rw [div_div_eq_div_mul, div_div_eq_div_mul, mul_comm]
lemma div_div_div_cancel_right (a : G₀) (hc : c ≠ 0) : (a / c) / (b / c) = a / b :=
by rw [div_div_eq_mul_div, div_mul_cancel _ hc]
lemma div_mul_div_cancel (a : G₀) (hc : c ≠ 0) : (a / c) * (c / b) = a / b :=
by rw [← mul_div_assoc, div_mul_cancel _ hc]
@[field_simps] lemma div_eq_div_iff (hb : b ≠ 0) (hd : d ≠ 0) : a / b = c / d ↔ a * d = c * b :=
calc a / b = c / d ↔ a / b * (b * d) = c / d * (b * d) :
by rw [mul_left_inj' (mul_ne_zero hb hd)]
... ↔ a * d = c * b :
by rw [← mul_assoc, div_mul_cancel _ hb,
← mul_assoc, mul_right_comm, div_mul_cancel _ hd]
@[field_simps] lemma div_eq_iff (hb : b ≠ 0) : a / b = c ↔ a = c * b :=
(div_eq_iff_mul_eq hb).trans eq_comm
@[field_simps] lemma eq_div_iff (hb : b ≠ 0) : c = a / b ↔ c * b = a :=
eq_div_iff_mul_eq hb
lemma div_div_cancel' (ha : a ≠ 0) : a / (a / b) = b :=
by rw [div_eq_mul_inv, inv_div, mul_div_cancel' _ ha]
end comm_group_with_zero
namespace semiconj_by
@[simp] lemma zero_right [mul_zero_class G₀] (a : G₀) : semiconj_by a 0 0 :=
by simp only [semiconj_by, mul_zero, zero_mul]
@[simp] lemma zero_left [mul_zero_class G₀] (x y : G₀) : semiconj_by 0 x y :=
by simp only [semiconj_by, mul_zero, zero_mul]
variables [group_with_zero G₀] {a x y x' y' : G₀}
@[simp] lemma inv_symm_left_iff₀ : semiconj_by a⁻¹ x y ↔ semiconj_by a y x :=
classical.by_cases
(λ ha : a = 0, by simp only [ha, inv_zero, semiconj_by.zero_left])
(λ ha, @units_inv_symm_left_iff _ _ (units.mk0 a ha) _ _)
lemma inv_symm_left₀ (h : semiconj_by a x y) : semiconj_by a⁻¹ y x :=
semiconj_by.inv_symm_left_iff₀.2 h
lemma inv_right₀ (h : semiconj_by a x y) : semiconj_by a x⁻¹ y⁻¹ :=
begin
by_cases ha : a = 0,
{ simp only [ha, zero_left] },
by_cases hx : x = 0,
{ subst x,
simp only [semiconj_by, mul_zero, @eq_comm _ _ (y * a), mul_eq_zero] at h,
simp [h.resolve_right ha] },
{ have := mul_ne_zero ha hx,
rw [h.eq, mul_ne_zero_iff] at this,
exact @units_inv_right _ _ _ (units.mk0 x hx) (units.mk0 y this.1) h },
end
@[simp] lemma inv_right_iff₀ : semiconj_by a x⁻¹ y⁻¹ ↔ semiconj_by a x y :=
⟨λ h, inv_inv₀ x ▸ inv_inv₀ y ▸ h.inv_right₀, inv_right₀⟩
lemma div_right (h : semiconj_by a x y) (h' : semiconj_by a x' y') :
semiconj_by a (x / x') (y / y') :=
by { rw [div_eq_mul_inv, div_eq_mul_inv], exact h.mul_right h'.inv_right₀ }
end semiconj_by
namespace commute
@[simp] theorem zero_right [mul_zero_class G₀] (a : G₀) :commute a 0 := semiconj_by.zero_right a
@[simp] theorem zero_left [mul_zero_class G₀] (a : G₀) : commute 0 a := semiconj_by.zero_left a a
variables [group_with_zero G₀] {a b c : G₀}
@[simp] theorem inv_left_iff₀ : commute a⁻¹ b ↔ commute a b :=
semiconj_by.inv_symm_left_iff₀
theorem inv_left₀ (h : commute a b) : commute a⁻¹ b := inv_left_iff₀.2 h
@[simp] theorem inv_right_iff₀ : commute a b⁻¹ ↔ commute a b :=
semiconj_by.inv_right_iff₀
theorem inv_right₀ (h : commute a b) : commute a b⁻¹ := inv_right_iff₀.2 h
theorem inv_inv₀ (h : commute a b) : commute a⁻¹ b⁻¹ := h.inv_left₀.inv_right₀
@[simp] theorem div_right (hab : commute a b) (hac : commute a c) :
commute a (b / c) :=
hab.div_right hac
@[simp] theorem div_left (hac : commute a c) (hbc : commute b c) :
commute (a / b) c :=
by { rw div_eq_mul_inv, exact hac.mul_left hbc.inv_left₀ }
end commute
namespace monoid_with_zero_hom
variables [group_with_zero G₀] [group_with_zero G₀'] [monoid_with_zero M₀] [nontrivial M₀]
section monoid_with_zero
variables (f : monoid_with_zero_hom G₀ M₀) {a : G₀}
lemma map_ne_zero : f a ≠ 0 ↔ a ≠ 0 :=
⟨λ hfa ha, hfa $ ha.symm ▸ f.map_zero, λ ha, ((is_unit.mk0 a ha).map f.to_monoid_hom).ne_zero⟩
@[simp] lemma map_eq_zero : f a = 0 ↔ a = 0 :=
not_iff_not.1 f.map_ne_zero
end monoid_with_zero
section group_with_zero
variables (f : monoid_with_zero_hom G₀ G₀') (a b : G₀)
/-- A monoid homomorphism between groups with zeros sending `0` to `0` sends `a⁻¹` to `(f a)⁻¹`. -/
@[simp] lemma map_inv : f a⁻¹ = (f a)⁻¹ :=
begin
by_cases h : a = 0, by simp [h],
apply eq_inv_of_mul_left_eq_one,
rw [← f.map_mul, inv_mul_cancel h, f.map_one]
end
@[simp] lemma map_div : f (a / b) = f a / f b :=
by simpa only [div_eq_mul_inv] using ((f.map_mul _ _).trans $ _root_.congr_arg _ $ f.map_inv b)
end group_with_zero
end monoid_with_zero_hom
@[simp] lemma monoid_hom.map_units_inv {M G₀ : Type*} [monoid M] [group_with_zero G₀]
(f : M →* G₀) (u : units M) : f ↑u⁻¹ = (f u)⁻¹ :=
by rw [← units.coe_map, ← units.coe_map, ← units.coe_inv', monoid_hom.map_inv]
section noncomputable_defs
variables {M : Type*} [nontrivial M]
/-- Constructs a `group_with_zero` structure on a `monoid_with_zero`
consisting only of units and 0. -/
noncomputable def group_with_zero_of_is_unit_or_eq_zero [hM : monoid_with_zero M]
(h : ∀ (a : M), is_unit a ∨ a = 0) : group_with_zero M :=
{ inv := λ a, if h0 : a = 0 then 0 else ↑((h a).resolve_right h0).unit⁻¹,
inv_zero := dif_pos rfl,
mul_inv_cancel := λ a h0, by {
change a * (if h0 : a = 0 then 0 else ↑((h a).resolve_right h0).unit⁻¹) = 1,
rw [dif_neg h0, units.mul_inv_eq_iff_eq_mul, one_mul, is_unit.unit_spec] },
exists_pair_ne := nontrivial.exists_pair_ne,
.. hM }
/-- Constructs a `comm_group_with_zero` structure on a `comm_monoid_with_zero`
consisting only of units and 0. -/
noncomputable def comm_group_with_zero_of_is_unit_or_eq_zero [hM : comm_monoid_with_zero M]
(h : ∀ (a : M), is_unit a ∨ a = 0) : comm_group_with_zero M :=
{ .. (group_with_zero_of_is_unit_or_eq_zero h), .. hM }
end noncomputable_defs
|
4a58cef26b7a764710ed4d03ab0f67bbb0ab4c52 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /scripts/modules_used.lean | 8a7634f0fd8056a26e8d7603b9fd9c174f8429a0 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 3,147 | lean | import all
import system.io
import tactic.algebra
/-!
# Find all imported modules which are used by the declarations in the target module.
```
lean --run scripts/modules_used.lean data.nat.order.basic
```
returns
```
order.synonym
order.rel_classes
order.monotone
order.lattice
order.heyting.basic
order.bounded_order
order.boolean_algebra
order.basic
logic.nontrivial
logic.nonempty
logic.is_empty
logic.function.basic
logic.equiv.defs
logic.basic
data.subtype
data.set.basic
data.nat.order.basic
data.nat.cast.defs
data.nat.basic
algebra.ring.defs
algebra.order.zero_le_one
algebra.order.sub.defs
algebra.order.sub.canonical
algebra.order.ring.lemmas
algebra.order.ring.defs
algebra.order.ring.canonical
algebra.order.monoid.lemmas
algebra.order.monoid.defs
algebra.order.monoid.canonical.defs
algebra.order.monoid.cancel.defs
algebra.group_with_zero.defs
algebra.group.defs
algebra.group.basic
algebra.covariant_and_contravariant
```
This is useful for finding imports which might be removable.
-/
open tactic declaration environment io io.fs
meta def tactic.get_decls_used (env : environment) : name → name_set → tactic name_set
| n ns := if ns.contains n then pure ns else (do
d ← env.get n,
-- Add `n` to the accumulated name set.
let ns := ns.insert n,
-- Run `get_decls_used` on any ancestors of `n` (if `n` is a structure)
ancestors ← get_ancestors n,
ns ← ancestors.mfoldl (λ ns n, tactic.get_decls_used n ns) ns,
-- Now traverse the body of the declaration, processing any constants.
let process (v : expr) : tactic (name_set) :=
v.fold (pure ns) $ λ e _ r, r >>= λ ns,
if e.is_constant then tactic.get_decls_used e.const_name ns else pure ns,
match d with
| (declaration.defn _ _ _ v _ _) := process v
| (declaration.thm _ _ _ v) := process v.get
| _ := pure ns
end) <|> (do
trace format!"Error while processing: {n}",
pure ns)
meta def tactic.get_modules_used_by_theorems_in (tgt : string) : tactic (list string) :=
do env ← tactic.get_env,
ns ← env.fold (pure mk_name_set) (λ d r,
if env.decl_olean d.to_name = some tgt then
r >>= tactic.get_decls_used env d.to_name
else r),
let mods := ns.fold native.mk_rb_set (λ n mods,
match env.decl_olean n with
| some mod := mods.insert mod
| none := mods
end),
pure mods.to_list.reverse
meta def main : io unit := do
[arg] ← io.cmdline_args,
tgt' ← io.run_tactic ((lean.parser.ident).run_with_input arg),
let tgt := module_info.resolve_module_name tgt',
let home_len := tgt.length - (tgt'.length + 5),
let project := ((tgt.to_list.take home_len)).as_string,
run_tactic $ do
files ← tactic.get_modules_used_by_theorems_in tgt,
-- Only return files in the same project.
let files := (files.filter_map (λ s, s.get_rest project)),
-- Convert paths to imports, e.g. `data/nat/order/basic.lean` -> `data.nat.order.basic`.
-- ... the string library is not exactly featureful.
let files := files.map (λ s, ((s.to_list.reverse.drop 5).reverse.as_string.split_on '/').foldl
(λ n s, name.mk_string s n) name.anonymous),
files.mmap' trace
|
be7bbedde6c1ec03deff0554a454207687f33f1e | 6dc0c8ce7a76229dd81e73ed4474f15f88a9e294 | /tests/lean/run/305.lean | f82d2f257dc07279386898a6c350fc99ffcff954 | [
"Apache-2.0"
] | permissive | williamdemeo/lean4 | 72161c58fe65c3ad955d6a3050bb7d37c04c0d54 | 6d00fcf1d6d873e195f9220c668ef9c58e9c4a35 | refs/heads/master | 1,678,305,356,877 | 1,614,708,995,000 | 1,614,708,995,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,307 | lean | def Unit.longName (f : Unit) : String := ""
inductive Cmd
| init
(name : String)
(subCmds : Array Cmd)
(flags : Array Unit)
open Inhabited in
instance : Inhabited Cmd where
default := Cmd.init default default default
namespace Cmd
def name : Cmd → String | init v _ _ => v
def subCmds : Cmd → Array Cmd | init _ v _ => v
def flags : Cmd → Array Unit | init _ _ v => v
def subCmd? (c : Cmd) (name : String) : Option Cmd := c.subCmds.find? (·.name = name)
def flag? (c : Cmd) (longName : String) : Option Unit := c.flags.find? (·.longName = longName)
def hasFlag (c : Cmd) (longName : String) : Bool := c.flag? longName |>.isSome
def subCmdByFullName? (c : Cmd) (fullName : Array String) : Option Cmd := do
let mut c := c
guard <| c.name = fullName.get? 0
for subName in fullName[1:] do
c ← c.subCmd? subName
return c
end Cmd
structure Flag.Parsed where
longName : String
abbrev FullCmdName := Array String
structure Cmd.Parsed where
name : FullCmdName
flags : Array Flag.Parsed
namespace Cmd.Parsed
def hasFlag (c : Cmd.Parsed) (longName : String) : Bool := false
end Cmd.Parsed
def readSubCmds : Id FullCmdName := panic! ""
def readArgs : Id (Array Flag.Parsed) := panic! ""
def parse (c : Cmd) : Id Cmd.Parsed := do
let cmdName ← readSubCmds
let flags ← readArgs
let cmd := c.subCmdByFullName? cmdName |>. get!
let defaultedFlags : Array Flag.Parsed := #[]
-- If we uncomment /-: Cmd.Parsed -/ two lines below or comment the line below, the elaborator stops hanging.
let flags := defaultedFlags
let parsedCmd /- : Cmd.Parsed -/ := {
name := cmdName,
flags := flags
}
-- If we remove `∨ cmd.hasFlag "version" ∧ parsedCmd.hasFlag "version"` from the condition below,
-- the timeout turns into an error. If we also remove `∧ parsedCmd.hasFlag "help"`, it works fine.
-- Error:
-- synthesized type class instance is not definitionally equal to expression inferred by typing rules, synthesized
-- instDecidableAnd
-- inferred
-- ?m.4652 flags✝ positionalArgs variableArgs
if cmd.hasFlag "help" ∧ parsedCmd.hasFlag "help" ∨ cmd.hasFlag "version" ∧ parsedCmd.hasFlag "version" then
return parsedCmd
return parsedCmd
|
550ee45548ff57fa33323fb18f142c3c043bde48 | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /stage0/src/Lean/Meta/Tactic/Simp/CongrLemmas.lean | f0227a76f5ee2bcfca3528c30cc601b85179ff65 | [
"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 | 5,196 | 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.ScopedEnvExtension
import Lean.Util.Recognizers
import Lean.Meta.Basic
namespace Lean.Meta
structure CongrLemma where
theoremName : Name
funName : Name
hypothesesPos : Array Nat
priority : Nat
deriving Inhabited, Repr
structure CongrLemmas where
lemmas : SMap Name (List CongrLemma) := {}
deriving Inhabited, Repr
def CongrLemmas.get (d : CongrLemmas) (declName : Name) : List CongrLemma :=
match d.lemmas.find? declName with
| none => []
| some cs => cs
def addCongrLemmaEntry (d : CongrLemmas) (e : CongrLemma) : CongrLemmas :=
{ d with lemmas :=
match d.lemmas.find? e.funName with
| none => d.lemmas.insert e.funName [e]
| some es => d.lemmas.insert e.funName <| insert es }
where
insert : List CongrLemma → List CongrLemma
| [] => [e]
| e'::es => if e.priority ≥ e'.priority then e::e'::es else e' :: insert es
builtin_initialize congrExtension : SimpleScopedEnvExtension CongrLemma CongrLemmas ←
registerSimpleScopedEnvExtension {
name := `congrExt
initial := {}
addEntry := addCongrLemmaEntry
finalizeImport := fun s => { s with lemmas := s.lemmas.switch }
}
def mkCongrLemma (declName : Name) (prio : Nat) : MetaM CongrLemma := withReducible do
let c ← mkConstWithLevelParams declName
let (xs, bis, type) ← forallMetaTelescopeReducing (← inferType c)
match type.eq? with
| none => throwError "invalid 'congr' theorem, equality expected{indentExpr type}"
| some (_, lhs, rhs) =>
lhs.withApp fun lhsFn lhsArgs => rhs.withApp fun rhsFn rhsArgs => do
unless lhsFn.isConst && rhsFn.isConst && lhsFn.constName! == rhsFn.constName! && lhsArgs.size == rhsArgs.size do
throwError "invalid 'congr' theorem, equality left/right-hand sides must be applications of the same function{indentExpr type}"
let mut foundMVars : NameSet := {}
for lhsArg in lhsArgs do
unless lhsArg.isSort do
unless lhsArg.isMVar do
throwError "invalid 'congr' theorem, arguments in the left-hand-side must be variables or sorts{indentExpr lhs}"
foundMVars := foundMVars.insert lhsArg.mvarId!
let mut i := 0
let mut hypothesesPos := #[]
for x in xs, bi in bis do
if bi.isExplicit && !foundMVars.contains x.mvarId! then
let rhsFn? ← forallTelescopeReducing (← inferType x) fun ys xType => do
match xType.eq? with
| none => pure none -- skip
| some (_, xLhs, xRhs) =>
let mut j := 0
for y in ys do
let yType ← inferType y
unless onlyMVarsAt yType foundMVars do
throwError "invalid 'congr' theorem, argument #{j+1} of parameter #{i+1} contains unresolved parameter{indentExpr yType}"
j := j + 1
unless onlyMVarsAt xLhs foundMVars do
throwError "invalid 'congr' theorem, parameter #{i+1} is not a valid hypothesis, the left-hand-side contains unresolved parameters{indentExpr xLhs}"
let xRhsFn := xRhs.getAppFn
unless xRhsFn.isMVar do
throwError "invalid 'congr' theorem, parameter #{i+1} is not a valid hypothesis, the right-hand-side head is not a metavariable{indentExpr xRhs}"
unless !foundMVars.contains xRhsFn.mvarId! do
throwError "invalid 'congr' theorem, parameter #{i+1} is not a valid hypothesis, the right-hand-side head was already resolved{indentExpr xRhs}"
for arg in xRhs.getAppArgs do
unless arg.isFVar do
throwError "invalid 'congr' theorem, parameter #{i+1} is not a valid hypothesis, the right-hand-side argument is not local variable{indentExpr xRhs}"
pure (some xRhsFn)
match rhsFn? with
| none => pure ()
| some rhsFn =>
foundMVars := foundMVars.insert x.mvarId! |>.insert rhsFn.mvarId!
hypothesesPos := hypothesesPos.push i
i := i + 1
trace[Meta.debug] "c: {c} : {type}"
return {
theoremName := declName
funName := lhsFn.constName!
hypothesesPos := hypothesesPos
priority := prio
}
where
/-- Return `true` if `t` contains a metavariable that is not in `mvarSet` -/
onlyMVarsAt (t : Expr) (mvarSet : NameSet) : Bool :=
Option.isNone <| t.find? fun e => e.isMVar && !mvarSet.contains e.mvarId!
def addCongrLemma (declName : Name) (attrKind : AttributeKind) (prio : Nat) : MetaM Unit := do
let lemma ← mkCongrLemma declName prio
congrExtension.add lemma attrKind
builtin_initialize
registerBuiltinAttribute {
name := `congr
descr := "congruence theorem"
add := fun declName stx attrKind => do
let prio ← getAttrParamOptPrio stx[1]
discard <| addCongrLemma declName attrKind prio |>.run {} {}
}
def getCongrLemmas : MetaM CongrLemmas :=
return congrExtension.getState (← getEnv)
end Lean.Meta
|
184193bee76334af1db960191384d6d4faacb4cb | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/group_theory/submonoid.lean | e50cbb9fc494a8b5ab260980047ad6354cafb04d | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 13,243 | lean | /-
Copyright (c) 2018 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Kenny Lau, Johan Commelin, Mario Carneiro
-/
import algebra.big_operators
import data.finset
import tactic.subtype_instance
variables {α : Type*} [monoid α] {s : set α}
variables {β : Type*} [add_monoid β] {t : set β}
/-- `s` is a submonoid: a set containing 1 and closed under multiplication. -/
class is_submonoid (s : set α) : Prop :=
(one_mem : (1:α) ∈ s)
(mul_mem {a b} : a ∈ s → b ∈ s → a * b ∈ s)
/-- `s` is an additive submonoid: a set containing 0 and closed under addition. -/
class is_add_submonoid (s : set β) : Prop :=
(zero_mem : (0:β) ∈ s)
(add_mem {a b} : a ∈ s → b ∈ s → a + b ∈ s)
attribute [to_additive is_add_submonoid] is_submonoid
attribute [to_additive is_add_submonoid.zero_mem] is_submonoid.one_mem
attribute [to_additive is_add_submonoid.add_mem] is_submonoid.mul_mem
attribute [to_additive is_add_submonoid.mk] is_submonoid.mk
instance additive.is_add_submonoid
(s : set α) : ∀ [is_submonoid s], @is_add_submonoid (additive α) _ s
| ⟨h₁, h₂⟩ := ⟨h₁, @h₂⟩
theorem additive.is_add_submonoid_iff
{s : set α} : @is_add_submonoid (additive α) _ s ↔ is_submonoid s :=
⟨λ ⟨h₁, h₂⟩, ⟨h₁, @h₂⟩, λ h, by resetI; apply_instance⟩
instance multiplicative.is_submonoid
(s : set β) : ∀ [is_add_submonoid s], @is_submonoid (multiplicative β) _ s
| ⟨h₁, h₂⟩ := ⟨h₁, @h₂⟩
theorem multiplicative.is_submonoid_iff
{s : set β} : @is_submonoid (multiplicative β) _ s ↔ is_add_submonoid s :=
⟨λ ⟨h₁, h₂⟩, ⟨h₁, @h₂⟩, λ h, by resetI; apply_instance⟩
lemma is_submonoid_Union_of_directed {ι : Type*} [hι : nonempty ι]
(s : ι → set α) [∀ i, is_submonoid (s i)]
(directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) :
is_submonoid (⋃i, s i) :=
{ one_mem := let ⟨i⟩ := hι in set.mem_Union.2 ⟨i, is_submonoid.one_mem _⟩,
mul_mem := λ a b ha hb,
let ⟨i, hi⟩ := set.mem_Union.1 ha in
let ⟨j, hj⟩ := set.mem_Union.1 hb in
let ⟨k, hk⟩ := directed i j in
set.mem_Union.2 ⟨k, is_submonoid.mul_mem (hk.1 hi) (hk.2 hj)⟩ }
lemma is_add_submonoid_Union_of_directed {ι : Type*} [hι : nonempty ι]
(s : ι → set β) [∀ i, is_add_submonoid (s i)]
(directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) :
is_add_submonoid (⋃i, s i) :=
multiplicative.is_submonoid_iff.1 $
@is_submonoid_Union_of_directed (multiplicative β) _ _ _ s _ directed
attribute [to_additive is_add_submonoid_Union_of_directed] is_submonoid_Union_of_directed
section powers
def powers (x : α) : set α := {y | ∃ n:ℕ, x^n = y}
def multiples (x : β) : set β := {y | ∃ n:ℕ, add_monoid.smul n x = y}
attribute [to_additive multiples] powers
lemma powers.one_mem {x : α} : (1 : α) ∈ powers x := ⟨0, pow_zero _⟩
lemma multiples.zero_mem {x : β} : (0 : β) ∈ multiples x := ⟨0, add_monoid.zero_smul _⟩
attribute [to_additive multiples.zero_mem] powers.one_mem
lemma powers.self_mem {x : α} : x ∈ powers x := ⟨1, pow_one _⟩
lemma multiples.self_mem {x : β} : x ∈ multiples x := ⟨1, add_monoid.one_smul _⟩
attribute [to_additive multiples.self_mem] powers.self_mem
instance powers.is_submonoid (x : α) : is_submonoid (powers x) :=
{ one_mem := ⟨0, by simp⟩,
mul_mem := λ x₁ x₂ ⟨n₁, hn₁⟩ ⟨n₂, hn₂⟩, ⟨n₁ + n₂, by simp [pow_add, *]⟩ }
instance multiples.is_add_submonoid (x : β) : is_add_submonoid (multiples x) :=
multiplicative.is_submonoid_iff.1 $ powers.is_submonoid _
attribute [to_additive multiples.is_add_submonoid] powers.is_submonoid
@[to_additive univ.is_add_submonoid]
instance univ.is_submonoid : is_submonoid (@set.univ α) := by split; simp
@[to_additive preimage.is_add_submonoid]
instance preimage.is_submonoid {γ : Type*} [monoid γ] (f : α → γ) [is_monoid_hom f]
(s : set γ) [is_submonoid s] : is_submonoid (f ⁻¹' s) :=
{ one_mem := show f 1 ∈ s, by rw is_monoid_hom.map_one f; exact is_submonoid.one_mem s,
mul_mem := λ a b (ha : f a ∈ s) (hb : f b ∈ s),
show f (a * b) ∈ s, by rw is_monoid_hom.map_mul f; exact is_submonoid.mul_mem ha hb }
@[instance, to_additive image.is_add_submonoid]
lemma image.is_submonoid {γ : Type*} [monoid γ] (f : α → γ) [is_monoid_hom f]
(s : set α) [is_submonoid s] : is_submonoid (f '' s) :=
{ one_mem := ⟨1, is_submonoid.one_mem s, is_monoid_hom.map_one f⟩,
mul_mem := λ a b ⟨x, hx⟩ ⟨y, hy⟩, ⟨x * y, is_submonoid.mul_mem hx.1 hy.1,
by rw [is_monoid_hom.map_mul f, hx.2, hy.2]⟩ }
instance range.is_submonoid {γ : Type*} [monoid γ] (f : α → γ) [is_monoid_hom f] :
is_submonoid (set.range f) :=
by rw ← set.image_univ; apply_instance
lemma is_submonoid.pow_mem {a : α} [is_submonoid s] (h : a ∈ s) : ∀ {n : ℕ}, a ^ n ∈ s
| 0 := is_submonoid.one_mem s
| (n + 1) := is_submonoid.mul_mem h is_submonoid.pow_mem
lemma is_add_submonoid.smul_mem {a : β} [is_add_submonoid t] :
∀ (h : a ∈ t) {n : ℕ}, add_monoid.smul n a ∈ t :=
@is_submonoid.pow_mem (multiplicative β) _ _ _ _
attribute [to_additive is_add_submonoid.smul_mem] is_submonoid.pow_mem
lemma is_submonoid.power_subset {a : α} [is_submonoid s] (h : a ∈ s) : powers a ⊆ s :=
assume x ⟨n, hx⟩, hx ▸ is_submonoid.pow_mem h
lemma is_add_submonoid.multiple_subset {a : β} [is_add_submonoid t] :
a ∈ t → multiples a ⊆ t :=
@is_submonoid.power_subset (multiplicative β) _ _ _ _
attribute [to_additive is_add_submonoid.multiple_subset] is_add_submonoid.multiple_subset
end powers
namespace is_submonoid
@[to_additive is_add_submonoid.list_sum_mem]
lemma list_prod_mem [is_submonoid s] : ∀{l : list α}, (∀x∈l, x ∈ s) → l.prod ∈ s
| [] h := one_mem s
| (a::l) h :=
suffices a * l.prod ∈ s, by simpa,
have a ∈ s ∧ (∀x∈l, x ∈ s), by simpa using h,
is_submonoid.mul_mem this.1 (list_prod_mem this.2)
@[to_additive is_add_submonoid.multiset_sum_mem]
lemma multiset_prod_mem {α} [comm_monoid α] (s : set α) [is_submonoid s] (m : multiset α) :
(∀a∈m, a ∈ s) → m.prod ∈ s :=
begin
refine quotient.induction_on m (assume l hl, _),
rw [multiset.quot_mk_to_coe, multiset.coe_prod],
exact list_prod_mem hl
end
@[to_additive is_add_submonoid.finset_sum_mem]
lemma finset_prod_mem {α β} [comm_monoid α] (s : set α) [is_submonoid s] (f : β → α) :
∀(t : finset β), (∀b∈t, f b ∈ s) → t.prod f ∈ s
| ⟨m, hm⟩ hs :=
begin
refine multiset_prod_mem s _ _,
simp,
rintros a b hb rfl,
exact hs _ hb
end
end is_submonoid
instance subtype.monoid {s : set α} [is_submonoid s] : monoid s :=
by subtype_instance
attribute [to_additive subtype.add_monoid._proof_1] subtype.monoid._proof_1
attribute [to_additive subtype.add_monoid._proof_2] subtype.monoid._proof_2
attribute [to_additive subtype.add_monoid._proof_3] subtype.monoid._proof_3
attribute [to_additive subtype.add_monoid._proof_4] subtype.monoid._proof_4
attribute [to_additive subtype.add_monoid._proof_5] subtype.monoid._proof_5
attribute [to_additive subtype.add_monoid] subtype.monoid
@[simp, to_additive is_add_submonoid.coe_zero]
lemma is_submonoid.coe_one [is_submonoid s] : ((1 : s) : α) = 1 := rfl
@[simp, to_additive is_add_submonoid.coe_add]
lemma is_submonoid.coe_mul [is_submonoid s] (a b : s) : ((a * b : s) : α) = a * b := rfl
@[simp] lemma is_submonoid.coe_pow [is_submonoid s] (a : s) (n : ℕ) : ((a ^ n : s) : α) = a ^ n :=
by induction n; simp [*, pow_succ]
@[simp] lemma is_add_submonoid.smul_coe {β : Type*} [add_monoid β] {s : set β}
[is_add_submonoid s] (a : s) (n : ℕ) : ((add_monoid.smul n a : s) : β) = add_monoid.smul n a :=
by induction n; [refl, simp [*, succ_smul]]
attribute [to_additive is_add_submonoid.smul_coe] is_submonoid.coe_pow
@[to_additive subtype_val.is_add_monoid_hom]
instance subtype_val.is_monoid_hom [is_submonoid s] : is_monoid_hom (subtype.val : s → α) :=
{ map_one := rfl, map_mul := λ _ _, rfl }
@[to_additive coe.is_add_monoid_hom]
instance coe.is_monoid_hom [is_submonoid s] : is_monoid_hom (coe : s → α) :=
subtype_val.is_monoid_hom
@[to_additive subtype_mk.is_add_monoid_hom]
instance subtype_mk.is_monoid_hom {γ : Type*} [monoid γ] [is_submonoid s] (f : γ → α)
[is_monoid_hom f] (h : ∀ x, f x ∈ s) : is_monoid_hom (λ x, (⟨f x, h x⟩ : s)) :=
{ map_one := subtype.eq (is_monoid_hom.map_one f),
map_mul := λ _ _, subtype.eq (is_monoid_hom.map_mul f) }
@[to_additive set_inclusion.is_add_monoid_hom]
instance set_inclusion.is_monoid_hom (t : set α) [is_submonoid s] [is_submonoid t] (h : s ⊆ t) :
is_monoid_hom (set.inclusion h) :=
subtype_mk.is_monoid_hom _ _
namespace monoid
inductive in_closure (s : set α) : α → Prop
| basic {a : α} : a ∈ s → in_closure a
| one : in_closure 1
| mul {a b : α} : in_closure a → in_closure b → in_closure (a * b)
def closure (s : set α) : set α := {a | in_closure s a }
instance closure.is_submonoid (s : set α) : is_submonoid (closure s) :=
{ one_mem := in_closure.one s, mul_mem := assume a b, in_closure.mul }
theorem subset_closure {s : set α} : s ⊆ closure s :=
assume a, in_closure.basic
theorem closure_subset {s t : set α} [is_submonoid t] (h : s ⊆ t) : closure s ⊆ t :=
assume a ha, by induction ha; simp [h _, *, is_submonoid.one_mem, is_submonoid.mul_mem]
theorem closure_mono {s t : set α} (h : s ⊆ t) : closure s ⊆ closure t :=
closure_subset $ set.subset.trans h subset_closure
theorem closure_singleton {x : α} : closure ({x} : set α) = powers x :=
set.eq_of_subset_of_subset (closure_subset $ set.singleton_subset_iff.2 $ powers.self_mem) $
is_submonoid.power_subset $ set.singleton_subset_iff.1 $ subset_closure
theorem exists_list_of_mem_closure {s : set α} {a : α} (h : a ∈ closure s) :
(∃l:list α, (∀x∈l, x ∈ s) ∧ l.prod = a) :=
begin
induction h,
case in_closure.basic : a ha { existsi ([a]), simp [ha] },
case in_closure.one { existsi ([]), simp },
case in_closure.mul : a b _ _ ha hb {
rcases ha with ⟨la, ha, eqa⟩,
rcases hb with ⟨lb, hb, eqb⟩,
existsi (la ++ lb),
simp [eqa.symm, eqb.symm, or_imp_distrib],
exact assume a, ⟨ha a, hb a⟩
}
end
theorem mem_closure_union_iff {α : Type*} [comm_monoid α] {s t : set α} {x : α} :
x ∈ closure (s ∪ t) ↔ ∃ y ∈ closure s, ∃ z ∈ closure t, y * z = x :=
⟨λ hx, let ⟨L, HL1, HL2⟩ := exists_list_of_mem_closure hx in HL2 ▸
list.rec_on L (λ _, ⟨1, is_submonoid.one_mem _, 1, is_submonoid.one_mem _, mul_one _⟩)
(λ hd tl ih HL1, let ⟨y, hy, z, hz, hyzx⟩ := ih (list.forall_mem_of_forall_mem_cons HL1) in
or.cases_on (HL1 hd $ list.mem_cons_self _ _)
(λ hs, ⟨hd * y, is_submonoid.mul_mem (subset_closure hs) hy, z, hz, by rw [mul_assoc, list.prod_cons, ← hyzx]; refl⟩)
(λ ht, ⟨y, hy, z * hd, is_submonoid.mul_mem hz (subset_closure ht), by rw [← mul_assoc, list.prod_cons, ← hyzx, mul_comm hd]; refl⟩)) HL1,
λ ⟨y, hy, z, hz, hyzx⟩, hyzx ▸ is_submonoid.mul_mem (closure_mono (set.subset_union_left _ _) hy)
(closure_mono (set.subset_union_right _ _) hz)⟩
end monoid
namespace add_monoid
def closure (s : set β) : set β := @monoid.closure (multiplicative β) _ s
attribute [to_additive add_monoid.closure] monoid.closure
instance closure.is_add_submonoid (s : set β) : is_add_submonoid (closure s) :=
multiplicative.is_submonoid_iff.1 $ monoid.closure.is_submonoid s
attribute [to_additive add_monoid.closure.is_add_submonoid] monoid.closure.is_submonoid
theorem subset_closure {s : set β} : s ⊆ closure s :=
monoid.subset_closure
attribute [to_additive add_monoid.subset_closure] monoid.subset_closure
theorem closure_subset {s t : set β} [is_add_submonoid t] : s ⊆ t → closure s ⊆ t :=
monoid.closure_subset
attribute [to_additive add_monoid.closure_subset] monoid.closure_subset
theorem closure_mono {s t : set β} (h : s ⊆ t) : closure s ⊆ closure t :=
closure_subset $ set.subset.trans h subset_closure
attribute [to_additive add_monoid.closure_mono] monoid.closure_mono
theorem closure_singleton {x : β} : closure ({x} : set β) = multiples x :=
monoid.closure_singleton
attribute [to_additive add_monoid.closure_singleton] monoid.closure_singleton
theorem exists_list_of_mem_closure {s : set β} {a : β} :
a ∈ closure s → ∃l:list β, (∀x∈l, x ∈ s) ∧ l.sum = a :=
monoid.exists_list_of_mem_closure
attribute [to_additive add_monoid.exists_list_of_mem_closure] monoid.exists_list_of_mem_closure
@[elab_as_eliminator]
theorem in_closure.rec_on {s : set β} {C : β → Prop}
{a : β} (H : a ∈ closure s)
(H1 : ∀ {a : β}, a ∈ s → C a) (H2 : C 0)
(H3 : ∀ {a b : β}, a ∈ closure s → b ∈ closure s → C a → C b → C (a + b)) :
C a :=
monoid.in_closure.rec_on H (λ _, H1) H2 (λ _ _, H3)
theorem mem_closure_union_iff {β : Type*} [add_comm_monoid β] {s t : set β} {x : β} :
x ∈ closure (s ∪ t) ↔ ∃ y ∈ closure s, ∃ z ∈ closure t, y + z = x :=
monoid.mem_closure_union_iff
end add_monoid
|
36c2c482dd1ebcecf664ef433ad0ed9596c05c0e | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/extra/616b.hlean | 6f6a3ae8d204a87ba0205ae6f33eb4e5c3459688 | [
"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 | 249 | hlean | import .f616a
open eq
definition my_elim {A P : Type} {R : A → A → Type} (Pc : A → P)
(Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a = Pc a') (x : quotient R) : P :=
begin
induction x,
exact (Pc a),
refine (pathover_of_eq _ (Pp H))
end
|
51d1f267ba03dbdc94fb8584df69e63690932d9b | 05d69962fb9deab19838de9bbcf33ebdbf8faa57 | /supp.lean | ea395cae4421b72d0dc14d0bfaf4f66dfcaeba03 | [] | no_license | pj0y1/polynom | 6eb7c96dbf34960be5721a232a67f7a592aedf7a | 9e198cc9104017fae7774574f141197bb295ee66 | refs/heads/master | 1,611,193,417,139 | 1,501,472,138,000 | 1,501,472,138,000 | 64,856,946 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,632 | lean | /- Define supp and zero-/
import algebra.group_bigops data.set
open classical set
namespace function
/- supp and zero-/
section
variables {A B: Type}[has_zero B]
definition supp (f: A -> B): A -> Prop :=
λa, f a ≠ (0:B)
theorem ne_zero_iff_mem_supp{f: A -> B}{a: A}:
(f a ≠ 0) ↔ a∈ supp f :=
iff.intro (λl, l)(λr, r)
corollary ne_zero_eq_mem_supp(f: A -> B)(a: A):
(f a ≠ 0) = (a∈ supp f) :=
propext ne_zero_iff_mem_supp
theorem eq_zero_iff_not_mem_supp{f: A -> B}{a: A}:
(f a = 0) ↔ a∉ supp f :=
iff.intro
(λl, or.elim (em (a∈supp f))
(λh, absurd l (iff.mpr ne_zero_iff_mem_supp h))
(λh, h))
(λr, or.elim (em (f a = 0))
(λh, h)
(λh, absurd (iff.mp ne_zero_iff_mem_supp h) r))
corollary eq_zero_eq_not_mem_supp(f: A -> B)(a: A):
(f a = 0) = ( a∉ supp f) :=
propext eq_zero_iff_not_mem_supp
definition zero : A -> B := λa, (0:B)
theorem zero_empty_supp : supp (@zero A B _)= ∅ :=
eq_empty_of_forall_not_mem
(λ x, iff.mp eq_zero_iff_not_mem_supp (show (λa:A, 0) x = 0, from rfl))
end
definition add {A B:Type}[has_add B](f g:A -> B): A -> B :=
λa, add (f a) (g a)
notation f + g := add f g
theorem add_assoc {A B:Type}[add_semigroup B](f g h: A -> B):
(f + g) + h = f + (g + h) :=
funext (λa, !add_semigroup.add_assoc)
theorem add_comm {A B:Type}[add_comm_semigroup B](f g: A -> B):
f + g = g + f :=
funext (λa, !add_comm_semigroup.add_comm)
theorem add_zero {A B:Type}[add_monoid B](f: A -> B):
f + zero = f :=
funext (λa, !add_monoid.add_zero)
theorem zero_add {A B:Type}[add_monoid B](f: A -> B):
zero + f = f :=
funext (λa, !add_monoid.zero_add)
theorem add_left_cancel {A B:Type}[add_left_cancel_semigroup B](f g h: A -> B)
(H: f + g = f + h): g = h :=
have ∀a:A, f a + g a = f a + h a, from λa,
by rewrite [↑add at H]; apply congr H (eq.refl a),
funext (λa, !add_left_cancel_semigroup.add_left_cancel (this a))
theorem add_right_cancel {A B:Type}[add_right_cancel_semigroup B](f g h: A -> B)
(H: g + f = h + f): g = h :=
funext (λa, by rewrite [↑add at H];
apply !add_right_cancel_semigroup.add_right_cancel;
apply congr H (eq.refl a))
theorem add_supp_subset_union {A B:Type}[add_monoid B]{f g: A -> B}:
supp (f + g) ⊆ supp f ∪ supp g :=
λ x H, by_contradiction
assume Hn: x ∉ (supp f) ∪ (supp g),
have x ∈ -(supp f ∪ supp g), from mem_compl Hn,
have x ∈ (-supp f) ∩ (-supp g), from eq.subst !compl_union this,
have Hf : f x = 0, by rewrite (eq_zero_eq_not_mem_supp f x);
apply (not_mem_of_mem_compl (and.left this)),
have Hg : g x = 0, by rewrite (eq_zero_eq_not_mem_supp g x);
apply (not_mem_of_mem_compl (and.right this)),
have Heq: f x + g x = 0, by rewrite [Hf, Hg];simp,
have (f + g) x = 0, from Heq,
have x∉supp (f + g),
by rewrite [(eq_zero_eq_not_mem_supp (f + g) x) at this];exact this,
show false, from absurd H this
definition neg {A B:Type}[has_neg B](f: A -> B): A -> B :=
λa, neg (f a)
theorem neg_zero {A B:Type}[add_group B]: neg (@zero A B _) = zero :=
funext (λa, !neg_zero)
theorem add_left_inv {A B:Type}[add_group B]{f:A -> B}:
(neg f) + f = zero :=
funext (λa, !add_group.add_left_inv)
theorem neg_supp_eq {A B:Type}[add_group B]{f: A -> B}: supp (neg f) = supp f :=
ext (λ x, iff.intro
(assume l, have neg f x ≠ 0, from l,
have f x ≠ 0, from assume h: f x = 0,
absurd (iff.mpr !neg_eq_zero_iff_eq_zero h) this,
show x ∈ supp f,
by rewrite [(ne_zero_eq_mem_supp f x) at this];exact this)
(assume r, have f x ≠ 0, from r,
have neg f x ≠ 0, from assume h: neg f x = 0,
absurd (eq_zero_of_neg_eq_zero h) this,
show x ∈ supp (neg f),
by rewrite [(ne_zero_eq_mem_supp (neg f) x) at this];exact this))
section --defining One
variables {A B:Type}[monoid A][semiring B]
noncomputable definition one: A -> B := λa, ite (a=(1:A)) 1 0
/- one supp-/
lemma one_supp_singleton (H:(0:B)≠(1:B)): supp (@one A B _ _) = '{1} :=
ext (λx:A, iff.intro
(λl, have hne:(@one A B _ _) x ≠ (0:B),
from (iff.mpr ne_zero_iff_mem_supp) l,
have h1: x=(1:A), from proof
by_contradiction assume h:¬ x =(1:A),
have x≠(1:A), from h,
have (one x) = (0:B), from if_neg this,
absurd this hne qed,
mem_singleton_of_eq h1)
(λr, have x=(1:A), from eq_of_mem_singleton r,
have h2:(one x) =(1:B), from if_pos this,
have (0:B) ≠ (one x), by rewrite h2; apply H,
have (one x) ≠ (0:B), by inst_simp,
by rewrite ne_zero_eq_mem_supp at this;exact this))
lemma one_supp_empty (H:(0:B)=(1:B)): supp(@one A B _ _) =∅ :=
have hx:∀x:A, one x = (0:B), from proof
λx:A, or.elim (em (x = 1))
(λh, eq.subst (eq.symm H) (if_pos h))
(λh, if_neg h) qed,
by apply eq_empty_of_forall_not_mem;intro x;
rewrite [-(@eq_zero_eq_not_mem_supp A B _ one x)];exact (hx x)
theorem one_supp_empty_or_singleton :
supp (@one A B _ _) = ∅ ∨ supp (@one A B _ _) = '{1} :=
or.elim (em ((0:B)=(1:B)))
(λheq, or.inl (one_supp_empty heq))
(λhne, or.inr (one_supp_singleton hne))
end
section --Mul
variables {A B:Type}[has_mul A][semiring B]
noncomputable definition mul (f g: A -> B): A -> B :=
λa, ∑x∈ supp f,∑y∈ supp g, (ite (a=x*y) 1 0)*((f x)*(g y))
-- a simple by trick by add brackets ((f x)*(g y))
end
end function
|
8734b28f48d82fab1a554214b4744e332ed05017 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/category_theory/monoidal/opposite.lean | 28f98b1404a0dcf9c0987067ad4fec41949ab0a0 | [
"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 | 5,218 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.monoidal.coherence
/-!
# Monoidal opposites
We write `Cᵐᵒᵖ` for the monoidal opposite of a monoidal category `C`.
-/
universes v₁ v₂ u₁ u₂
variables {C : Type u₁}
namespace category_theory
open category_theory.monoidal_category
/-- A type synonym for the monoidal opposite. Use the notation `Cᴹᵒᵖ`. -/
@[nolint has_inhabited_instance]
def monoidal_opposite (C : Type u₁) := C
namespace monoidal_opposite
notation C `ᴹᵒᵖ`:std.prec.max_plus := monoidal_opposite C
/-- Think of an object of `C` as an object of `Cᴹᵒᵖ`. -/
@[pp_nodot]
def mop (X : C) : Cᴹᵒᵖ := X
/-- Think of an object of `Cᴹᵒᵖ` as an object of `C`. -/
@[pp_nodot]
def unmop (X : Cᴹᵒᵖ) : C := X
lemma op_injective : function.injective (mop : C → Cᴹᵒᵖ) := λ _ _, id
lemma unop_injective : function.injective (unmop : Cᴹᵒᵖ → C) := λ _ _, id
@[simp] lemma op_inj_iff (x y : C) : mop x = mop y ↔ x = y := iff.rfl
@[simp] lemma unop_inj_iff (x y : Cᴹᵒᵖ) : unmop x = unmop y ↔ x = y := iff.rfl
attribute [irreducible] monoidal_opposite
@[simp] lemma mop_unmop (X : Cᴹᵒᵖ) : mop (unmop X) = X := rfl
@[simp] lemma unmop_mop (X : C) : unmop (mop X) = X := rfl
instance monoidal_opposite_category [I : category.{v₁} C] : category Cᴹᵒᵖ :=
{ hom := λ X Y, unmop X ⟶ unmop Y,
id := λ X, 𝟙 (unmop X),
comp := λ X Y Z f g, f ≫ g, }
end monoidal_opposite
end category_theory
open category_theory
open category_theory.monoidal_opposite
variables [category.{v₁} C]
/-- The monoidal opposite of a morphism `f : X ⟶ Y` is just `f`, thought of as `mop X ⟶ mop Y`. -/
def quiver.hom.mop {X Y : C} (f : X ⟶ Y) : @quiver.hom Cᴹᵒᵖ _ (mop X) (mop Y) := f
/-- We can think of a morphism `f : mop X ⟶ mop Y` as a morphism `X ⟶ Y`. -/
def quiver.hom.unmop {X Y : Cᴹᵒᵖ} (f : X ⟶ Y) : unmop X ⟶ unmop Y := f
namespace category_theory
lemma mop_inj {X Y : C} :
function.injective (quiver.hom.mop : (X ⟶ Y) → (mop X ⟶ mop Y)) :=
λ _ _ H, congr_arg quiver.hom.unmop H
lemma unmop_inj {X Y : Cᴹᵒᵖ} :
function.injective (quiver.hom.unmop : (X ⟶ Y) → (unmop X ⟶ unmop Y)) :=
λ _ _ H, congr_arg quiver.hom.mop H
@[simp] lemma unmop_mop {X Y : C} {f : X ⟶ Y} : f.mop.unmop = f := rfl
@[simp] lemma mop_unmop {X Y : Cᴹᵒᵖ} {f : X ⟶ Y} : f.unmop.mop = f := rfl
@[simp] lemma mop_comp {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} :
(f ≫ g).mop = f.mop ≫ g.mop := rfl
@[simp] lemma mop_id {X : C} : (𝟙 X).mop = 𝟙 (mop X) := rfl
@[simp] lemma unmop_comp {X Y Z : Cᴹᵒᵖ} {f : X ⟶ Y} {g : Y ⟶ Z} :
(f ≫ g).unmop = f.unmop ≫ g.unmop := rfl
@[simp] lemma unmop_id {X : Cᴹᵒᵖ} : (𝟙 X).unmop = 𝟙 (unmop X) := rfl
@[simp] lemma unmop_id_mop {X : C} : (𝟙 (mop X)).unmop = 𝟙 X := rfl
@[simp] lemma mop_id_unmop {X : Cᴹᵒᵖ} : (𝟙 (unmop X)).mop = 𝟙 X := rfl
namespace iso
variables {X Y : C}
/-- An isomorphism in `C` gives an isomorphism in `Cᴹᵒᵖ`. -/
@[simps]
def mop (f : X ≅ Y) : mop X ≅ mop Y :=
{ hom := f.hom.mop,
inv := f.inv.mop,
hom_inv_id' := unmop_inj f.hom_inv_id,
inv_hom_id' := unmop_inj f.inv_hom_id }
end iso
variables [monoidal_category.{v₁} C]
open opposite monoidal_category
instance monoidal_category_op : monoidal_category Cᵒᵖ :=
{ tensor_obj := λ X Y, op (unop X ⊗ unop Y),
tensor_hom := λ X₁ Y₁ X₂ Y₂ f g, (f.unop ⊗ g.unop).op,
tensor_unit := op (𝟙_ C),
associator := λ X Y Z, (α_ (unop X) (unop Y) (unop Z)).symm.op,
left_unitor := λ X, (λ_ (unop X)).symm.op,
right_unitor := λ X, (ρ_ (unop X)).symm.op,
associator_naturality' := by { intros, apply quiver.hom.unop_inj, simp, },
left_unitor_naturality' := by { intros, apply quiver.hom.unop_inj, simp, },
right_unitor_naturality' := by { intros, apply quiver.hom.unop_inj, simp, },
triangle' := by { intros, apply quiver.hom.unop_inj, coherence, },
pentagon' := by { intros, apply quiver.hom.unop_inj, coherence, }, }
lemma op_tensor_obj (X Y : Cᵒᵖ) : X ⊗ Y = op (unop X ⊗ unop Y) := rfl
lemma op_tensor_unit : (𝟙_ Cᵒᵖ) = op (𝟙_ C) := rfl
instance monoidal_category_mop : monoidal_category Cᴹᵒᵖ :=
{ tensor_obj := λ X Y, mop (unmop Y ⊗ unmop X),
tensor_hom := λ X₁ Y₁ X₂ Y₂ f g, (g.unmop ⊗ f.unmop).mop,
tensor_unit := mop (𝟙_ C),
associator := λ X Y Z, (α_ (unmop Z) (unmop Y) (unmop X)).symm.mop,
left_unitor := λ X, (ρ_ (unmop X)).mop,
right_unitor := λ X, (λ_ (unmop X)).mop,
associator_naturality' := by { intros, apply unmop_inj, simp, },
left_unitor_naturality' := by { intros, apply unmop_inj, simp, },
right_unitor_naturality' := by { intros, apply unmop_inj, simp, },
triangle' := by { intros, apply unmop_inj, coherence, },
pentagon' := by { intros, apply unmop_inj, coherence, }, }
lemma mop_tensor_obj (X Y : Cᴹᵒᵖ) : X ⊗ Y = mop (unmop Y ⊗ unmop X) := rfl
lemma mop_tensor_unit : (𝟙_ Cᴹᵒᵖ) = mop (𝟙_ C) := rfl
end category_theory
|
337d2e01ae362ca52f6974f2e9d21c6dc0c5360a | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/let3.lean | 58b36b4d0a43d51904899d4f6a99543cd8958f96 | [
"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 | 148 | lean | import data.num
constant f : num → num → num → num
check
let a := 10
in f a 10
/-
check
let a := 10,
b := 10
in f a b 10
-/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.