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
0e715b94cde73b4f08762de70e5445d81ab5da49
618003631150032a5676f229d13a079ac875ff77
/test/doc_commands.lean
3f77fffd3fe99b4060e71c9c6977d599d103b0d6
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
159
lean
import tactic.doc_commands open tactic namespace bar def foo := 5 /-- ok -/ add_decl_doc foo #eval do ds ← doc_string ``foo, guard $ ds = "ok" end bar
707c6150c4af62dd93e6527a7b43ee267ad3ff71
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/algebra/opposites.lean
453a18fc44c4bff7398d75effa0614cdd686acd3
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
23,849
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import data.opposite import algebra.field import algebra.group.commute import group_theory.group_action.defs import data.equiv.mul_add /-! # Algebraic operations on `αᵒᵖ` This file records several basic facts about the opposite of an algebraic structure, e.g. the opposite of a ring is a ring (with multiplication `x * y = yx`). Use is made of the identity functions `op : α → αᵒᵖ` and `unop : αᵒᵖ → α`. -/ namespace opposite universes u variables (α : Type u) instance [has_zero α] : has_zero (opposite α) := { zero := op 0 } instance [has_one α] : has_one (opposite α) := { one := op 1 } instance [has_add α] : has_add (opposite α) := { add := λ x y, op (unop x + unop y) } instance [has_sub α] : has_sub (opposite α) := { sub := λ x y, op (unop x - unop y) } instance [has_neg α] : has_neg (opposite α) := { neg := λ x, op $ -(unop x) } instance [has_mul α] : has_mul (opposite α) := { mul := λ x y, op (unop y * unop x) } instance [has_inv α] : has_inv (opposite α) := { inv := λ x, op $ (unop x)⁻¹ } instance (R : Type*) [has_scalar R α] : has_scalar R (opposite α) := { smul := λ c x, op (c • unop x) } section variables (α) @[simp] lemma op_zero [has_zero α] : op (0 : α) = 0 := rfl @[simp] lemma unop_zero [has_zero α] : unop (0 : αᵒᵖ) = 0 := rfl @[simp] lemma op_one [has_one α] : op (1 : α) = 1 := rfl @[simp] lemma unop_one [has_one α] : unop (1 : αᵒᵖ) = 1 := rfl variable {α} @[simp] lemma op_add [has_add α] (x y : α) : op (x + y) = op x + op y := rfl @[simp] lemma unop_add [has_add α] (x y : αᵒᵖ) : unop (x + y) = unop x + unop y := rfl @[simp] lemma op_neg [has_neg α] (x : α) : op (-x) = -op x := rfl @[simp] lemma unop_neg [has_neg α] (x : αᵒᵖ) : unop (-x) = -unop x := rfl @[simp] lemma op_mul [has_mul α] (x y : α) : op (x * y) = op y * op x := rfl @[simp] lemma unop_mul [has_mul α] (x y : αᵒᵖ) : unop (x * y) = unop y * unop x := rfl @[simp] lemma op_inv [has_inv α] (x : α) : op (x⁻¹) = (op x)⁻¹ := rfl @[simp] lemma unop_inv [has_inv α] (x : αᵒᵖ) : unop (x⁻¹) = (unop x)⁻¹ := rfl @[simp] lemma op_sub [add_group α] (x y : α) : op (x - y) = op x - op y := rfl @[simp] lemma unop_sub [add_group α] (x y : αᵒᵖ) : unop (x - y) = unop x - unop y := rfl @[simp] lemma op_smul {R : Type*} [has_scalar R α] (c : R) (a : α) : op (c • a) = c • op a := rfl @[simp] lemma unop_smul {R : Type*} [has_scalar R α] (c : R) (a : αᵒᵖ) : unop (c • a) = c • unop a := rfl end instance [add_semigroup α] : add_semigroup (opposite α) := { add_assoc := λ x y z, unop_injective $ add_assoc (unop x) (unop y) (unop z), .. opposite.has_add α } instance [add_left_cancel_semigroup α] : add_left_cancel_semigroup (opposite α) := { add_left_cancel := λ x y z H, unop_injective $ add_left_cancel $ op_injective H, .. opposite.add_semigroup α } instance [add_right_cancel_semigroup α] : add_right_cancel_semigroup (opposite α) := { add_right_cancel := λ x y z H, unop_injective $ add_right_cancel $ op_injective H, .. opposite.add_semigroup α } instance [add_comm_semigroup α] : add_comm_semigroup (opposite α) := { add_comm := λ x y, unop_injective $ add_comm (unop x) (unop y), .. opposite.add_semigroup α } instance [nontrivial α] : nontrivial (opposite α) := let ⟨x, y, h⟩ := exists_pair_ne α in nontrivial_of_ne (op x) (op y) (op_injective.ne h) section local attribute [semireducible] opposite @[simp] lemma unop_eq_zero_iff {α} [has_zero α] (a : αᵒᵖ) : a.unop = (0 : α) ↔ a = (0 : αᵒᵖ) := iff.refl _ @[simp] lemma op_eq_zero_iff {α} [has_zero α] (a : α) : op a = (0 : αᵒᵖ) ↔ a = (0 : α) := iff.refl _ end lemma unop_ne_zero_iff {α} [has_zero α] (a : αᵒᵖ) : a.unop ≠ (0 : α) ↔ a ≠ (0 : αᵒᵖ) := not_iff_not.mpr $ unop_eq_zero_iff a lemma op_ne_zero_iff {α} [has_zero α] (a : α) : op a ≠ (0 : αᵒᵖ) ↔ a ≠ (0 : α) := not_iff_not.mpr $ op_eq_zero_iff a instance [add_zero_class α] : add_zero_class (opposite α) := { zero_add := λ x, unop_injective $ zero_add $ unop x, add_zero := λ x, unop_injective $ add_zero $ unop x, .. opposite.has_add α, .. opposite.has_zero α } instance [add_monoid α] : add_monoid (opposite α) := { .. opposite.add_semigroup α, .. opposite.add_zero_class α } instance [add_comm_monoid α] : add_comm_monoid (opposite α) := { .. opposite.add_monoid α, .. opposite.add_comm_semigroup α } instance [add_group α] : add_group (opposite α) := { add_left_neg := λ x, unop_injective $ add_left_neg $ unop x, sub_eq_add_neg := λ x y, unop_injective $ sub_eq_add_neg (unop x) (unop y), .. opposite.add_monoid α, .. opposite.has_neg α, .. opposite.has_sub α } instance [add_comm_group α] : add_comm_group (opposite α) := { .. opposite.add_group α, .. opposite.add_comm_monoid α } instance [semigroup α] : semigroup (opposite α) := { mul_assoc := λ x y z, unop_injective $ eq.symm $ mul_assoc (unop z) (unop y) (unop x), .. opposite.has_mul α } instance [right_cancel_semigroup α] : left_cancel_semigroup (opposite α) := { mul_left_cancel := λ x y z H, unop_injective $ mul_right_cancel $ op_injective H, .. opposite.semigroup α } instance [left_cancel_semigroup α] : right_cancel_semigroup (opposite α) := { mul_right_cancel := λ x y z H, unop_injective $ mul_left_cancel $ op_injective H, .. opposite.semigroup α } instance [comm_semigroup α] : comm_semigroup (opposite α) := { mul_comm := λ x y, unop_injective $ mul_comm (unop y) (unop x), .. opposite.semigroup α } section local attribute [semireducible] opposite @[simp] lemma unop_eq_one_iff {α} [has_one α] (a : αᵒᵖ) : a.unop = 1 ↔ a = 1 := iff.refl _ @[simp] lemma op_eq_one_iff {α} [has_one α] (a : α) : op a = 1 ↔ a = 1 := iff.refl _ end instance [mul_one_class α] : mul_one_class (opposite α) := { one_mul := λ x, unop_injective $ mul_one $ unop x, mul_one := λ x, unop_injective $ one_mul $ unop x, .. opposite.has_mul α, .. opposite.has_one α } instance [monoid α] : monoid (opposite α) := { npow := λ n x, op $ monoid.npow n x.unop, npow_zero' := λ x, unop_injective $ monoid.npow_zero' x.unop, npow_succ' := λ n x, unop_injective $ (monoid.npow_succ' n x.unop).trans begin dsimp, induction n with n ih, { rw [monoid.npow_zero', one_mul, mul_one] }, { rw [monoid.npow_succ' n x.unop, mul_assoc, ih], }, end, .. opposite.semigroup α, .. opposite.mul_one_class α } instance [right_cancel_monoid α] : left_cancel_monoid (opposite α) := { .. opposite.left_cancel_semigroup α, ..opposite.monoid α } instance [left_cancel_monoid α] : right_cancel_monoid (opposite α) := { .. opposite.right_cancel_semigroup α, ..opposite.monoid α } instance [cancel_monoid α] : cancel_monoid (opposite α) := { .. opposite.right_cancel_monoid α, ..opposite.left_cancel_monoid α } instance [comm_monoid α] : comm_monoid (opposite α) := { .. opposite.monoid α, .. opposite.comm_semigroup α } instance [cancel_comm_monoid α] : cancel_comm_monoid (opposite α) := { .. opposite.cancel_monoid α, ..opposite.comm_monoid α } instance [div_inv_monoid α] : div_inv_monoid (opposite α) := { gpow := λ n x, op $ div_inv_monoid.gpow n x.unop, gpow_zero' := λ x, unop_injective $ div_inv_monoid.gpow_zero' x.unop, gpow_succ' := λ n x, unop_injective $ (div_inv_monoid.gpow_succ' n x.unop).trans begin dsimp, induction n with n ih, { rw [int.of_nat_zero, div_inv_monoid.gpow_zero', one_mul, mul_one] }, { rw [div_inv_monoid.gpow_succ' n x.unop, mul_assoc, ih], }, end, gpow_neg' := λ z x, unop_injective $ div_inv_monoid.gpow_neg' z x.unop, .. opposite.monoid α, .. opposite.has_inv α } instance [group α] : group (opposite α) := { mul_left_inv := λ x, unop_injective $ mul_inv_self $ unop x, .. opposite.div_inv_monoid α, } instance [comm_group α] : comm_group (opposite α) := { .. opposite.group α, .. opposite.comm_monoid α } instance [distrib α] : distrib (opposite α) := { left_distrib := λ x y z, unop_injective $ add_mul (unop y) (unop z) (unop x), right_distrib := λ x y z, unop_injective $ mul_add (unop z) (unop x) (unop y), .. opposite.has_add α, .. opposite.has_mul α } instance [mul_zero_class α] : mul_zero_class (opposite α) := { zero := 0, mul := (*), zero_mul := λ x, unop_injective $ mul_zero $ unop x, mul_zero := λ x, unop_injective $ zero_mul $ unop x } instance [mul_zero_one_class α] : mul_zero_one_class (opposite α) := { .. opposite.mul_zero_class α, .. opposite.mul_one_class α } instance [semigroup_with_zero α] : semigroup_with_zero (opposite α) := { .. opposite.semigroup α, .. opposite.mul_zero_class α } instance [monoid_with_zero α] : monoid_with_zero (opposite α) := { .. opposite.monoid α, .. opposite.mul_zero_one_class α } instance [non_unital_non_assoc_semiring α] : non_unital_non_assoc_semiring (opposite α) := { .. opposite.add_comm_monoid α, .. opposite.mul_zero_class α, .. opposite.distrib α } instance [non_unital_semiring α] : non_unital_semiring (opposite α) := { .. opposite.semigroup_with_zero α, .. opposite.non_unital_non_assoc_semiring α } instance [non_assoc_semiring α] : non_assoc_semiring (opposite α) := { .. opposite.mul_zero_one_class α, .. opposite.non_unital_non_assoc_semiring α } instance [semiring α] : semiring (opposite α) := { .. opposite.non_unital_semiring α, .. opposite.non_assoc_semiring α, .. opposite.monoid_with_zero α } instance [comm_semiring α] : comm_semiring (opposite α) := { .. opposite.semiring α, .. opposite.comm_semigroup α } instance [ring α] : ring (opposite α) := { .. opposite.add_comm_group α, .. opposite.monoid α, .. opposite.semiring α } instance [comm_ring α] : comm_ring (opposite α) := { .. opposite.ring α, .. opposite.comm_semiring α } instance [has_zero α] [has_mul α] [no_zero_divisors α] : no_zero_divisors (opposite α) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ x y (H : op (_ * _) = op (0:α)), or.cases_on (eq_zero_or_eq_zero_of_mul_eq_zero $ op_injective H) (λ hy, or.inr $ unop_injective $ hy) (λ hx, or.inl $ unop_injective $ hx), } instance [ring α] [domain α] : domain (opposite α) := { .. opposite.no_zero_divisors α, .. opposite.ring α, .. opposite.nontrivial α } instance [comm_ring α] [integral_domain α] : integral_domain (opposite α) := { .. opposite.no_zero_divisors α, .. opposite.comm_ring α, .. opposite.nontrivial α } instance [group_with_zero α] : group_with_zero (opposite α) := { mul_inv_cancel := λ x hx, unop_injective $ inv_mul_cancel $ unop_injective.ne hx, inv_zero := unop_injective inv_zero, .. opposite.monoid_with_zero α, .. opposite.div_inv_monoid α, .. opposite.nontrivial α } instance [division_ring α] : division_ring (opposite α) := { .. opposite.group_with_zero α, .. opposite.ring α } instance [field α] : field (opposite α) := { .. opposite.division_ring α, .. opposite.comm_ring α } instance (R : Type*) [monoid R] [mul_action R α] : mul_action R (opposite α) := { one_smul := λ x, unop_injective $ one_smul R (unop x), mul_smul := λ r₁ r₂ x, unop_injective $ mul_smul r₁ r₂ (unop x), ..opposite.has_scalar α R } instance (R : Type*) [monoid R] [add_monoid α] [distrib_mul_action R α] : distrib_mul_action R (opposite α) := { smul_add := λ r x₁ x₂, unop_injective $ smul_add r (unop x₁) (unop x₂), smul_zero := λ r, unop_injective $ smul_zero r, ..opposite.mul_action α R } instance (R : Type*) [monoid R] [monoid α] [mul_distrib_mul_action R α] : mul_distrib_mul_action R (opposite α) := { smul_mul := λ r x₁ x₂, unop_injective $ smul_mul' r (unop x₂) (unop x₁), smul_one := λ r, unop_injective $ smul_one r, ..opposite.mul_action α R } instance {M N} [has_scalar M N] [has_scalar M α] [has_scalar N α] [is_scalar_tower M N α] : is_scalar_tower M N αᵒᵖ := ⟨λ x y z, unop_injective $ smul_assoc _ _ _⟩ instance {M N} [has_scalar M α] [has_scalar N α] [smul_comm_class M N α] : smul_comm_class M N αᵒᵖ := ⟨λ x y z, unop_injective $ smul_comm _ _ _⟩ /-- Like `has_mul.to_has_scalar`, but multiplies on the right. See also `monoid.to_opposite_mul_action` and `monoid_with_zero.to_opposite_mul_action`. -/ instance _root_.has_mul.to_has_opposite_scalar [has_mul α] : has_scalar (opposite α) α := { smul := λ c x, x * c.unop } @[simp] lemma op_smul_eq_mul [has_mul α] {a a' : α} : op a • a' = a' * a := rfl instance _root_.semigroup.opposite_smul_comm_class [semigroup α] : smul_comm_class (opposite α) α α := { smul_comm := λ x y z, (mul_assoc _ _ _) } instance _root_.semigroup.opposite_smul_comm_class' [semigroup α] : smul_comm_class α (opposite α) α := { smul_comm := λ x y z, (mul_assoc _ _ _).symm } /-- Like `monoid.to_mul_action`, but multiplies on the right. -/ instance _root_.monoid.to_opposite_mul_action [monoid α] : mul_action (opposite α) α := { smul := (•), one_smul := mul_one, mul_smul := λ x y r, (mul_assoc _ _ _).symm } instance _root_.is_scalar_tower.opposite_mid {M N} [monoid N] [has_scalar M N] [smul_comm_class M N N] : is_scalar_tower M Nᵒᵖ N := ⟨λ x y z, mul_smul_comm _ _ _⟩ instance _root_.smul_comm_class.opposite_mid {M N} [monoid N] [has_scalar M N] [is_scalar_tower M N N] : smul_comm_class M Nᵒᵖ N := ⟨λ x y z, by { induction y using opposite.rec, simp [smul_mul_assoc] }⟩ -- The above instance does not create an unwanted diamond, the two paths to -- `mul_action (opposite α) (opposite α)` are defeq. example [monoid α] : monoid.to_mul_action (opposite α) = opposite.mul_action α (opposite α) := rfl /-- `monoid.to_opposite_mul_action` is faithful on cancellative monoids. -/ instance _root_.left_cancel_monoid.to_has_faithful_opposite_scalar [left_cancel_monoid α] : has_faithful_scalar (opposite α) α := ⟨λ x y h, unop_injective $ mul_left_cancel (h 1)⟩ /-- `monoid.to_opposite_mul_action` is faithful on nontrivial cancellative monoids with zero. -/ instance _root_.cancel_monoid_with_zero.to_has_faithful_opposite_scalar [cancel_monoid_with_zero α] [nontrivial α] : has_faithful_scalar (opposite α) α := ⟨λ x y h, unop_injective $ mul_left_cancel₀ one_ne_zero (h 1)⟩ variable {α} lemma semiconj_by.op [has_mul α] {a x y : α} (h : semiconj_by a x y) : semiconj_by (op a) (op y) (op x) := begin dunfold semiconj_by, rw [← op_mul, ← op_mul, h.eq] end lemma semiconj_by.unop [has_mul α] {a x y : αᵒᵖ} (h : semiconj_by a x y) : semiconj_by (unop a) (unop y) (unop x) := begin dunfold semiconj_by, rw [← unop_mul, ← unop_mul, h.eq] end @[simp] lemma semiconj_by_op [has_mul α] {a x y : α} : semiconj_by (op a) (op y) (op x) ↔ semiconj_by a x y := begin split, { intro h, rw [← unop_op a, ← unop_op x, ← unop_op y], exact semiconj_by.unop h }, { intro h, exact semiconj_by.op h } end @[simp] lemma semiconj_by_unop [has_mul α] {a x y : αᵒᵖ} : semiconj_by (unop a) (unop y) (unop x) ↔ semiconj_by a x y := by conv_rhs { rw [← op_unop a, ← op_unop x, ← op_unop y, semiconj_by_op] } lemma commute.op [has_mul α] {x y : α} (h : commute x y) : commute (op x) (op y) := begin dunfold commute at h ⊢, exact semiconj_by.op h end lemma commute.unop [has_mul α] {x y : αᵒᵖ} (h : commute x y) : commute (unop x) (unop y) := begin dunfold commute at h ⊢, exact semiconj_by.unop h end @[simp] lemma commute_op [has_mul α] {x y : α} : commute (op x) (op y) ↔ commute x y := begin dunfold commute, rw semiconj_by_op end @[simp] lemma commute_unop [has_mul α] {x y : αᵒᵖ} : commute (unop x) (unop y) ↔ commute x y := begin dunfold commute, rw semiconj_by_unop end /-- The function `op` is an additive equivalence. -/ def op_add_equiv [has_add α] : α ≃+ αᵒᵖ := { map_add' := λ a b, rfl, .. equiv_to_opposite } @[simp] lemma coe_op_add_equiv [has_add α] : (op_add_equiv : α → αᵒᵖ) = op := rfl @[simp] lemma coe_op_add_equiv_symm [has_add α] : (op_add_equiv.symm : αᵒᵖ → α) = unop := rfl @[simp] lemma op_add_equiv_to_equiv [has_add α] : (op_add_equiv : α ≃+ αᵒᵖ).to_equiv = equiv_to_opposite := rfl end opposite open opposite /-- Inversion on a group is a `mul_equiv` to the opposite group. When `G` is commutative, there is `mul_equiv.inv`. -/ @[simps {fully_applied := ff}] def mul_equiv.inv' (G : Type*) [group G] : G ≃* Gᵒᵖ := { to_fun := opposite.op ∘ has_inv.inv, inv_fun := has_inv.inv ∘ opposite.unop, map_mul' := λ x y, unop_injective $ mul_inv_rev x y, ..(equiv.inv G).trans equiv_to_opposite} /-- A monoid homomorphism `f : R →* S` such that `f x` commutes with `f y` for all `x, y` defines a monoid homomorphism to `Sᵒᵖ`. -/ @[simps {fully_applied := ff}] def monoid_hom.to_opposite {R S : Type*} [mul_one_class R] [mul_one_class S] (f : R →* S) (hf : ∀ x y, commute (f x) (f y)) : R →* Sᵒᵖ := { to_fun := opposite.op ∘ f, map_one' := congr_arg op f.map_one, map_mul' := λ x y, by simp [(hf x y).eq] } /-- A ring homomorphism `f : R →+* S` such that `f x` commutes with `f y` for all `x, y` defines a ring homomorphism to `Sᵒᵖ`. -/ @[simps {fully_applied := ff}] def ring_hom.to_opposite {R S : Type*} [semiring R] [semiring S] (f : R →+* S) (hf : ∀ x y, commute (f x) (f y)) : R →+* Sᵒᵖ := { to_fun := opposite.op ∘ f, .. ((opposite.op_add_equiv : S ≃+ Sᵒᵖ).to_add_monoid_hom.comp ↑f : R →+ Sᵒᵖ), .. f.to_monoid_hom.to_opposite hf } /-- The units of the opposites are equivalent to the opposites of the units. -/ def units.op_equiv {R} [monoid R] : units Rᵒᵖ ≃* (units R)ᵒᵖ := { to_fun := λ u, op ⟨unop u, unop ↑(u⁻¹), op_injective u.4, op_injective u.3⟩, inv_fun := opposite.rec $ λ u, ⟨op ↑(u), op ↑(u⁻¹), unop_injective $ u.4, unop_injective u.3⟩, map_mul' := λ x y, unop_injective $ units.ext $ rfl, left_inv := λ x, units.ext $ rfl, right_inv := λ x, unop_injective $ units.ext $ rfl } @[simp] lemma units.coe_unop_op_equiv {R} [monoid R] (u : units Rᵒᵖ) : ((units.op_equiv u).unop : R) = unop (u : Rᵒᵖ) := rfl @[simp] lemma units.coe_op_equiv_symm {R} [monoid R] (u : (units R)ᵒᵖ) : (units.op_equiv.symm u : Rᵒᵖ) = op (u.unop : R) := rfl /-- A hom `α →* β` can equivalently be viewed as a hom `αᵒᵖ →* βᵒᵖ`. This is the action of the (fully faithful) `ᵒᵖ`-functor on morphisms. -/ @[simps] def monoid_hom.op {α β} [mul_one_class α] [mul_one_class β] : (α →* β) ≃ (αᵒᵖ →* βᵒᵖ) := { to_fun := λ f, { to_fun := op ∘ f ∘ unop, map_one' := unop_injective f.map_one, map_mul' := λ x y, unop_injective (f.map_mul y.unop x.unop) }, inv_fun := λ f, { to_fun := unop ∘ f ∘ op, map_one' := congr_arg unop f.map_one, map_mul' := λ x y, congr_arg unop (f.map_mul (op y) (op x)) }, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, refl } } /-- The 'unopposite' of a monoid hom `αᵒᵖ →* βᵒᵖ`. Inverse to `monoid_hom.op`. -/ @[simp] def monoid_hom.unop {α β} [mul_one_class α] [mul_one_class β] : (αᵒᵖ →* βᵒᵖ) ≃ (α →* β) := monoid_hom.op.symm /-- A hom `α →+ β` can equivalently be viewed as a hom `αᵒᵖ →+ βᵒᵖ`. This is the action of the (fully faithful) `ᵒᵖ`-functor on morphisms. -/ @[simps] def add_monoid_hom.op {α β} [add_zero_class α] [add_zero_class β] : (α →+ β) ≃ (αᵒᵖ →+ βᵒᵖ) := { to_fun := λ f, { to_fun := op ∘ f ∘ unop, map_zero' := unop_injective f.map_zero, map_add' := λ x y, unop_injective (f.map_add x.unop y.unop) }, inv_fun := λ f, { to_fun := unop ∘ f ∘ op, map_zero' := congr_arg unop f.map_zero, map_add' := λ x y, congr_arg unop (f.map_add (op x) (op y)) }, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, refl } } /-- The 'unopposite' of an additive monoid hom `αᵒᵖ →+ βᵒᵖ`. Inverse to `add_monoid_hom.op`. -/ @[simp] def add_monoid_hom.unop {α β} [add_zero_class α] [add_zero_class β] : (αᵒᵖ →+ βᵒᵖ) ≃ (α →+ β) := add_monoid_hom.op.symm /-- A ring hom `α →+* β` can equivalently be viewed as a ring hom `αᵒᵖ →+* βᵒᵖ`. This is the action of the (fully faithful) `ᵒᵖ`-functor on morphisms. -/ @[simps] def ring_hom.op {α β} [non_assoc_semiring α] [non_assoc_semiring β] : (α →+* β) ≃ (αᵒᵖ →+* βᵒᵖ) := { to_fun := λ f, { ..f.to_add_monoid_hom.op, ..f.to_monoid_hom.op }, inv_fun := λ f, { ..f.to_add_monoid_hom.unop, ..f.to_monoid_hom.unop }, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, refl } } /-- The 'unopposite' of a ring hom `αᵒᵖ →+* βᵒᵖ`. Inverse to `ring_hom.op`. -/ @[simp] def ring_hom.unop {α β} [non_assoc_semiring α] [non_assoc_semiring β] : (αᵒᵖ →+* βᵒᵖ) ≃ (α →+* β) := ring_hom.op.symm /-- A iso `α ≃+ β` can equivalently be viewed as an iso `αᵒᵖ ≃+ βᵒᵖ`. -/ @[simps] def add_equiv.op {α β} [has_add α] [has_add β] : (α ≃+ β) ≃ (αᵒᵖ ≃+ βᵒᵖ) := { to_fun := λ f, op_add_equiv.symm.trans (f.trans op_add_equiv), inv_fun := λ f, op_add_equiv.trans (f.trans op_add_equiv.symm), left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, refl } } /-- The 'unopposite' of an iso `αᵒᵖ ≃+ βᵒᵖ`. Inverse to `add_equiv.op`. -/ @[simp] def add_equiv.unop {α β} [has_add α] [has_add β] : (αᵒᵖ ≃+ βᵒᵖ) ≃ (α ≃+ β) := add_equiv.op.symm /-- A iso `α ≃* β` can equivalently be viewed as an iso `αᵒᵖ ≃+ βᵒᵖ`. -/ @[simps] def mul_equiv.op {α β} [has_mul α] [has_mul β] : (α ≃* β) ≃ (αᵒᵖ ≃* βᵒᵖ) := { to_fun := λ f, { to_fun := op ∘ f ∘ unop, inv_fun := op ∘ f.symm ∘ unop, left_inv := λ x, unop_injective (f.symm_apply_apply x.unop), right_inv := λ x, unop_injective (f.apply_symm_apply x.unop), map_mul' := λ x y, unop_injective (f.map_mul y.unop x.unop) }, inv_fun := λ f, { to_fun := unop ∘ f ∘ op, inv_fun := unop ∘ f.symm ∘ op, left_inv := λ x, op_injective (f.symm_apply_apply (op x)), right_inv := λ x, op_injective (f.apply_symm_apply (op x)), map_mul' := λ x y, congr_arg unop (f.map_mul (op y) (op x)) }, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, refl } } /-- The 'unopposite' of an iso `αᵒᵖ ≃* βᵒᵖ`. Inverse to `mul_equiv.op`. -/ @[simp] def mul_equiv.unop {α β} [has_mul α] [has_mul β] : (αᵒᵖ ≃* βᵒᵖ) ≃ (α ≃* β) := mul_equiv.op.symm section ext /-- This ext lemma change equalities on `αᵒᵖ →+ β` to equalities on `α →+ β`. This is useful because there are often ext lemmas for specific `α`s that will apply to an equality of `α →+ β` such as `finsupp.add_hom_ext'`. -/ @[ext] lemma add_monoid_hom.op_ext {α β} [add_zero_class α] [add_zero_class β] (f g : αᵒᵖ →+ β) (h : f.comp (op_add_equiv : α ≃+ αᵒᵖ).to_add_monoid_hom = g.comp (op_add_equiv : α ≃+ αᵒᵖ).to_add_monoid_hom) : f = g := add_monoid_hom.ext $ λ x, (add_monoid_hom.congr_fun h : _) x.unop end ext
52303e4ffc7ff06de36a3ad9ce889f9c88d0df4f
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/ring_theory/adjoin/basic.lean
d096a9484f91a7bc231a23030aa956b1dc6cf218
[ "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
9,233
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.algebra.subalgebra import linear_algebra.prod /-! # Adjoining elements to form subalgebras This file develops the basic theory of subalgebras of an R-algebra generated by a set of elements. A basic interface for `adjoin` is set up, and various results about finitely-generated subalgebras and submodules are proved. ## Definitions * `fg (S : subalgebra R A)` : A predicate saying that the subalgebra is finitely-generated as an A-algebra ## Tags adjoin, algebra, finitely-generated algebra -/ universes u v w open_locale pointwise open submodule subsemiring variables {R : Type u} {A : Type v} {B : Type w} namespace algebra section semiring variables [comm_semiring R] [semiring A] [semiring B] variables [algebra R A] [algebra R B] {s t : set A} theorem subset_adjoin : s ⊆ adjoin R s := algebra.gc.le_u_l s theorem adjoin_le {S : subalgebra R A} (H : s ⊆ S) : adjoin R s ≤ S := algebra.gc.l_le H theorem adjoin_le_iff {S : subalgebra R A} : adjoin R s ≤ S ↔ s ⊆ S:= algebra.gc _ _ theorem adjoin_mono (H : s ⊆ t) : adjoin R s ≤ adjoin R t := algebra.gc.monotone_l H theorem adjoin_eq_of_le (S : subalgebra R A) (h₁ : s ⊆ S) (h₂ : S ≤ adjoin R s) : adjoin R s = S := le_antisymm (adjoin_le h₁) h₂ theorem adjoin_eq (S : subalgebra R A) : adjoin R ↑S = S := adjoin_eq_of_le _ (set.subset.refl _) subset_adjoin @[elab_as_eliminator] theorem adjoin_induction {p : A → Prop} {x : A} (h : x ∈ adjoin R s) (Hs : ∀ x ∈ s, p x) (Halg : ∀ r, p (algebra_map R A r)) (Hadd : ∀ x y, p x → p y → p (x + y)) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := let S : subalgebra R A := { carrier := p, mul_mem' := Hmul, add_mem' := Hadd, algebra_map_mem' := Halg } in adjoin_le (show s ≤ S, from Hs) h lemma adjoin_union (s t : set A) : adjoin R (s ∪ t) = adjoin R s ⊔ adjoin R t := (algebra.gc : galois_connection _ (coe : subalgebra R A → set A)).l_sup variables (R A) @[simp] theorem adjoin_empty : adjoin R (∅ : set A) = ⊥ := show adjoin R ⊥ = ⊥, by { apply galois_connection.l_bot, exact algebra.gc } @[simp] theorem adjoin_univ : adjoin R (set.univ : set A) = ⊤ := eq_top_iff.2 $ λ x, subset_adjoin $ set.mem_univ _ variables (R) {A} (s) theorem adjoin_eq_span : (adjoin R s).to_submodule = span R (submonoid.closure s) := begin apply le_antisymm, { intros r hr, rcases subsemiring.mem_closure_iff_exists_list.1 hr with ⟨L, HL, rfl⟩, clear hr, induction L with hd tl ih, { exact zero_mem _ }, rw list.forall_mem_cons at HL, rw [list.map_cons, list.sum_cons], refine submodule.add_mem _ _ (ih HL.2), replace HL := HL.1, clear ih tl, suffices : ∃ z r (hr : r ∈ submonoid.closure s), has_scalar.smul z r = list.prod hd, { rcases this with ⟨z, r, hr, hzr⟩, rw ← hzr, exact smul_mem _ _ (subset_span hr) }, induction hd with hd tl ih, { exact ⟨1, 1, (submonoid.closure s).one_mem', one_smul _ _⟩ }, rw list.forall_mem_cons at HL, rcases (ih HL.2) with ⟨z, r, hr, hzr⟩, rw [list.prod_cons, ← hzr], rcases HL.1 with ⟨hd, rfl⟩ | hs, { refine ⟨hd * z, r, hr, _⟩, rw [algebra.smul_def, algebra.smul_def, (algebra_map _ _).map_mul, _root_.mul_assoc] }, { exact ⟨z, hd * r, submonoid.mul_mem _ (submonoid.subset_closure hs) hr, (mul_smul_comm _ _ _).symm⟩ } }, refine span_le.2 _, change submonoid.closure s ≤ (adjoin R s).to_subsemiring.to_submonoid, exact submonoid.closure_le.2 subset_adjoin end lemma span_le_adjoin (s : set A) : span R s ≤ (adjoin R s).to_submodule := span_le.mpr subset_adjoin lemma adjoin_to_submodule_le {s : set A} {t : submodule R A} : (adjoin R s).to_submodule ≤ t ↔ ↑(submonoid.closure s) ⊆ (t : set A) := by rw [adjoin_eq_span, span_le] lemma adjoin_eq_span_of_subset {s : set A} (hs : ↑(submonoid.closure s) ⊆ (span R s : set A)) : (adjoin R s).to_submodule = span R s := le_antisymm ((adjoin_to_submodule_le R).mpr hs) (span_le_adjoin R s) lemma adjoin_image (f : A →ₐ[R] B) (s : set A) : adjoin R (f '' s) = (adjoin R s).map f := le_antisymm (adjoin_le $ set.image_subset _ subset_adjoin) $ subalgebra.map_le.2 $ adjoin_le $ set.image_subset_iff.1 subset_adjoin @[simp] lemma adjoin_insert_adjoin (x : A) : adjoin R (insert x ↑(adjoin R s)) = adjoin R (insert x s) := le_antisymm (adjoin_le (set.insert_subset.mpr ⟨subset_adjoin (set.mem_insert _ _), adjoin_mono (set.subset_insert _ _)⟩)) (algebra.adjoin_mono (set.insert_subset_insert algebra.subset_adjoin)) lemma adjoin_prod_le (s : set A) (t : set B) : adjoin R (set.prod s t) ≤ (adjoin R s).prod (adjoin R t) := adjoin_le $ set.prod_mono subset_adjoin subset_adjoin lemma mem_adjoin_of_map_mul {s} {x : A} {f : A →ₗ[R] B} (hf : ∀ a₁ a₂, f(a₁ * a₂) = f a₁ * f a₂) (h : x ∈ adjoin R s) : f x ∈ adjoin R (f '' (s ∪ {1})) := begin refine @adjoin_induction R A _ _ _ _ (λ a, f a ∈ adjoin R (f '' (s ∪ {1}))) x h (λ a ha, subset_adjoin ⟨a, ⟨set.subset_union_left _ _ ha, rfl⟩⟩) (λ r, _) (λ y z hy hz, by simpa [hy, hz] using subalgebra.add_mem _ hy hz) (λ y z hy hz, by simpa [hy, hz, hf y z] using subalgebra.mul_mem _ hy hz), have : f 1 ∈ adjoin R (f '' (s ∪ {1})) := subset_adjoin ⟨1, ⟨set.subset_union_right _ _ $ set.mem_singleton 1, rfl⟩⟩, replace this := subalgebra.smul_mem (adjoin R (f '' (s ∪ {1}))) this r, convert this, rw algebra_map_eq_smul_one, exact f.map_smul _ _ end lemma adjoin_inl_union_inr_eq_prod (s) (t) : adjoin R (linear_map.inl R A B '' (s ∪ {1}) ∪ linear_map.inr R A B '' (t ∪ {1})) = (adjoin R s).prod (adjoin R t) := begin apply le_antisymm, { simp only [adjoin_le_iff, set.insert_subset, subalgebra.zero_mem, subalgebra.one_mem, subset_adjoin, -- the rest comes from `squeeze_simp` set.union_subset_iff, linear_map.coe_inl, set.mk_preimage_prod_right, set.image_subset_iff, set_like.mem_coe, set.mk_preimage_prod_left, linear_map.coe_inr, and_self, set.union_singleton, subalgebra.coe_prod] }, { rintro ⟨a, b⟩ ⟨ha, hb⟩, let P := adjoin R (linear_map.inl R A B '' (s ∪ {1}) ∪ linear_map.inr R A B '' (t ∪ {1})), have Ha : (a, (0 : B)) ∈ adjoin R ((linear_map.inl R A B) '' (s ∪ {1})) := mem_adjoin_of_map_mul R (linear_map.inl_map_mul) ha, have Hb : ((0 : A), b) ∈ adjoin R ((linear_map.inr R A B) '' (t ∪ {1})) := mem_adjoin_of_map_mul R (linear_map.inr_map_mul) hb, replace Ha : (a, (0 : B)) ∈ P := adjoin_mono (set.subset_union_left _ _) Ha, replace Hb : ((0 : A), b) ∈ P := adjoin_mono (set.subset_union_right _ _) Hb, simpa using subalgebra.add_mem _ Ha Hb } end end semiring section comm_semiring variables [comm_semiring R] [comm_semiring A] variables [algebra R A] {s t : set A} variables (R s t) theorem adjoin_union_eq_under : adjoin R (s ∪ t) = (adjoin R s).under (adjoin (adjoin R s) t) := le_antisymm (closure_mono $ set.union_subset (set.range_subset_iff.2 $ λ r, or.inl ⟨algebra_map R (adjoin R s) r, rfl⟩) (set.union_subset_union_left _ $ λ x hxs, ⟨⟨_, subset_adjoin hxs⟩, rfl⟩)) (closure_le.2 $ set.union_subset (set.range_subset_iff.2 $ λ x, adjoin_mono (set.subset_union_left _ _) x.2) (set.subset.trans (set.subset_union_right _ _) subset_adjoin)) lemma adjoin_singleton_one : adjoin R ({1} : set A) = ⊥ := eq_bot_iff.2 $ adjoin_le $ set.singleton_subset_iff.2 $ set_like.mem_coe.2 $ one_mem _ theorem adjoin_union_coe_submodule : (adjoin R (s ∪ t)).to_submodule = (adjoin R s).to_submodule * (adjoin R t).to_submodule := begin rw [adjoin_eq_span, adjoin_eq_span, adjoin_eq_span, span_mul_span], congr' 1 with z, simp [submonoid.closure_union, submonoid.mem_sup, set.mem_mul] end end comm_semiring section ring variables [comm_ring R] [ring A] variables [algebra R A] {s t : set A} variables {R s t} theorem adjoin_int (s : set R) : adjoin ℤ s = subalgebra_of_subring (subring.closure s) := le_antisymm (adjoin_le subring.subset_closure) (subring.closure_le.2 subset_adjoin : subring.closure s ≤ (adjoin ℤ s).to_subring) theorem mem_adjoin_iff {s : set A} {x : A} : x ∈ adjoin R s ↔ x ∈ subring.closure (set.range (algebra_map R A) ∪ s) := ⟨λ hx, subsemiring.closure_induction hx subring.subset_closure (subring.zero_mem _) (subring.one_mem _) (λ _ _, subring.add_mem _) ( λ _ _, subring.mul_mem _), suffices subring.closure (set.range ⇑(algebra_map R A) ∪ s) ≤ (adjoin R s).to_subring, from @this x, subring.closure_le.2 subsemiring.subset_closure⟩ theorem adjoin_eq_ring_closure (s : set A) : (adjoin R s).to_subring = subring.closure (set.range (algebra_map R A) ∪ s) := subring.ext $ λ x, mem_adjoin_iff end ring end algebra open algebra subalgebra namespace alg_hom variables [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] lemma map_adjoin (φ : A →ₐ[R] B) (s : set A) : (adjoin R s).map φ = adjoin R (φ '' s) := (adjoin_image _ _ _).symm end alg_hom
832327be2cff26391a15c4a509f81c4615b474ff
957a80ea22c5abb4f4670b250d55534d9db99108
/library/init/propext.lean
bb6fde2f5645a42675c2886f157b2b77e3573de8
[ "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
1,387
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.logic constant propext {a b : Prop} : (a ↔ b) → a = b /- Additional congruence lemmas. -/ universes u v lemma forall_congr_eq {a : Sort u} {p q : a → Prop} (h : ∀ x, p x = q x) : (∀ x, p x) = ∀ x, q x := propext (forall_congr (λ a, (h a).to_iff)) lemma imp_congr_eq {a b c d : Prop} (h₁ : a = c) (h₂ : b = d) : (a → b) = (c → d) := propext (imp_congr h₁.to_iff h₂.to_iff) lemma imp_congr_ctx_eq {a b c d : Prop} (h₁ : a = c) (h₂ : c → (b = d)) : (a → b) = (c → d) := propext (imp_congr_ctx h₁.to_iff (λ hc, (h₂ hc).to_iff)) lemma eq_true_intro {a : Prop} (h : a) : a = true := propext (iff_true_intro h) lemma eq_false_intro {a : Prop} (h : ¬a) : a = false := propext (iff_false_intro h) theorem iff.to_eq {a b : Prop} (h : a ↔ b) : a = b := propext h theorem iff_eq_eq {a b : Prop} : (a ↔ b) = (a = b) := propext (iff.intro (assume h, iff.to_eq h) (assume h, h.to_iff)) lemma eq_false {a : Prop} : (a = false) = (¬ a) := have (a ↔ false) = (¬ a), from propext (iff_false a), eq.subst (@iff_eq_eq a false) this lemma eq_true {a : Prop} : (a = true) = a := have (a ↔ true) = a, from propext (iff_true a), eq.subst (@iff_eq_eq a true) this
06b4e71c1b0b8a51bbed8a2cf66fa8a9bb6a764d
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/print_ax3.lean
6101b7d62dcf8095c256d45e2f0f97f6b2532e5b
[ "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
207
lean
theorem foo1 : 0 = 0 := rfl theorem foo2 : 0 = 0 := rfl theorem foo3 : 0 = 0 := foo2 definition foo4 : 0 = 0 := eq.trans foo2 foo1 print axioms foo4 print "------" print axioms print "------" print foo3
652f485dee2d8db03395d3a692c2a36757779420
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/tests/lean/interactive/run.lean
422cb0360c55129c3af6158815462777aec57117
[ "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
7,263
lean
import Lean.Data.Lsp import Lean.Widget open Lean open Lean.Lsp open Lean.JsonRpc namespace Client /- Client-side types for showing interactive goals. -/ structure SubexprInfo where subexprPos : String highlightColor? : Option String deriving FromJson, Repr structure Hyp where type : Widget.TaggedText SubexprInfo names : Array String isInserted?: Option Bool isRemoved?: Option Bool deriving FromJson, Repr structure InteractiveGoal where type : Widget.TaggedText SubexprInfo isInserted?: Option Bool := none isRemoved?: Option Bool := none hyps : Array Hyp deriving FromJson, Repr structure InteractiveGoals where goals : Array InteractiveGoal deriving FromJson, Repr end Client def word : Parsec String := Parsec.many1Chars <| Parsec.digit <|> Parsec.asciiLetter <|> Parsec.pchar '_' def ident : Parsec Name := do let head ← word let xs ← Parsec.many1 (Parsec.pchar '.' *> word) return xs.foldl Name.mkStr $ head partial def main (args : List String) : IO Unit := do let uri := s!"file://{args.head!}" Ipc.runWith (←IO.appPath) #["--server"] do let capabilities := { textDocument? := some { completion? := some { completionItem? := some { insertReplaceSupport? := true } } } } Ipc.writeRequest ⟨0, "initialize", { capabilities : InitializeParams }⟩ let _ ← Ipc.readResponseAs 0 InitializeResult Ipc.writeNotification ⟨"initialized", InitializedParams.mk⟩ let text ← IO.FS.readFile args.head! Ipc.writeNotification ⟨"textDocument/didOpen", { textDocument := { uri := uri, languageId := "lean", version := 1, text := text } : DidOpenTextDocumentParams }⟩ let _ ← Ipc.collectDiagnostics 1 uri 1 let mut lineNo := 0 let mut lastActualLineNo := 0 let mut versionNo : Nat := 2 let mut requestNo : Nat := 2 let mut rpcSessionId : Option UInt64 := none for line in text.splitOn "\n" do match line.splitOn "--" with | [ws, directive] => let line ← match directive.front with | 'v' => pure <| lineNo + 1 -- TODO: support subsequent 'v'... or not | '^' => pure <| lastActualLineNo | _ => lastActualLineNo := lineNo lineNo := lineNo + 1 continue let directive := directive.drop 1 let colon := directive.posOf ':' let method := directive.extract 0 colon |>.trim -- TODO: correctly compute in presence of Unicode let column := ws.endPos + "--" let pos : Lsp.Position := { line := line, character := column.byteIdx } let params := if colon < directive.endPos then directive.extract (colon + ':') directive.endPos |>.trim else "{}" match method with | "insert" => let params : DidChangeTextDocumentParams := { textDocument := { uri := uri version? := versionNo } contentChanges := #[TextDocumentContentChangeEvent.rangeChange { start := pos «end» := { pos with character := pos.character + params.endPos.byteIdx } } params] } let params := toJson params IO.eprintln params Ipc.writeNotification ⟨"textDocument/didChange", params⟩ -- We don't want to wait for changes to be processed so we can test concurrency --let _ ← Ipc.collectDiagnostics requestNo uri versionNo requestNo := requestNo + 1 versionNo := versionNo + 1 | "collectDiagnostics" => let diags ← Ipc.collectDiagnostics requestNo uri (versionNo - 1) for diag in diags do IO.eprintln (toJson diag.param) requestNo := requestNo + 1 | "goals" => if rpcSessionId.isNone then Ipc.writeRequest ⟨requestNo, "$/lean/rpc/connect", RpcConnectParams.mk uri⟩ let r ← Ipc.readResponseAs requestNo RpcConnected rpcSessionId := some r.result.sessionId requestNo := requestNo + 1 let params : Lsp.PlainGoalParams := { textDocument := { uri } position := pos, } let ps : RpcCallParams := { params := toJson params textDocument := { uri } position := pos, sessionId := rpcSessionId.get!, method := `Lean.Widget.getInteractiveGoals } Ipc.writeRequest ⟨requestNo, "$/lean/rpc/call", ps⟩ let response ← Ipc.readResponseAs requestNo Client.InteractiveGoals requestNo := requestNo + 1 IO.eprintln (repr response.result) IO.eprintln "" | "widgets" => if rpcSessionId.isNone then Ipc.writeRequest ⟨requestNo, "$/lean/rpc/connect", RpcConnectParams.mk uri⟩ let r ← Ipc.readResponseAs requestNo RpcConnected rpcSessionId := some r.result.sessionId requestNo := requestNo + 1 let ps : RpcCallParams := { textDocument := {uri := uri}, position := pos, sessionId := rpcSessionId.get!, method := `Lean.Widget.getWidgets, params := toJson pos, } Ipc.writeRequest ⟨requestNo, "$/lean/rpc/call", ps⟩ let response ← Ipc.readResponseAs requestNo Lean.Widget.GetWidgetsResponse requestNo := requestNo + 1 IO.eprintln (toJson response.result) for w in response.result.widgets do let params : Lean.Widget.GetWidgetSourceParams := { pos, hash := w.javascriptHash } let ps : RpcCallParams := { ps with method := `Lean.Widget.getWidgetSource, params := toJson params, } Ipc.writeRequest ⟨requestNo, "$/lean/rpc/call", ps⟩ let resp ← Ipc.readResponseAs requestNo Lean.Widget.WidgetSource IO.eprintln (toJson resp.result) requestNo := requestNo + 1 | _ => let Except.ok params ← pure <| Json.parse params | throw <| IO.userError s!"failed to parse {params}" let params := params.setObjVal! "textDocument" (toJson { uri := uri : TextDocumentIdentifier }) -- TODO: correctly compute in presence of Unicode let params := params.setObjVal! "position" (toJson pos) IO.eprintln params Ipc.writeRequest ⟨requestNo, method, params⟩ let rec readFirstResponse := do match ← Ipc.readMessage with | Message.response id r => assert! id == requestNo return r | Message.notification .. => readFirstResponse | msg => throw <| IO.userError s!"unexpected message {toJson msg}" let resp ← readFirstResponse IO.eprintln resp requestNo := requestNo + 1 | _ => lastActualLineNo := lineNo lineNo := lineNo + 1 Ipc.writeRequest ⟨requestNo, "shutdown", Json.null⟩ let shutResp ← Ipc.readResponseAs requestNo Json assert! shutResp.result.isNull Ipc.writeNotification ⟨"exit", Json.null⟩ discard <| Ipc.waitForExit
6cfd342c2ddfc1589ce60f6f22b24ba3c87b6f87
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/src/Lean/Data/Name.lean
c55b14082e033df234dd85f6075e8bfd3d9a341d
[ "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
5,146
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ import Std.Data.HashSet import Std.Data.RBMap import Std.Data.RBTree namespace Lean instance : Coe String Name := ⟨Name.mkSimple⟩ namespace Name @[export lean_name_hash] def hashEx : Name → USize := Name.hash def getPrefix : Name → Name | anonymous => anonymous | str p s _ => p | num p s _ => p def getRoot : Name → Name | anonymous => anonymous | n@(str anonymous _ _) => n | n@(num anonymous _ _) => n | str n _ _ => getRoot n | num n _ _ => getRoot n def getString! : Name → String | str _ s _ => s | _ => unreachable! def getNumParts : Name → Nat | anonymous => 0 | str p _ _ => getNumParts p + 1 | num p _ _ => getNumParts p + 1 def updatePrefix : Name → Name → Name | anonymous, newP => anonymous | str p s _, newP => Name.mkStr newP s | num p s _, newP => Name.mkNum newP s def components' : Name → List Name | anonymous => [] | str n s _ => Name.mkStr anonymous s :: components' n | num n v _ => Name.mkNum anonymous v :: components' n def components (n : Name) : List Name := n.components'.reverse def eqStr : Name → String → Bool | str anonymous s _, s' => s == s' | _, _ => false def isPrefixOf : Name → Name → Bool | p, anonymous => p == anonymous | p, n@(num p' _ _) => p == n || isPrefixOf p p' | p, n@(str p' _ _) => p == n || isPrefixOf p p' def isSuffixOf : Name → Name → Bool | anonymous, _ => true | str p₁ s₁ _, str p₂ s₂ _ => s₁ == s₂ && isSuffixOf p₁ p₂ | num p₁ n₁ _, num p₂ n₂ _ => n₁ == n₂ && isSuffixOf p₁ p₂ | _, _ => false def lt : Name → Name → Bool | anonymous, anonymous => false | anonymous, _ => true | num p₁ i₁ _, num p₂ i₂ _ => lt p₁ p₂ || (p₁ == p₂ && i₁ < i₂) | num _ _ _, str _ _ _ => true | str p₁ n₁ _, str p₂ n₂ _ => lt p₁ p₂ || (p₁ == p₂ && n₁ < n₂) | _, _ => false def quickLtAux : Name → Name → Bool | anonymous, anonymous => false | anonymous, _ => true | num n v _, num n' v' _ => v < v' || (v = v' && n.quickLtAux n') | num _ _ _, str _ _ _ => true | str n s _, str n' s' _ => s < s' || (s = s' && n.quickLtAux n') | _, _ => false def quickLt (n₁ n₂ : Name) : Bool := if n₁.hash < n₂.hash then true else if n₁.hash > n₂.hash then false else quickLtAux n₁ n₂ /- Alternative HasLt instance. -/ @[inline] protected def hasLtQuick : HasLess Name := ⟨fun a b => Name.quickLt a b = true⟩ @[inline] instance : DecidableRel (@Less Name Name.hasLtQuick) := inferInstanceAs (DecidableRel (fun a b => Name.quickLt a b = true)) /- The frontend does not allow user declarations to start with `_` in any of its parts. We use name parts starting with `_` internally to create auxiliary names (e.g., `_private`). -/ def isInternal : Name → Bool | str p s _ => s.get 0 == '_' || isInternal p | num p _ _ => isInternal p | _ => false def isAtomic : Name → Bool | anonymous => true | str anonymous _ _ => true | num anonymous _ _ => true | _ => false def isAnonymous : Name → Bool | anonymous => true | _ => false def isStr : Name → Bool | str .. => true | _ => false def isNum : Name → Bool | num .. => true | _ => false end Name open Std (RBMap RBTree mkRBMap mkRBTree) def NameMap (α : Type) := Std.RBMap Name α Name.quickLt @[inline] def mkNameMap (α : Type) : NameMap α := Std.mkRBMap Name α Name.quickLt namespace NameMap variable {α : Type} instance (α : Type) : EmptyCollection (NameMap α) := ⟨mkNameMap α⟩ instance (α : Type) : Inhabited (NameMap α) where default := {} def insert (m : NameMap α) (n : Name) (a : α) := Std.RBMap.insert m n a def contains (m : NameMap α) (n : Name) : Bool := Std.RBMap.contains m n @[inline] def find? (m : NameMap α) (n : Name) : Option α := Std.RBMap.find? m n end NameMap def NameSet := RBTree Name Name.quickLt namespace NameSet def empty : NameSet := mkRBTree Name Name.quickLt instance : EmptyCollection NameSet := ⟨empty⟩ instance : Inhabited NameSet := ⟨{}⟩ def insert (s : NameSet) (n : Name) : NameSet := Std.RBTree.insert s n def contains (s : NameSet) (n : Name) : Bool := Std.RBMap.contains s n end NameSet def NameHashSet := Std.HashSet Name namespace NameHashSet @[inline] def empty : NameHashSet := Std.HashSet.empty instance : EmptyCollection NameHashSet := ⟨empty⟩ instance : Inhabited NameHashSet := ⟨{}⟩ def insert (s : NameHashSet) (n : Name) := Std.HashSet.insert s n def contains (s : NameHashSet) (n : Name) : Bool := Std.HashSet.contains s n end NameHashSet end Lean open Lean def String.toName (s : String) : Name := let ps := s.splitOn "."; ps.foldl (fun n p => Name.mkStr n p.trim) Name.anonymous
d4eabfcfbbd915dd391e4858df139b6e3793c356
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Compiler/IR/LiveVars.lean
e4c707943b5350315e6291ac4920396d3d9686d1
[ "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
6,905
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 import Lean.Compiler.IR.FreeVars namespace Lean.IR /-! Remark: in the paper "Counting Immutable Beans" the concepts of free and live variables coincide because the paper does *not* consider join points. For example, consider the function body `B` ``` let x := ctor_0; jmp block_1 x ``` in a context where we have the join point `block_1` defined as ``` block_1 (x : obj) : obj := let z := ctor_0 x y; ret z ``` The variable `y` is live in the function body `B` since it occurs in `block_1` which is "invoked" by `B`. -/ namespace IsLive /-- We use `State Context` instead of `ReaderT Context Id` because we remove non local joint points from `Context` whenever we visit them instead of maintaining a set of visited non local join points. Remark: we don't need to track local join points because we assume there is no variable or join point shadowing in our IR. -/ abbrev M := StateM LocalContext abbrev visitVar (w : Index) (x : VarId) : M Bool := pure (HasIndex.visitVar w x) abbrev visitJP (w : Index) (x : JoinPointId) : M Bool := pure (HasIndex.visitJP w x) abbrev visitArg (w : Index) (a : Arg) : M Bool := pure (HasIndex.visitArg w a) abbrev visitArgs (w : Index) (as : Array Arg) : M Bool := pure (HasIndex.visitArgs w as) abbrev visitExpr (w : Index) (e : Expr) : M Bool := pure (HasIndex.visitExpr w e) partial def visitFnBody (w : Index) : FnBody → M Bool | FnBody.vdecl _ _ v b => visitExpr w v <||> visitFnBody w b | FnBody.jdecl _ _ v b => visitFnBody w v <||> visitFnBody w b | FnBody.set x _ y b => visitVar w x <||> visitArg w y <||> visitFnBody w b | FnBody.uset x _ y b => visitVar w x <||> visitVar w y <||> visitFnBody w b | FnBody.sset x _ _ y _ b => visitVar w x <||> visitVar w y <||> visitFnBody w b | FnBody.setTag x _ b => visitVar w x <||> visitFnBody w b | FnBody.inc x _ _ _ b => visitVar w x <||> visitFnBody w b | FnBody.dec x _ _ _ b => visitVar w x <||> visitFnBody w b | FnBody.del x b => visitVar w x <||> visitFnBody w b | FnBody.mdata _ b => visitFnBody w b | FnBody.jmp j ys => visitArgs w ys <||> do let ctx ← get match ctx.getJPBody j with | some b => -- `j` is not a local join point since we assume we cannot shadow join point declarations. -- Instead of marking the join points that we have already been visited, we permanently remove `j` from the context. set (ctx.eraseJoinPointDecl j) *> visitFnBody w b | none => -- `j` must be a local join point. So do nothing since we have already visite its body. pure false | FnBody.ret x => visitArg w x | FnBody.case _ x _ alts => visitVar w x <||> alts.anyM (fun alt => visitFnBody w alt.body) | FnBody.unreachable => pure false end IsLive /-- Return true if `x` is live in the function body `b` in the context `ctx`. Remark: the context only needs to contain all (free) join point declarations. Recall that we say that a join point `j` is free in `b` if `b` contains `FnBody.jmp j ys` and `j` is not local. -/ def FnBody.hasLiveVar (b : FnBody) (ctx : LocalContext) (x : VarId) : Bool := (IsLive.visitFnBody x.idx b).run' ctx abbrev LiveVarSet := VarIdSet abbrev JPLiveVarMap := RBMap JoinPointId LiveVarSet (fun j₁ j₂ => compare j₁.idx j₂.idx) instance : Inhabited LiveVarSet where default := {} def mkLiveVarSet (x : VarId) : LiveVarSet := RBTree.empty.insert x namespace LiveVars abbrev Collector := LiveVarSet → LiveVarSet @[inline] private def skip : Collector := fun s => s @[inline] private def collectVar (x : VarId) : Collector := fun s => s.insert x private def collectArg : Arg → Collector | Arg.var x => collectVar x | _ => skip private def collectArray {α : Type} (as : Array α) (f : α → Collector) : Collector := fun s => as.foldl (fun s a => f a s) s private def collectArgs (as : Array Arg) : Collector := collectArray as collectArg private def accumulate (s' : LiveVarSet) : Collector := fun s => s'.fold (fun s x => s.insert x) s private def collectJP (m : JPLiveVarMap) (j : JoinPointId) : Collector := match m.find? j with | some xs => accumulate xs | none => skip -- unreachable for well-formed code private def bindVar (x : VarId) : Collector := fun s => s.erase x private def bindParams (ps : Array Param) : Collector := fun s => ps.foldl (fun s p => s.erase p.x) s def collectExpr : Expr → Collector | Expr.ctor _ ys => collectArgs ys | Expr.reset _ x => collectVar x | Expr.reuse x _ _ ys => collectVar x ∘ collectArgs ys | Expr.proj _ x => collectVar x | Expr.uproj _ x => collectVar x | Expr.sproj _ _ x => collectVar x | Expr.fap _ ys => collectArgs ys | Expr.pap _ ys => collectArgs ys | Expr.ap x ys => collectVar x ∘ collectArgs ys | Expr.box _ x => collectVar x | Expr.unbox x => collectVar x | Expr.lit _ => skip | Expr.isShared x => collectVar x partial def collectFnBody : FnBody → JPLiveVarMap → Collector | FnBody.vdecl x _ v b, m => collectExpr v ∘ bindVar x ∘ collectFnBody b m | FnBody.jdecl j ys v b, m => let jLiveVars := (bindParams ys ∘ collectFnBody v m) {}; let m := m.insert j jLiveVars; collectFnBody b m | FnBody.set x _ y b, m => collectVar x ∘ collectArg y ∘ collectFnBody b m | FnBody.setTag x _ b, m => collectVar x ∘ collectFnBody b m | FnBody.uset x _ y b, m => collectVar x ∘ collectVar y ∘ collectFnBody b m | FnBody.sset x _ _ y _ b, m => collectVar x ∘ collectVar y ∘ collectFnBody b m | FnBody.inc x _ _ _ b, m => collectVar x ∘ collectFnBody b m | FnBody.dec x _ _ _ b, m => collectVar x ∘ collectFnBody b m | FnBody.del x b, m => collectVar x ∘ collectFnBody b m | FnBody.mdata _ b, m => collectFnBody b m | FnBody.ret x, _ => collectArg x | FnBody.case _ x _ alts, m => collectVar x ∘ collectArray alts (fun alt => collectFnBody alt.body m) | FnBody.unreachable, _ => skip | FnBody.jmp j xs, m => collectJP m j ∘ collectArgs xs def updateJPLiveVarMap (j : JoinPointId) (ys : Array Param) (v : FnBody) (m : JPLiveVarMap) : JPLiveVarMap := let jLiveVars := (bindParams ys ∘ collectFnBody v m) {}; m.insert j jLiveVars end LiveVars def updateLiveVars (e : Expr) (v : LiveVarSet) : LiveVarSet := LiveVars.collectExpr e v def collectLiveVars (b : FnBody) (m : JPLiveVarMap) (v : LiveVarSet := {}) : LiveVarSet := LiveVars.collectFnBody b m v export LiveVars (updateJPLiveVarMap) end Lean.IR
4bdba6679227766f14abc6a260fc3077c25c01cf
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/finsupp/to_dfinsupp.lean
1721a0622f4c9a9c97c68039e0fe1a844a63d548
[ "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
11,401
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.module.equiv import data.dfinsupp.basic import data.finsupp.basic /-! # Conversion between `finsupp` and homogenous `dfinsupp` This module provides conversions between `finsupp` and `dfinsupp`. It is in its own file since neither `finsupp` or `dfinsupp` depend on each other. ## Main definitions * "identity" maps between `finsupp` and `dfinsupp`: * `finsupp.to_dfinsupp : (ι →₀ M) → (Π₀ i : ι, M)` * `dfinsupp.to_finsupp : (Π₀ i : ι, M) → (ι →₀ M)` * Bundled equiv versions of the above: * `finsupp_equiv_dfinsupp : (ι →₀ M) ≃ (Π₀ i : ι, M)` * `finsupp_add_equiv_dfinsupp : (ι →₀ M) ≃+ (Π₀ i : ι, M)` * `finsupp_lequiv_dfinsupp R : (ι →₀ M) ≃ₗ[R] (Π₀ i : ι, M)` * stronger versions of `finsupp.split`: * `sigma_finsupp_equiv_dfinsupp : ((Σ i, η i) →₀ N) ≃ (Π₀ i, (η i →₀ N))` * `sigma_finsupp_add_equiv_dfinsupp : ((Σ i, η i) →₀ N) ≃+ (Π₀ i, (η i →₀ N))` * `sigma_finsupp_lequiv_dfinsupp : ((Σ i, η i) →₀ N) ≃ₗ[R] (Π₀ i, (η i →₀ N))` ## Theorems The defining features of these operations is that they preserve the function and support: * `finsupp.to_dfinsupp_coe` * `finsupp.to_dfinsupp_support` * `dfinsupp.to_finsupp_coe` * `dfinsupp.to_finsupp_support` and therefore map `finsupp.single` to `dfinsupp.single` and vice versa: * `finsupp.to_dfinsupp_single` * `dfinsupp.to_finsupp_single` as well as preserving arithmetic operations. For the bundled equivalences, we provide lemmas that they reduce to `finsupp.to_dfinsupp`: * `finsupp_add_equiv_dfinsupp_apply` * `finsupp_lequiv_dfinsupp_apply` * `finsupp_add_equiv_dfinsupp_symm_apply` * `finsupp_lequiv_dfinsupp_symm_apply` ## Implementation notes We provide `dfinsupp.to_finsupp` and `finsupp_equiv_dfinsupp` computably by adding `[decidable_eq ι]` and `[Π m : M, decidable (m ≠ 0)]` arguments. To aid with definitional unfolding, these arguments are also present on the `noncomputable` equivs. -/ variables {ι : Type*} {R : Type*} {M : Type*} /-! ### Basic definitions and lemmas -/ section defs /-- Interpret a `finsupp` as a homogenous `dfinsupp`. -/ def finsupp.to_dfinsupp [has_zero M] (f : ι →₀ M) : Π₀ i : ι, M := ⟦⟨f, f.support.1, λ i, (classical.em (f i = 0)).symm.imp_left (finsupp.mem_support_iff.mpr)⟩⟧ @[simp] lemma finsupp.to_dfinsupp_coe [has_zero M] (f : ι →₀ M) : ⇑f.to_dfinsupp = f := rfl section variables [decidable_eq ι] [has_zero M] @[simp] lemma finsupp.to_dfinsupp_single (i : ι) (m : M) : (finsupp.single i m).to_dfinsupp = dfinsupp.single i m := by { ext, simp [finsupp.single_apply, dfinsupp.single_apply] } variables [Π m : M, decidable (m ≠ 0)] @[simp] lemma to_dfinsupp_support (f : ι →₀ M) : f.to_dfinsupp.support = f.support := by { ext, simp, } /-- Interpret a homogenous `dfinsupp` as a `finsupp`. Note that the elaborator has a lot of trouble with this definition - it is often necessary to write `(dfinsupp.to_finsupp f : ι →₀ M)` instead of `f.to_finsupp`, as for some unknown reason using dot notation or omitting the type ascription prevents the type being resolved correctly. -/ def dfinsupp.to_finsupp (f : Π₀ i : ι, M) : ι →₀ M := ⟨f.support, f, λ i, by simp only [dfinsupp.mem_support_iff]⟩ @[simp] lemma dfinsupp.to_finsupp_coe (f : Π₀ i : ι, M) : ⇑f.to_finsupp = f := rfl @[simp] lemma dfinsupp.to_finsupp_support (f : Π₀ i : ι, M) : f.to_finsupp.support = f.support := by { ext, simp, } @[simp] lemma dfinsupp.to_finsupp_single (i : ι) (m : M) : (dfinsupp.single i m : Π₀ i : ι, M).to_finsupp = finsupp.single i m := by { ext, simp [finsupp.single_apply, dfinsupp.single_apply] } @[simp] lemma finsupp.to_dfinsupp_to_finsupp (f : ι →₀ M) : f.to_dfinsupp.to_finsupp = f := finsupp.coe_fn_injective rfl @[simp] lemma dfinsupp.to_finsupp_to_dfinsupp (f : Π₀ i : ι, M) : f.to_finsupp.to_dfinsupp = f := dfinsupp.coe_fn_injective rfl end end defs /-! ### Lemmas about arithmetic operations -/ section lemmas namespace finsupp @[simp] lemma to_dfinsupp_zero [has_zero M] : (0 : ι →₀ M).to_dfinsupp = 0 := dfinsupp.coe_fn_injective rfl @[simp] lemma to_dfinsupp_add [add_zero_class M] (f g : ι →₀ M) : (f + g).to_dfinsupp = f.to_dfinsupp + g.to_dfinsupp := dfinsupp.coe_fn_injective rfl @[simp] lemma to_dfinsupp_neg [add_group M] (f : ι →₀ M) : (-f).to_dfinsupp = -f.to_dfinsupp := dfinsupp.coe_fn_injective rfl @[simp] lemma to_dfinsupp_sub [add_group M] (f g : ι →₀ M) : (f - g).to_dfinsupp = f.to_dfinsupp - g.to_dfinsupp := dfinsupp.coe_fn_injective rfl @[simp] lemma to_dfinsupp_smul [monoid R] [add_monoid M] [distrib_mul_action R M] (r : R) (f : ι →₀ M) : (r • f).to_dfinsupp = r • f.to_dfinsupp := dfinsupp.coe_fn_injective rfl end finsupp namespace dfinsupp variables [decidable_eq ι] @[simp] lemma to_finsupp_zero [has_zero M] [Π m : M, decidable (m ≠ 0)] : to_finsupp 0 = (0 : ι →₀ M) := finsupp.coe_fn_injective rfl @[simp] lemma to_finsupp_add [add_zero_class M] [Π m : M, decidable (m ≠ 0)] (f g : Π₀ i : ι, M) : (to_finsupp (f + g) : ι →₀ M) = (to_finsupp f + to_finsupp g) := finsupp.coe_fn_injective $ dfinsupp.coe_add _ _ @[simp] lemma to_finsupp_neg [add_group M] [Π m : M, decidable (m ≠ 0)] (f : Π₀ i : ι, M) : (to_finsupp (-f) : ι →₀ M) = -to_finsupp f := finsupp.coe_fn_injective $ dfinsupp.coe_neg _ @[simp] lemma to_finsupp_sub [add_group M] [Π m : M, decidable (m ≠ 0)] (f g : Π₀ i : ι, M) : (to_finsupp (f - g) : ι →₀ M) = to_finsupp f - to_finsupp g := finsupp.coe_fn_injective $ dfinsupp.coe_sub _ _ @[simp] lemma to_finsupp_smul [monoid R] [add_monoid M] [distrib_mul_action R M] [Π m : M, decidable (m ≠ 0)] (r : R) (f : Π₀ i : ι, M) : (to_finsupp (r • f) : ι →₀ M) = r • to_finsupp f := finsupp.coe_fn_injective $ dfinsupp.coe_smul _ _ end dfinsupp end lemmas /-! ### Bundled `equiv`s -/ section equivs /-- `finsupp.to_dfinsupp` and `dfinsupp.to_finsupp` together form an equiv. -/ @[simps {fully_applied := ff}] def finsupp_equiv_dfinsupp [decidable_eq ι] [has_zero M] [Π m : M, decidable (m ≠ 0)] : (ι →₀ M) ≃ (Π₀ i : ι, M) := { to_fun := finsupp.to_dfinsupp, inv_fun := dfinsupp.to_finsupp, left_inv := finsupp.to_dfinsupp_to_finsupp, right_inv := dfinsupp.to_finsupp_to_dfinsupp } /-- The additive version of `finsupp.to_finsupp`. Note that this is `noncomputable` because `finsupp.has_add` is noncomputable. -/ @[simps {fully_applied := ff}] def finsupp_add_equiv_dfinsupp [decidable_eq ι] [add_zero_class M] [Π m : M, decidable (m ≠ 0)] : (ι →₀ M) ≃+ (Π₀ i : ι, M) := { to_fun := finsupp.to_dfinsupp, inv_fun := dfinsupp.to_finsupp, map_add' := finsupp.to_dfinsupp_add, .. finsupp_equiv_dfinsupp} variables (R) /-- The additive version of `finsupp.to_finsupp`. Note that this is `noncomputable` because `finsupp.has_add` is noncomputable. -/ @[simps {fully_applied := ff}] def finsupp_lequiv_dfinsupp [decidable_eq ι] [semiring R] [add_comm_monoid M] [Π m : M, decidable (m ≠ 0)] [module R M] : (ι →₀ M) ≃ₗ[R] (Π₀ i : ι, M) := { to_fun := finsupp.to_dfinsupp, inv_fun := dfinsupp.to_finsupp, map_smul' := finsupp.to_dfinsupp_smul, map_add' := finsupp.to_dfinsupp_add, .. finsupp_equiv_dfinsupp} section sigma /-- ### Stronger versions of `finsupp.split` -/ noncomputable theory open_locale classical variables {η : ι → Type*} {N : Type*} [semiring R] open finsupp /-- `finsupp.split` is an equivalence between `(Σ i, η i) →₀ N` and `Π₀ i, (η i →₀ N)`. -/ def sigma_finsupp_equiv_dfinsupp [has_zero N] : ((Σ i, η i) →₀ N) ≃ (Π₀ i, (η i →₀ N)) := { to_fun := λ f, ⟦⟨split f, (split_support f : finset ι).val, λ i, begin rw [← finset.mem_def, mem_split_support_iff_nonzero], exact (decidable.em _).symm end⟩⟧, inv_fun := λ f, begin refine on_finset (finset.sigma f.support (λ j, (f j).support)) (λ ji, f ji.1 ji.2) (λ g hg, finset.mem_sigma.mpr ⟨_, mem_support_iff.mpr hg⟩), simp only [ne.def, dfinsupp.mem_support_to_fun], intro h, rw h at hg, simpa using hg end, left_inv := λ f, by { ext, simp [split] }, right_inv := λ f, by { ext, simp [split] } } @[simp] lemma sigma_finsupp_equiv_dfinsupp_apply [has_zero N] (f : (Σ i, η i) →₀ N) : (sigma_finsupp_equiv_dfinsupp f : Π i, (η i →₀ N)) = finsupp.split f := rfl @[simp] lemma sigma_finsupp_equiv_dfinsupp_symm_apply [has_zero N] (f : Π₀ i, (η i →₀ N)) (s : Σ i, η i) : (sigma_finsupp_equiv_dfinsupp.symm f : (Σ i, η i) →₀ N) s = f s.1 s.2 := rfl @[simp] lemma sigma_finsupp_equiv_dfinsupp_support [has_zero N] (f : (Σ i, η i) →₀ N) : (sigma_finsupp_equiv_dfinsupp f).support = finsupp.split_support f := begin ext, rw dfinsupp.mem_support_to_fun, exact (finsupp.mem_split_support_iff_nonzero _ _).symm, end @[simp] lemma sigma_finsupp_equiv_dfinsupp_single [has_zero N] (a : Σ i, η i) (n : N) : sigma_finsupp_equiv_dfinsupp (finsupp.single a n) = @dfinsupp.single _ (λ i, η i →₀ N) _ _ a.1 (finsupp.single a.2 n) := begin obtain ⟨i, a⟩ := a, ext j b, by_cases h : i = j, { subst h, simp [split_apply, finsupp.single_apply] }, suffices : finsupp.single (⟨i, a⟩ : Σ i, η i) n ⟨j, b⟩ = 0, { simp [split_apply, dif_neg h, this] }, have H : (⟨i, a⟩ : Σ i, η i) ≠ ⟨j, b⟩ := by simp [h], rw [finsupp.single_apply, if_neg H] end -- Without this Lean fails to find the `add_zero_class` instance on `Π₀ i, (η i →₀ N)`. local attribute [-instance] finsupp.has_zero @[simp] lemma sigma_finsupp_equiv_dfinsupp_add [add_zero_class N] (f g : (Σ i, η i) →₀ N) : sigma_finsupp_equiv_dfinsupp (f + g) = (sigma_finsupp_equiv_dfinsupp f + (sigma_finsupp_equiv_dfinsupp g) : (Π₀ (i : ι), η i →₀ N)) := by {ext, refl} /-- `finsupp.split` is an additive equivalence between `(Σ i, η i) →₀ N` and `Π₀ i, (η i →₀ N)`. -/ @[simps] def sigma_finsupp_add_equiv_dfinsupp [add_zero_class N] : ((Σ i, η i) →₀ N) ≃+ (Π₀ i, (η i →₀ N)) := { to_fun := sigma_finsupp_equiv_dfinsupp, inv_fun := sigma_finsupp_equiv_dfinsupp.symm, map_add' := sigma_finsupp_equiv_dfinsupp_add, .. sigma_finsupp_equiv_dfinsupp } local attribute [-instance] finsupp.add_zero_class --tofix: r • (sigma_finsupp_equiv_dfinsupp f) doesn't work. @[simp] lemma sigma_finsupp_equiv_dfinsupp_smul {R} [monoid R] [add_monoid N] [distrib_mul_action R N] (r : R) (f : (Σ i, η i) →₀ N) : sigma_finsupp_equiv_dfinsupp (r • f) = @has_smul.smul R (Π₀ i, η i →₀ N) mul_action.to_has_smul r (sigma_finsupp_equiv_dfinsupp f) := by { ext, refl } local attribute [-instance] finsupp.add_monoid /-- `finsupp.split` is a linear equivalence between `(Σ i, η i) →₀ N` and `Π₀ i, (η i →₀ N)`. -/ @[simps] def sigma_finsupp_lequiv_dfinsupp [add_comm_monoid N] [module R N] : ((Σ i, η i) →₀ N) ≃ₗ[R] (Π₀ i, (η i →₀ N)) := { map_smul' := sigma_finsupp_equiv_dfinsupp_smul, .. sigma_finsupp_add_equiv_dfinsupp } end sigma end equivs
4873bddad616d26b1868d9197931581cf36cb864
94637389e03c919023691dcd05bd4411b1034aa5
/src/inClassNotes/higherOrderFunctions/composeTest.lean
97b04ceda29d7a44f572831d1b791908c3d15971
[]
no_license
kevinsullivan/complogic-s21
7c4eef2105abad899e46502270d9829d913e8afc
99039501b770248c8ceb39890be5dfe129dc1082
refs/heads/master
1,682,985,669,944
1,621,126,241,000
1,621,126,241,000
335,706,272
0
38
null
1,618,325,669,000
1,612,374,118,000
Lean
UTF-8
Lean
false
false
4,613
lean
/- Let's build up to notion of higher-order functions. -/ namespace hidden -- Increment functions def inc (n : nat) := n + 1 def sqr (n : nat) := n * n def incThenSqr (n : nat) := sqr (inc n) /- 36 <-- sqr <-- inc <-- 5 Think of data flowing right to left through a composition of functions: given n (on the right) first send it through inc, then send that result "to the left" through sqr. -/ def sqrThenInc (n : nat) := inc (sqr n) /- 26 <-- inc <-- sqr <-- 5 -/ #eval incThenSqr 5 #eval sqrThenInc 5 /- A diagram of the evaluation order 36 <-- (sqr <-- (inc <-- 5)) 26 <-- (inc <-- (sqr <-- 5)) -/ /- Regrouping parenthesis tells us that sending the input through two functions right to left is equivalent to running it through a single function, one that "combines" the effects of the two. 36 <-- (sqr <-- inc) <-- 5) ^^^^^^^^^^^^^ a function 26 <-- (inc <-- sqr) <-- 5) ^^^^^^^^^^^^^ a function -/ /- 36 <-- (compose sqr inc) <-- 5) 26 <-- (compose inc sqr) <-- 5) ^^^^^^^^^^^^^^^^^ a function -/ /- 36 <-- (compose sqr inc) <-- 5) 26 <-- (compose inc sqr) <-- 5) ^^^^^^^ higher-order function -/ /- Remember that a lambda term is a literal value that represents a function. What's special about the form of data is that it can be *applied* to an argument to produce a result. A higher-order function is just a function that takes a lambda term (aka "a function") as an argument and/or returns one as a result. In particular, we will often want to define functions that not only take "functions" as arguments but that return new functions as results, where the new functions, *when applied* use given functions to compute results. Such a higher-order function is a machine that takes smaller data consuming and producing machines (functions) and combines them into larger/new data consuming and producing machines. Composition of functions is a special case in which a new function is returned that, when applied to an argument, applies each of the given functions in turn. -/ /- 36 <-- (sqr ∘ inc) <-- 5) 26 <-- (inc ∘ sqr) <-- 5) -/ /- Can we write a function that takes two smaller functions, f and g, and that returns a function, (g ∘ f), that first applies f to its argument and then applies g to that result? Let's try this for the special case of two argument functions, such as sqr and inc, each being of type nat → nat. -/ def compose_nat_nat (g f: ℕ → ℕ) : (ℕ → ℕ) := _ -- let's test it out #eval (compose_nat_nat sqr inc) 5 -- ^^^^^^^^^^^^^^^^^^^^^^^^^ function! def sqrinc := compose_nat_nat sqr inc #eval sqrinc 5 #eval (compose_nat_nat inc sqr) 5 def incsqr := compose_nat_nat inc sqr #eval incsrq 5 /- Suppose we want to compose functions that have different types. The return type of one has to match the argument type of the next one in the pipeline. Parametric polymorphism to the rescue. -/ def compose_α_β_φ { α β φ : Type } (g : β → φ) (f: α → β) : α → φ := _ #eval (compose_α_β_φ sqr string.length) "Hello!" /- The previous version works great as long as the functions all takes values of types, α, β, and φ, of type Type. But in general, we'll want a function that can operate on functions that take arguments and that return results in arbitrary type universes. So here, then is the most general form of our higher-order compose function. -/ universes u₁ u₂ u₃ -- plural of universe def compose {α : Type u₁} {β : Type u₂} {φ : Type u₃} (g : β → φ) (f: α → β) : α → φ := fun a, g (f a) /- Return a *function* that takes one argument, a, and returns the result of applying g to the result of applying f to a. -/ def incThenSqr' := compose sqr inc def sqrThenInc' := compose inc sqr def sqrlen := compose sqr string.length #eval incThenSqr 5 -- expect 36 #eval incThenSqr 5 -- expect 26 #eval sqrlen "Hello!" /- Lean implements function composition as function.comp, with ∘ as an infix notation for this binary operation. -/ #check function.comp #check @function.comp /- function.comp : Π {α : Sort u_1} {β : Sort u_2} {φ : Sort u_3}, (β → φ) → (α → β) → α → φ -/ /- Prop (Sort 0) -- logic Type (Type 0) Sort 1 -- computation Type 1 Sort 2 Type 2 Sort 3 etc -/ universes u₁ u₂ u₃ -- introduce some local assumptions variables (f : Sort u₁ → Sort u₂) (g : Sort u₂ → Sort u₃) #check function.comp g f #check g ∘ f end hidden
dd2c2a889b42d888014081457107a5b09b79842d
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/analysis/complex/exponential.lean
42014efce6b6b11d478f7f71edb6b7b621020acb
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
88,648
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne -/ import tactic.linarith data.complex.exponential analysis.specific_limits group_theory.quotient_group analysis.complex.basic /-! # Exponential ## Main definitions This file contains the following definitions: * π, arcsin, arccos, arctan * argument of a complex number * logarithm on real and complex numbers * complex and real power function ## Main statements The following functions are shown to be continuous: * complex and real exponential function * sin, cos, tan, sinh, cosh * logarithm on real numbers * real power function * square root function The following functions are shown to be differentiable, and their derivatives are computed: * complex and real exponential function * sin, cos, sinh, cosh ## Tags exp, log, sin, cos, tan, arcsin, arccos, arctan, angle, argument, power, square root, -/ noncomputable theory open finset filter metric asymptotics open_locale classical open_locale topological_space namespace complex /-- The complex exponential is everywhere differentiable, with the derivative `exp x`. -/ lemma has_deriv_at_exp (x : ℂ) : has_deriv_at exp (exp x) x := begin rw has_deriv_at_iff_is_o_nhds_zero, have : (1 : ℕ) < 2 := by norm_num, refine is_O.trans_is_o ⟨∥exp x∥, _⟩ (is_o_pow_id this), have : metric.ball (0 : ℂ) 1 ∈ nhds (0 : ℂ) := metric.ball_mem_nhds 0 zero_lt_one, apply filter.mem_sets_of_superset this (λz hz, _), simp only [metric.mem_ball, dist_zero_right] at hz, simp only [exp_zero, mul_one, one_mul, add_comm, normed_field.norm_pow, zero_add, set.mem_set_of_eq], calc ∥exp (x + z) - exp x - z * exp x∥ = ∥exp x * (exp z - 1 - z)∥ : by { congr, rw [exp_add], ring } ... = ∥exp x∥ * ∥exp z - 1 - z∥ : normed_field.norm_mul _ _ ... ≤ ∥exp x∥ * ∥z∥^2 : mul_le_mul_of_nonneg_left (abs_exp_sub_one_sub_id_le (le_of_lt hz)) (norm_nonneg _) end lemma differentiable_exp : differentiable ℂ exp := λx, (has_deriv_at_exp x).differentiable_at @[simp] lemma deriv_exp : deriv exp = exp := funext $ λ x, (has_deriv_at_exp x).deriv @[simp] lemma iter_deriv_exp : ∀ n : ℕ, (deriv^[n] exp) = exp | 0 := rfl | (n+1) := by rw [nat.iterate_succ, deriv_exp, iter_deriv_exp n] lemma continuous_exp : continuous exp := differentiable_exp.continuous end complex lemma has_deriv_at.cexp {f : ℂ → ℂ} {f' x : ℂ} (hf : has_deriv_at f f' x) : has_deriv_at (complex.exp ∘ f) (f' * complex.exp (f x)) x := (complex.has_deriv_at_exp (f x)).comp x hf lemma has_deriv_within_at.cexp {f : ℂ → ℂ} {f' x : ℂ} {s : set ℂ} (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (complex.exp ∘ f) (f' * complex.exp (f x)) s x := (complex.has_deriv_at_exp (f x)).comp_has_deriv_within_at x hf namespace complex /-- The complex sine function is everywhere differentiable, with the derivative `cos x`. -/ lemma has_deriv_at_sin (x : ℂ) : has_deriv_at sin (cos x) x := begin simp only [cos, div_eq_mul_inv], convert ((((has_deriv_at_id x).neg.mul_const I).cexp.sub ((has_deriv_at_id x).mul_const I).cexp).mul_const I).mul_const (2:ℂ)⁻¹, simp only [function.comp, id], rw [add_comm, one_mul, mul_comm (_ - _), mul_sub, mul_left_comm, ← mul_assoc, ← mul_assoc, I_mul_I, mul_assoc (-1:ℂ), I_mul_I, neg_one_mul, neg_neg, one_mul, neg_one_mul, sub_neg_eq_add] end lemma differentiable_sin : differentiable ℂ sin := λx, (has_deriv_at_sin x).differentiable_at @[simp] lemma deriv_sin : deriv sin = cos := funext $ λ x, (has_deriv_at_sin x).deriv lemma continuous_sin : continuous sin := differentiable_sin.continuous /-- The complex cosine function is everywhere differentiable, with the derivative `-sin x`. -/ lemma has_deriv_at_cos (x : ℂ) : has_deriv_at cos (-sin x) x := begin simp only [sin, div_eq_mul_inv, neg_mul_eq_neg_mul], convert (((has_deriv_at_id x).mul_const I).cexp.add ((has_deriv_at_id x).neg.mul_const I).cexp).mul_const (2:ℂ)⁻¹, simp only [function.comp, id], rw [one_mul, neg_one_mul, neg_sub, mul_comm, mul_sub, sub_eq_add_neg, neg_mul_eq_neg_mul] end lemma differentiable_cos : differentiable ℂ cos := λx, (has_deriv_at_cos x).differentiable_at lemma deriv_cos {x : ℂ} : deriv cos x = -sin x := (has_deriv_at_cos x).deriv @[simp] lemma deriv_cos' : deriv cos = (λ x, -sin x) := funext $ λ x, deriv_cos lemma continuous_cos : continuous cos := differentiable_cos.continuous lemma continuous_tan : continuous (λ x : {x // cos x ≠ 0}, tan x) := (continuous_sin.comp continuous_subtype_val).mul (continuous.inv subtype.property (continuous_cos.comp continuous_subtype_val)) /-- The complex hyperbolic sine function is everywhere differentiable, with the derivative `sinh x`. -/ lemma has_deriv_at_sinh (x : ℂ) : has_deriv_at sinh (cosh x) x := begin simp only [cosh, div_eq_mul_inv], convert ((has_deriv_at_exp x).sub (has_deriv_at_id x).neg.cexp).mul_const (2:ℂ)⁻¹, rw [id, neg_one_mul, neg_neg] end lemma differentiable_sinh : differentiable ℂ sinh := λx, (has_deriv_at_sinh x).differentiable_at @[simp] lemma deriv_sinh : deriv sinh = cosh := funext $ λ x, (has_deriv_at_sinh x).deriv lemma continuous_sinh : continuous sinh := differentiable_sinh.continuous /-- The complex hyperbolic cosine function is everywhere differentiable, with the derivative `cosh x`. -/ lemma has_deriv_at_cosh (x : ℂ) : has_deriv_at cosh (sinh x) x := begin simp only [sinh, div_eq_mul_inv], convert ((has_deriv_at_exp x).add (has_deriv_at_id x).neg.cexp).mul_const (2:ℂ)⁻¹, rw [id, neg_one_mul, sub_eq_add_neg] end lemma differentiable_cosh : differentiable ℂ cosh := λx, (has_deriv_at_cosh x).differentiable_at @[simp] lemma deriv_cosh : deriv cosh = sinh := funext $ λ x, (has_deriv_at_cosh x).deriv lemma continuous_cosh : continuous cosh := differentiable_cosh.continuous end complex namespace real variables {x y z : ℝ} lemma has_deriv_at_exp (x : ℝ) : has_deriv_at exp (exp x) x := has_deriv_at_real_of_complex (complex.has_deriv_at_exp x) lemma differentiable_exp : differentiable ℝ exp := λx, (has_deriv_at_exp x).differentiable_at @[simp] lemma deriv_exp : deriv exp = exp := funext $ λ x, (has_deriv_at_exp x).deriv @[simp] lemma iter_deriv_exp : ∀ n : ℕ, (deriv^[n] exp) = exp | 0 := rfl | (n+1) := by rw [nat.iterate_succ, deriv_exp, iter_deriv_exp n] lemma continuous_exp : continuous exp := differentiable_exp.continuous lemma has_deriv_at_sin (x : ℝ) : has_deriv_at sin (cos x) x := has_deriv_at_real_of_complex (complex.has_deriv_at_sin x) lemma differentiable_sin : differentiable ℝ sin := λx, (has_deriv_at_sin x).differentiable_at @[simp] lemma deriv_sin : deriv sin = cos := funext $ λ x, (has_deriv_at_sin x).deriv lemma continuous_sin : continuous sin := differentiable_sin.continuous lemma has_deriv_at_cos (x : ℝ) : has_deriv_at cos (-sin x) x := (has_deriv_at_real_of_complex (complex.has_deriv_at_cos x) : _) lemma differentiable_cos : differentiable ℝ cos := λx, (has_deriv_at_cos x).differentiable_at lemma deriv_cos : deriv cos x = - sin x := (has_deriv_at_cos x).deriv @[simp] lemma deriv_cos' : deriv cos = (λ x, - sin x) := funext $ λ _, deriv_cos lemma continuous_cos : continuous cos := differentiable_cos.continuous lemma continuous_tan : continuous (λ x : {x // cos x ≠ 0}, tan x) := by simp only [tan_eq_sin_div_cos]; exact (continuous_sin.comp continuous_subtype_val).mul (continuous.inv subtype.property (continuous_cos.comp continuous_subtype_val)) lemma has_deriv_at_sinh (x : ℝ) : has_deriv_at sinh (cosh x) x := has_deriv_at_real_of_complex (complex.has_deriv_at_sinh x) lemma differentiable_sinh : differentiable ℝ sinh := λx, (has_deriv_at_sinh x).differentiable_at @[simp] lemma deriv_sinh : deriv sinh = cosh := funext $ λ x, (has_deriv_at_sinh x).deriv lemma continuous_sinh : continuous sinh := differentiable_sinh.continuous lemma has_deriv_at_cosh (x : ℝ) : has_deriv_at cosh (sinh x) x := has_deriv_at_real_of_complex (complex.has_deriv_at_cosh x) lemma differentiable_cosh : differentiable ℝ cosh := λx, (has_deriv_at_cosh x).differentiable_at @[simp] lemma deriv_cosh : deriv cosh = sinh := funext $ λ x, (has_deriv_at_cosh x).deriv lemma continuous_cosh : continuous cosh := differentiable_cosh.continuous lemma exists_exp_eq_of_pos {x : ℝ} (hx : 0 < x) : ∃ y, exp y = x := have ∀ {z:ℝ}, 1 ≤ z → z ∈ set.range exp, from λ z hz, intermediate_value_univ 0 (z - 1) continuous_exp ⟨by simpa, by simpa using add_one_le_exp_of_nonneg (sub_nonneg.2 hz)⟩, match le_total x 1 with | (or.inl hx1) := let ⟨y, hy⟩ := this (one_le_inv hx hx1) in ⟨-y, by rw [exp_neg, hy, inv_inv']⟩ | (or.inr hx1) := this hx1 end /-- The real logarithm function, equal to `0` for `x ≤ 0` and to the inverse of the exponential for `x > 0`. -/ noncomputable def log (x : ℝ) : ℝ := if hx : 0 < x then classical.some (exists_exp_eq_of_pos hx) else 0 lemma exp_log {x : ℝ} (hx : 0 < x) : exp (log x) = x := by rw [log, dif_pos hx]; exact classical.some_spec (exists_exp_eq_of_pos hx) @[simp] lemma log_exp (x : ℝ) : log (exp x) = x := exp_injective $ exp_log (exp_pos x) @[simp] lemma log_zero : log 0 = 0 := by simp [log, lt_irrefl] @[simp] lemma log_one : log 1 = 0 := exp_injective $ by rw [exp_log zero_lt_one, exp_zero] lemma log_mul {x y : ℝ} (hx : 0 < x) (hy : 0 < y) : log (x * y) = log x + log y := exp_injective $ by rw [exp_log (mul_pos hx hy), exp_add, exp_log hx, exp_log hy] lemma log_le_log {x y : ℝ} (h : 0 < x) (h₁ : 0 < y) : real.log x ≤ real.log y ↔ x ≤ y := ⟨λ h₂, by rwa [←real.exp_le_exp, real.exp_log h, real.exp_log h₁] at h₂, λ h₂, (real.exp_le_exp).1 $ by rwa [real.exp_log h₁, real.exp_log h]⟩ lemma log_lt_log (hx : 0 < x) : x < y → log x < log y := by { intro h, rwa [← exp_lt_exp, exp_log hx, exp_log (lt_trans hx h)] } lemma log_lt_log_iff (hx : 0 < x) (hy : 0 < y) : log x < log y ↔ x < y := by { rw [← exp_lt_exp, exp_log hx, exp_log hy] } lemma log_pos_iff (x : ℝ) : 0 < log x ↔ 1 < x := begin by_cases h : 0 < x, { rw ← log_one, exact log_lt_log_iff (by norm_num) h }, { rw [log, dif_neg], split, repeat {intro, linarith} } end lemma log_pos : 1 < x → 0 < log x := (log_pos_iff x).2 lemma log_neg_iff (h : 0 < x) : log x < 0 ↔ x < 1 := by { rw ← log_one, exact log_lt_log_iff h (by norm_num) } lemma log_neg (h0 : 0 < x) (h1 : x < 1) : log x < 0 := (log_neg_iff h0).2 h1 lemma log_nonneg : 1 ≤ x → 0 ≤ log x := by { intro, rwa [← log_one, log_le_log], norm_num, linarith } lemma log_nonpos : x ≤ 1 → log x ≤ 0 := begin intro, by_cases hx : 0 < x, { rwa [← log_one, log_le_log], exact hx, norm_num }, { simp [log, dif_neg hx] } end section prove_log_is_continuous lemma tendsto_log_one_zero : tendsto log (𝓝 1) (𝓝 0) := begin rw tendsto_nhds_nhds, assume ε ε0, let δ := min (exp ε - 1) (1 - exp (-ε)), have : 0 < δ, refine lt_min (sub_pos_of_lt (by rwa one_lt_exp_iff)) (sub_pos_of_lt _), by { rw exp_lt_one_iff, linarith }, use [δ, this], assume x h, cases le_total 1 x with hx hx, { have h : x < exp ε, rw [dist_eq, abs_of_nonneg (sub_nonneg_of_le hx)] at h, linarith [(min_le_left _ _ : δ ≤ exp ε - 1)], calc abs (log x - 0) = abs (log x) : by simp ... = log x : abs_of_nonneg $ log_nonneg hx ... < ε : by { rwa [← exp_lt_exp, exp_log], linarith }}, { have h : exp (-ε) < x, rw [dist_eq, abs_of_nonpos (sub_nonpos_of_le hx)] at h, linarith [(min_le_right _ _ : δ ≤ 1 - exp (-ε))], have : 0 < x := lt_trans (exp_pos _) h, calc abs (log x - 0) = abs (log x) : by simp ... = -log x : abs_of_nonpos $ log_nonpos hx ... < ε : by { rw [neg_lt, ← exp_lt_exp, exp_log], assumption' } } end lemma continuous_log' : continuous (λx : {x:ℝ // 0 < x}, log x.val) := continuous_iff_continuous_at.2 $ λ x, begin rw continuous_at, let f₁ := λ h:{h:ℝ // 0 < h}, log (x.1 * h.1), let f₂ := λ y:{y:ℝ // 0 < y}, subtype.mk (x.1 ⁻¹ * y.1) (mul_pos (inv_pos.2 x.2) y.2), have H1 : tendsto f₁ (𝓝 ⟨1, zero_lt_one⟩) (𝓝 (log (x.1*1))), have : f₁ = λ h:{h:ℝ // 0 < h}, log x.1 + log h.1, ext h, rw ← log_mul x.2 h.2, simp only [this, log_mul x.2 zero_lt_one, log_one], exact tendsto_const_nhds.add (tendsto.comp tendsto_log_one_zero continuous_at_subtype_val), have H2 : tendsto f₂ (𝓝 x) (𝓝 ⟨x.1⁻¹ * x.1, mul_pos (inv_pos.2 x.2) x.2⟩), rw tendsto_subtype_rng, exact tendsto_const_nhds.mul continuous_at_subtype_val, suffices h : tendsto (f₁ ∘ f₂) (𝓝 x) (𝓝 (log x.1)), begin convert h, ext y, have : x.val * (x.val⁻¹ * y.val) = y.val, rw [← mul_assoc, mul_inv_cancel (ne_of_gt x.2), one_mul], show log (y.val) = log (x.val * (x.val⁻¹ * y.val)), rw this end, exact tendsto.comp (by rwa mul_one at H1) (by { simp only [inv_mul_cancel (ne_of_gt x.2)] at H2, assumption }) end lemma continuous_at_log (hx : 0 < x) : continuous_at log x := continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_log' _ hx) (mem_nhds_sets (is_open_lt' _) hx) /-- Three forms of the continuity of `real.log` is provided. For the other two forms, see `real.continuous_log'` and `real.continuous_at_log` -/ lemma continuous_log {α : Type*} [topological_space α] {f : α → ℝ} (h : ∀a, 0 < f a) (hf : continuous f) : continuous (λa, log (f a)) := show continuous ((log ∘ @subtype.val ℝ (λr, 0 < r)) ∘ λa, ⟨f a, h a⟩), from continuous_log'.comp (continuous_subtype_mk _ hf) end prove_log_is_continuous lemma exists_cos_eq_zero : 0 ∈ cos '' set.Icc (1:ℝ) 2 := intermediate_value_Icc' (by norm_num) continuous_cos.continuous_on ⟨le_of_lt cos_two_neg, le_of_lt cos_one_pos⟩ /-- The number π = 3.14159265... Defined here using choice as twice a zero of cos in [1,2], from which one can derive all its properties. For explicit bounds on π, see `data.real.pi`. -/ noncomputable def pi : ℝ := 2 * classical.some exists_cos_eq_zero localized "notation `π` := real.pi" in real @[simp] lemma cos_pi_div_two : cos (π / 2) = 0 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).2 lemma one_le_pi_div_two : (1 : ℝ) ≤ π / 2 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).1.1 lemma pi_div_two_le_two : π / 2 ≤ 2 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).1.2 lemma two_le_pi : (2 : ℝ) ≤ π := (div_le_div_right (show (0 : ℝ) < 2, by norm_num)).1 (by rw div_self (@two_ne_zero' ℝ _ _ _); exact one_le_pi_div_two) lemma pi_le_four : π ≤ 4 := (div_le_div_right (show (0 : ℝ) < 2, by norm_num)).1 (calc π / 2 ≤ 2 : pi_div_two_le_two ... = 4 / 2 : by norm_num) lemma pi_pos : 0 < π := lt_of_lt_of_le (by norm_num) two_le_pi lemma pi_div_two_pos : 0 < π / 2 := half_pos pi_pos lemma two_pi_pos : 0 < 2 * π := by linarith [pi_pos] @[simp] lemma sin_pi : sin π = 0 := by rw [← mul_div_cancel_left pi (@two_ne_zero ℝ _), two_mul, add_div, sin_add, cos_pi_div_two]; simp @[simp] lemma cos_pi : cos π = -1 := by rw [← mul_div_cancel_left pi (@two_ne_zero ℝ _), mul_div_assoc, cos_two_mul, cos_pi_div_two]; simp [bit0, pow_add] @[simp] lemma sin_two_pi : sin (2 * π) = 0 := by simp [two_mul, sin_add] @[simp] lemma cos_two_pi : cos (2 * π) = 1 := by simp [two_mul, cos_add] lemma sin_add_pi (x : ℝ) : sin (x + π) = -sin x := by simp [sin_add] lemma sin_add_two_pi (x : ℝ) : sin (x + 2 * π) = sin x := by simp [sin_add_pi, sin_add, sin_two_pi, cos_two_pi] lemma cos_add_two_pi (x : ℝ) : cos (x + 2 * π) = cos x := by simp [cos_add, cos_two_pi, sin_two_pi] lemma sin_pi_sub (x : ℝ) : sin (π - x) = sin x := by simp [sub_eq_add_neg, sin_add] lemma cos_add_pi (x : ℝ) : cos (x + π) = -cos x := by simp [cos_add] lemma cos_pi_sub (x : ℝ) : cos (π - x) = -cos x := by simp [sub_eq_add_neg, cos_add] lemma sin_pos_of_pos_of_lt_pi {x : ℝ} (h0x : 0 < x) (hxp : x < π) : 0 < sin x := if hx2 : x ≤ 2 then sin_pos_of_pos_of_le_two h0x hx2 else have (2 : ℝ) + 2 = 4, from rfl, have π - x ≤ 2, from sub_le_iff_le_add.2 (le_trans pi_le_four (this ▸ add_le_add_left (le_of_not_ge hx2) _)), sin_pi_sub x ▸ sin_pos_of_pos_of_le_two (sub_pos.2 hxp) this lemma sin_nonneg_of_nonneg_of_le_pi {x : ℝ} (h0x : 0 ≤ x) (hxp : x ≤ π) : 0 ≤ sin x := match lt_or_eq_of_le h0x with | or.inl h0x := (lt_or_eq_of_le hxp).elim (le_of_lt ∘ sin_pos_of_pos_of_lt_pi h0x) (λ hpx, by simp [hpx]) | or.inr h0x := by simp [h0x.symm] end lemma sin_neg_of_neg_of_neg_pi_lt {x : ℝ} (hx0 : x < 0) (hpx : -π < x) : sin x < 0 := neg_pos.1 $ sin_neg x ▸ sin_pos_of_pos_of_lt_pi (neg_pos.2 hx0) (neg_lt.1 hpx) lemma sin_nonpos_of_nonnpos_of_neg_pi_le {x : ℝ} (hx0 : x ≤ 0) (hpx : -π ≤ x) : sin x ≤ 0 := neg_nonneg.1 $ sin_neg x ▸ sin_nonneg_of_nonneg_of_le_pi (neg_nonneg.2 hx0) (neg_le.1 hpx) @[simp] lemma sin_pi_div_two : sin (π / 2) = 1 := have sin (π / 2) = 1 ∨ sin (π / 2) = -1 := by simpa [pow_two, mul_self_eq_one_iff] using sin_sq_add_cos_sq (π / 2), this.resolve_right (λ h, (show ¬(0 : ℝ) < -1, by norm_num) $ h ▸ sin_pos_of_pos_of_lt_pi pi_div_two_pos (half_lt_self pi_pos)) lemma sin_add_pi_div_two (x : ℝ) : sin (x + π / 2) = cos x := by simp [sin_add] lemma sin_sub_pi_div_two (x : ℝ) : sin (x - π / 2) = -cos x := by simp [sub_eq_add_neg, sin_add] lemma sin_pi_div_two_sub (x : ℝ) : sin (π / 2 - x) = cos x := by simp [sub_eq_add_neg, sin_add] lemma cos_add_pi_div_two (x : ℝ) : cos (x + π / 2) = -sin x := by simp [cos_add] lemma cos_sub_pi_div_two (x : ℝ) : cos (x - π / 2) = sin x := by simp [sub_eq_add_neg, cos_add] lemma cos_pi_div_two_sub (x : ℝ) : cos (π / 2 - x) = sin x := by rw [← cos_neg, neg_sub, cos_sub_pi_div_two] lemma cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two {x : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) : 0 < cos x := sin_add_pi_div_two x ▸ sin_pos_of_pos_of_lt_pi (by linarith) (by linarith) lemma cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two {x : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) : 0 ≤ cos x := match lt_or_eq_of_le hx₁, lt_or_eq_of_le hx₂ with | or.inl hx₁, or.inl hx₂ := le_of_lt (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two hx₁ hx₂) | or.inl hx₁, or.inr hx₂ := by simp [hx₂] | or.inr hx₁, _ := by simp [hx₁.symm] end lemma cos_neg_of_pi_div_two_lt_of_lt {x : ℝ} (hx₁ : π / 2 < x) (hx₂ : x < π + π / 2) : cos x < 0 := neg_pos.1 $ cos_pi_sub x ▸ cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) (by linarith) lemma cos_nonpos_of_pi_div_two_le_of_le {x : ℝ} (hx₁ : π / 2 ≤ x) (hx₂ : x ≤ π + π / 2) : cos x ≤ 0 := neg_nonneg.1 $ cos_pi_sub x ▸ cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two (by linarith) (by linarith) lemma sin_nat_mul_pi (n : ℕ) : sin (n * π) = 0 := by induction n; simp [add_mul, sin_add, *] lemma sin_int_mul_pi (n : ℤ) : sin (n * π) = 0 := by cases n; simp [add_mul, sin_add, *, sin_nat_mul_pi] lemma cos_nat_mul_two_pi (n : ℕ) : cos (n * (2 * π)) = 1 := by induction n; simp [*, mul_add, cos_add, add_mul, cos_two_pi, sin_two_pi] lemma cos_int_mul_two_pi (n : ℤ) : cos (n * (2 * π)) = 1 := by cases n; simp only [cos_nat_mul_two_pi, int.of_nat_eq_coe, int.neg_succ_of_nat_coe, int.cast_coe_nat, int.cast_neg, (neg_mul_eq_neg_mul _ _).symm, cos_neg] lemma cos_int_mul_two_pi_add_pi (n : ℤ) : cos (n * (2 * π) + π) = -1 := by simp [cos_add, sin_add, cos_int_mul_two_pi] lemma sin_eq_zero_iff_of_lt_of_lt {x : ℝ} (hx₁ : -π < x) (hx₂ : x < π) : sin x = 0 ↔ x = 0 := ⟨λ h, le_antisymm (le_of_not_gt (λ h0, lt_irrefl (0 : ℝ) $ calc 0 < sin x : sin_pos_of_pos_of_lt_pi h0 hx₂ ... = 0 : h)) (le_of_not_gt (λ h0, lt_irrefl (0 : ℝ) $ calc 0 = sin x : h.symm ... < 0 : sin_neg_of_neg_of_neg_pi_lt h0 hx₁)), λ h, by simp [h]⟩ lemma sin_eq_zero_iff {x : ℝ} : sin x = 0 ↔ ∃ n : ℤ, (n : ℝ) * π = x := ⟨λ h, ⟨⌊x / π⌋, le_antisymm (sub_nonneg.1 (sub_floor_div_mul_nonneg _ pi_pos)) (sub_nonpos.1 $ le_of_not_gt $ λ h₃, ne_of_lt (sin_pos_of_pos_of_lt_pi h₃ (sub_floor_div_mul_lt _ pi_pos)) (by simp [sub_eq_add_neg, sin_add, h, sin_int_mul_pi]))⟩, λ ⟨n, hn⟩, hn ▸ sin_int_mul_pi _⟩ lemma sin_eq_zero_iff_cos_eq {x : ℝ} : sin x = 0 ↔ cos x = 1 ∨ cos x = -1 := by rw [← mul_self_eq_one_iff (cos x), ← sin_sq_add_cos_sq x, pow_two, pow_two, ← sub_eq_iff_eq_add, sub_self]; exact ⟨λ h, by rw [h, mul_zero], eq_zero_of_mul_self_eq_zero ∘ eq.symm⟩ theorem sin_sub_sin (θ ψ : ℝ) : sin θ - sin ψ = 2 * sin((θ - ψ)/2) * cos((θ + ψ)/2) := begin have s1 := sin_add ((θ + ψ) / 2) ((θ - ψ) / 2), have s2 := sin_sub ((θ + ψ) / 2) ((θ - ψ) / 2), rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, add_self_div_two] at s1, rw [div_sub_div_same, ←sub_add, add_sub_cancel', add_self_div_two] at s2, rw [s1, s2, ←sub_add, add_sub_cancel', ← two_mul, ← mul_assoc, mul_right_comm] end lemma cos_eq_one_iff (x : ℝ) : cos x = 1 ↔ ∃ n : ℤ, (n : ℝ) * (2 * π) = x := ⟨λ h, let ⟨n, hn⟩ := sin_eq_zero_iff.1 (sin_eq_zero_iff_cos_eq.2 (or.inl h)) in ⟨n / 2, (int.mod_two_eq_zero_or_one n).elim (λ hn0, by rwa [← mul_assoc, ← @int.cast_two ℝ, ← int.cast_mul, int.div_mul_cancel ((int.dvd_iff_mod_eq_zero _ _).2 hn0)]) (λ hn1, by rw [← int.mod_add_div n 2, hn1, int.cast_add, int.cast_one, add_mul, one_mul, add_comm, mul_comm (2 : ℤ), int.cast_mul, mul_assoc, int.cast_two] at hn; rw [← hn, cos_int_mul_two_pi_add_pi] at h; exact absurd h (by norm_num))⟩, λ ⟨n, hn⟩, hn ▸ cos_int_mul_two_pi _⟩ theorem cos_eq_zero_iff {θ : ℝ} : cos θ = 0 ↔ ∃ k : ℤ, θ = (2 * k + 1) * pi / 2 := begin rw [←real.sin_pi_div_two_sub, sin_eq_zero_iff], split, { rintro ⟨n, hn⟩, existsi -n, rw [int.cast_neg, add_mul, add_div, mul_assoc, mul_div_cancel_left _ (@two_ne_zero ℝ _), one_mul, ←neg_mul_eq_neg_mul, hn, neg_sub, sub_add_cancel] }, { rintro ⟨n, hn⟩, existsi -n, rw [hn, add_mul, one_mul, add_div, mul_assoc, mul_div_cancel_left _ (@two_ne_zero ℝ _), sub_add_eq_sub_sub_swap, sub_self, zero_sub, neg_mul_eq_neg_mul, int.cast_neg] } end lemma cos_eq_one_iff_of_lt_of_lt {x : ℝ} (hx₁ : -(2 * π) < x) (hx₂ : x < 2 * π) : cos x = 1 ↔ x = 0 := ⟨λ h, let ⟨n, hn⟩ := (cos_eq_one_iff x).1 h in begin clear _let_match, subst hn, rw [mul_lt_iff_lt_one_left two_pi_pos, ← int.cast_one, int.cast_lt, ← int.le_sub_one_iff, sub_self] at hx₂, rw [neg_lt, neg_mul_eq_neg_mul, mul_lt_iff_lt_one_left two_pi_pos, neg_lt, ← int.cast_one, ← int.cast_neg, int.cast_lt, ← int.add_one_le_iff, neg_add_self] at hx₁, exact mul_eq_zero.2 (or.inl (int.cast_eq_zero.2 (le_antisymm hx₂ hx₁))), end, λ h, by simp [h]⟩ theorem cos_sub_cos (θ ψ : ℝ) : cos θ - cos ψ = -2 * sin((θ + ψ)/2) * sin((θ - ψ)/2) := by rw [← sin_pi_div_two_sub, ← sin_pi_div_two_sub, sin_sub_sin, sub_sub_sub_cancel_left, add_sub, sub_add_eq_add_sub, add_halves, sub_sub, sub_div π, cos_pi_div_two_sub, ← neg_sub, neg_div, sin_neg, ← neg_mul_eq_mul_neg, neg_mul_eq_neg_mul, mul_right_comm] lemma cos_lt_cos_of_nonneg_of_le_pi_div_two {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π / 2) (hxy : x < y) : cos y < cos x := calc cos y = cos x * cos (y - x) - sin x * sin (y - x) : by rw [← cos_add, add_sub_cancel'_right] ... < (cos x * 1) - sin x * sin (y - x) : sub_lt_sub_right ((mul_lt_mul_left (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (lt_of_lt_of_le (neg_neg_of_pos pi_div_two_pos) hx₁) (lt_of_lt_of_le hxy hy₂))).2 (lt_of_le_of_ne (cos_le_one _) (mt (cos_eq_one_iff_of_lt_of_lt (show -(2 * π) < y - x, by linarith) (show y - x < 2 * π, by linarith)).1 (sub_ne_zero.2 (ne_of_lt hxy).symm)))) _ ... ≤ _ : by rw mul_one; exact sub_le_self _ (mul_nonneg (sin_nonneg_of_nonneg_of_le_pi hx₁ (by linarith)) (sin_nonneg_of_nonneg_of_le_pi (by linarith) (by linarith))) lemma cos_lt_cos_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : x < y) : cos y < cos x := match (le_total x (π / 2) : x ≤ π / 2 ∨ π / 2 ≤ x), le_total y (π / 2) with | or.inl hx, or.inl hy := cos_lt_cos_of_nonneg_of_le_pi_div_two hx₁ hx hy₁ hy hxy | or.inl hx, or.inr hy := (lt_or_eq_of_le hx).elim (λ hx, calc cos y ≤ 0 : cos_nonpos_of_pi_div_two_le_of_le hy (by linarith [pi_pos]) ... < cos x : cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hx) (λ hx, calc cos y < 0 : cos_neg_of_pi_div_two_lt_of_lt (by linarith) (by linarith [pi_pos]) ... = cos x : by rw [hx, cos_pi_div_two]) | or.inr hx, or.inl hy := by linarith | or.inr hx, or.inr hy := neg_lt_neg_iff.1 (by rw [← cos_pi_sub, ← cos_pi_sub]; apply cos_lt_cos_of_nonneg_of_le_pi_div_two; linarith) end lemma cos_le_cos_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : x ≤ y) : cos y ≤ cos x := (lt_or_eq_of_le hxy).elim (le_of_lt ∘ cos_lt_cos_of_nonneg_of_le_pi hx₁ hx₂ hy₁ hy₂) (λ h, h ▸ le_refl _) lemma sin_lt_sin_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y) (hy₂ : y ≤ π / 2) (hxy : x < y) : sin x < sin y := by rw [← cos_sub_pi_div_two, ← cos_sub_pi_div_two, ← cos_neg (x - _), ← cos_neg (y - _)]; apply cos_lt_cos_of_nonneg_of_le_pi; linarith lemma sin_le_sin_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y) (hy₂ : y ≤ π / 2) (hxy : x ≤ y) : sin x ≤ sin y := (lt_or_eq_of_le hxy).elim (le_of_lt ∘ sin_lt_sin_of_le_of_le_pi_div_two hx₁ hx₂ hy₁ hy₂) (λ h, h ▸ le_refl _) lemma sin_inj_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y) (hy₂ : y ≤ π / 2) (hxy : sin x = sin y) : x = y := match lt_trichotomy x y with | or.inl h := absurd (sin_lt_sin_of_le_of_le_pi_div_two hx₁ hx₂ hy₁ hy₂ h) (by rw hxy; exact lt_irrefl _) | or.inr (or.inl h) := h | or.inr (or.inr h) := absurd (sin_lt_sin_of_le_of_le_pi_div_two hy₁ hy₂ hx₁ hx₂ h) (by rw hxy; exact lt_irrefl _) end lemma cos_inj_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : cos x = cos y) : x = y := begin rw [← sin_pi_div_two_sub, ← sin_pi_div_two_sub] at hxy, refine (sub_left_inj).1 (sin_inj_of_le_of_le_pi_div_two _ _ _ _ hxy); linarith end lemma exists_sin_eq : set.Icc (-1:ℝ) 1 ⊆ sin '' set.Icc (-(π / 2)) (π / 2) := by convert intermediate_value_Icc (le_trans (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos)) continuous_sin.continuous_on; simp only [sin_neg, sin_pi_div_two] lemma sin_lt {x : ℝ} (h : 0 < x) : sin x < x := begin cases le_or_gt x 1 with h' h', { have hx : abs x = x := abs_of_nonneg (le_of_lt h), have : abs x ≤ 1, rwa [hx], have := sin_bound this, rw [abs_le] at this, have := this.2, rw [sub_le_iff_le_add', hx] at this, apply lt_of_le_of_lt this, rw [sub_add], apply lt_of_lt_of_le _ (le_of_eq (sub_zero x)), apply sub_lt_sub_left, rw sub_pos, apply mul_lt_mul', { rw [pow_succ x 3], refine le_trans _ (le_of_eq (one_mul _)), rw mul_le_mul_right, exact h', apply pow_pos h }, norm_num, norm_num, apply pow_pos h }, exact lt_of_le_of_lt (sin_le_one x) h' end /- note 1: this inequality is not tight, the tighter inequality is sin x > x - x ^ 3 / 6. note 2: this is also true for x > 1, but it's nontrivial for x just above 1. -/ lemma sin_gt_sub_cube {x : ℝ} (h : 0 < x) (h' : x ≤ 1) : x - x ^ 3 / 4 < sin x := begin have hx : abs x = x := abs_of_nonneg (le_of_lt h), have : abs x ≤ 1, rwa [hx], have := sin_bound this, rw [abs_le] at this, have := this.1, rw [le_sub_iff_add_le, hx] at this, refine lt_of_lt_of_le _ this, rw [add_comm, sub_add, sub_neg_eq_add], apply sub_lt_sub_left, apply add_lt_of_lt_sub_left, rw (show x ^ 3 / 4 - x ^ 3 / 6 = x ^ 3 / 12, by simp [div_eq_mul_inv, (mul_sub _ _ _).symm, -sub_eq_add_neg]; congr; norm_num), apply mul_lt_mul', { rw [pow_succ x 3], refine le_trans _ (le_of_eq (one_mul _)), rw mul_le_mul_right, exact h', apply pow_pos h }, norm_num, norm_num, apply pow_pos h end /-- The type of angles -/ def angle : Type := quotient_add_group.quotient (gmultiples (2 * π)) namespace angle instance angle.add_comm_group : add_comm_group angle := quotient_add_group.add_comm_group _ instance : inhabited angle := ⟨0⟩ instance angle.has_coe : has_coe ℝ angle := ⟨quotient.mk'⟩ instance angle.is_add_group_hom : @is_add_group_hom ℝ angle _ _ (coe : ℝ → angle) := @quotient_add_group.is_add_group_hom _ _ _ (normal_add_subgroup_of_add_comm_group _) @[simp] lemma coe_zero : ↑(0 : ℝ) = (0 : angle) := rfl @[simp] lemma coe_add (x y : ℝ) : ↑(x + y : ℝ) = (↑x + ↑y : angle) := rfl @[simp] lemma coe_neg (x : ℝ) : ↑(-x : ℝ) = -(↑x : angle) := rfl @[simp] lemma coe_sub (x y : ℝ) : ↑(x - y : ℝ) = (↑x - ↑y : angle) := rfl @[simp] lemma coe_smul (x : ℝ) (n : ℕ) : ↑(add_monoid.smul n x : ℝ) = add_monoid.smul n (↑x : angle) := add_monoid_hom.map_smul ⟨coe, coe_zero, coe_add⟩ _ _ @[simp] lemma coe_gsmul (x : ℝ) (n : ℤ) : ↑(gsmul n x : ℝ) = gsmul n (↑x : angle) := add_monoid_hom.map_gsmul ⟨coe, coe_zero, coe_add⟩ _ _ @[simp] lemma coe_two_pi : ↑(2 * π : ℝ) = (0 : angle) := quotient.sound' ⟨-1, by dsimp only; rw [neg_one_gsmul, add_zero]⟩ lemma angle_eq_iff_two_pi_dvd_sub {ψ θ : ℝ} : (θ : angle) = ψ ↔ ∃ k : ℤ, θ - ψ = 2 * π * k := by simp only [quotient_add_group.eq, gmultiples, set.mem_range, gsmul_eq_mul', (sub_eq_neg_add _ _).symm, eq_comm] theorem cos_eq_iff_eq_or_eq_neg {θ ψ : ℝ} : cos θ = cos ψ ↔ (θ : angle) = ψ ∨ (θ : angle) = -ψ := begin split, { intro Hcos, rw [←sub_eq_zero, cos_sub_cos, mul_eq_zero, mul_eq_zero, neg_eq_zero, eq_false_intro two_ne_zero, false_or, sin_eq_zero_iff, sin_eq_zero_iff] at Hcos, rcases Hcos with ⟨n, hn⟩ | ⟨n, hn⟩, { right, rw [eq_div_iff_mul_eq _ _ (@two_ne_zero ℝ _), ← sub_eq_iff_eq_add] at hn, rw [← hn, coe_sub, eq_neg_iff_add_eq_zero, sub_add_cancel, mul_assoc, ← gsmul_eq_mul, coe_gsmul, mul_comm, coe_two_pi, gsmul_zero] }, { left, rw [eq_div_iff_mul_eq _ _ (@two_ne_zero ℝ _), eq_sub_iff_add_eq] at hn, rw [← hn, coe_add, mul_assoc, ← gsmul_eq_mul, coe_gsmul, mul_comm, coe_two_pi, gsmul_zero, zero_add] } }, { rw [angle_eq_iff_two_pi_dvd_sub, ← coe_neg, angle_eq_iff_two_pi_dvd_sub], rintro (⟨k, H⟩ | ⟨k, H⟩), rw [← sub_eq_zero_iff_eq, cos_sub_cos, H, mul_assoc 2 π k, mul_div_cancel_left _ (@two_ne_zero ℝ _), mul_comm π _, sin_int_mul_pi, mul_zero], rw [←sub_eq_zero_iff_eq, cos_sub_cos, ← sub_neg_eq_add, H, mul_assoc 2 π k, mul_div_cancel_left _ (@two_ne_zero ℝ _), mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul] } end theorem sin_eq_iff_eq_or_add_eq_pi {θ ψ : ℝ} : sin θ = sin ψ ↔ (θ : angle) = ψ ∨ (θ : angle) + ψ = π := begin split, { intro Hsin, rw [← cos_pi_div_two_sub, ← cos_pi_div_two_sub] at Hsin, cases cos_eq_iff_eq_or_eq_neg.mp Hsin with h h, { left, rw coe_sub at h, exact sub_left_inj.1 h }, right, rw [coe_sub, coe_sub, eq_neg_iff_add_eq_zero, add_sub, sub_add_eq_add_sub, ← coe_add, add_halves, sub_sub, sub_eq_zero] at h, exact h.symm }, { rw [angle_eq_iff_two_pi_dvd_sub, ←eq_sub_iff_add_eq, ←coe_sub, angle_eq_iff_two_pi_dvd_sub], rintro (⟨k, H⟩ | ⟨k, H⟩), rw [← sub_eq_zero_iff_eq, sin_sub_sin, H, mul_assoc 2 π k, mul_div_cancel_left _ (@two_ne_zero ℝ _), mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul], have H' : θ + ψ = (2 * k) * π + π := by rwa [←sub_add, sub_add_eq_add_sub, sub_eq_iff_eq_add, mul_assoc, mul_comm π _, ←mul_assoc] at H, rw [← sub_eq_zero_iff_eq, sin_sub_sin, H', add_div, mul_assoc 2 _ π, mul_div_cancel_left _ (@two_ne_zero ℝ _), cos_add_pi_div_two, sin_int_mul_pi, neg_zero, mul_zero] } end theorem cos_sin_inj {θ ψ : ℝ} (Hcos : cos θ = cos ψ) (Hsin : sin θ = sin ψ) : (θ : angle) = ψ := begin cases cos_eq_iff_eq_or_eq_neg.mp Hcos with hc hc, { exact hc }, cases sin_eq_iff_eq_or_add_eq_pi.mp Hsin with hs hs, { exact hs }, rw [eq_neg_iff_add_eq_zero, hs] at hc, cases quotient.exact' hc with n hn, dsimp only at hn, rw [← neg_one_mul, add_zero, ← sub_eq_zero_iff_eq, gsmul_eq_mul, ← mul_assoc, ← sub_mul, mul_eq_zero, eq_false_intro (ne_of_gt pi_pos), or_false, sub_neg_eq_add, ← int.cast_zero, ← int.cast_one, ← int.cast_bit0, ← int.cast_mul, ← int.cast_add, int.cast_inj] at hn, have : (n * 2 + 1) % (2:ℤ) = 0 % (2:ℤ) := congr_arg (%(2:ℤ)) hn, rw [add_comm, int.add_mul_mod_self] at this, exact absurd this one_ne_zero end end angle /-- Inverse of the `sin` function, returns values in the range `-π / 2 ≤ arcsin x` and `arcsin x ≤ π / 2`. If the argument is not between `-1` and `1` it defaults to `0` -/ noncomputable def arcsin (x : ℝ) : ℝ := if hx : -1 ≤ x ∧ x ≤ 1 then classical.some (exists_sin_eq hx) else 0 lemma arcsin_le_pi_div_two (x : ℝ) : arcsin x ≤ π / 2 := if hx : -1 ≤ x ∧ x ≤ 1 then by rw [arcsin, dif_pos hx]; exact (classical.some_spec (exists_sin_eq hx)).1.2 else by rw [arcsin, dif_neg hx]; exact le_of_lt pi_div_two_pos lemma neg_pi_div_two_le_arcsin (x : ℝ) : -(π / 2) ≤ arcsin x := if hx : -1 ≤ x ∧ x ≤ 1 then by rw [arcsin, dif_pos hx]; exact (classical.some_spec (exists_sin_eq hx)).1.1 else by rw [arcsin, dif_neg hx]; exact neg_nonpos.2 (le_of_lt pi_div_two_pos) lemma sin_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arcsin x) = x := by rw [arcsin, dif_pos (and.intro hx₁ hx₂)]; exact (classical.some_spec (exists_sin_eq ⟨hx₁, hx₂⟩)).2 lemma arcsin_sin {x : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) : arcsin (sin x) = x := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) hx₁ hx₂ (by rw sin_arcsin (neg_one_le_sin _) (sin_le_one _)) lemma arcsin_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1) (hxy : arcsin x = arcsin y) : x = y := by rw [← sin_arcsin hx₁ hx₂, ← sin_arcsin hy₁ hy₂, hxy] @[simp] lemma arcsin_zero : arcsin 0 = 0 := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos) (by rw [sin_arcsin, sin_zero]; norm_num) @[simp] lemma arcsin_one : arcsin 1 = π / 2 := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (by linarith [pi_pos]) (le_refl _) (by rw [sin_arcsin, sin_pi_div_two]; norm_num) @[simp] lemma arcsin_neg (x : ℝ) : arcsin (-x) = -arcsin x := if h : -1 ≤ x ∧ x ≤ 1 then have -1 ≤ -x ∧ -x ≤ 1, by rwa [neg_le_neg_iff, neg_le, and.comm], sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (neg_le_neg (arcsin_le_pi_div_two _)) (neg_le.1 (neg_pi_div_two_le_arcsin _)) (by rw [sin_arcsin this.1 this.2, sin_neg, sin_arcsin h.1 h.2]) else have ¬(-1 ≤ -x ∧ -x ≤ 1) := by rwa [neg_le_neg_iff, neg_le, and.comm], by rw [arcsin, arcsin, dif_neg h, dif_neg this, neg_zero] @[simp] lemma arcsin_neg_one : arcsin (-1) = -(π / 2) := by simp lemma arcsin_nonneg {x : ℝ} (hx : 0 ≤ x) : 0 ≤ arcsin x := if hx₁ : x ≤ 1 then not_lt.1 (λ h, not_lt.2 hx begin have := sin_lt_sin_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos) h, rw [real.sin_arcsin, sin_zero] at this; linarith end) else by rw [arcsin, dif_neg]; simp [hx₁] lemma arcsin_eq_zero_iff {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : arcsin x = 0 ↔ x = 0 := ⟨λ h, have sin (arcsin x) = 0, by simp [h], by rwa [sin_arcsin hx₁ hx₂] at this, λ h, by simp [h]⟩ lemma arcsin_pos {x : ℝ} (hx₁ : 0 < x) (hx₂ : x ≤ 1) : 0 < arcsin x := lt_of_le_of_ne (arcsin_nonneg (le_of_lt hx₁)) (ne.symm (mt (arcsin_eq_zero_iff (by linarith) hx₂).1 (ne_of_lt hx₁).symm)) lemma arcsin_nonpos {x : ℝ} (hx : x ≤ 0) : arcsin x ≤ 0 := neg_nonneg.1 (arcsin_neg x ▸ arcsin_nonneg (neg_nonneg.2 hx)) /-- Inverse of the `cos` function, returns values in the range `0 ≤ arccos x` and `arccos x ≤ π`. If the argument is not between `-1` and `1` it defaults to `π / 2` -/ noncomputable def arccos (x : ℝ) : ℝ := π / 2 - arcsin x lemma arccos_eq_pi_div_two_sub_arcsin (x : ℝ) : arccos x = π / 2 - arcsin x := rfl lemma arcsin_eq_pi_div_two_sub_arccos (x : ℝ) : arcsin x = π / 2 - arccos x := by simp [sub_eq_add_neg, arccos] lemma arccos_le_pi (x : ℝ) : arccos x ≤ π := by unfold arccos; linarith [neg_pi_div_two_le_arcsin x] lemma arccos_nonneg (x : ℝ) : 0 ≤ arccos x := by unfold arccos; linarith [arcsin_le_pi_div_two x] lemma cos_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arccos x) = x := by rw [arccos, cos_pi_div_two_sub, sin_arcsin hx₁ hx₂] lemma arccos_cos {x : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) : arccos (cos x) = x := by rw [arccos, ← sin_pi_div_two_sub, arcsin_sin]; simp [sub_eq_add_neg]; linarith lemma arccos_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1) (hxy : arccos x = arccos y) : x = y := arcsin_inj hx₁ hx₂ hy₁ hy₂ $ by simp [arccos, *] at * @[simp] lemma arccos_zero : arccos 0 = π / 2 := by simp [arccos] @[simp] lemma arccos_one : arccos 1 = 0 := by simp [arccos] @[simp] lemma arccos_neg_one : arccos (-1) = π := by simp [arccos, add_halves] lemma arccos_neg (x : ℝ) : arccos (-x) = π - arccos x := by rw [← add_halves π, arccos, arcsin_neg, arccos, add_sub_assoc, sub_sub_self]; simp lemma cos_arcsin_nonneg (x : ℝ) : 0 ≤ cos (arcsin x) := cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) lemma cos_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arcsin x) = sqrt (1 - x ^ 2) := have sin (arcsin x) ^ 2 + cos (arcsin x) ^ 2 = 1 := sin_sq_add_cos_sq (arcsin x), begin rw [← eq_sub_iff_add_eq', ← sqrt_inj (pow_two_nonneg _) (sub_nonneg.2 (sin_sq_le_one (arcsin x))), pow_two, sqrt_mul_self (cos_arcsin_nonneg _)] at this, rw [this, sin_arcsin hx₁ hx₂], end lemma sin_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arccos x) = sqrt (1 - x ^ 2) := by rw [arccos_eq_pi_div_two_sub_arcsin, sin_pi_div_two_sub, cos_arcsin hx₁ hx₂] lemma abs_div_sqrt_one_add_lt (x : ℝ) : abs (x / sqrt (1 + x ^ 2)) < 1 := have h₁ : 0 < 1 + x ^ 2, from add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg _), have h₂ : 0 < sqrt (1 + x ^ 2), from sqrt_pos.2 h₁, by rw [abs_div, div_lt_iff (abs_pos_of_pos h₂), one_mul, mul_self_lt_mul_self_iff (abs_nonneg x) (abs_nonneg _), ← abs_mul, ← abs_mul, mul_self_sqrt (add_nonneg zero_le_one (pow_two_nonneg _)), abs_of_nonneg (mul_self_nonneg x), abs_of_nonneg (le_of_lt h₁), pow_two, add_comm]; exact lt_add_one _ lemma div_sqrt_one_add_lt_one (x : ℝ) : x / sqrt (1 + x ^ 2) < 1 := (abs_lt.1 (abs_div_sqrt_one_add_lt _)).2 lemma neg_one_lt_div_sqrt_one_add (x : ℝ) : -1 < x / sqrt (1 + x ^ 2) := (abs_lt.1 (abs_div_sqrt_one_add_lt _)).1 lemma tan_pos_of_pos_of_lt_pi_div_two {x : ℝ} (h0x : 0 < x) (hxp : x < π / 2) : 0 < tan x := by rw tan_eq_sin_div_cos; exact div_pos (sin_pos_of_pos_of_lt_pi h0x (by linarith)) (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hxp) lemma tan_nonneg_of_nonneg_of_le_pi_div_two {x : ℝ} (h0x : 0 ≤ x) (hxp : x ≤ π / 2) : 0 ≤ tan x := match lt_or_eq_of_le h0x, lt_or_eq_of_le hxp with | or.inl hx0, or.inl hxp := le_of_lt (tan_pos_of_pos_of_lt_pi_div_two hx0 hxp) | or.inl hx0, or.inr hxp := by simp [hxp, tan_eq_sin_div_cos] | or.inr hx0, _ := by simp [hx0.symm] end lemma tan_neg_of_neg_of_pi_div_two_lt {x : ℝ} (hx0 : x < 0) (hpx : -(π / 2) < x) : tan x < 0 := neg_pos.1 (tan_neg x ▸ tan_pos_of_pos_of_lt_pi_div_two (by linarith) (by linarith [pi_pos])) lemma tan_nonpos_of_nonpos_of_neg_pi_div_two_le {x : ℝ} (hx0 : x ≤ 0) (hpx : -(π / 2) ≤ x) : tan x ≤ 0 := neg_nonneg.1 (tan_neg x ▸ tan_nonneg_of_nonneg_of_le_pi_div_two (by linarith) (by linarith [pi_pos])) lemma tan_lt_tan_of_nonneg_of_lt_pi_div_two {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x < π / 2) (hy₁ : 0 ≤ y) (hy₂ : y < π / 2) (hxy : x < y) : tan x < tan y := begin rw [tan_eq_sin_div_cos, tan_eq_sin_div_cos], exact div_lt_div (sin_lt_sin_of_le_of_le_pi_div_two (by linarith) (le_of_lt hx₂) (by linarith) (le_of_lt hy₂) hxy) (cos_le_cos_of_nonneg_of_le_pi hx₁ (by linarith) hy₁ (by linarith) (le_of_lt hxy)) (sin_nonneg_of_nonneg_of_le_pi hy₁ (by linarith)) (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hy₂) end lemma tan_lt_tan_of_lt_of_lt_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) (hy₁ : -(π / 2) < y) (hy₂ : y < π / 2) (hxy : x < y) : tan x < tan y := match le_total x 0, le_total y 0 with | or.inl hx0, or.inl hy0 := neg_lt_neg_iff.1 $ by rw [← tan_neg, ← tan_neg]; exact tan_lt_tan_of_nonneg_of_lt_pi_div_two (neg_nonneg.2 hy0) (neg_lt.2 hy₁) (neg_nonneg.2 hx0) (neg_lt.2 hx₁) (neg_lt_neg hxy) | or.inl hx0, or.inr hy0 := (lt_or_eq_of_le hy0).elim (λ hy0, calc tan x ≤ 0 : tan_nonpos_of_nonpos_of_neg_pi_div_two_le hx0 (le_of_lt hx₁) ... < tan y : tan_pos_of_pos_of_lt_pi_div_two hy0 hy₂) (λ hy0, by rw [← hy0, tan_zero]; exact tan_neg_of_neg_of_pi_div_two_lt (hy0.symm ▸ hxy) hx₁) | or.inr hx0, or.inl hy0 := by linarith | or.inr hx0, or.inr hy0 := tan_lt_tan_of_nonneg_of_lt_pi_div_two hx0 hx₂ hy0 hy₂ hxy end lemma tan_inj_of_lt_of_lt_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) (hy₁ : -(π / 2) < y) (hy₂ : y < π / 2) (hxy : tan x = tan y) : x = y := match lt_trichotomy x y with | or.inl h := absurd (tan_lt_tan_of_lt_of_lt_pi_div_two hx₁ hx₂ hy₁ hy₂ h) (by rw hxy; exact lt_irrefl _) | or.inr (or.inl h) := h | or.inr (or.inr h) := absurd (tan_lt_tan_of_lt_of_lt_pi_div_two hy₁ hy₂ hx₁ hx₂ h) (by rw hxy; exact lt_irrefl _) end /-- Inverse of the `tan` function, returns values in the range `-π / 2 < arctan x` and `arctan x < π / 2` -/ noncomputable def arctan (x : ℝ) : ℝ := arcsin (x / sqrt (1 + x ^ 2)) lemma sin_arctan (x : ℝ) : sin (arctan x) = x / sqrt (1 + x ^ 2) := sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)) lemma cos_arctan (x : ℝ) : cos (arctan x) = 1 / sqrt (1 + x ^ 2) := have h₁ : (0 : ℝ) < 1 + x ^ 2, from add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg _), have h₂ : (x / sqrt (1 + x ^ 2)) ^ 2 < 1, by rw [pow_two, ← abs_mul_self, _root_.abs_mul]; exact mul_lt_one_of_nonneg_of_lt_one_left (abs_nonneg _) (abs_div_sqrt_one_add_lt _) (le_of_lt (abs_div_sqrt_one_add_lt _)), by rw [arctan, cos_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), one_div_eq_inv, ← sqrt_inv, sqrt_inj (sub_nonneg.2 (le_of_lt h₂)) (inv_nonneg.2 (le_of_lt h₁)), div_pow, pow_two (sqrt _), mul_self_sqrt (le_of_lt h₁), ← domain.mul_left_inj (ne.symm (ne_of_lt h₁)), mul_sub, mul_div_cancel' _ (ne.symm (ne_of_lt h₁)), mul_inv_cancel (ne.symm (ne_of_lt h₁))]; simp lemma tan_arctan (x : ℝ) : tan (arctan x) = x := by rw [tan_eq_sin_div_cos, sin_arctan, cos_arctan, div_div_div_div_eq, mul_one, mul_div_assoc, div_self (mt sqrt_eq_zero'.1 (not_le_of_gt (add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg x)))), mul_one] lemma arctan_lt_pi_div_two (x : ℝ) : arctan x < π / 2 := lt_of_le_of_ne (arcsin_le_pi_div_two _) (λ h, ne_of_lt (div_sqrt_one_add_lt_one x) $ by rw [← sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), ← arctan, h, sin_pi_div_two]) lemma neg_pi_div_two_lt_arctan (x : ℝ) : -(π / 2) < arctan x := lt_of_le_of_ne (neg_pi_div_two_le_arcsin _) (λ h, ne_of_lt (neg_one_lt_div_sqrt_one_add x) $ by rw [← sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), ← arctan, ← h, sin_neg, sin_pi_div_two]) lemma tan_surjective : function.surjective tan := function.surjective_of_has_right_inverse ⟨_, tan_arctan⟩ lemma arctan_tan {x : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) : arctan (tan x) = x := tan_inj_of_lt_of_lt_pi_div_two (neg_pi_div_two_lt_arctan _) (arctan_lt_pi_div_two _) hx₁ hx₂ (by rw tan_arctan) @[simp] lemma arctan_zero : arctan 0 = 0 := by simp [arctan] @[simp] lemma arctan_neg (x : ℝ) : arctan (-x) = - arctan x := by simp [arctan, neg_div] end real namespace complex open_locale real /-- `arg` returns values in the range (-π, π], such that for `x ≠ 0`, `sin (arg x) = x.im / x.abs` and `cos (arg x) = x.re / x.abs`, `arg 0` defaults to `0` -/ noncomputable def arg (x : ℂ) : ℝ := if 0 ≤ x.re then real.arcsin (x.im / x.abs) else if 0 ≤ x.im then real.arcsin ((-x).im / x.abs) + π else real.arcsin ((-x).im / x.abs) - π lemma arg_le_pi (x : ℂ) : arg x ≤ π := if hx₁ : 0 ≤ x.re then by rw [arg, if_pos hx₁]; exact le_trans (real.arcsin_le_pi_div_two _) (le_of_lt (half_lt_self real.pi_pos)) else have hx : x ≠ 0, from λ h, by simpa [h, lt_irrefl] using hx₁, if hx₂ : 0 ≤ x.im then by rw [arg, if_neg hx₁, if_pos hx₂]; exact le_sub_iff_add_le.1 (by rw sub_self; exact real.arcsin_nonpos (by rw [neg_im, neg_div, neg_nonpos]; exact div_nonneg hx₂ (abs_pos.2 hx))) else by rw [arg, if_neg hx₁, if_neg hx₂]; exact sub_le_iff_le_add.2 (le_trans (real.arcsin_le_pi_div_two _) (by linarith [real.pi_pos])) lemma neg_pi_lt_arg (x : ℂ) : -π < arg x := if hx₁ : 0 ≤ x.re then by rw [arg, if_pos hx₁]; exact lt_of_lt_of_le (neg_lt_neg (half_lt_self real.pi_pos)) (real.neg_pi_div_two_le_arcsin _) else have hx : x ≠ 0, from λ h, by simpa [h, lt_irrefl] using hx₁, if hx₂ : 0 ≤ x.im then by rw [arg, if_neg hx₁, if_pos hx₂]; exact sub_lt_iff_lt_add.1 (lt_of_lt_of_le (by linarith [real.pi_pos]) (real.neg_pi_div_two_le_arcsin _)) else by rw [arg, if_neg hx₁, if_neg hx₂]; exact lt_sub_iff_add_lt.2 (by rw neg_add_self; exact real.arcsin_pos (by rw [neg_im]; exact div_pos (neg_pos.2 (lt_of_not_ge hx₂)) (abs_pos.2 hx)) (by rw [← abs_neg x]; exact (abs_le.1 (abs_im_div_abs_le_one _)).2)) lemma arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg {x : ℂ} (hxr : x.re < 0) (hxi : 0 ≤ x.im) : arg x = arg (-x) + π := have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos], by rw [arg, arg, if_neg (not_le.2 hxr), if_pos this, if_pos hxi, abs_neg] lemma arg_eq_arg_neg_sub_pi_of_im_neg_of_re_neg {x : ℂ} (hxr : x.re < 0) (hxi : x.im < 0) : arg x = arg (-x) - π := have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos], by rw [arg, arg, if_neg (not_le.2 hxr), if_neg (not_le.2 hxi), if_pos this, abs_neg] @[simp] lemma arg_zero : arg 0 = 0 := by simp [arg, le_refl] @[simp] lemma arg_one : arg 1 = 0 := by simp [arg, zero_le_one] @[simp] lemma arg_neg_one : arg (-1) = π := by simp [arg, le_refl, not_le.2 (@zero_lt_one ℝ _)] @[simp] lemma arg_I : arg I = π / 2 := by simp [arg, le_refl] @[simp] lemma arg_neg_I : arg (-I) = -(π / 2) := by simp [arg, le_refl] lemma sin_arg (x : ℂ) : real.sin (arg x) = x.im / x.abs := by unfold arg; split_ifs; simp [sub_eq_add_neg, arg, real.sin_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1 (abs_le.1 (abs_im_div_abs_le_one x)).2, real.sin_add, neg_div, real.arcsin_neg, real.sin_neg] private lemma cos_arg_of_re_nonneg {x : ℂ} (hx : x ≠ 0) (hxr : 0 ≤ x.re) : real.cos (arg x) = x.re / x.abs := have 0 ≤ 1 - (x.im / abs x) ^ 2, from sub_nonneg.2 $ by rw [pow_two, ← _root_.abs_mul_self, _root_.abs_mul, ← pow_two]; exact pow_le_one _ (_root_.abs_nonneg _) (abs_im_div_abs_le_one _), by rw [eq_div_iff_mul_eq _ _ (mt abs_eq_zero.1 hx), ← real.mul_self_sqrt (abs_nonneg x), arg, if_pos hxr, real.cos_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1 (abs_le.1 (abs_im_div_abs_le_one x)).2, ← real.sqrt_mul (abs_nonneg _), ← real.sqrt_mul this, sub_mul, div_pow, ← pow_two, div_mul_cancel _ (pow_ne_zero 2 (mt abs_eq_zero.1 hx)), one_mul, pow_two, mul_self_abs, norm_sq, pow_two, add_sub_cancel, real.sqrt_mul_self hxr] lemma cos_arg {x : ℂ} (hx : x ≠ 0) : real.cos (arg x) = x.re / x.abs := if hxr : 0 ≤ x.re then cos_arg_of_re_nonneg hx hxr else have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos] using hxr, if hxi : 0 ≤ x.im then have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos] using hxr, by rw [arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg (not_le.1 hxr) hxi, real.cos_add_pi, cos_arg_of_re_nonneg (neg_ne_zero.2 hx) this]; simp [neg_div] else by rw [arg_eq_arg_neg_sub_pi_of_im_neg_of_re_neg (not_le.1 hxr) (not_le.1 hxi)]; simp [sub_eq_add_neg, real.cos_add, neg_div, cos_arg_of_re_nonneg (neg_ne_zero.2 hx) this] lemma tan_arg {x : ℂ} : real.tan (arg x) = x.im / x.re := begin by_cases h : x = 0, { simp only [h, euclidean_domain.zero_div, complex.zero_im, complex.arg_zero, real.tan_zero, complex.zero_re]}, rw [real.tan_eq_sin_div_cos, sin_arg, cos_arg h, div_div_div_cancel_right' _ (mt abs_eq_zero.1 h)] end lemma arg_cos_add_sin_mul_I {x : ℝ} (hx₁ : -π < x) (hx₂ : x ≤ π) : arg (cos x + sin x * I) = x := if hx₃ : -(π / 2) ≤ x ∧ x ≤ π / 2 then have hx₄ : 0 ≤ (cos x + sin x * I).re, by simp; exact real.cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two hx₃.1 hx₃.2, by rw [arg, if_pos hx₄]; simp [abs_cos_add_sin_mul_I, sin_of_real_re, real.arcsin_sin hx₃.1 hx₃.2] else if hx₄ : x < -(π / 2) then have hx₅ : ¬0 ≤ (cos x + sin x * I).re := suffices ¬ 0 ≤ real.cos x, by simpa, not_le.2 $ by rw ← real.cos_neg; apply real.cos_neg_of_pi_div_two_lt_of_lt; linarith, have hx₆ : ¬0 ≤ (cos ↑x + sin ↑x * I).im := suffices real.sin x < 0, by simpa, by apply real.sin_neg_of_neg_of_neg_pi_lt; linarith, suffices -π + -real.arcsin (real.sin x) = x, by rw [arg, if_neg hx₅, if_neg hx₆]; simpa [sub_eq_add_neg, add_comm, abs_cos_add_sin_mul_I, sin_of_real_re], by rw [← real.arcsin_neg, ← real.sin_add_pi, real.arcsin_sin]; try {simp [add_left_comm]}; linarith else have hx₅ : π / 2 < x, by cases not_and_distrib.1 hx₃; linarith, have hx₆ : ¬0 ≤ (cos x + sin x * I).re := suffices ¬0 ≤ real.cos x, by simpa, not_le.2 $ by apply real.cos_neg_of_pi_div_two_lt_of_lt; linarith, have hx₇ : 0 ≤ (cos x + sin x * I).im := suffices 0 ≤ real.sin x, by simpa, by apply real.sin_nonneg_of_nonneg_of_le_pi; linarith, suffices π - real.arcsin (real.sin x) = x, by rw [arg, if_neg hx₆, if_pos hx₇]; simpa [sub_eq_add_neg, add_comm, abs_cos_add_sin_mul_I, sin_of_real_re], by rw [← real.sin_pi_sub, real.arcsin_sin]; simp [sub_eq_add_neg]; linarith lemma arg_eq_arg_iff {x y : ℂ} (hx : x ≠ 0) (hy : y ≠ 0) : arg x = arg y ↔ (abs y / abs x : ℂ) * x = y := have hax : abs x ≠ 0, from (mt abs_eq_zero.1 hx), have hay : abs y ≠ 0, from (mt abs_eq_zero.1 hy), ⟨λ h, begin have hcos := congr_arg real.cos h, rw [cos_arg hx, cos_arg hy, div_eq_div_iff hax hay] at hcos, have hsin := congr_arg real.sin h, rw [sin_arg, sin_arg, div_eq_div_iff hax hay] at hsin, apply complex.ext, { rw [mul_re, ← of_real_div, of_real_re, of_real_im, zero_mul, sub_zero, mul_comm, ← mul_div_assoc, hcos, mul_div_cancel _ hax] }, { rw [mul_im, ← of_real_div, of_real_re, of_real_im, zero_mul, add_zero, mul_comm, ← mul_div_assoc, hsin, mul_div_cancel _ hax] } end, λ h, have hre : abs (y / x) * x.re = y.re, by rw ← of_real_div at h; simpa [-of_real_div] using congr_arg re h, have hre' : abs (x / y) * y.re = x.re, by rw [← hre, abs_div, abs_div, ← mul_assoc, div_mul_div, mul_comm (abs _), div_self (mul_ne_zero hay hax), one_mul], have him : abs (y / x) * x.im = y.im, by rw ← of_real_div at h; simpa [-of_real_div] using congr_arg im h, have him' : abs (x / y) * y.im = x.im, by rw [← him, abs_div, abs_div, ← mul_assoc, div_mul_div, mul_comm (abs _), div_self (mul_ne_zero hay hax), one_mul], have hxya : x.im / abs x = y.im / abs y, by rw [← him, abs_div, mul_comm, ← mul_div_comm, mul_div_cancel_left _ hay], have hnxya : (-x).im / abs x = (-y).im / abs y, by rw [neg_im, neg_im, neg_div, neg_div, hxya], if hxr : 0 ≤ x.re then have hyr : 0 ≤ y.re, from hre ▸ mul_nonneg (abs_nonneg _) hxr, by simp [arg, *] at * else have hyr : ¬ 0 ≤ y.re, from λ hyr, hxr $ hre' ▸ mul_nonneg (abs_nonneg _) hyr, if hxi : 0 ≤ x.im then have hyi : 0 ≤ y.im, from him ▸ mul_nonneg (abs_nonneg _) hxi, by simp [arg, *] at * else have hyi : ¬ 0 ≤ y.im, from λ hyi, hxi $ him' ▸ mul_nonneg (abs_nonneg _) hyi, by simp [arg, *] at *⟩ lemma arg_real_mul (x : ℂ) {r : ℝ} (hr : 0 < r) : arg (r * x) = arg x := if hx : x = 0 then by simp [hx] else (arg_eq_arg_iff (mul_ne_zero (of_real_ne_zero.2 (ne_of_lt hr).symm) hx) hx).2 $ by rw [abs_mul, abs_of_nonneg (le_of_lt hr), ← mul_assoc, of_real_mul, mul_comm (r : ℂ), ← div_div_eq_div_mul, div_mul_cancel _ (of_real_ne_zero.2 (ne_of_lt hr).symm), div_self (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), one_mul] lemma ext_abs_arg {x y : ℂ} (h₁ : x.abs = y.abs) (h₂ : x.arg = y.arg) : x = y := if hy : y = 0 then by simp * at * else have hx : x ≠ 0, from λ hx, by simp [*, eq_comm] at *, by rwa [arg_eq_arg_iff hx hy, h₁, div_self (of_real_ne_zero.2 (mt abs_eq_zero.1 hy)), one_mul] at h₂ lemma arg_of_real_of_nonneg {x : ℝ} (hx : 0 ≤ x) : arg x = 0 := by simp [arg, hx] lemma arg_of_real_of_neg {x : ℝ} (hx : x < 0) : arg x = π := by rw [arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg, ← of_real_neg, arg_of_real_of_nonneg]; simp [*, le_iff_eq_or_lt, lt_neg] /-- Inverse of the `exp` function. Returns values such that `(log x).im > - π` and `(log x).im ≤ π`. `log 0 = 0`-/ noncomputable def log (x : ℂ) : ℂ := x.abs.log + arg x * I lemma log_re (x : ℂ) : x.log.re = x.abs.log := by simp [log] lemma log_im (x : ℂ) : x.log.im = x.arg := by simp [log] lemma exp_log {x : ℂ} (hx : x ≠ 0) : exp (log x) = x := by rw [log, exp_add_mul_I, ← of_real_sin, sin_arg, ← of_real_cos, cos_arg hx, ← of_real_exp, real.exp_log (abs_pos.2 hx), mul_add, of_real_div, of_real_div, mul_div_cancel' _ (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), ← mul_assoc, mul_div_cancel' _ (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), re_add_im] lemma exp_inj_of_neg_pi_lt_of_le_pi {x y : ℂ} (hx₁ : -π < x.im) (hx₂ : x.im ≤ π) (hy₁ : - π < y.im) (hy₂ : y.im ≤ π) (hxy : exp x = exp y) : x = y := by rw [exp_eq_exp_re_mul_sin_add_cos, exp_eq_exp_re_mul_sin_add_cos y] at hxy; exact complex.ext (real.exp_injective $ by simpa [abs_mul, abs_cos_add_sin_mul_I] using congr_arg complex.abs hxy) (by simpa [(of_real_exp _).symm, - of_real_exp, arg_real_mul _ (real.exp_pos _), arg_cos_add_sin_mul_I hx₁ hx₂, arg_cos_add_sin_mul_I hy₁ hy₂] using congr_arg arg hxy) lemma log_exp {x : ℂ} (hx₁ : -π < x.im) (hx₂: x.im ≤ π) : log (exp x) = x := exp_inj_of_neg_pi_lt_of_le_pi (by rw log_im; exact neg_pi_lt_arg _) (by rw log_im; exact arg_le_pi _) hx₁ hx₂ (by rw [exp_log (exp_ne_zero _)]) lemma of_real_log {x : ℝ} (hx : 0 ≤ x) : (x.log : ℂ) = log x := complex.ext (by rw [log_re, of_real_re, abs_of_nonneg hx]) (by rw [of_real_im, log_im, arg_of_real_of_nonneg hx]) @[simp] lemma log_zero : log 0 = 0 := by simp [log] @[simp] lemma log_one : log 1 = 0 := by simp [log] lemma log_neg_one : log (-1) = π * I := by simp [log] lemma log_I : log I = π / 2 * I := by simp [log] lemma log_neg_I : log (-I) = -(π / 2) * I := by simp [log] lemma exp_eq_one_iff {x : ℂ} : exp x = 1 ↔ ∃ n : ℤ, x = n * ((2 * π) * I) := have real.exp (x.re) * real.cos (x.im) = 1 → real.cos x.im ≠ -1, from λ h₁ h₂, begin rw [h₂, mul_neg_eq_neg_mul_symm, mul_one, neg_eq_iff_neg_eq] at h₁, have := real.exp_pos x.re, rw ← h₁ at this, exact absurd this (by norm_num) end, calc exp x = 1 ↔ (exp x).re = 1 ∧ (exp x).im = 0 : by simp [complex.ext_iff] ... ↔ real.cos x.im = 1 ∧ real.sin x.im = 0 ∧ x.re = 0 : begin rw exp_eq_exp_re_mul_sin_add_cos, simp [complex.ext_iff, cos_of_real_re, sin_of_real_re, exp_of_real_re, real.exp_ne_zero], split; finish [real.sin_eq_zero_iff_cos_eq] end ... ↔ (∃ n : ℤ, ↑n * (2 * π) = x.im) ∧ (∃ n : ℤ, ↑n * π = x.im) ∧ x.re = 0 : by rw [real.sin_eq_zero_iff, real.cos_eq_one_iff] ... ↔ ∃ n : ℤ, x = n * ((2 * π) * I) : ⟨λ ⟨⟨n, hn⟩, ⟨m, hm⟩, h⟩, ⟨n, by simp [complex.ext_iff, hn.symm, h]⟩, λ ⟨n, hn⟩, ⟨⟨n, by simp [hn]⟩, ⟨2 * n, by simp [hn, mul_comm, mul_assoc, mul_left_comm]⟩, by simp [hn]⟩⟩ lemma exp_eq_exp_iff_exp_sub_eq_one {x y : ℂ} : exp x = exp y ↔ exp (x - y) = 1 := by rw [exp_sub, div_eq_one_iff_eq _ (exp_ne_zero _)] lemma exp_eq_exp_iff_exists_int {x y : ℂ} : exp x = exp y ↔ ∃ n : ℤ, x = y + n * ((2 * π) * I) := by simp only [exp_eq_exp_iff_exp_sub_eq_one, exp_eq_one_iff, sub_eq_iff_eq_add'] @[simp] lemma cos_pi_div_two : cos (π / 2) = 0 := calc cos (π / 2) = real.cos (π / 2) : by rw [of_real_cos]; simp ... = 0 : by simp @[simp] lemma sin_pi_div_two : sin (π / 2) = 1 := calc sin (π / 2) = real.sin (π / 2) : by rw [of_real_sin]; simp ... = 1 : by simp @[simp] lemma sin_pi : sin π = 0 := by rw [← of_real_sin, real.sin_pi]; simp @[simp] lemma cos_pi : cos π = -1 := by rw [← of_real_cos, real.cos_pi]; simp @[simp] lemma sin_two_pi : sin (2 * π) = 0 := by simp [two_mul, sin_add] @[simp] lemma cos_two_pi : cos (2 * π) = 1 := by simp [two_mul, cos_add] lemma sin_add_pi (x : ℝ) : sin (x + π) = -sin x := by simp [sin_add] lemma sin_add_two_pi (x : ℝ) : sin (x + 2 * π) = sin x := by simp [sin_add_pi, sin_add, sin_two_pi, cos_two_pi] lemma cos_add_two_pi (x : ℝ) : cos (x + 2 * π) = cos x := by simp [cos_add, cos_two_pi, sin_two_pi] lemma sin_pi_sub (x : ℝ) : sin (π - x) = sin x := by simp [sub_eq_add_neg, sin_add] lemma cos_add_pi (x : ℝ) : cos (x + π) = -cos x := by simp [cos_add] lemma cos_pi_sub (x : ℝ) : cos (π - x) = -cos x := by simp [sub_eq_add_neg, cos_add] lemma sin_add_pi_div_two (x : ℝ) : sin (x + π / 2) = cos x := by simp [sin_add] lemma sin_sub_pi_div_two (x : ℝ) : sin (x - π / 2) = -cos x := by simp [sub_eq_add_neg, sin_add] lemma sin_pi_div_two_sub (x : ℝ) : sin (π / 2 - x) = cos x := by simp [sub_eq_add_neg, sin_add] lemma cos_add_pi_div_two (x : ℝ) : cos (x + π / 2) = -sin x := by simp [cos_add] lemma cos_sub_pi_div_two (x : ℝ) : cos (x - π / 2) = sin x := by simp [sub_eq_add_neg, cos_add] lemma cos_pi_div_two_sub (x : ℝ) : cos (π / 2 - x) = sin x := by rw [← cos_neg, neg_sub, cos_sub_pi_div_two] lemma sin_nat_mul_pi (n : ℕ) : sin (n * π) = 0 := by induction n; simp [add_mul, sin_add, *] lemma sin_int_mul_pi (n : ℤ) : sin (n * π) = 0 := by cases n; simp [add_mul, sin_add, *, sin_nat_mul_pi] lemma cos_nat_mul_two_pi (n : ℕ) : cos (n * (2 * π)) = 1 := by induction n; simp [*, mul_add, cos_add, add_mul, cos_two_pi, sin_two_pi] lemma cos_int_mul_two_pi (n : ℤ) : cos (n * (2 * π)) = 1 := by cases n; simp only [cos_nat_mul_two_pi, int.of_nat_eq_coe, int.neg_succ_of_nat_coe, int.cast_coe_nat, int.cast_neg, (neg_mul_eq_neg_mul _ _).symm, cos_neg] lemma cos_int_mul_two_pi_add_pi (n : ℤ) : cos (n * (2 * π) + π) = -1 := by simp [cos_add, sin_add, cos_int_mul_two_pi] section pow /-- The complex power function `x^y`, given by `x^y = exp(y log x)` (where `log` is the principal determination of the logarithm), unless `x = 0` where one sets `0^0 = 1` and `0^y = 0` for `y ≠ 0`. -/ noncomputable def cpow (x y : ℂ) : ℂ := if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) noncomputable instance : has_pow ℂ ℂ := ⟨cpow⟩ @[simp] lemma cpow_eq_pow (x y : ℂ) : cpow x y = x ^ y := rfl lemma cpow_def (x y : ℂ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := rfl @[simp] lemma cpow_zero (x : ℂ) : x ^ (0 : ℂ) = 1 := by simp [cpow_def] @[simp] lemma cpow_eq_zero_iff (x y : ℂ) : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := by { simp only [cpow_def], split_ifs; simp [*, exp_ne_zero] } @[simp] lemma zero_cpow {x : ℂ} (h : x ≠ 0) : (0 : ℂ) ^ x = 0 := by simp [cpow_def, *] @[simp] lemma cpow_one (x : ℂ) : x ^ (1 : ℂ) = x := if hx : x = 0 then by simp [hx, cpow_def] else by rw [cpow_def, if_neg (@one_ne_zero ℂ _), if_neg hx, mul_one, exp_log hx] @[simp] lemma one_cpow (x : ℂ) : (1 : ℂ) ^ x = 1 := by rw cpow_def; split_ifs; simp [one_ne_zero, *] at * lemma cpow_add {x : ℂ} (y z : ℂ) (hx : x ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := by simp [cpow_def]; split_ifs; simp [*, exp_add, mul_add] at * lemma cpow_mul {x y : ℂ} (z : ℂ) (h₁ : -π < (log x * y).im) (h₂ : (log x * y).im ≤ π) : x ^ (y * z) = (x ^ y) ^ z := begin simp [cpow_def], split_ifs; simp [*, exp_ne_zero, log_exp h₁ h₂, mul_assoc] at * end lemma cpow_neg (x y : ℂ) : x ^ -y = (x ^ y)⁻¹ := by simp [cpow_def]; split_ifs; simp [exp_neg] @[simp] lemma cpow_nat_cast (x : ℂ) : ∀ (n : ℕ), x ^ (n : ℂ) = x ^ n | 0 := by simp | (n + 1) := if hx : x = 0 then by simp only [hx, pow_succ, complex.zero_cpow (nat.cast_ne_zero.2 (nat.succ_ne_zero _)), zero_mul] else by simp [cpow_def, hx, mul_comm, mul_add, exp_add, pow_succ, (cpow_nat_cast n).symm, exp_log hx] @[simp] lemma cpow_int_cast (x : ℂ) : ∀ (n : ℤ), x ^ (n : ℂ) = x ^ n | (n : ℕ) := by simp; refl | -[1+ n] := by rw fpow_neg_succ_of_nat; simp only [int.neg_succ_of_nat_coe, int.cast_neg, complex.cpow_neg, inv_eq_one_div, int.cast_coe_nat, cpow_nat_cast] lemma cpow_nat_inv_pow (x : ℂ) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℂ)) ^ n = x := have (log x * (↑n)⁻¹).im = (log x).im / n, by rw [div_eq_mul_inv, ← of_real_nat_cast, ← of_real_inv, mul_im, of_real_re, of_real_im]; simp, have h : -π < (log x * (↑n)⁻¹).im ∧ (log x * (↑n)⁻¹).im ≤ π, from (le_total (log x).im 0).elim (λ h, ⟨calc -π < (log x).im : by simp [log, neg_pi_lt_arg] ... ≤ ((log x).im * 1) / n : le_div_of_mul_le (nat.cast_pos.2 hn) (mul_le_mul_of_nonpos_left (by rw ← nat.cast_one; exact nat.cast_le.2 hn) h) ... = (log x * (↑n)⁻¹).im : by simp [this], this.symm ▸ le_trans (div_nonpos_of_nonpos_of_pos h (nat.cast_pos.2 hn)) (le_of_lt real.pi_pos)⟩) (λ h, ⟨this.symm ▸ lt_of_lt_of_le (neg_neg_of_pos real.pi_pos) (div_nonneg h (nat.cast_pos.2 hn)), calc (log x * (↑n)⁻¹).im = (1 * (log x).im) / n : by simp [this] ... ≤ (log x).im : (div_le_of_le_mul (nat.cast_pos.2 hn) (mul_le_mul_of_nonneg_right (by rw ← nat.cast_one; exact nat.cast_le.2 hn) h)) ... ≤ _ : by simp [log, arg_le_pi]⟩), by rw [← cpow_nat_cast, ← cpow_mul _ h.1 h.2, inv_mul_cancel (show (n : ℂ) ≠ 0, from nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 hn)), cpow_one] end pow end complex namespace real /-- The real power function `x^y`, defined as the real part of the complex power function. For `x > 0`, it is equal to `exp(y log x)`. For `x = 0`, one sets `0^0=1` and `0^y=0` for `y ≠ 0`. For `x < 0`, the definition is somewhat arbitary as it depends on the choice of a complex determination of the logarithm. With our conventions, it is equal to `exp (y log (-x)) cos (πy)`. -/ noncomputable def rpow (x y : ℝ) := ((x : ℂ) ^ (y : ℂ)).re noncomputable instance : has_pow ℝ ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x y : ℝ) : rpow x y = x ^ y := rfl lemma rpow_def (x y : ℝ) : x ^ y = ((x : ℂ) ^ (y : ℂ)).re := rfl lemma rpow_def_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := by simp only [rpow_def, complex.cpow_def]; split_ifs; simp [*, (complex.of_real_log hx).symm, -complex.of_real_mul, (complex.of_real_mul _ _).symm, complex.exp_of_real_re] at * lemma rpow_def_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : x ^ y = exp (log x * y) := by rw [rpow_def_of_nonneg (le_of_lt hx), if_neg (ne_of_gt hx)] lemma rpow_eq_zero_iff_of_nonneg {x y : ℝ} (hx : 0 ≤ x) : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := by { simp only [rpow_def_of_nonneg hx], split_ifs; simp [*, exp_ne_zero] } open_locale real lemma rpow_def_of_neg {x : ℝ} (hx : x < 0) (y : ℝ) : x ^ y = exp (log (-x) * y) * cos (y * π) := begin rw [rpow_def, complex.cpow_def, if_neg], have : complex.log x * y = ↑(log(-x) * y) + ↑(y * π) * complex.I, simp only [complex.log, abs_of_neg hx, complex.arg_of_real_of_neg hx, complex.abs_of_real, complex.of_real_mul], ring, { rw [this, complex.exp_add_mul_I, ← complex.of_real_exp, ← complex.of_real_cos, ← complex.of_real_sin, mul_add, ← complex.of_real_mul, ← mul_assoc, ← complex.of_real_mul, complex.add_re, complex.of_real_re, complex.mul_re, complex.I_re, complex.of_real_im], ring }, { rw complex.of_real_eq_zero, exact ne_of_lt hx } end lemma rpow_def_of_nonpos {x : ℝ} (hx : x ≤ 0) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log (-x) * y) * cos (y * π) := by split_ifs; simp [rpow_def, *]; exact rpow_def_of_neg (lt_of_le_of_ne hx h) _ lemma rpow_pos_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : 0 < x ^ y := by rw rpow_def_of_pos hx; apply exp_pos lemma abs_rpow_le_abs_rpow (x y : ℝ) : abs (x ^ y) ≤ abs (x) ^ y := abs_le_of_le_of_neg_le begin cases lt_trichotomy 0 x, { rw abs_of_pos h }, cases h, { simp [h.symm] }, rw [rpow_def_of_neg h, rpow_def_of_pos (abs_pos_of_neg h), abs_of_neg h], calc exp (log (-x) * y) * cos (y * π) ≤ exp (log (-x) * y) * 1 : mul_le_mul_of_nonneg_left (cos_le_one _) (le_of_lt $ exp_pos _) ... = _ : mul_one _ end begin cases lt_trichotomy 0 x, { rw abs_of_pos h, have : 0 < x^y := rpow_pos_of_pos h _, linarith }, cases h, { simp only [h.symm, abs_zero, rpow_def_of_nonneg], split_ifs, repeat {norm_num}}, rw [rpow_def_of_neg h, rpow_def_of_pos (abs_pos_of_neg h), abs_of_neg h], calc -(exp (log (-x) * y) * cos (y * π)) = exp (log (-x) * y) * (-cos (y * π)) : by ring ... ≤ exp (log (-x) * y) * 1 : mul_le_mul_of_nonneg_left (neg_le.2 $ neg_one_le_cos _) (le_of_lt $ exp_pos _) ... = exp (log (-x) * y) : mul_one _ end end real namespace complex lemma of_real_cpow {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : ((x ^ y : ℝ) : ℂ) = (x : ℂ) ^ (y : ℂ) := by simp [real.rpow_def_of_nonneg hx, complex.cpow_def]; split_ifs; simp [complex.of_real_log hx] @[simp] lemma abs_cpow_real (x : ℂ) (y : ℝ) : abs (x ^ (y : ℂ)) = x.abs ^ y := begin rw [real.rpow_def_of_nonneg (abs_nonneg _), complex.cpow_def], split_ifs; simp [*, abs_of_nonneg (le_of_lt (real.exp_pos _)), complex.log, complex.exp_add, add_mul, mul_right_comm _ I, exp_mul_I, abs_cos_add_sin_mul_I, (complex.of_real_mul _ _).symm, -complex.of_real_mul] at * end @[simp] lemma abs_cpow_inv_nat (x : ℂ) (n : ℕ) : abs (x ^ (n⁻¹ : ℂ)) = x.abs ^ (n⁻¹ : ℝ) := by rw ← abs_cpow_real; simp [-abs_cpow_real] end complex namespace real open_locale real variables {x y z : ℝ} @[simp] lemma rpow_zero (x : ℝ) : x ^ (0 : ℝ) = 1 := by simp [rpow_def] @[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ) ^ x = 0 := by simp [rpow_def, *] @[simp] lemma rpow_one (x : ℝ) : x ^ (1 : ℝ) = x := by simp [rpow_def] @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ) ^ x = 1 := by simp [rpow_def] lemma rpow_nonneg_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : 0 ≤ x ^ y := by rw [rpow_def_of_nonneg hx]; split_ifs; simp only [zero_le_one, le_refl, le_of_lt (exp_pos _)] lemma rpow_add {x : ℝ} (y z : ℝ) (hx : 0 < x) : x ^ (y + z) = x ^ y * x ^ z := by simp only [rpow_def_of_pos hx, mul_add, exp_add] lemma rpow_mul {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := by rw [← complex.of_real_inj, complex.of_real_cpow (rpow_nonneg_of_nonneg hx _), complex.of_real_cpow hx, complex.of_real_mul, complex.cpow_mul, complex.of_real_cpow hx]; simp only [(complex.of_real_mul _ _).symm, (complex.of_real_log hx).symm, complex.of_real_im, neg_lt_zero, pi_pos, le_of_lt pi_pos] lemma rpow_neg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := by simp only [rpow_def_of_nonneg hx]; split_ifs; simp [*, exp_neg] at * @[simp] lemma rpow_nat_cast (x : ℝ) (n : ℕ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, (complex.of_real_pow _ _).symm, complex.cpow_nat_cast, complex.of_real_nat_cast, complex.of_real_re] @[simp] lemma rpow_int_cast (x : ℝ) (n : ℤ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, (complex.of_real_fpow _ _).symm, complex.cpow_int_cast, complex.of_real_int_cast, complex.of_real_re] lemma mul_rpow {x y z : ℝ} (h : 0 ≤ x) (h₁ : 0 ≤ y) : (x*y)^z = x^z * y^z := begin iterate 3 { rw real.rpow_def_of_nonneg }, split_ifs; simp * at *, { have hx : 0 < x, cases lt_or_eq_of_le h with h₂ h₂, exact h₂, exfalso, apply h_2, exact eq.symm h₂, have hy : 0 < y, cases lt_or_eq_of_le h₁ with h₂ h₂, exact h₂, exfalso, apply h_3, exact eq.symm h₂, rw [log_mul hx hy, add_mul, exp_add]}, { exact h₁}, { exact h}, { exact mul_nonneg h h₁}, end lemma one_le_rpow {x z : ℝ} (h : 1 ≤ x) (h₁ : 0 ≤ z) : 1 ≤ x^z := begin rw real.rpow_def_of_nonneg, split_ifs with h₂ h₃, { refl}, { simp [*, not_le_of_gt zero_lt_one] at *}, { have hx : 0 < x, exact lt_of_lt_of_le zero_lt_one h, rw [←log_le_log zero_lt_one hx, log_one] at h, have pos : 0 ≤ log x * z, exact mul_nonneg h h₁, rwa [←exp_le_exp, exp_zero] at pos}, { exact le_trans zero_le_one h}, end lemma rpow_le_rpow {x y z: ℝ} (h : 0 ≤ x) (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := begin rw le_iff_eq_or_lt at h h₂, cases h₂, { rw [←h₂, rpow_zero, rpow_zero]}, { cases h, { rw [←h, zero_rpow], rw real.rpow_def_of_nonneg, split_ifs, { exact zero_le_one}, { refl}, { exact le_of_lt (exp_pos (log y * z))}, { rwa ←h at h₁}, { exact ne.symm (ne_of_lt h₂)}}, { have one_le : 1 ≤ y / x, rw one_le_div_iff_le h, exact h₁, have one_le_pow : 1 ≤ (y / x)^z, exact one_le_rpow one_le (le_of_lt h₂), rw [←mul_div_cancel y (ne.symm (ne_of_lt h)), mul_comm, mul_div_assoc], rw [mul_rpow (le_of_lt h) (le_trans zero_le_one one_le), mul_comm], exact (le_mul_of_ge_one_left (rpow_nonneg_of_nonneg (le_of_lt h) z) one_le_pow) } } end lemma rpow_lt_rpow (hx : 0 ≤ x) (hxy : x < y) (hz : 0 < z) : x^z < y^z := begin rw le_iff_eq_or_lt at hx, cases hx, { rw [← hx, zero_rpow (ne_of_gt hz)], exact rpow_pos_of_pos (by rwa ← hx at hxy) _ }, rw [rpow_def_of_pos hx, rpow_def_of_pos (lt_trans hx hxy), exp_lt_exp], exact mul_lt_mul_of_pos_right (log_lt_log hx hxy) hz end lemma rpow_lt_rpow_of_exponent_lt (hx : 1 < x) (hyz : y < z) : x^y < x^z := begin repeat {rw [rpow_def_of_pos (lt_trans zero_lt_one hx)]}, rw exp_lt_exp, exact mul_lt_mul_of_pos_left hyz (log_pos hx), end lemma rpow_le_rpow_of_exponent_le (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := begin repeat {rw [rpow_def_of_pos (lt_of_lt_of_le zero_lt_one hx)]}, rw exp_le_exp, exact mul_le_mul_of_nonneg_left hyz (log_nonneg hx), end lemma rpow_lt_rpow_of_exponent_gt (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := begin repeat {rw [rpow_def_of_pos hx0]}, rw exp_lt_exp, exact mul_lt_mul_of_neg_left hyz (log_neg hx0 hx1), end lemma rpow_le_rpow_of_exponent_ge (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := begin repeat {rw [rpow_def_of_pos hx0]}, rw exp_le_exp, exact mul_le_mul_of_nonpos_left hyz (log_nonpos hx1), end lemma rpow_le_one {x e : ℝ} (he : 0 ≤ e) (hx : 0 ≤ x) (hx2 : x ≤ 1) : x^e ≤ 1 := by rw ←one_rpow e; apply rpow_le_rpow; assumption lemma one_lt_rpow (hx : 1 < x) (hz : 0 < z) : 1 < x^z := by { rw ← one_rpow z, exact rpow_lt_rpow zero_le_one hx hz } lemma rpow_lt_one (hx : 0 < x) (hx1 : x < 1) (hz : 0 < z) : x^z < 1 := by { rw ← one_rpow z, exact rpow_lt_rpow (le_of_lt hx) hx1 hz } lemma pow_nat_rpow_nat_inv {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) : (x ^ n) ^ (n⁻¹ : ℝ) = x := have hn0 : (n : ℝ) ≠ 0, by simpa [nat.pos_iff_ne_zero] using hn, by rw [← rpow_nat_cast, ← rpow_mul hx, mul_inv_cancel hn0, rpow_one] lemma rpow_nat_inv_pow_nat {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℝ)) ^ n = x := have hn0 : (n : ℝ) ≠ 0, by simpa [nat.pos_iff_ne_zero] using hn, by rw [← rpow_nat_cast, ← rpow_mul hx, inv_mul_cancel hn0, rpow_one] section prove_rpow_is_continuous lemma continuous_rpow_aux1 : continuous (λp : {p:ℝ×ℝ // 0 < p.1}, p.val.1 ^ p.val.2) := suffices h : continuous (λ p : {p:ℝ×ℝ // 0 < p.1 }, exp (log p.val.1 * p.val.2)), by { convert h, ext p, rw rpow_def_of_pos p.2 }, continuous_exp.comp $ (show continuous ((λp:{p:ℝ//0 < p}, log (p.val)) ∘ (λp:{p:ℝ×ℝ//0<p.fst}, ⟨p.val.1, p.2⟩)), from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_fst.comp continuous_subtype_val).mul (continuous_snd.comp $ continuous_subtype_val.comp continuous_id) lemma continuous_rpow_aux2 : continuous (λ p : {p:ℝ×ℝ // p.1 < 0}, p.val.1 ^ p.val.2) := suffices h : continuous (λp:{p:ℝ×ℝ // p.1 < 0}, exp (log (-p.val.1) * p.val.2) * cos (p.val.2 * π)), by { convert h, ext p, rw [rpow_def_of_neg p.2] }, (continuous_exp.comp $ (show continuous $ (λp:{p:ℝ//0<p}, log (p.val))∘(λp:{p:ℝ×ℝ//p.1<0}, ⟨-p.val.1, neg_pos_of_neg p.2⟩), from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_neg.comp $ continuous_fst.comp continuous_subtype_val).mul (continuous_snd.comp $ continuous_subtype_val.comp continuous_id)).mul (continuous_cos.comp $ (continuous_snd.comp $ continuous_subtype_val.comp continuous_id).mul continuous_const) lemma continuous_at_rpow_of_ne_zero (hx : x ≠ 0) (y : ℝ) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := begin cases lt_trichotomy 0 x, exact continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux1 _ h) (mem_nhds_sets (by { convert is_open_prod (is_open_lt' (0:ℝ)) is_open_univ, ext, finish }) h), cases h, { exact absurd h.symm hx }, exact continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux2 _ h) (mem_nhds_sets (by { convert is_open_prod (is_open_gt' (0:ℝ)) is_open_univ, ext, finish }) h) end lemma continuous_rpow_aux3 : continuous (λ p : {p:ℝ×ℝ // 0 < p.2}, p.val.1 ^ p.val.2) := continuous_iff_continuous_at.2 $ λ ⟨(x₀, y₀), hy₀⟩, begin by_cases hx₀ : x₀ = 0, { simp only [continuous_at, hx₀, zero_rpow (ne_of_gt hy₀), tendsto_nhds_nhds], assume ε ε0, rcases exists_pos_rat_lt (half_pos hy₀) with ⟨q, q_pos, q_lt⟩, let q := (q:ℝ), replace q_pos : 0 < q := rat.cast_pos.2 q_pos, let δ := min (min q (ε ^ (1 / q))) (1/2), have δ0 : 0 < δ := lt_min (lt_min q_pos (rpow_pos_of_pos ε0 _)) (by norm_num), have : δ ≤ q := le_trans (min_le_left _ _) (min_le_left _ _), have : δ ≤ ε ^ (1 / q) := le_trans (min_le_left _ _) (min_le_right _ _), have : δ < 1 := lt_of_le_of_lt (min_le_right _ _) (by norm_num), use δ, use δ0, rintros ⟨⟨x, y⟩, hy⟩, simp only [subtype.dist_eq, real.dist_eq, prod.dist_eq, sub_zero, subtype.coe_mk], assume h, rw max_lt_iff at h, cases h with xδ yy₀, have qy : q < y, calc q < y₀ / 2 : q_lt ... = y₀ - y₀ / 2 : (sub_half _).symm ... ≤ y₀ - δ : by linarith ... < y : sub_lt_of_abs_sub_lt_left yy₀, calc abs(x^y) ≤ abs(x)^y : abs_rpow_le_abs_rpow _ _ ... < δ ^ y : rpow_lt_rpow (abs_nonneg _) xδ hy ... < δ ^ q : by { refine rpow_lt_rpow_of_exponent_gt _ _ _, repeat {linarith} } ... ≤ (ε ^ (1 / q)) ^ q : by { refine rpow_le_rpow _ _ _, repeat {linarith} } ... = ε : by { rw [← rpow_mul, div_mul_cancel, rpow_one], exact ne_of_gt q_pos, linarith }}, { exact (continuous_within_at_iff_continuous_at_restrict (λp:ℝ×ℝ, p.1^p.2) _).1 (continuous_at_rpow_of_ne_zero hx₀ _).continuous_within_at } end lemma continuous_at_rpow_of_pos (hy : 0 < y) (x : ℝ) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux3 _ hy) (mem_nhds_sets (by { convert is_open_prod is_open_univ (is_open_lt' (0:ℝ)), ext, finish }) hy) lemma continuous_at_rpow {x y : ℝ} (h : x ≠ 0 ∨ 0 < y) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := by { cases h, exact continuous_at_rpow_of_ne_zero h _, exact continuous_at_rpow_of_pos h x } variables {α : Type*} [topological_space α] {f g : α → ℝ} /-- `real.rpow` is continuous at all points except for the lower half of the y-axis. In other words, the function `λp:ℝ×ℝ, p.1^p.2` is continuous at `(x, y)` if `x ≠ 0` or `y > 0`. Multiple forms of the claim is provided in the current section. -/ lemma continuous_rpow (h : ∀a, f a ≠ 0 ∨ 0 < g a) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_iff_continuous_at.2 $ λ a, begin show continuous_at ((λp:ℝ×ℝ, p.1^p.2) ∘ (λa, (f a, g a))) a, refine continuous_at.comp _ (continuous_iff_continuous_at.1 (hf.prod_mk hg) _), { replace h := h a, cases h, { exact continuous_at_rpow_of_ne_zero h _ }, { exact continuous_at_rpow_of_pos h _ }}, end lemma continuous_rpow_of_ne_zero (h : ∀a, f a ≠ 0) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inl $ h a) hf hg lemma continuous_rpow_of_pos (h : ∀a, 0 < g a) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inr $ h a) hf hg end prove_rpow_is_continuous section sqrt lemma sqrt_eq_rpow : sqrt = λx:ℝ, x ^ (1/(2:ℝ)) := begin funext, by_cases h : 0 ≤ x, { rw [← mul_self_inj_of_nonneg, mul_self_sqrt h, ← pow_two, ← rpow_nat_cast, ← rpow_mul h], norm_num, exact sqrt_nonneg _, exact rpow_nonneg_of_nonneg h _ }, { replace h : x < 0 := lt_of_not_ge h, have : 1 / (2:ℝ) * π = π / (2:ℝ), ring, rw [sqrt_eq_zero_of_nonpos (le_of_lt h), rpow_def_of_neg h, this, cos_pi_div_two, mul_zero] } end lemma continuous_sqrt : continuous sqrt := by rw sqrt_eq_rpow; exact continuous_rpow_of_pos (λa, by norm_num) continuous_id continuous_const end sqrt section exp /-- The real exponential function tends to +infinity at +infinity -/ lemma tendsto_exp_at_top : tendsto exp at_top at_top := begin have A : tendsto (λx:ℝ, x + 1) at_top at_top := tendsto_at_top_add_const_right at_top 1 tendsto_id, have B : ∀ᶠ x in at_top, x + 1 ≤ exp x, { have : ∀ᶠ (x : ℝ) in at_top, 0 ≤ x := mem_at_top 0, filter_upwards [this], exact λx hx, add_one_le_exp_of_nonneg hx }, exact tendsto_at_top_mono' at_top B A end /-- The real exponential function tends to 0 at -infinity or, equivalently, `exp(-x)` tends to `0` at +infinity -/ lemma tendsto_exp_neg_at_top_nhds_0 : tendsto (λx, exp (-x)) at_top (𝓝 0) := (tendsto_inv_at_top_zero.comp (tendsto_exp_at_top)).congr (λx, (exp_neg x).symm) /-- The function `exp(x)/x^n` tends to +infinity at +infinity, for any natural number `n` -/ lemma tendsto_exp_div_pow_at_top (n : ℕ) : tendsto (λx, exp x / x^n) at_top at_top := begin have n_pos : (0 : ℝ) < n + 1 := nat.cast_add_one_pos n, have n_ne_zero : (n : ℝ) + 1 ≠ 0 := ne_of_gt n_pos, have A : ∀x:ℝ, 0 < x → exp (x / (n+1)) / (n+1)^n ≤ exp x / x^n, { assume x hx, let y := x / (n+1), have y_pos : 0 < y := div_pos hx n_pos, have : exp (x / (n+1)) ≤ (n+1)^n * (exp x / x^n), from calc exp y = exp y * 1 : by simp ... ≤ exp y * (exp y / y)^n : begin apply mul_le_mul_of_nonneg_left (one_le_pow_of_one_le _ n) (le_of_lt (exp_pos _)), apply one_le_div_of_le _ y_pos, apply le_trans _ (add_one_le_exp_of_nonneg (le_of_lt y_pos)), exact le_add_of_le_of_nonneg (le_refl _) (zero_le_one) end ... = exp y * exp (n * y) / y^n : by rw [div_pow, exp_nat_mul, mul_div_assoc] ... = exp ((n + 1) * y) / y^n : by rw [← exp_add, add_mul, one_mul, add_comm] ... = exp x / (x / (n+1))^n : by { dsimp [y], rw mul_div_cancel' _ n_ne_zero } ... = (n+1)^n * (exp x / x^n) : by rw [← mul_div_assoc, div_pow, div_div_eq_mul_div, mul_comm], rwa div_le_iff' (pow_pos n_pos n) }, have B : ∀ᶠ x in at_top, exp (x / (n+1)) / (n+1)^n ≤ exp x / x^n := mem_at_top_sets.2 ⟨1, λx hx, A _ (lt_of_lt_of_le zero_lt_one hx)⟩, have C : tendsto (λx, exp (x / (n+1)) / (n+1)^n) at_top at_top := tendsto_at_top_div (pow_pos n_pos n) (tendsto_exp_at_top.comp (tendsto_at_top_div (nat.cast_add_one_pos n) tendsto_id)), exact tendsto_at_top_mono' at_top B C end /-- The function `x^n * exp(-x)` tends to `0` at +infinity, for any natural number `n`. -/ lemma tendsto_pow_mul_exp_neg_at_top_nhds_0 (n : ℕ) : tendsto (λx, x^n * exp (-x)) at_top (𝓝 0) := (tendsto_inv_at_top_zero.comp (tendsto_exp_div_pow_at_top n)).congr $ λx, by rw [function.comp_app, inv_eq_one_div, div_div_eq_mul_div, one_mul, div_eq_mul_inv, exp_neg] end exp end real lemma has_deriv_at.rexp {f : ℝ → ℝ} {f' x : ℝ} (hf : has_deriv_at f f' x) : has_deriv_at (real.exp ∘ f) (f' * real.exp (f x)) x := (real.has_deriv_at_exp (f x)).comp x hf lemma has_deriv_within_at.rexp {f : ℝ → ℝ} {f' x : ℝ} {s : set ℝ} (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (real.exp ∘ f) (f' * real.exp (f x)) s x := (real.has_deriv_at_exp (f x)).comp_has_deriv_within_at x hf namespace nnreal /-- The nonnegative real power function `x^y`, defined for `x : nnreal` and `y : ℝ ` as the restriction of the real power function. For `x > 0`, it is equal to `exp (y log x)`. For `x = 0`, one sets `0 ^ 0 = 1` and `0 ^ y = 0` for `y ≠ 0`. -/ noncomputable def rpow (x : nnreal) (y : ℝ) : nnreal := ⟨(x : ℝ) ^ y, real.rpow_nonneg_of_nonneg x.2 y⟩ noncomputable instance : has_pow nnreal ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x : nnreal) (y : ℝ) : rpow x y = x ^ y := rfl @[simp, move_cast] lemma coe_rpow (x : nnreal) (y : ℝ) : ((x ^ y : nnreal) : ℝ) = (x : ℝ) ^ y := rfl @[simp] lemma rpow_zero (x : nnreal) : x ^ (0 : ℝ) = 1 := by { rw ← nnreal.coe_eq, exact real.rpow_zero _ } @[simp] lemma rpow_eq_zero_iff {x : nnreal} {y : ℝ} : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := begin rw [← nnreal.coe_eq, coe_rpow, ← nnreal.coe_eq_zero], exact real.rpow_eq_zero_iff_of_nonneg x.2 end @[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : nnreal) ^ x = 0 := by { rw ← nnreal.coe_eq, exact real.zero_rpow h } @[simp] lemma rpow_one (x : nnreal) : x ^ (1 : ℝ) = x := by { rw ← nnreal.coe_eq, exact real.rpow_one _ } @[simp] lemma one_rpow (x : ℝ) : (1 : nnreal) ^ x = 1 := by { rw ← nnreal.coe_eq, exact real.one_rpow _ } lemma rpow_add {x : nnreal} (y z : ℝ) (hx : 0 < x) : x ^ (y + z) = x ^ y * x ^ z := by { rw ← nnreal.coe_eq, exact real.rpow_add _ _ hx } lemma rpow_mul (x : nnreal) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := by { rw ← nnreal.coe_eq, exact real.rpow_mul x.2 y z } lemma rpow_neg (x : nnreal) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := by { rw ← nnreal.coe_eq, exact real.rpow_neg x.2 _ } @[simp] lemma rpow_nat_cast (x : nnreal) (n : ℕ) : x ^ (n : ℝ) = x ^ n := by { rw [← nnreal.coe_eq, coe_pow], exact real.rpow_nat_cast (x : ℝ) n } lemma mul_rpow {x y : nnreal} {z : ℝ} : (x*y)^z = x^z * y^z := by { rw ← nnreal.coe_eq, exact real.mul_rpow x.2 y.2 } lemma one_le_rpow {x : nnreal} {z : ℝ} (h : 1 ≤ x) (h₁ : 0 ≤ z) : 1 ≤ x^z := real.one_le_rpow h h₁ lemma rpow_le_rpow {x y : nnreal} {z: ℝ} (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := real.rpow_le_rpow x.2 h₁ h₂ lemma rpow_lt_rpow {x y : nnreal} {z: ℝ} (h₁ : x < y) (h₂ : 0 < z) : x^z < y^z := real.rpow_lt_rpow x.2 h₁ h₂ lemma rpow_lt_rpow_of_exponent_lt {x : nnreal} {y z : ℝ} (hx : 1 < x) (hyz : y < z) : x^y < x^z := real.rpow_lt_rpow_of_exponent_lt hx hyz lemma rpow_le_rpow_of_exponent_le {x : nnreal} {y z : ℝ} (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := real.rpow_le_rpow_of_exponent_le hx hyz lemma rpow_lt_rpow_of_exponent_gt {x : nnreal} {y z : ℝ} (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := real.rpow_lt_rpow_of_exponent_gt hx0 hx1 hyz lemma rpow_le_rpow_of_exponent_ge {x : nnreal} {y z : ℝ} (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := real.rpow_le_rpow_of_exponent_ge hx0 hx1 hyz lemma rpow_le_one {x : nnreal} {e : ℝ} (he : 0 ≤ e) (hx2 : x ≤ 1) : x^e ≤ 1 := real.rpow_le_one he x.2 hx2 lemma one_lt_rpow {x : nnreal} {z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z := real.one_lt_rpow hx hz lemma rpow_lt_one {x : nnreal} {z : ℝ} (hx : 0 < x) (hx1 : x < 1) (hz : 0 < z) : x^z < 1 := real.rpow_lt_one hx hx1 hz lemma pow_nat_rpow_nat_inv (x : nnreal) {n : ℕ} (hn : 0 < n) : (x ^ n) ^ (n⁻¹ : ℝ) = x := by { rw [← nnreal.coe_eq, coe_rpow, coe_pow], exact real.pow_nat_rpow_nat_inv x.2 hn } lemma rpow_nat_inv_pow_nat (x : nnreal) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℝ)) ^ n = x := by { rw [← nnreal.coe_eq, coe_pow, coe_rpow], exact real.rpow_nat_inv_pow_nat x.2 hn } lemma continuous_at_rpow {x : nnreal} {y : ℝ} (h : x ≠ 0 ∨ 0 < y) : continuous_at (λp:nnreal×ℝ, p.1^p.2) (x, y) := begin have : (λp:nnreal×ℝ, p.1^p.2) = nnreal.of_real ∘ (λp:ℝ×ℝ, p.1^p.2) ∘ (λp:nnreal × ℝ, (p.1.1, p.2)), { ext p, rw [← nnreal.coe_eq, coe_rpow, coe_of_real _ (real.rpow_nonneg_of_nonneg p.1.2 _)], refl }, rw this, refine continuous_of_real.continuous_at.comp (continuous_at.comp _ _), { apply real.continuous_at_rpow, simp at h, rw ← (nnreal.coe_eq_zero x) at h, exact h }, { exact ((continuous_subtype_val.comp continuous_fst).prod_mk continuous_snd).continuous_at } end end nnreal lemma filter.tendsto.nnrpow {α : Type*} {f : filter α} {u : α → nnreal} {v : α → ℝ} {x : nnreal} {y : ℝ} (hx : tendsto u f (𝓝 x)) (hy : tendsto v f (𝓝 y)) (h : x ≠ 0 ∨ 0 < y) : tendsto (λ a, (u a) ^ (v a)) f (𝓝 (x ^ y)) := tendsto.comp (nnreal.continuous_at_rpow h) (tendsto.prod_mk_nhds hx hy)
6fefd977b0921751bd4f4f18f3284d25633de0d8
205f0fc16279a69ea36e9fd158e3a97b06834ce2
/src/06_Forall/00_intro.lean
2d993be2f3042e35265cf8325a6cbf59e8e4164c
[]
no_license
kevinsullivan/cs-dm-lean
b21d3ca1a9b2a0751ba13fcb4e7b258010a5d124
a06a94e98be77170ca1df486c8189338b16cf6c6
refs/heads/master
1,585,948,743,595
1,544,339,346,000
1,544,339,346,000
155,570,767
1
3
null
1,541,540,372,000
1,540,995,993,000
Lean
UTF-8
Lean
false
false
10,010
lean
/- We've met but haven't yet been properly introduced to ∀. Assuming P is a Type and Q is a proposition, What does (∀ p : P, Q) mean? For example, what does this mean? ∀ n : nat, n + 1 ≠ 0 First, you can read ∀ n : nat "for all values, n, of type nat." This proposition thus asserts that, for all natural numbers, n, of type nat, (i.e., "for any natural number, n") the successor of n is not 0. More generally, with P as any type, and Q as a proposition, (∀ p : P, Q) states that for every value, p, in the set of values defined by the type, P, one can derive a proof of Q. Here's our concrete example stated and proved in Lean. -/ example : ∀ n : nat, n + 1 ≠ 0 := -- assume an arbitrary nat, n λ n : nat, -- assume proof of n + 1 = 0 λ h : (n + 1 = 0), -- derive a contradiction (nat.no_confusion h : false) -- therefore n + 1 ≠ 0 /- Note that the parentheses around (n: nat) are not required by Lean, but they might help the human reader to understand the intention better. -/ /- Here's another example, which you have seen before (without a proof). It says that for any proposition, P (in the set of all propositions defined by the type, Prop), it is not possible to have both P and ¬ P be true at the same time. -/ example : ∀ P : Prop, ¬ (P ∧ ¬ P) := -- assume an arbitrary proposition λ P : Prop, -- assume it's both true and false λ h : (P ∧ ¬ P), -- derive a contradiction (h.right h.left) -- thereby proving ¬ h #check (3) /- The ∀ parts of these propositions, before the commas, give names to arbitrary elements of a type. The parts after the commas then state a claim (that is usually) about the named element. Look at the preceding examples. In the case of ∀ n : nat, n + 1 ≠ 0, the part before the comma asserts that the proposition following the comma is true of any arbitrary (and thus of every) element, n, of type nat. We say that the ∀ "binds" the name to an arbitrary value of the given type. The binding is operative for the remainder of the proposition. We note that successive bindings accumulate, defining a context in which the remainder of a proposition is stated and proved. Here's an example that states that for any two natural numbers, n and m, either n = m or n ≠ m. We use the connective, ∨, to denote disjunction (logical or). More about that later. We "stub out" the simple proof for now. -/ example : ∀ (n : nat), ∀ (m : nat), m = n ∨ m ≠ n := begin assume n : nat, -- the context now includes n assume m : nat, -- the context now also has m sorry end -- the bindings no longer hold here /- So that should give an understanding of the use and meaning of the universal quantifier, ∀, in predicate logic. What does (∀ (p : P), Q) mean in the constructive logic of Lean? Let's check! First we'll assume two arbitrary propositions, P and Q, and a proof of ∀ p : P, Q. Then we can ask what is the type of ∀ p : P, Q. It is a proposition, after all, and in Lean, propositions are types. What type is it? -/ -- Assume P and Q are propositions variables P Q : Prop -- What is the type of (∀ p : P, Q) #check (∀ p : P, Q) #check ∀ n: nat, nat /- What? the proposition/type, (∀ p : P, Q) is really just the proposition/type, P → Q. -/ /- If that's true, we should be able to assume proof of (∀ p : P, Q) and then use it as a function. Let's see. -/ -- Assume a proof of ∀ (p : P), Q. variable ap2q : (∀ p : P, Q) -- Assume a proof of P. variable p : P -- What is the type of (ap2q p). Q #check ap2q p -- They're the same types! Here's a proof. theorem same : (∀ p : P, Q) = (P → Q) := rfl /- So why not just use → instead of ∀? The answer is that ∀ let's us bind a name to an assumed value, a name that we can then use in the remainder of the expression. The → connective doesn't let us bind a name to a value. The following example thus defines a type of function that, given a natural number, n, reduces to (returns) the proposition that that particular n is either 0 or not 0. This is a function type. -/ #check ∀ n : nat, n = 0 ∨ n ≠ 0. /- A proof of this proposition/type is then a function that, if given any nat value, n, returns a value of type (a proof that) that particular n is either 0 or not 0. The binding of a name to an assumed value effected by a ∀ provides us a context in which we can state the remainder of the universally quantified proposition. -/ /- Some work done in class -/ def inc : ℕ → ℕ := λ n : nat, n + 1 def inc' : ∀ n: nat, nat := λ n : nat, n + 1 def add : ∀ n : nat, ∀ m :nat, nat := λ n m, n + m def add' : ∀ n : nat, (∀ m :nat, nat) := λ n : nat, λ m : nat, n + m #eval add 3 4 #eval add' 3 4 #check add' 3 #eval (add' 3) def add3 := (add' 3) #check add3 #eval add3 4 /- ** Further explanation ** -/ /- So now we can see at least three ways to read (∀ p : P, Q). (1) As a universally quantified logical proposition. As such, it asserts that if p is any value of type P, then from it one can derive a proof of the proposition, Q, which will typically involve p. (2) As a logical implication, P → Q. This is read simply as P implies Q. (3) As the type of total functions from P to Q. By a total function, we mean a function that is defined "for all" values of its argument types. It cannot be a "partial" function that is undefined on some values of its argument type. The concepts of "for all" and of total functions are intimately related here. The ∀ explicitly requires that such a function be defined "for all" values of the designated type. That functions are total is fundamental to constructive logic. We will explain why later. -/ /- ** Further examples ** -/ /- #1. Nested ∀ bindings. Let' assume we have another proposition, R. -/ variable R : Prop /- So, what does this mean: ∀ p : P, ∀ q : Q, R? The ∀ is right-associative so we read this as ∀ p : P, (∀ q : Q, R). Using what we learned above, we can see that it means P → Q → R! -/ #check ∀ (p : P), (∀ q : Q, R) /- There are at least three ways to think about this construct. (1) It is the universally quantified proposition that holds that if one assumes any proof P and then further assumes any proof of Q, then in that context one can derive a proof of R. (2) It is the logical proposition, P implies Q implies R, written as P → Q → R. (3) Is it the function type, P → Q → R. As we've discussed, → is right associative, so this is the function type is P → (Q → R). -/ #check ∀(n: ℕ), (∀(m: ℕ), m + n >= 0) /- ** Chained implications ** -/ /- What is the function type, P → Q → R? It is the type of function that takes a value of type P as an argument and reduces to a function of type (Q → R), a function that takes a value of type Q, and that finally reduces to a value of type R. Of course, you can just think of this as a function that takes two arguments, the first of type P and the second of type Q, and that then reduces to a value of type R. In fact in Lean and in most functional languages, you can treat any function that takes multiple arguments as one that takes one argument (the first) and then reduces to a function that takes the next argument, and so on until the last argument has been consumed, at which point it reduces to a result of the type at the end of the chain. Let's look at an example involving the + operator applied to two natural numbers. The + operator is a shorthand for nat.add. -/ #check nat.add 2 3 #check (nat.add 2) 3 -- same thing #check nat.add 2 #check nat.add /- Function application is left-associative. Here, for example, nat.add consumes a 2 in the first line and reduces to a function (one that "bakes in the 2") that consumes the 3 and finally reduces to 5. -/ /- #2 Let's return to an example we saw on the recent in-class no-contradiction exercise: no_contradiction: ∀ P : Prop, ¬ (P ∧ ¬ P). We can now this type as a function type for functions that take a proposition, P, and that reduce to the proposition, ¬ (P ∧ ¬ P), which is to say, to (P ∧ ¬ P) → false. We thus have a function type like this: (P : Prop) → (P ∧ ¬ P) → false. But we can't write it like that because Lean doesn't allow us to bind names to value in this way. We have to use ∀ instead. ∀ P : Prop, (P ∧ ¬ P) → false. Nevertheless, if we have a value of this type, it will be a function whose first argument is any proposition. Let's see this in action. -/ -- Assume a proof/function of the given type variable no_contra : ∀ (P : Prop), ¬ (P ∧ ¬ P) /- Now look at what we get when we apply this function to any proposition, P. We get back a value of type (the proposition), P ∧ ¬ P. -/ #check no_contra (0 = 0) #check no_contra ¬ P #check no_contra (P → Q) /- Of course each of the results is a value of type ¬ (P ∧ ¬ P), which is to say it's another function: from proofs of (P ∧ ¬ P) to false. For a little (logic-destroying) fun,let's assume we have a proof of 0 = 0 ∧ ¬ 0 = 0 and produce a proof of false. -/ -- Assume a proof of 0 = 0 ∧ 0 ≠ 0, variable inconsistency : 0 = 0 ∧ 0 ≠ 0 --Apply the function, contra (0 = 0), to it #check (no_contra (0 = 0)) inconsistency /- Voila! A proof of false. Of course we never could have constructed it without having made an absurd assumption. -/ /- ** Conclusion ** -/ /- Now we know that (∀ p : P, Q) means P → Q, but it also binds a name to an assumed value of type P that we can use in expressing Q. An easy way to think about this is that a binding of a name to a value of type P is exactly like the declaration of an argument to a function, and Q is like the body of the function in which the name P can be used. -/
c92c6b7ac717d689d881d1ec370dc86a628597b5
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/order/absolute_value.lean
128c200ecb03eff6e4f11ec0a4438cd159c56193
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,009
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Anne Baanen -/ import algebra.order.field /-! # Absolute values This file defines a bundled type of absolute values `absolute_value R S`. ## Main definitions * `absolute_value R S` is the type of absolute values on `R` mapping to `S`. * `absolute_value.abs` is the "standard" absolute value on `S`, mapping negative `x` to `-x`. * `absolute_value.to_monoid_with_zero_hom`: absolute values mapping to a linear ordered field preserve `0`, `*` and `1` * `is_absolute_value`: a type class stating that `f : β → α` satisfies the axioms of an abs val -/ /-- `absolute_value R S` is the type of absolute values on `R` mapping to `S`: the maps that preserve `*`, are nonnegative, positive definite and satisfy the triangle equality. -/ structure absolute_value (R S : Type*) [semiring R] [ordered_semiring S] extends mul_hom R S := (nonneg' : ∀ x, 0 ≤ to_fun x) (eq_zero' : ∀ x, to_fun x = 0 ↔ x = 0) (add_le' : ∀ x y, to_fun (x + y) ≤ to_fun x + to_fun y) namespace absolute_value attribute [nolint doc_blame] absolute_value.to_mul_hom initialize_simps_projections absolute_value (to_mul_hom_to_fun → apply) section ordered_semiring variables {R S : Type*} [semiring R] [ordered_semiring S] (abv : absolute_value R S) instance : has_coe_to_fun (absolute_value R S) (λ f, R → S) := ⟨λ f, f.to_fun⟩ @[simp] lemma coe_to_mul_hom : ⇑abv.to_mul_hom = abv := rfl protected theorem nonneg (x : R) : 0 ≤ abv x := abv.nonneg' x @[simp] protected theorem eq_zero {x : R} : abv x = 0 ↔ x = 0 := abv.eq_zero' x protected theorem add_le (x y : R) : abv (x + y) ≤ abv x + abv y := abv.add_le' x y @[simp] protected theorem map_mul (x y : R) : abv (x * y) = abv x * abv y := abv.map_mul' x y protected theorem pos {x : R} (hx : x ≠ 0) : 0 < abv x := lt_of_le_of_ne (abv.nonneg x) (ne.symm $ mt abv.eq_zero.mp hx) @[simp] protected theorem pos_iff {x : R} : 0 < abv x ↔ x ≠ 0 := ⟨λ h₁, mt abv.eq_zero.mpr h₁.ne', abv.pos⟩ protected theorem ne_zero {x : R} (hx : x ≠ 0) : abv x ≠ 0 := (abv.pos hx).ne' @[simp] protected theorem map_zero : abv 0 = 0 := abv.eq_zero.2 rfl end ordered_semiring section ordered_ring variables {R S : Type*} [ring R] [ordered_ring S] (abv : absolute_value R S) protected lemma sub_le (a b c : R) : abv (a - c) ≤ abv (a - b) + abv (b - c) := by simpa [sub_eq_add_neg, add_assoc] using abv.add_le (a - b) (b - c) protected lemma le_sub (a b : R) : abv a - abv b ≤ abv (a - b) := sub_le_iff_le_add.2 $ by simpa using abv.add_le (a - b) b @[simp] lemma map_sub_eq_zero_iff (a b : R) : abv (a - b) = 0 ↔ a = b := abv.eq_zero.trans sub_eq_zero end ordered_ring section linear_ordered_ring variables {R S : Type*} [semiring R] [linear_ordered_ring S] (abv : absolute_value R S) /-- `absolute_value.abs` is `abs` as a bundled `absolute_value`. -/ @[simps] protected def abs : absolute_value S S := { to_fun := abs, nonneg' := abs_nonneg, eq_zero' := λ _, abs_eq_zero, add_le' := abs_add, map_mul' := abs_mul } instance : inhabited (absolute_value S S) := ⟨absolute_value.abs⟩ variables [nontrivial R] @[simp] protected theorem map_one : abv 1 = 1 := (mul_right_inj' $ abv.ne_zero one_ne_zero).1 $ by rw [← abv.map_mul, mul_one, mul_one] /-- Absolute values from a nontrivial `R` to a linear ordered ring preserve `*`, `0` and `1`. -/ def to_monoid_with_zero_hom : monoid_with_zero_hom R S := { to_fun := abv, map_zero' := abv.map_zero, map_one' := abv.map_one, .. abv } @[simp] lemma coe_to_monoid_with_zero_hom : ⇑abv.to_monoid_with_zero_hom = abv := rfl /-- Absolute values from a nontrivial `R` to a linear ordered ring preserve `*` and `1`. -/ def to_monoid_hom : monoid_hom R S := { to_fun := abv, map_one' := abv.map_one, .. abv } @[simp] lemma coe_to_monoid_hom : ⇑abv.to_monoid_hom = abv := rfl @[simp] protected lemma map_pow (a : R) (n : ℕ) : abv (a ^ n) = abv a ^ n := abv.to_monoid_hom.map_pow a n end linear_ordered_ring section linear_ordered_comm_ring section ring variables {R S : Type*} [ring R] [linear_ordered_comm_ring S] (abv : absolute_value R S) @[simp] protected theorem map_neg (a : R) : abv (-a) = abv a := begin by_cases ha : a = 0, { simp [ha] }, refine (mul_self_eq_mul_self_iff.mp (by rw [← abv.map_mul, neg_mul_neg, abv.map_mul])).resolve_right _, exact ((neg_lt_zero.mpr (abv.pos ha)).trans (abv.pos (neg_ne_zero.mpr ha))).ne' end protected theorem map_sub (a b : R) : abv (a - b) = abv (b - a) := by rw [← neg_sub, abv.map_neg] lemma abs_abv_sub_le_abv_sub (a b : R) : abs (abv a - abv b) ≤ abv (a - b) := abs_sub_le_iff.2 ⟨abv.le_sub _ _, by rw abv.map_sub; apply abv.le_sub⟩ end ring end linear_ordered_comm_ring section linear_ordered_field section field variables {R S : Type*} [division_ring R] [linear_ordered_field S] (abv : absolute_value R S) @[simp] protected theorem map_inv (a : R) : abv a⁻¹ = (abv a)⁻¹ := abv.to_monoid_with_zero_hom.map_inv a @[simp] protected theorem map_div (a b : R) : abv (a / b) = abv a / abv b := abv.to_monoid_with_zero_hom.map_div a b end field end linear_ordered_field end absolute_value section is_absolute_value /-- A function `f` is an absolute value if it is nonnegative, zero only at 0, additive, and multiplicative. See also the type `absolute_value` which represents a bundled version of absolute values. -/ class is_absolute_value {S} [ordered_semiring S] {R} [semiring R] (f : R → S) : Prop := (abv_nonneg [] : ∀ x, 0 ≤ f x) (abv_eq_zero [] : ∀ {x}, f x = 0 ↔ x = 0) (abv_add [] : ∀ x y, f (x + y) ≤ f x + f y) (abv_mul [] : ∀ x y, f (x * y) = f x * f y) namespace is_absolute_value section ordered_semiring variables {S : Type*} [ordered_semiring S] variables {R : Type*} [semiring R] (abv : R → S) [is_absolute_value abv] /-- A bundled absolute value is an absolute value. -/ instance absolute_value.is_absolute_value (abv : absolute_value R S) : is_absolute_value abv := { abv_nonneg := abv.nonneg, abv_eq_zero := λ _, abv.eq_zero, abv_add := abv.add_le, abv_mul := abv.map_mul } /-- Convert an unbundled `is_absolute_value` to a bundled `absolute_value`. -/ @[simps] def to_absolute_value : absolute_value R S := { to_fun := abv, add_le' := abv_add abv, eq_zero' := λ _, abv_eq_zero abv, nonneg' := abv_nonneg abv, map_mul' := abv_mul abv } theorem abv_zero : abv 0 = 0 := (abv_eq_zero abv).2 rfl theorem abv_pos {a : R} : 0 < abv a ↔ a ≠ 0 := by rw [lt_iff_le_and_ne, ne, eq_comm]; simp [abv_eq_zero abv, abv_nonneg abv] end ordered_semiring section linear_ordered_ring variables {S : Type*} [linear_ordered_ring S] variables {R : Type*} [semiring R] (abv : R → S) [is_absolute_value abv] instance abs_is_absolute_value {S} [linear_ordered_ring S] : is_absolute_value (abs : S → S) := { abv_nonneg := abs_nonneg, abv_eq_zero := λ _, abs_eq_zero, abv_add := abs_add, abv_mul := abs_mul } end linear_ordered_ring section linear_ordered_comm_ring variables {S : Type*} [linear_ordered_comm_ring S] section semiring variables {R : Type*} [semiring R] (abv : R → S) [is_absolute_value abv] theorem abv_one [nontrivial R] : abv 1 = 1 := (mul_right_inj' $ mt (abv_eq_zero abv).1 one_ne_zero).1 $ by rw [← abv_mul abv, mul_one, mul_one] /-- `abv` as a `monoid_with_zero_hom`. -/ def abv_hom [nontrivial R] : monoid_with_zero_hom R S := ⟨abv, abv_zero abv, abv_one abv, abv_mul abv⟩ lemma abv_pow [nontrivial R] (abv : R → S) [is_absolute_value abv] (a : R) (n : ℕ) : abv (a ^ n) = abv a ^ n := (abv_hom abv).to_monoid_hom.map_pow a n end semiring end linear_ordered_comm_ring section linear_ordered_field variables {S : Type*} [linear_ordered_field S] section ring variables {R : Type*} [ring R] (abv : R → S) [is_absolute_value abv] theorem abv_neg (a : R) : abv (-a) = abv a := by rw [← mul_self_inj_of_nonneg (abv_nonneg abv _) (abv_nonneg abv _), ← abv_mul abv, ← abv_mul abv]; simp theorem abv_sub (a b : R) : abv (a - b) = abv (b - a) := by rw [← neg_sub, abv_neg abv] lemma abv_sub_le (a b c : R) : abv (a - c) ≤ abv (a - b) + abv (b - c) := by simpa [sub_eq_add_neg, add_assoc] using abv_add abv (a - b) (b - c) lemma sub_abv_le_abv_sub (a b : R) : abv a - abv b ≤ abv (a - b) := sub_le_iff_le_add.2 $ by simpa using abv_add abv (a - b) b lemma abs_abv_sub_le_abv_sub (a b : R) : abs (abv a - abv b) ≤ abv (a - b) := abs_sub_le_iff.2 ⟨sub_abv_le_abv_sub abv _ _, by rw abv_sub abv; apply sub_abv_le_abv_sub abv⟩ end ring section field variables {R : Type*} [division_ring R] (abv : R → S) [is_absolute_value abv] theorem abv_inv (a : R) : abv a⁻¹ = (abv a)⁻¹ := (abv_hom abv).map_inv a theorem abv_div (a b : R) : abv (a / b) = abv a / abv b := (abv_hom abv).map_div a b end field end linear_ordered_field end is_absolute_value end is_absolute_value
1ba783e8dd65644888171d37127fe285e4e19090
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/computability/primrec.lean
d0860bfbdc7af7f50c946c70325e4a503af641b3
[ "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
51,980
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.equiv.list import logic.function.iterate /-! # The primitive recursive functions The primitive recursive functions are the least collection of functions `nat → nat` which are closed under projections (using the mkpair pairing function), composition, zero, successor, and primitive recursion (i.e. nat.rec where the motive is C n := nat). We can extend this definition to a large class of basic types by using canonical encodings of types as natural numbers (Gödel numbering), which we implement through the type class `encodable`. (More precisely, we need that the composition of encode with decode yields a primitive recursive function, so we have the `primcodable` type class for this.) ## References * [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019] -/ open denumerable encodable namespace nat def elim {C : Sort*} : C → (ℕ → C → C) → ℕ → C := @nat.rec (λ _, C) @[simp] theorem elim_zero {C} (a f) : @nat.elim C a f 0 = a := rfl @[simp] theorem elim_succ {C} (a f n) : @nat.elim C a f (succ n) = f n (nat.elim a f n) := rfl def cases {C : Sort*} (a : C) (f : ℕ → C) : ℕ → C := nat.elim a (λ n _, f n) @[simp] theorem cases_zero {C} (a f) : @nat.cases C a f 0 = a := rfl @[simp] theorem cases_succ {C} (a f n) : @nat.cases C a f (succ n) = f n := rfl @[simp, reducible] def unpaired {α} (f : ℕ → ℕ → α) (n : ℕ) : α := f n.unpair.1 n.unpair.2 /-- The primitive recursive functions `ℕ → ℕ`. -/ inductive primrec : (ℕ → ℕ) → Prop | zero : primrec (λ n, 0) | succ : primrec succ | left : primrec (λ n, n.unpair.1) | right : primrec (λ n, n.unpair.2) | pair {f g} : primrec f → primrec g → primrec (λ n, mkpair (f n) (g n)) | comp {f g} : primrec f → primrec g → primrec (λ n, f (g n)) | prec {f g} : primrec f → primrec g → primrec (unpaired (λ z n, n.elim (f z) (λ y IH, g $ mkpair z $ mkpair y IH))) namespace primrec theorem of_eq {f g : ℕ → ℕ} (hf : primrec f) (H : ∀ n, f n = g n) : primrec g := (funext H : f = g) ▸ hf theorem const : ∀ (n : ℕ), primrec (λ _, n) | 0 := zero | (n+1) := succ.comp (const n) protected theorem id : primrec id := (left.pair right).of_eq $ λ n, by simp theorem prec1 {f} (m : ℕ) (hf : primrec f) : primrec (λ n, n.elim m (λ y IH, f $ mkpair y IH)) := ((prec (const m) (hf.comp right)).comp (zero.pair primrec.id)).of_eq $ λ n, by simp; dsimp; rw [unpair_mkpair] theorem cases1 {f} (m : ℕ) (hf : primrec f) : primrec (nat.cases m f) := (prec1 m (hf.comp left)).of_eq $ by simp [cases] theorem cases {f g} (hf : primrec f) (hg : primrec g) : primrec (unpaired (λ z n, n.cases (f z) (λ y, g $ mkpair z y))) := (prec hf (hg.comp (pair left (left.comp right)))).of_eq $ by simp [cases] protected theorem swap : primrec (unpaired (function.swap mkpair)) := (pair right left).of_eq $ λ n, by simp theorem swap' {f} (hf : primrec (unpaired f)) : primrec (unpaired (function.swap f)) := (hf.comp primrec.swap).of_eq $ λ n, by simp theorem pred : primrec pred := (cases1 0 primrec.id).of_eq $ λ n, by cases n; simp * theorem add : primrec (unpaired (+)) := (prec primrec.id ((succ.comp right).comp right)).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, -add_comm, add_succ] theorem sub : primrec (unpaired has_sub.sub) := (prec primrec.id ((pred.comp right).comp right)).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, -add_comm, sub_succ] theorem mul : primrec (unpaired (*)) := (prec zero (add.comp (pair left (right.comp right)))).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, mul_succ, add_comm] theorem pow : primrec (unpaired (^)) := (prec (const 1) (mul.comp (pair (right.comp right) left))).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, pow_succ'] end primrec end nat /-- A `primcodable` type is an `encodable` type for which the encode/decode functions are primitive recursive. -/ class primcodable (α : Type*) extends encodable α := (prim [] : nat.primrec (λ n, encodable.encode (decode n))) namespace primcodable open nat.primrec @[priority 10] instance of_denumerable (α) [denumerable α] : primcodable α := ⟨succ.of_eq $ by simp⟩ def of_equiv (α) {β} [primcodable α] (e : β ≃ α) : primcodable β := { prim := (primcodable.prim α).of_eq $ λ n, show encode (decode α n) = (option.cases_on (option.map e.symm (decode α n)) 0 (λ a, nat.succ (encode (e a))) : ℕ), by cases decode α n; dsimp; simp, ..encodable.of_equiv α e } instance empty : primcodable empty := ⟨zero⟩ instance unit : primcodable punit := ⟨(cases1 1 zero).of_eq $ λ n, by cases n; simp⟩ instance option {α : Type*} [h : primcodable α] : primcodable (option α) := ⟨(cases1 1 ((cases1 0 (succ.comp succ)).comp (primcodable.prim α))).of_eq $ λ n, by cases n; simp; cases decode α n; refl⟩ instance bool : primcodable bool := ⟨(cases1 1 (cases1 2 zero)).of_eq $ λ n, begin cases n, {refl}, cases n, {refl}, rw decode_ge_two, {refl}, exact dec_trivial end⟩ end primcodable /-- `primrec f` means `f` is primitive recursive (after encoding its input and output as natural numbers). -/ def primrec {α β} [primcodable α] [primcodable β] (f : α → β) : Prop := nat.primrec (λ n, encode ((decode α n).map f)) namespace primrec variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] open nat.primrec protected theorem encode : primrec (@encode α _) := (primcodable.prim α).of_eq $ λ n, by cases decode α n; refl protected theorem decode : primrec (decode α) := succ.comp (primcodable.prim α) theorem dom_denumerable {α β} [denumerable α] [primcodable β] {f : α → β} : primrec f ↔ nat.primrec (λ n, encode (f (of_nat α n))) := ⟨λ h, (pred.comp h).of_eq $ λ n, by simp; refl, λ h, (succ.comp h).of_eq $ λ n, by simp; refl⟩ theorem nat_iff {f : ℕ → ℕ} : primrec f ↔ nat.primrec f := dom_denumerable theorem encdec : primrec (λ n, encode (decode α n)) := nat_iff.2 (primcodable.prim α) theorem option_some : primrec (@some α) := ((cases1 0 (succ.comp succ)).comp (primcodable.prim α)).of_eq $ λ n, by cases decode α n; simp theorem of_eq {f g : α → σ} (hf : primrec f) (H : ∀ n, f n = g n) : primrec g := (funext H : f = g) ▸ hf theorem const (x : σ) : primrec (λ a : α, x) := ((cases1 0 (const (encode x).succ)).comp (primcodable.prim α)).of_eq $ λ n, by cases decode α n; refl protected theorem id : primrec (@id α) := (primcodable.prim α).of_eq $ by simp theorem comp {f : β → σ} {g : α → β} (hf : primrec f) (hg : primrec g) : primrec (λ a, f (g a)) := ((cases1 0 (hf.comp $ pred.comp hg)).comp (primcodable.prim α)).of_eq $ λ n, begin cases decode α n, {refl}, simp [encodek] end theorem succ : primrec nat.succ := nat_iff.2 nat.primrec.succ theorem pred : primrec nat.pred := nat_iff.2 nat.primrec.pred theorem encode_iff {f : α → σ} : primrec (λ a, encode (f a)) ↔ primrec f := ⟨λ h, nat.primrec.of_eq h $ λ n, by cases decode α n; refl, primrec.encode.comp⟩ theorem of_nat_iff {α β} [denumerable α] [primcodable β] {f : α → β} : primrec f ↔ primrec (λ n, f (of_nat α n)) := dom_denumerable.trans $ nat_iff.symm.trans encode_iff protected theorem of_nat (α) [denumerable α] : primrec (of_nat α) := of_nat_iff.1 primrec.id theorem option_some_iff {f : α → σ} : primrec (λ a, some (f a)) ↔ primrec f := ⟨λ h, encode_iff.1 $ pred.comp $ encode_iff.2 h, option_some.comp⟩ theorem of_equiv {β} {e : β ≃ α} : by haveI := primcodable.of_equiv α e; exact primrec e := (primcodable.prim α).of_eq $ λ n, show _ = encode (option.map e (option.map _ _)), by cases decode α n; simp theorem of_equiv_symm {β} {e : β ≃ α} : by haveI := primcodable.of_equiv α e; exact primrec e.symm := by letI := primcodable.of_equiv α e; exact encode_iff.1 (show primrec (λ a, encode (e (e.symm a))), by simp [primrec.encode]) theorem of_equiv_iff {β} (e : β ≃ α) {f : σ → β} : by haveI := primcodable.of_equiv α e; exact primrec (λ a, e (f a)) ↔ primrec f := by letI := primcodable.of_equiv α e; exact ⟨λ h, (of_equiv_symm.comp h).of_eq (λ a, by simp), of_equiv.comp⟩ theorem of_equiv_symm_iff {β} (e : β ≃ α) {f : σ → α} : by haveI := primcodable.of_equiv α e; exact primrec (λ a, e.symm (f a)) ↔ primrec f := by letI := primcodable.of_equiv α e; exact ⟨λ h, (of_equiv.comp h).of_eq (λ a, by simp), of_equiv_symm.comp⟩ end primrec namespace primcodable open nat.primrec instance prod {α β} [primcodable α] [primcodable β] : primcodable (α × β) := ⟨((cases zero ((cases zero succ).comp (pair right ((primcodable.prim β).comp left)))).comp (pair right ((primcodable.prim α).comp left))).of_eq $ λ n, begin simp [nat.unpaired], cases decode α n.unpair.1, { simp }, cases decode β n.unpair.2; simp end⟩ end primcodable namespace primrec variables {α : Type*} {σ : Type*} [primcodable α] [primcodable σ] open nat.primrec theorem fst {α β} [primcodable α] [primcodable β] : primrec (@prod.fst α β) := ((cases zero ((cases zero (nat.primrec.succ.comp left)).comp (pair right ((primcodable.prim β).comp left)))).comp (pair right ((primcodable.prim α).comp left))).of_eq $ λ n, begin simp, cases decode α n.unpair.1; simp, cases decode β n.unpair.2; simp end theorem snd {α β} [primcodable α] [primcodable β] : primrec (@prod.snd α β) := ((cases zero ((cases zero (nat.primrec.succ.comp right)).comp (pair right ((primcodable.prim β).comp left)))).comp (pair right ((primcodable.prim α).comp left))).of_eq $ λ n, begin simp, cases decode α n.unpair.1; simp, cases decode β n.unpair.2; simp end theorem pair {α β γ} [primcodable α] [primcodable β] [primcodable γ] {f : α → β} {g : α → γ} (hf : primrec f) (hg : primrec g) : primrec (λ a, (f a, g a)) := ((cases1 0 (nat.primrec.succ.comp $ pair (nat.primrec.pred.comp hf) (nat.primrec.pred.comp hg))).comp (primcodable.prim α)).of_eq $ λ n, by cases decode α n; simp [encodek]; refl theorem unpair : primrec nat.unpair := (pair (nat_iff.2 nat.primrec.left) (nat_iff.2 nat.primrec.right)).of_eq $ λ n, by simp theorem list_nth₁ : ∀ (l : list α), primrec l.nth | [] := dom_denumerable.2 zero | (a::l) := dom_denumerable.2 $ (cases1 (encode a).succ $ dom_denumerable.1 $ list_nth₁ l).of_eq $ λ n, by cases n; simp end primrec /-- `primrec₂ f` means `f` is a binary primitive recursive function. This is technically unnecessary since we can always curry all the arguments together, but there are enough natural two-arg functions that it is convenient to express this directly. -/ def primrec₂ {α β σ} [primcodable α] [primcodable β] [primcodable σ] (f : α → β → σ) := primrec (λ p : α × β, f p.1 p.2) /-- `primrec_pred p` means `p : α → Prop` is a (decidable) primitive recursive predicate, which is to say that `to_bool ∘ p : α → bool` is primitive recursive. -/ def primrec_pred {α} [primcodable α] (p : α → Prop) [decidable_pred p] := primrec (λ a, to_bool (p a)) /-- `primrec_rel p` means `p : α → β → Prop` is a (decidable) primitive recursive relation, which is to say that `to_bool ∘ p : α → β → bool` is primitive recursive. -/ def primrec_rel {α β} [primcodable α] [primcodable β] (s : α → β → Prop) [∀ a b, decidable (s a b)] := primrec₂ (λ a b, to_bool (s a b)) namespace primrec₂ variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] theorem of_eq {f g : α → β → σ} (hg : primrec₂ f) (H : ∀ a b, f a b = g a b) : primrec₂ g := (by funext a b; apply H : f = g) ▸ hg theorem const (x : σ) : primrec₂ (λ (a : α) (b : β), x) := primrec.const _ protected theorem pair : primrec₂ (@prod.mk α β) := primrec.pair primrec.fst primrec.snd theorem left : primrec₂ (λ (a : α) (b : β), a) := primrec.fst theorem right : primrec₂ (λ (a : α) (b : β), b) := primrec.snd theorem mkpair : primrec₂ nat.mkpair := by simp [primrec₂, primrec]; constructor theorem unpaired {f : ℕ → ℕ → α} : primrec (nat.unpaired f) ↔ primrec₂ f := ⟨λ h, by simpa using h.comp mkpair, λ h, h.comp primrec.unpair⟩ theorem unpaired' {f : ℕ → ℕ → ℕ} : nat.primrec (nat.unpaired f) ↔ primrec₂ f := primrec.nat_iff.symm.trans unpaired theorem encode_iff {f : α → β → σ} : primrec₂ (λ a b, encode (f a b)) ↔ primrec₂ f := primrec.encode_iff theorem option_some_iff {f : α → β → σ} : primrec₂ (λ a b, some (f a b)) ↔ primrec₂ f := primrec.option_some_iff theorem of_nat_iff {α β σ} [denumerable α] [denumerable β] [primcodable σ] {f : α → β → σ} : primrec₂ f ↔ primrec₂ (λ m n : ℕ, f (of_nat α m) (of_nat β n)) := (primrec.of_nat_iff.trans $ by simp).trans unpaired theorem uncurry {f : α → β → σ} : primrec (function.uncurry f) ↔ primrec₂ f := by rw [show function.uncurry f = λ (p : α × β), f p.1 p.2, from funext $ λ ⟨a, b⟩, rfl]; refl theorem curry {f : α × β → σ} : primrec₂ (function.curry f) ↔ primrec f := by rw [← uncurry, function.uncurry_curry] end primrec₂ section comp variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem primrec.comp₂ {f : γ → σ} {g : α → β → γ} (hf : primrec f) (hg : primrec₂ g) : primrec₂ (λ a b, f (g a b)) := hf.comp hg theorem primrec₂.comp {f : β → γ → σ} {g : α → β} {h : α → γ} (hf : primrec₂ f) (hg : primrec g) (hh : primrec h) : primrec (λ a, f (g a) (h a)) := hf.comp (hg.pair hh) theorem primrec₂.comp₂ {f : γ → δ → σ} {g : α → β → γ} {h : α → β → δ} (hf : primrec₂ f) (hg : primrec₂ g) (hh : primrec₂ h) : primrec₂ (λ a b, f (g a b) (h a b)) := hf.comp hg hh theorem primrec_pred.comp {p : β → Prop} [decidable_pred p] {f : α → β} : primrec_pred p → primrec f → primrec_pred (λ a, p (f a)) := primrec.comp theorem primrec_rel.comp {R : β → γ → Prop} [∀ a b, decidable (R a b)] {f : α → β} {g : α → γ} : primrec_rel R → primrec f → primrec g → primrec_pred (λ a, R (f a) (g a)) := primrec₂.comp theorem primrec_rel.comp₂ {R : γ → δ → Prop} [∀ a b, decidable (R a b)] {f : α → β → γ} {g : α → β → δ} : primrec_rel R → primrec₂ f → primrec₂ g → primrec_rel (λ a b, R (f a b) (g a b)) := primrec_rel.comp end comp theorem primrec_pred.of_eq {α} [primcodable α] {p q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (H : ∀ a, p a ↔ q a) : primrec_pred q := primrec.of_eq hp (λ a, to_bool_congr (H a)) theorem primrec_rel.of_eq {α β} [primcodable α] [primcodable β] {r s : α → β → Prop} [∀ a b, decidable (r a b)] [∀ a b, decidable (s a b)] (hr : primrec_rel r) (H : ∀ a b, r a b ↔ s a b) : primrec_rel s := primrec₂.of_eq hr (λ a b, to_bool_congr (H a b)) namespace primrec₂ variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] open nat.primrec theorem swap {f : α → β → σ} (h : primrec₂ f) : primrec₂ (function.swap f) := h.comp₂ primrec₂.right primrec₂.left theorem nat_iff {f : α → β → σ} : primrec₂ f ↔ nat.primrec (nat.unpaired $ λ m n : ℕ, encode $ (decode α m).bind $ λ a, (decode β n).map (f a)) := have ∀ (a : option α) (b : option β), option.map (λ (p : α × β), f p.1 p.2) (option.bind a (λ (a : α), option.map (prod.mk a) b)) = option.bind a (λ a, option.map (f a) b), by intros; cases a; [refl, {cases b; refl}], by simp [primrec₂, primrec, this] theorem nat_iff' {f : α → β → σ} : primrec₂ f ↔ primrec₂ (λ m n : ℕ, option.bind (decode α m) (λ a, option.map (f a) (decode β n))) := nat_iff.trans $ unpaired'.trans encode_iff end primrec₂ namespace primrec variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem to₂ {f : α × β → σ} (hf : primrec f) : primrec₂ (λ a b, f (a, b)) := hf.of_eq $ λ ⟨a, b⟩, rfl theorem nat_elim {f : α → β} {g : α → ℕ × β → β} (hf : primrec f) (hg : primrec₂ g) : primrec₂ (λ a (n : ℕ), n.elim (f a) (λ n IH, g a (n, IH))) := primrec₂.nat_iff.2 $ ((nat.primrec.cases nat.primrec.zero $ (nat.primrec.prec hf $ nat.primrec.comp hg $ nat.primrec.left.pair $ (nat.primrec.left.comp nat.primrec.right).pair $ nat.primrec.pred.comp $ nat.primrec.right.comp nat.primrec.right).comp $ nat.primrec.right.pair $ nat.primrec.right.comp nat.primrec.left).comp $ nat.primrec.id.pair $ (primcodable.prim α).comp nat.primrec.left).of_eq $ λ n, begin simp, cases decode α n.unpair.1 with a, {refl}, simp [encodek], induction n.unpair.2 with m; simp [encodek], simp [ih, encodek] end theorem nat_elim' {f : α → ℕ} {g : α → β} {h : α → ℕ × β → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (f a).elim (g a) (λ n IH, h a (n, IH))) := (nat_elim hg hh).comp primrec.id hf theorem nat_elim₁ {f : ℕ → α → α} (a : α) (hf : primrec₂ f) : primrec (nat.elim a f) := nat_elim' primrec.id (const a) $ comp₂ hf primrec₂.right theorem nat_cases' {f : α → β} {g : α → ℕ → β} (hf : primrec f) (hg : primrec₂ g) : primrec₂ (λ a, nat.cases (f a) (g a)) := nat_elim hf $ hg.comp₂ primrec₂.left $ comp₂ fst primrec₂.right theorem nat_cases {f : α → ℕ} {g : α → β} {h : α → ℕ → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (f a).cases (g a) (h a)) := (nat_cases' hg hh).comp primrec.id hf theorem nat_cases₁ {f : ℕ → α} (a : α) (hf : primrec f) : primrec (nat.cases a f) := nat_cases primrec.id (const a) (comp₂ hf primrec₂.right) theorem nat_iterate {f : α → ℕ} {g : α → β} {h : α → β → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (h a)^[f a] (g a)) := (nat_elim' hf hg (hh.comp₂ primrec₂.left $ snd.comp₂ primrec₂.right)).of_eq $ λ a, by induction f a; simp [*, function.iterate_succ'] theorem option_cases {o : α → option β} {f : α → σ} {g : α → β → σ} (ho : primrec o) (hf : primrec f) (hg : primrec₂ g) : @primrec _ σ _ _ (λ a, option.cases_on (o a) (f a) (g a)) := encode_iff.1 $ (nat_cases (encode_iff.2 ho) (encode_iff.2 hf) $ pred.comp₂ $ primrec₂.encode_iff.2 $ (primrec₂.nat_iff'.1 hg).comp₂ ((@primrec.encode α _).comp fst).to₂ primrec₂.right).of_eq $ λ a, by cases o a with b; simp [encodek]; refl theorem option_bind {f : α → option β} {g : α → β → option σ} (hf : primrec f) (hg : primrec₂ g) : primrec (λ a, (f a).bind (g a)) := (option_cases hf (const none) hg).of_eq $ λ a, by cases f a; refl theorem option_bind₁ {f : α → option σ} (hf : primrec f) : primrec (λ o, option.bind o f) := option_bind primrec.id (hf.comp snd).to₂ theorem option_map {f : α → option β} {g : α → β → σ} (hf : primrec f) (hg : primrec₂ g) : primrec (λ a, (f a).map (g a)) := option_bind hf (option_some.comp₂ hg) theorem option_map₁ {f : α → σ} (hf : primrec f) : primrec (option.map f) := option_map primrec.id (hf.comp snd).to₂ theorem option_iget [inhabited α] : primrec (@option.iget α _) := (option_cases primrec.id (const $ default α) primrec₂.right).of_eq $ λ o, by cases o; refl theorem option_is_some : primrec (@option.is_some α) := (option_cases primrec.id (const ff) (const tt).to₂).of_eq $ λ o, by cases o; refl theorem option_get_or_else : primrec₂ (@option.get_or_else α) := primrec.of_eq (option_cases primrec₂.left primrec₂.right primrec₂.right) $ λ ⟨o, a⟩, by cases o; refl theorem bind_decode_iff {f : α → β → option σ} : primrec₂ (λ a n, (decode β n).bind (f a)) ↔ primrec₂ f := ⟨λ h, by simpa [encodek] using h.comp fst ((@primrec.encode β _).comp snd), λ h, option_bind (primrec.decode.comp snd) $ h.comp (fst.comp fst) snd⟩ theorem map_decode_iff {f : α → β → σ} : primrec₂ (λ a n, (decode β n).map (f a)) ↔ primrec₂ f := bind_decode_iff.trans primrec₂.option_some_iff theorem nat_add : primrec₂ ((+) : ℕ → ℕ → ℕ) := primrec₂.unpaired'.1 nat.primrec.add theorem nat_sub : primrec₂ (has_sub.sub : ℕ → ℕ → ℕ) := primrec₂.unpaired'.1 nat.primrec.sub theorem nat_mul : primrec₂ ((*) : ℕ → ℕ → ℕ) := primrec₂.unpaired'.1 nat.primrec.mul theorem cond {c : α → bool} {f : α → σ} {g : α → σ} (hc : primrec c) (hf : primrec f) (hg : primrec g) : primrec (λ a, cond (c a) (f a) (g a)) := (nat_cases (encode_iff.2 hc) hg (hf.comp fst).to₂).of_eq $ λ a, by cases c a; refl theorem ite {c : α → Prop} [decidable_pred c] {f : α → σ} {g : α → σ} (hc : primrec_pred c) (hf : primrec f) (hg : primrec g) : primrec (λ a, if c a then f a else g a) := by simpa using cond hc hf hg theorem nat_le : primrec_rel ((≤) : ℕ → ℕ → Prop) := (nat_cases nat_sub (const tt) (const ff).to₂).of_eq $ λ p, begin dsimp [function.swap], cases e : p.1 - p.2 with n, { simp [nat.sub_eq_zero_iff_le.1 e] }, { simp [not_le.2 (nat.lt_of_sub_eq_succ e)] } end theorem nat_min : primrec₂ (@min ℕ _) := ite nat_le fst snd theorem nat_max : primrec₂ (@max ℕ _) := ite (nat_le.comp primrec.snd primrec.fst) fst snd theorem dom_bool (f : bool → α) : primrec f := (cond primrec.id (const (f tt)) (const (f ff))).of_eq $ λ b, by cases b; refl theorem dom_bool₂ (f : bool → bool → α) : primrec₂ f := (cond fst ((dom_bool (f tt)).comp snd) ((dom_bool (f ff)).comp snd)).of_eq $ λ ⟨a, b⟩, by cases a; refl protected theorem bnot : primrec bnot := dom_bool _ protected theorem band : primrec₂ band := dom_bool₂ _ protected theorem bor : primrec₂ bor := dom_bool₂ _ protected theorem not {p : α → Prop} [decidable_pred p] (hp : primrec_pred p) : primrec_pred (λ a, ¬ p a) := (primrec.bnot.comp hp).of_eq $ λ n, by simp protected theorem and {p q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (hq : primrec_pred q) : primrec_pred (λ a, p a ∧ q a) := (primrec.band.comp hp hq).of_eq $ λ n, by simp protected theorem or {p q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (hq : primrec_pred q) : primrec_pred (λ a, p a ∨ q a) := (primrec.bor.comp hp hq).of_eq $ λ n, by simp protected theorem eq [decidable_eq α] : primrec_rel (@eq α) := have primrec_rel (λ a b : ℕ, a = b), from (primrec.and nat_le nat_le.swap).of_eq $ λ a, by simp [le_antisymm_iff], (this.comp₂ (primrec.encode.comp₂ primrec₂.left) (primrec.encode.comp₂ primrec₂.right)).of_eq $ λ a b, encode_injective.eq_iff theorem nat_lt : primrec_rel ((<) : ℕ → ℕ → Prop) := (nat_le.comp snd fst).not.of_eq $ λ p, by simp theorem option_guard {p : α → β → Prop} [∀ a b, decidable (p a b)] (hp : primrec_rel p) {f : α → β} (hf : primrec f) : primrec (λ a, option.guard (p a) (f a)) := ite (hp.comp primrec.id hf) (option_some_iff.2 hf) (const none) theorem option_orelse : primrec₂ ((<|>) : option α → option α → option α) := (option_cases fst snd (fst.comp fst).to₂).of_eq $ λ ⟨o₁, o₂⟩, by cases o₁; cases o₂; refl protected theorem decode2 : primrec (decode2 α) := option_bind primrec.decode $ option_guard ((@primrec.eq _ _ nat.decidable_eq).comp (encode_iff.2 snd) (fst.comp fst)) snd theorem list_find_index₁ {p : α → β → Prop} [∀ a b, decidable (p a b)] (hp : primrec_rel p) : ∀ (l : list β), primrec (λ a, l.find_index (p a)) | [] := const 0 | (a::l) := ite (hp.comp primrec.id (const a)) (const 0) (succ.comp (list_find_index₁ l)) theorem list_index_of₁ [decidable_eq α] (l : list α) : primrec (λ a, l.index_of a) := list_find_index₁ primrec.eq l theorem dom_fintype [fintype α] (f : α → σ) : primrec f := let ⟨l, nd, m⟩ := fintype.exists_univ_list α in option_some_iff.1 $ begin haveI := decidable_eq_of_encodable α, refine ((list_nth₁ (l.map f)).comp (list_index_of₁ l)).of_eq (λ a, _), rw [list.nth_map, list.nth_le_nth (list.index_of_lt_length.2 (m _)), list.index_of_nth_le]; refl end theorem nat_bodd_div2 : primrec nat.bodd_div2 := (nat_elim' primrec.id (const (ff, 0)) (((cond fst (pair (const ff) (succ.comp snd)) (pair (const tt) snd)).comp snd).comp snd).to₂).of_eq $ λ n, begin simp [-nat.bodd_div2_eq], induction n with n IH, {refl}, simp [-nat.bodd_div2_eq, nat.bodd_div2, *], rcases nat.bodd_div2 n with ⟨_|_, m⟩; simp [nat.bodd_div2] end theorem nat_bodd : primrec nat.bodd := fst.comp nat_bodd_div2 theorem nat_div2 : primrec nat.div2 := snd.comp nat_bodd_div2 theorem nat_bit0 : primrec (@bit0 ℕ _) := nat_add.comp primrec.id primrec.id theorem nat_bit1 : primrec (@bit1 ℕ _ _) := nat_add.comp nat_bit0 (const 1) theorem nat_bit : primrec₂ nat.bit := (cond primrec.fst (nat_bit1.comp primrec.snd) (nat_bit0.comp primrec.snd)).of_eq $ λ n, by cases n.1; refl theorem nat_div_mod : primrec₂ (λ n k : ℕ, (n / k, n % k)) := let f (a : ℕ × ℕ) : ℕ × ℕ := a.1.elim (0, 0) (λ _ IH, if nat.succ IH.2 = a.2 then (nat.succ IH.1, 0) else (IH.1, nat.succ IH.2)) in have hf : primrec f, from nat_elim' fst (const (0, 0)) $ ((ite ((@primrec.eq ℕ _ _).comp (succ.comp $ snd.comp snd) fst) (pair (succ.comp $ fst.comp snd) (const 0)) (pair (fst.comp snd) (succ.comp $ snd.comp snd))) .comp (pair (snd.comp fst) (snd.comp snd))).to₂, suffices ∀ k n, (n / k, n % k) = f (n, k), from hf.of_eq $ λ ⟨m, n⟩, by simp [this], λ k n, begin have : (f (n, k)).2 + k * (f (n, k)).1 = n ∧ (0 < k → (f (n, k)).2 < k) ∧ (k = 0 → (f (n, k)).1 = 0), { induction n with n IH, {exact ⟨rfl, id, λ _, rfl⟩}, rw [λ n:ℕ, show f (n.succ, k) = _root_.ite ((f (n, k)).2.succ = k) (nat.succ (f (n, k)).1, 0) ((f (n, k)).1, (f (n, k)).2.succ), from rfl], by_cases h : (f (n, k)).2.succ = k; simp [h], { have := congr_arg nat.succ IH.1, refine ⟨_, λ k0, nat.no_confusion (h.trans k0)⟩, rwa [← nat.succ_add, h, add_comm, ← nat.mul_succ] at this }, { exact ⟨by rw [nat.succ_add, IH.1], λ k0, lt_of_le_of_ne (IH.2.1 k0) h, IH.2.2⟩ } }, revert this, cases f (n, k) with D M, simp, intros h₁ h₂ h₃, cases nat.eq_zero_or_pos k, { simp [h, h₃ h] at h₁ ⊢, simp [h₁] }, { exact (nat.div_mod_unique h).2 ⟨h₁, h₂ h⟩ } end theorem nat_div : primrec₂ ((/) : ℕ → ℕ → ℕ) := fst.comp₂ nat_div_mod theorem nat_mod : primrec₂ ((%) : ℕ → ℕ → ℕ) := snd.comp₂ nat_div_mod end primrec section variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] variable (H : nat.primrec (λ n, encodable.encode (decode (list β) n))) include H open primrec private def prim : primcodable (list β) := ⟨H⟩ private lemma list_cases' {f : α → list β} {g : α → σ} {h : α → β × list β → σ} (hf : by haveI := prim H; exact primrec f) (hg : primrec g) (hh : by haveI := prim H; exact primrec₂ h) : @primrec _ σ _ _ (λ a, list.cases_on (f a) (g a) (λ b l, h a (b, l))) := by letI := prim H; exact have @primrec _ (option σ) _ _ (λ a, (decode (option (β × list β)) (encode (f a))).map (λ o, option.cases_on o (g a) (h a))), from ((@map_decode_iff _ (option (β × list β)) _ _ _ _ _).2 $ to₂ $ option_cases snd (hg.comp fst) (hh.comp₂ (fst.comp₂ primrec₂.left) primrec₂.right)) .comp primrec.id (encode_iff.2 hf), option_some_iff.1 $ this.of_eq $ λ a, by cases f a with b l; simp [encodek]; refl private lemma list_foldl' {f : α → list β} {g : α → σ} {h : α → σ × β → σ} (hf : by haveI := prim H; exact primrec f) (hg : primrec g) (hh : by haveI := prim H; exact primrec₂ h) : primrec (λ a, (f a).foldl (λ s b, h a (s, b)) (g a)) := by letI := prim H; exact let G (a : α) (IH : σ × list β) : σ × list β := list.cases_on IH.2 IH (λ b l, (h a (IH.1, b), l)) in let F (a : α) (n : ℕ) := (G a)^[n] (g a, f a) in have primrec (λ a, (F a (encode (f a))).1), from fst.comp $ nat_iterate (encode_iff.2 hf) (pair hg hf) $ list_cases' H (snd.comp snd) snd $ to₂ $ pair (hh.comp (fst.comp fst) $ pair ((fst.comp snd).comp fst) (fst.comp snd)) (snd.comp snd), this.of_eq $ λ a, begin have : ∀ n, F a n = ((list.take n (f a)).foldl (λ s b, h a (s, b)) (g a), list.drop n (f a)), { intro, simp [F], generalize : f a = l, generalize : g a = x, induction n with n IH generalizing l x, {refl}, simp, cases l with b l; simp [IH] }, rw [this, list.take_all_of_le (length_le_encode _)] end private lemma list_cons' : by haveI := prim H; exact primrec₂ (@list.cons β) := by letI := prim H; exact encode_iff.1 (succ.comp $ primrec₂.mkpair.comp (encode_iff.2 fst) (encode_iff.2 snd)) private lemma list_reverse' : by haveI := prim H; exact primrec (@list.reverse β) := by letI := prim H; exact (list_foldl' H primrec.id (const []) $ to₂ $ ((list_cons' H).comp snd fst).comp snd).of_eq (suffices ∀ l r, list.foldl (λ (s : list β) (b : β), b :: s) r l = list.reverse_core l r, from λ l, this l [], λ l, by induction l; simp [*, list.reverse_core]) end namespace primcodable variables {α : Type*} {β : Type*} variables [primcodable α] [primcodable β] open primrec instance sum : primcodable (α ⊕ β) := ⟨primrec.nat_iff.1 $ (encode_iff.2 (cond nat_bodd (((@primrec.decode β _).comp nat_div2).option_map $ to₂ $ nat_bit.comp (const tt) (primrec.encode.comp snd)) (((@primrec.decode α _).comp nat_div2).option_map $ to₂ $ nat_bit.comp (const ff) (primrec.encode.comp snd)))).of_eq $ λ n, show _ = encode (decode_sum n), begin simp [decode_sum], cases nat.bodd n; simp [decode_sum], { cases decode α n.div2; refl }, { cases decode β n.div2; refl } end⟩ instance list : primcodable (list α) := ⟨ by letI H := primcodable.prim (list ℕ); exact have primrec₂ (λ (a : α) (o : option (list ℕ)), o.map (list.cons (encode a))), from option_map snd $ (list_cons' H).comp ((@primrec.encode α _).comp (fst.comp fst)) snd, have primrec (λ n, (of_nat (list ℕ) n).reverse.foldl (λ o m, (decode α m).bind (λ a, o.map (list.cons (encode a)))) (some [])), from list_foldl' H ((list_reverse' H).comp (primrec.of_nat (list ℕ))) (const (some [])) (primrec.comp₂ (bind_decode_iff.2 $ primrec₂.swap this) primrec₂.right), nat_iff.1 $ (encode_iff.2 this).of_eq $ λ n, begin rw list.foldl_reverse, apply nat.case_strong_induction_on n, {refl}, intros n IH, simp, cases decode α n.unpair.1 with a, {refl}, simp, suffices : ∀ (o : option (list ℕ)) p (_ : encode o = encode p), encode (option.map (list.cons (encode a)) o) = encode (option.map (list.cons a) p), from this _ _ (IH _ (nat.unpair_le_right n)), intros o p IH, cases o; cases p; injection IH with h, exact congr_arg (λ k, (nat.mkpair (encode a) k).succ.succ) h end⟩ end primcodable namespace primrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem sum_inl : primrec (@sum.inl α β) := encode_iff.1 $ nat_bit0.comp primrec.encode theorem sum_inr : primrec (@sum.inr α β) := encode_iff.1 $ nat_bit1.comp primrec.encode theorem sum_cases {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ → σ} (hf : primrec f) (hg : primrec₂ g) (hh : primrec₂ h) : @primrec _ σ _ _ (λ a, sum.cases_on (f a) (g a) (h a)) := option_some_iff.1 $ (cond (nat_bodd.comp $ encode_iff.2 hf) (option_map (primrec.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hh) (option_map (primrec.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hg)).of_eq $ λ a, by cases f a with b c; simp [nat.div2_bit, nat.bodd_bit, encodek]; refl theorem list_cons : primrec₂ (@list.cons α) := list_cons' (primcodable.prim _) theorem list_cases {f : α → list β} {g : α → σ} {h : α → β × list β → σ} : primrec f → primrec g → primrec₂ h → @primrec _ σ _ _ (λ a, list.cases_on (f a) (g a) (λ b l, h a (b, l))) := list_cases' (primcodable.prim _) theorem list_foldl {f : α → list β} {g : α → σ} {h : α → σ × β → σ} : primrec f → primrec g → primrec₂ h → primrec (λ a, (f a).foldl (λ s b, h a (s, b)) (g a)) := list_foldl' (primcodable.prim _) theorem list_reverse : primrec (@list.reverse α) := list_reverse' (primcodable.prim _) theorem list_foldr {f : α → list β} {g : α → σ} {h : α → β × σ → σ} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (f a).foldr (λ b s, h a (b, s)) (g a)) := (list_foldl (list_reverse.comp hf) hg $ to₂ $ hh.comp fst $ (pair snd fst).comp snd).of_eq $ λ a, by simp [list.foldl_reverse] theorem list_head' : primrec (@list.head' α) := (list_cases primrec.id (const none) (option_some_iff.2 $ (fst.comp snd)).to₂).of_eq $ λ l, by cases l; refl theorem list_head [inhabited α] : primrec (@list.head α _) := (option_iget.comp list_head').of_eq $ λ l, l.head_eq_head'.symm theorem list_tail : primrec (@list.tail α) := (list_cases primrec.id (const []) (snd.comp snd).to₂).of_eq $ λ l, by cases l; refl theorem list_rec {f : α → list β} {g : α → σ} {h : α → β × list β × σ → σ} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : @primrec _ σ _ _ (λ a, list.rec_on (f a) (g a) (λ b l IH, h a (b, l, IH))) := let F (a : α) := (f a).foldr (λ (b : β) (s : list β × σ), (b :: s.1, h a (b, s))) ([], g a) in have primrec F, from list_foldr hf (pair (const []) hg) $ to₂ $ pair ((list_cons.comp fst (fst.comp snd)).comp snd) hh, (snd.comp this).of_eq $ λ a, begin suffices : F a = (f a, list.rec_on (f a) (g a) (λ b l IH, h a (b, l, IH))), {rw this}, simp [F], induction f a with b l IH; simp * end theorem list_nth : primrec₂ (@list.nth α) := let F (l : list α) (n : ℕ) := l.foldl (λ (s : ℕ ⊕ α) (a : α), sum.cases_on s (@nat.cases (ℕ ⊕ α) (sum.inr a) sum.inl) sum.inr) (sum.inl n) in have hF : primrec₂ F, from list_foldl fst (sum_inl.comp snd) ((sum_cases fst (nat_cases snd (sum_inr.comp $ snd.comp fst) (sum_inl.comp snd).to₂).to₂ (sum_inr.comp snd).to₂).comp snd).to₂, have @primrec _ (option α) _ _ (λ p : list α × ℕ, sum.cases_on (F p.1 p.2) (λ _, none) some), from sum_cases hF (const none).to₂ (option_some.comp snd).to₂, this.to₂.of_eq $ λ l n, begin dsimp, symmetry, induction l with a l IH generalizing n, {refl}, cases n with n, { rw [(_ : F (a :: l) 0 = sum.inr a)], {refl}, clear IH, dsimp [F], induction l with b l IH; simp * }, { apply IH } end theorem list_inth [inhabited α] : primrec₂ (@list.inth α _) := option_iget.comp₂ list_nth theorem list_append : primrec₂ ((++) : list α → list α → list α) := (list_foldr fst snd $ to₂ $ comp (@list_cons α _) snd).to₂.of_eq $ λ l₁ l₂, by induction l₁; simp * theorem list_concat : primrec₂ (λ l (a:α), l ++ [a]) := list_append.comp fst (list_cons.comp snd (const [])) theorem list_map {f : α → list β} {g : α → β → σ} (hf : primrec f) (hg : primrec₂ g) : primrec (λ a, (f a).map (g a)) := (list_foldr hf (const []) $ to₂ $ list_cons.comp (hg.comp fst (fst.comp snd)) (snd.comp snd)).of_eq $ λ a, by induction f a; simp * theorem list_range : primrec list.range := (nat_elim' primrec.id (const []) ((list_concat.comp snd fst).comp snd).to₂).of_eq $ λ n, by simp; induction n; simp [*, list.range_concat]; refl theorem list_join : primrec (@list.join α) := (list_foldr primrec.id (const []) $ to₂ $ comp (@list_append α _) snd).of_eq $ λ l, by dsimp; induction l; simp * theorem list_length : primrec (@list.length α) := (list_foldr (@primrec.id (list α) _) (const 0) $ to₂ $ (succ.comp $ snd.comp snd).to₂).of_eq $ λ l, by dsimp; induction l; simp [*, -add_comm] theorem list_find_index {f : α → list β} {p : α → β → Prop} [∀ a b, decidable (p a b)] (hf : primrec f) (hp : primrec_rel p) : primrec (λ a, (f a).find_index (p a)) := (list_foldr hf (const 0) $ to₂ $ ite (hp.comp fst $ fst.comp snd) (const 0) (succ.comp $ snd.comp snd)).of_eq $ λ a, eq.symm $ by dsimp; induction f a with b l; [refl, simp [*, list.find_index]] theorem list_index_of [decidable_eq α] : primrec₂ (@list.index_of α _) := to₂ $ list_find_index snd $ primrec.eq.comp₂ (fst.comp fst).to₂ snd.to₂ theorem nat_strong_rec (f : α → ℕ → σ) {g : α → list σ → option σ} (hg : primrec₂ g) (H : ∀ a n, g a ((list.range n).map (f a)) = some (f a n)) : primrec₂ f := suffices primrec₂ (λ a n, (list.range n).map (f a)), from primrec₂.option_some_iff.1 $ (list_nth.comp (this.comp fst (succ.comp snd)) snd).to₂.of_eq $ λ a n, by simp [list.nth_range (nat.lt_succ_self n)]; refl, primrec₂.option_some_iff.1 $ (nat_elim (const (some [])) (to₂ $ option_bind (snd.comp snd) $ to₂ $ option_map (hg.comp (fst.comp fst) snd) (to₂ $ list_concat.comp (snd.comp fst) snd))).of_eq $ λ a n, begin simp, induction n with n IH, {refl}, simp [IH, H, list.range_concat] end end primrec namespace primcodable variables {α : Type*} {β : Type*} variables [primcodable α] [primcodable β] open primrec def subtype {p : α → Prop} [decidable_pred p] (hp : primrec_pred p) : primcodable (subtype p) := ⟨have primrec (λ n, (decode α n).bind (λ a, option.guard p a)), from option_bind primrec.decode (option_guard (hp.comp snd) snd), nat_iff.1 $ (encode_iff.2 this).of_eq $ λ n, show _ = encode ((decode α n).bind (λ a, _)), begin cases decode α n with a, {refl}, dsimp [option.guard], by_cases h : p a; simp [h]; refl end⟩ instance fin {n} : primcodable (fin n) := @of_equiv _ _ (subtype $ nat_lt.comp primrec.id (const n)) (equiv.fin_equiv_subtype _) instance vector {n} : primcodable (vector α n) := subtype ((@primrec.eq _ _ nat.decidable_eq).comp list_length (const _)) instance fin_arrow {n} : primcodable (fin n → α) := of_equiv _ (equiv.vector_equiv_fin _ _).symm instance array {n} : primcodable (array n α) := of_equiv _ (equiv.array_equiv_fin _ _) section ulower local attribute [instance, priority 100] encodable.decidable_range_encode encodable.decidable_eq_of_encodable instance ulower : primcodable (ulower α) := have primrec_pred (λ n, encodable.decode2 α n ≠ none), from primrec.not (primrec.eq.comp (primrec.option_bind primrec.decode (primrec.ite (primrec.eq.comp (primrec.encode.comp primrec.snd) primrec.fst) (primrec.option_some.comp primrec.snd) (primrec.const _))) (primrec.const _)), primcodable.subtype $ primrec_pred.of_eq this $ by simp [set.range, option.eq_none_iff_forall_not_mem, encodable.mem_decode2] end ulower end primcodable namespace primrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem subtype_val {p : α → Prop} [decidable_pred p] {hp : primrec_pred p} : by haveI := primcodable.subtype hp; exact primrec (@subtype.val α p) := begin letI := primcodable.subtype hp, refine (primcodable.prim (subtype p)).of_eq (λ n, _), rcases decode (subtype p) n with _|⟨a,h⟩; refl end theorem subtype_val_iff {p : β → Prop} [decidable_pred p] {hp : primrec_pred p} {f : α → subtype p} : by haveI := primcodable.subtype hp; exact primrec (λ a, (f a).1) ↔ primrec f := begin letI := primcodable.subtype hp, refine ⟨λ h, _, λ hf, subtype_val.comp hf⟩, refine nat.primrec.of_eq h (λ n, _), cases decode α n with a, {refl}, simp, cases f a; refl end theorem subtype_mk {p : β → Prop} [decidable_pred p] {hp : primrec_pred p} {f : α → β} {h : ∀ a, p (f a)} (hf : primrec f) : by haveI := primcodable.subtype hp; exact primrec (λ a, @subtype.mk β p (f a) (h a)) := subtype_val_iff.1 hf theorem option_get {f : α → option β} {h : ∀ a, (f a).is_some} : primrec f → primrec (λ a, option.get (h a)) := begin intro hf, refine (nat.primrec.pred.comp hf).of_eq (λ n, _), generalize hx : decode α n = x, cases x; simp end theorem ulower_down : primrec (ulower.down : α → ulower α) := by letI : ∀ a, decidable (a ∈ set.range (encode : α → ℕ)) := decidable_range_encode _; exact subtype_mk primrec.encode theorem ulower_up : primrec (ulower.up : ulower α → α) := by letI : ∀ a, decidable (a ∈ set.range (encode : α → ℕ)) := decidable_range_encode _; exact option_get (primrec.decode2.comp subtype_val) theorem fin_val_iff {n} {f : α → fin n} : primrec (λ a, (f a).1) ↔ primrec f := begin let : primcodable {a//id a<n}, swap, exactI (iff.trans (by refl) subtype_val_iff).trans (of_equiv_iff _) end theorem fin_val {n} : primrec (coe : fin n → ℕ) := fin_val_iff.2 primrec.id theorem fin_succ {n} : primrec (@fin.succ n) := fin_val_iff.1 $ by simp [succ.comp fin_val] theorem vector_to_list {n} : primrec (@vector.to_list α n) := subtype_val theorem vector_to_list_iff {n} {f : α → vector β n} : primrec (λ a, (f a).to_list) ↔ primrec f := subtype_val_iff theorem vector_cons {n} : primrec₂ (@vector.cons α n) := vector_to_list_iff.1 $ by simp; exact list_cons.comp fst (vector_to_list_iff.2 snd) theorem vector_length {n} : primrec (@vector.length α n) := const _ theorem vector_head {n} : primrec (@vector.head α n) := option_some_iff.1 $ (list_head'.comp vector_to_list).of_eq $ λ ⟨a::l, h⟩, rfl theorem vector_tail {n} : primrec (@vector.tail α n) := vector_to_list_iff.1 $ (list_tail.comp vector_to_list).of_eq $ λ ⟨l, h⟩, by cases l; refl theorem vector_nth {n} : primrec₂ (@vector.nth α n) := option_some_iff.1 $ (list_nth.comp (vector_to_list.comp fst) (fin_val.comp snd)).of_eq $ λ a, by simp [vector.nth_eq_nth_le]; rw [← list.nth_le_nth] theorem list_of_fn : ∀ {n} {f : fin n → α → σ}, (∀ i, primrec (f i)) → primrec (λ a, list.of_fn (λ i, f i a)) | 0 f hf := const [] | (n+1) f hf := by simp [list.of_fn_succ]; exact list_cons.comp (hf 0) (list_of_fn (λ i, hf i.succ)) theorem vector_of_fn {n} {f : fin n → α → σ} (hf : ∀ i, primrec (f i)) : primrec (λ a, vector.of_fn (λ i, f i a)) := vector_to_list_iff.1 $ by simp [list_of_fn hf] theorem vector_nth' {n} : primrec (@vector.nth α n) := of_equiv_symm theorem vector_of_fn' {n} : primrec (@vector.of_fn α n) := of_equiv theorem fin_app {n} : primrec₂ (@id (fin n → σ)) := (vector_nth.comp (vector_of_fn'.comp fst) snd).of_eq $ λ ⟨v, i⟩, by simp theorem fin_curry₁ {n} {f : fin n → α → σ} : primrec₂ f ↔ ∀ i, primrec (f i) := ⟨λ h i, h.comp (const i) primrec.id, λ h, (vector_nth.comp ((vector_of_fn h).comp snd) fst).of_eq $ λ a, by simp⟩ theorem fin_curry {n} {f : α → fin n → σ} : primrec f ↔ primrec₂ f := ⟨λ h, fin_app.comp (h.comp fst) snd, λ h, (vector_nth'.comp (vector_of_fn (λ i, show primrec (λ a, f a i), from h.comp primrec.id (const i)))).of_eq $ λ a, by funext i; simp⟩ end primrec namespace nat open vector /-- An alternative inductive definition of `primrec` which does not use the pairing function on ℕ, and so has to work with n-ary functions on ℕ instead of unary functions. We prove that this is equivalent to the regular notion in `to_prim` and `of_prim`. -/ inductive primrec' : ∀ {n}, (vector ℕ n → ℕ) → Prop | zero : @primrec' 0 (λ _, 0) | succ : @primrec' 1 (λ v, succ v.head) | nth {n} (i : fin n) : primrec' (λ v, v.nth i) | comp {m n f} (g : fin n → vector ℕ m → ℕ) : primrec' f → (∀ i, primrec' (g i)) → primrec' (λ a, f (of_fn (λ i, g i a))) | prec {n f g} : @primrec' n f → @primrec' (n+2) g → primrec' (λ v : vector ℕ (n+1), v.head.elim (f v.tail) (λ y IH, g (y :: IH :: v.tail))) end nat namespace nat.primrec' open vector primrec nat (primrec') nat.primrec' hide ite theorem to_prim {n f} (pf : @primrec' n f) : primrec f := begin induction pf, case nat.primrec'.zero { exact const 0 }, case nat.primrec'.succ { exact primrec.succ.comp vector_head }, case nat.primrec'.nth : n i { exact vector_nth.comp primrec.id (const i) }, case nat.primrec'.comp : m n f g _ _ hf hg { exact hf.comp (vector_of_fn (λ i, hg i)) }, case nat.primrec'.prec : n f g _ _ hf hg { exact nat_elim' vector_head (hf.comp vector_tail) (hg.comp $ vector_cons.comp (fst.comp snd) $ vector_cons.comp (snd.comp snd) $ (@vector_tail _ _ (n+1)).comp fst).to₂ }, end theorem of_eq {n} {f g : vector ℕ n → ℕ} (hf : primrec' f) (H : ∀ i, f i = g i) : primrec' g := (funext H : f = g) ▸ hf theorem const {n} : ∀ m, @primrec' n (λ v, m) | 0 := zero.comp fin.elim0 (λ i, i.elim0) | (m+1) := succ.comp _ (λ i, const m) theorem head {n : ℕ} : @primrec' n.succ head := (nth 0).of_eq $ λ v, by simp [nth_zero] theorem tail {n f} (hf : @primrec' n f) : @primrec' n.succ (λ v, f v.tail) := (hf.comp _ (λ i, @nth _ i.succ)).of_eq $ λ v, by rw [← of_fn_nth v.tail]; congr; funext i; simp def vec {n m} (f : vector ℕ n → vector ℕ m) := ∀ i, primrec' (λ v, (f v).nth i) protected theorem nil {n} : @vec n 0 (λ _, nil) := λ i, i.elim0 protected theorem cons {n m f g} (hf : @primrec' n f) (hg : @vec n m g) : vec (λ v, f v :: g v) := λ i, fin.cases (by simp *) (λ i, by simp [hg i]) i theorem idv {n} : @vec n n id := nth theorem comp' {n m f g} (hf : @primrec' m f) (hg : @vec n m g) : primrec' (λ v, f (g v)) := (hf.comp _ hg).of_eq $ λ v, by simp theorem comp₁ (f : ℕ → ℕ) (hf : @primrec' 1 (λ v, f v.head)) {n g} (hg : @primrec' n g) : primrec' (λ v, f (g v)) := hf.comp _ (λ i, hg) theorem comp₂ (f : ℕ → ℕ → ℕ) (hf : @primrec' 2 (λ v, f v.head v.tail.head)) {n g h} (hg : @primrec' n g) (hh : @primrec' n h) : primrec' (λ v, f (g v) (h v)) := by simpa using hf.comp' (hg.cons $ hh.cons primrec'.nil) theorem prec' {n f g h} (hf : @primrec' n f) (hg : @primrec' n g) (hh : @primrec' (n+2) h) : @primrec' n (λ v, (f v).elim (g v) (λ (y IH : ℕ), h (y :: IH :: v))) := by simpa using comp' (prec hg hh) (hf.cons idv) theorem pred : @primrec' 1 (λ v, v.head.pred) := (prec' head (const 0) head).of_eq $ λ v, by simp; cases v.head; refl theorem add : @primrec' 2 (λ v, v.head + v.tail.head) := (prec head (succ.comp₁ _ (tail head))).of_eq $ λ v, by simp; induction v.head; simp [*, nat.succ_add] theorem sub : @primrec' 2 (λ v, v.head - v.tail.head) := begin suffices, simpa using comp₂ (λ a b, b - a) this (tail head) head, refine (prec head (pred.comp₁ _ (tail head))).of_eq (λ v, _), simp, induction v.head; simp [*, nat.sub_succ] end theorem mul : @primrec' 2 (λ v, v.head * v.tail.head) := (prec (const 0) (tail (add.comp₂ _ (tail head) (head)))).of_eq $ λ v, by simp; induction v.head; simp [*, nat.succ_mul]; rw add_comm theorem if_lt {n a b f g} (ha : @primrec' n a) (hb : @primrec' n b) (hf : @primrec' n f) (hg : @primrec' n g) : @primrec' n (λ v, if a v < b v then f v else g v) := (prec' (sub.comp₂ _ hb ha) hg (tail $ tail hf)).of_eq $ λ v, begin cases e : b v - a v, { simp [not_lt.2 (nat.le_of_sub_eq_zero e)] }, { simp [nat.lt_of_sub_eq_succ e] } end theorem mkpair : @primrec' 2 (λ v, v.head.mkpair v.tail.head) := if_lt head (tail head) (add.comp₂ _ (tail $ mul.comp₂ _ head head) head) (add.comp₂ _ (add.comp₂ _ (mul.comp₂ _ head head) head) (tail head)) protected theorem encode : ∀ {n}, @primrec' n encode | 0 := (const 0).of_eq (λ v, by rw v.eq_nil; refl) | (n+1) := (succ.comp₁ _ (mkpair.comp₂ _ head (tail encode))) .of_eq $ λ ⟨a::l, e⟩, rfl theorem sqrt : @primrec' 1 (λ v, v.head.sqrt) := begin suffices H : ∀ n : ℕ, n.sqrt = n.elim 0 (λ x y, if x.succ < y.succ*y.succ then y else y.succ), { simp [H], have := @prec' 1 _ _ (λ v, by have x := v.head; have y := v.tail.head; from if x.succ < y.succ*y.succ then y else y.succ) head (const 0) _, { convert this, funext, congr, funext x y, congr; simp }, have x1 := succ.comp₁ _ head, have y1 := succ.comp₁ _ (tail head), exact if_lt x1 (mul.comp₂ _ y1 y1) (tail head) y1 }, intro, symmetry, induction n with n IH, {refl}, dsimp, rw IH, split_ifs, { exact le_antisymm (nat.sqrt_le_sqrt (nat.le_succ _)) (nat.lt_succ_iff.1 $ nat.sqrt_lt.2 h) }, { exact nat.eq_sqrt.2 ⟨not_lt.1 h, nat.sqrt_lt.1 $ nat.lt_succ_iff.2 $ nat.sqrt_succ_le_succ_sqrt _⟩ }, end theorem unpair₁ {n f} (hf : @primrec' n f) : @primrec' n (λ v, (f v).unpair.1) := begin have s := sqrt.comp₁ _ hf, have fss := sub.comp₂ _ hf (mul.comp₂ _ s s), refine (if_lt fss s fss s).of_eq (λ v, _), simp [nat.unpair], split_ifs; refl end theorem unpair₂ {n f} (hf : @primrec' n f) : @primrec' n (λ v, (f v).unpair.2) := begin have s := sqrt.comp₁ _ hf, have fss := sub.comp₂ _ hf (mul.comp₂ _ s s), refine (if_lt fss s s (sub.comp₂ _ fss s)).of_eq (λ v, _), simp [nat.unpair], split_ifs; refl end theorem of_prim : ∀ {n f}, primrec f → @primrec' n f := suffices ∀ f, nat.primrec f → @primrec' 1 (λ v, f v.head), from λ n f hf, (pred.comp₁ _ $ (this _ hf).comp₁ (λ m, encodable.encode $ (decode (vector ℕ n) m).map f) primrec'.encode).of_eq (λ i, by simp [encodek]), λ f hf, begin induction hf, case nat.primrec.zero { exact const 0 }, case nat.primrec.succ { exact succ }, case nat.primrec.left { exact unpair₁ head }, case nat.primrec.right { exact unpair₂ head }, case nat.primrec.pair : f g _ _ hf hg { exact mkpair.comp₂ _ hf hg }, case nat.primrec.comp : f g _ _ hf hg { exact hf.comp₁ _ hg }, case nat.primrec.prec : f g _ _ hf hg { simpa using prec' (unpair₂ head) (hf.comp₁ _ (unpair₁ head)) (hg.comp₁ _ $ mkpair.comp₂ _ (unpair₁ $ tail $ tail head) (mkpair.comp₂ _ head (tail head))) }, end theorem prim_iff {n f} : @primrec' n f ↔ primrec f := ⟨to_prim, of_prim⟩ theorem prim_iff₁ {f : ℕ → ℕ} : @primrec' 1 (λ v, f v.head) ↔ primrec f := prim_iff.trans ⟨ λ h, (h.comp $ vector_of_fn $ λ i, primrec.id).of_eq (λ v, by simp), λ h, h.comp vector_head⟩ theorem prim_iff₂ {f : ℕ → ℕ → ℕ} : @primrec' 2 (λ v, f v.head v.tail.head) ↔ primrec₂ f := prim_iff.trans ⟨ λ h, (h.comp $ vector_cons.comp fst $ vector_cons.comp snd (primrec.const nil)).of_eq (λ v, by simp), λ h, h.comp vector_head (vector_head.comp vector_tail)⟩ theorem vec_iff {m n f} : @vec m n f ↔ primrec f := ⟨λ h, by simpa using vector_of_fn (λ i, to_prim (h i)), λ h i, of_prim $ vector_nth.comp h (primrec.const i)⟩ end nat.primrec' theorem primrec.nat_sqrt : primrec nat.sqrt := nat.primrec'.prim_iff₁.1 nat.primrec'.sqrt
eb186d97d08be6645f6a1f277f5dac55d65cfadd
646fc4b41ca4adb82b3f7fbae3ea3c58ff496b4c
/plugin/ExamplePlugin.lean
d2da54f56e73d4c5bf4dd0c4e9749cfc52fa461f
[]
no_license
cpehle/lean4-plugin-example
82e63420463483381c91de0705b5626a336863fa
d32d3b310645cfecf4c33acafe996755f67cf30b
refs/heads/main
1,690,367,192,612
1,631,531,751,000
1,631,531,751,000
405,148,785
2
1
null
null
null
null
UTF-8
Lean
false
false
14
lean
import Example
be1ac3678885627516cedfc14e485b8d5cfc6be1
50e6ffa56cd703f20b86b116355ffd021acff51c
/06-formalizacija-dokazov/dokazi.lean
12f5d4a734b2d16d62f2c4e81c47fdcc1bdcef4c
[]
no_license
petrare/teorija-programskih-jezikov
bf258a448ae2c3c8157f9013ffb9f4dbfa636735
5092c07eded87a49c87d86dd8f44c681c3451b09
refs/heads/master
1,607,048,747,046
1,577,184,046,000
1,577,184,046,000
221,446,748
0
0
null
1,573,645,609,000
1,573,645,608,000
null
UTF-8
Lean
false
false
1,210
lean
inductive naravno : Type | nic : naravno | nasl : naravno -> naravno inductive seznam_naravnih_stevil : Type | prazen : seznam_naravnih_stevil | sestavljen : naravno -> seznam_naravnih_stevil -> seznam_naravnih_stevil inductive seznam_dolzine : naravno -> Type | prazen : seznam_dolzine naravno.nic | sestavljen : ∀ n, naravno -> seznam_dolzine n -> seznam_dolzine (naravno.nasl n) inductive ali : Prop -> Prop -> Prop | inl : ∀ p q, p -> ali p q | inr : ∀ p q, q -> ali p q #check ali.rec #check or.rec #check or.inl -- P \/ Q => Q \/ P def or_comm' : ∀ p q, p ∨ q -> q ∨ p := λ p q h_p_q, or.rec or.inr or.inl h_p_q theorem or_comm'' : ∀ p q, p ∨ q -> q ∨ p := begin intro p, intro q, intro h, cases h, case or.inl { apply or.inr, exact h, }, case or.inr { left, assumption, } end #print or_comm'' theorem or_comm'' : forall p q, p ∨ q -> q ∨ p := begin intros, cases a, case or.inl { apply or.inr, exact a }, case or.inr { apply (or.inl a) } end -- (P => Q) /\ P => Q -- P /\ Q => Q /\ P -- (P \/ Q) /\ R => (P /\ R) \/ (Q /\ R) -- (P /\ Q) \/ R => (P \/ R) /\ (Q \/ R) -- (P => R) => (Q => R) <=> ((P \/ Q) => R) -- P \/ Q => P /\ Q
4c5035464fbc187eeb9c0985e4518aa8c93d201b
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/group_theory/coset.lean
5a9fb7b1c9091038119f307af55cc3617ce20eb7
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
8,693
lean
/- Copyright (c) 2018 Mitchell Rowett. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mitchell Rowett, Scott Morrison -/ import group_theory.subgroup data.equiv.basic data.quot open set function variable {α : Type*} @[to_additive left_add_coset] def left_coset [has_mul α] (a : α) (s : set α) : set α := (λ x, a * x) '' s @[to_additive right_add_coset] def right_coset [has_mul α] (s : set α) (a : α) : set α := (λ x, x * a) '' s local infix ` *l `:70 := left_coset local infix ` +l `:70 := left_add_coset local infix ` *r `:70 := right_coset local infix ` +r `:70 := right_add_coset section coset_mul variable [has_mul α] @[to_additive mem_left_add_coset] lemma mem_left_coset {s : set α} {x : α} (a : α) (hxS : x ∈ s) : a * x ∈ a *l s := mem_image_of_mem (λ b : α, a * b) hxS @[to_additive mem_right_add_coset] lemma mem_right_coset {s : set α} {x : α} (a : α) (hxS : x ∈ s) : x * a ∈ s *r a := mem_image_of_mem (λ b : α, b * a) hxS @[to_additive left_add_coset_equiv] def left_coset_equiv (s : set α) (a b : α) := a *l s = b *l s @[to_additive left_add_coset_equiv_rel] lemma left_coset_equiv_rel (s : set α) : equivalence (left_coset_equiv s) := mk_equivalence (left_coset_equiv s) (λ a, rfl) (λ a b, eq.symm) (λ a b c, eq.trans) end coset_mul section coset_semigroup variable [semigroup α] @[simp] lemma left_coset_assoc (s : set α) (a b : α) : a *l (b *l s) = (a * b) *l s := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] attribute [to_additive left_add_coset_assoc] left_coset_assoc @[simp] lemma right_coset_assoc (s : set α) (a b : α) : s *r a *r b = s *r (a * b) := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] attribute [to_additive right_add_coset_assoc] right_coset_assoc @[to_additive left_add_coset_right_add_coset] lemma left_coset_right_coset (s : set α) (a b : α) : a *l s *r b = a *l (s *r b) := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] end coset_semigroup section coset_monoid variables [monoid α] (s : set α) @[simp] lemma one_left_coset : 1 *l s = s := set.ext $ by simp [left_coset] attribute [to_additive zero_left_add_coset] one_left_coset @[simp] lemma right_coset_one : s *r 1 = s := set.ext $ by simp [right_coset] attribute [to_additive right_add_coset_zero] right_coset_one end coset_monoid section coset_submonoid open is_submonoid variables [monoid α] (s : set α) [is_submonoid s] @[to_additive mem_own_left_add_coset] lemma mem_own_left_coset (a : α) : a ∈ a *l s := suffices a * 1 ∈ a *l s, by simpa, mem_left_coset a (one_mem s) @[to_additive mem_own_right_add_coset] lemma mem_own_right_coset (a : α) : a ∈ s *r a := suffices 1 * a ∈ s *r a, by simpa, mem_right_coset a (one_mem s) @[to_additive mem_left_add_coset_left_add_coset] lemma mem_left_coset_left_coset {a : α} (ha : a *l s = s) : a ∈ s := by rw [←ha]; exact mem_own_left_coset s a @[to_additive mem_right_add_coset_right_add_coset] lemma mem_right_coset_right_coset {a : α} (ha : s *r a = s) : a ∈ s := by rw [←ha]; exact mem_own_right_coset s a end coset_submonoid section coset_group variables [group α] {s : set α} {x : α} @[to_additive mem_left_add_coset_iff] lemma mem_left_coset_iff (a : α) : x ∈ a *l s ↔ a⁻¹ * x ∈ s := iff.intro (assume ⟨b, hb, eq⟩, by simp [eq.symm, hb]) (assume h, ⟨a⁻¹ * x, h, by simp⟩) @[to_additive mem_right_add_coset_iff] lemma mem_right_coset_iff (a : α) : x ∈ s *r a ↔ x * a⁻¹ ∈ s := iff.intro (assume ⟨b, hb, eq⟩, by simp [eq.symm, hb]) (assume h, ⟨x * a⁻¹, h, by simp⟩) end coset_group section coset_subgroup open is_submonoid open is_subgroup variables [group α] (s : set α) [is_subgroup s] @[to_additive left_add_coset_mem_left_add_coset] lemma left_coset_mem_left_coset {a : α} (ha : a ∈ s) : a *l s = s := set.ext $ by simp [mem_left_coset_iff, mul_mem_cancel_right s (inv_mem ha)] @[to_additive right_add_coset_mem_right_add_coset] lemma right_coset_mem_right_coset {a : α} (ha : a ∈ s) : s *r a = s := set.ext $ assume b, by simp [mem_right_coset_iff, mul_mem_cancel_left s (inv_mem ha)] @[to_additive normal_of_eq_add_cosets] theorem normal_of_eq_cosets [normal_subgroup s] (g : α) : g *l s = s *r g := set.ext $ assume a, by simp [mem_left_coset_iff, mem_right_coset_iff]; rw [mem_norm_comm_iff] @[to_additive eq_add_cosets_of_normal] theorem eq_cosets_of_normal (h : ∀ g, g *l s = s *r g) : normal_subgroup s := ⟨assume a ha g, show g * a * g⁻¹ ∈ s, by rw [← mem_right_coset_iff, ← h]; exact mem_left_coset g ha⟩ @[to_additive normal_iff_eq_add_cosets] theorem normal_iff_eq_cosets : normal_subgroup s ↔ ∀ g, g *l s = s *r g := ⟨@normal_of_eq_cosets _ _ s _, eq_cosets_of_normal s⟩ end coset_subgroup run_cmd to_additive.map_namespace `quotient_group `quotient_add_group namespace quotient_group @[to_additive] def left_rel [group α] (s : set α) [is_subgroup s] : setoid α := ⟨λ x y, x⁻¹ * y ∈ s, assume x, by simp [is_submonoid.one_mem], assume x y hxy, have (x⁻¹ * y)⁻¹ ∈ s, from is_subgroup.inv_mem hxy, by simpa using this, assume x y z hxy hyz, have x⁻¹ * y * (y⁻¹ * z) ∈ s, from is_submonoid.mul_mem hxy hyz, by simpa [mul_assoc] using this⟩ /-- `quotient s` is the quotient type representing the left cosets of `s`. If `s` is a normal subgroup, `quotient s` is a group -/ @[to_additive] def quotient [group α] (s : set α) [is_subgroup s] : Type* := quotient (left_rel s) variables [group α] {s : set α} [is_subgroup s] @[to_additive] def mk (a : α) : quotient s := quotient.mk' a @[elab_as_eliminator, to_additive] lemma induction_on {C : quotient s → Prop} (x : quotient s) (H : ∀ z, C (quotient_group.mk z)) : C x := quotient.induction_on' x H @[to_additive] instance : has_coe α (quotient s) := ⟨mk⟩ @[elab_as_eliminator, to_additive] lemma induction_on' {C : quotient s → Prop} (x : quotient s) (H : ∀ z : α, C z) : C x := quotient.induction_on' x H @[to_additive] instance [group α] (s : set α) [is_subgroup s] : inhabited (quotient s) := ⟨((1 : α) : quotient s)⟩ @[to_additive quotient_add_group.eq] protected lemma eq {a b : α} : (a : quotient s) = b ↔ a⁻¹ * b ∈ s := quotient.eq' @[to_additive] lemma eq_class_eq_left_coset [group α] (s : set α) [is_subgroup s] (g : α) : {x : α | (x : quotient s) = g} = left_coset g s := set.ext $ λ z, by rw [mem_left_coset_iff, set.mem_set_of_eq, eq_comm, quotient_group.eq] end quotient_group namespace is_subgroup open quotient_group variables [group α] {s : set α} @[to_additive] def left_coset_equiv_subgroup (g : α) : left_coset g s ≃ s := ⟨λ x, ⟨g⁻¹ * x.1, (mem_left_coset_iff _).1 x.2⟩, λ x, ⟨g * x.1, x.1, x.2, rfl⟩, λ ⟨x, hx⟩, subtype.eq $ by simp, λ ⟨g, hg⟩, subtype.eq $ by simp⟩ @[to_additive] noncomputable def group_equiv_quotient_times_subgroup (hs : is_subgroup s) : α ≃ quotient s × s := calc α ≃ Σ L : quotient s, {x : α // (x : quotient s)= L} : equiv.equiv_fib quotient_group.mk ... ≃ Σ L : quotient s, left_coset (quotient.out' L) s : equiv.sigma_congr_right (λ L, begin rw ← eq_class_eq_left_coset, show {x // quotient.mk' x = L} ≃ {x : α // quotient.mk' x = quotient.mk' _}, simp [-quotient.eq'] end) ... ≃ Σ L : quotient s, s : equiv.sigma_congr_right (λ L, left_coset_equiv_subgroup _) ... ≃ quotient s × s : equiv.sigma_equiv_prod _ _ end is_subgroup namespace quotient_group variables [group α] noncomputable def preimage_mk_equiv_subgroup_times_set (s : set α) [is_subgroup s] (t : set (quotient s)) : quotient_group.mk ⁻¹' t ≃ s × t := have h : ∀ {x : quotient s} {a : α}, x ∈ t → a ∈ s → (quotient.mk' (quotient.out' x * a) : quotient s) = quotient.mk' (quotient.out' x) := λ x a hx ha, quotient.sound' (show (quotient.out' x * a)⁻¹ * quotient.out' x ∈ s, from (is_subgroup.inv_mem_iff _).1 $ by rwa [mul_inv_rev, inv_inv, ← mul_assoc, inv_mul_self, one_mul]), { to_fun := λ ⟨a, ha⟩, ⟨⟨(quotient.out' (quotient.mk' a))⁻¹ * a, @quotient.exact' _ (left_rel s) _ _ $ (quotient.out_eq' _)⟩, ⟨quotient.mk' a, ha⟩⟩, inv_fun := λ ⟨⟨a, ha⟩, ⟨x, hx⟩⟩, ⟨quotient.out' x * a, show quotient.mk' _ ∈ t, by simp [h hx ha, hx]⟩, left_inv := λ ⟨a, ha⟩, subtype.eq $ show _ * _ = a, by simp, right_inv := λ ⟨⟨a, ha⟩, ⟨x, hx⟩⟩, show (_, _) = _, by simp [h hx ha] } end quotient_group
a45adb7b92f39ed6bf02167de23d9b2eda602b26
8b9f17008684d796c8022dab552e42f0cb6fb347
/tests/lean/run/reverts_tac.lean
9b3e0a34ab7af471acf6b3ac7909a01a8698e73b
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
552
lean
import logic theorem tst {a b c : Prop} : a → b → c → a ∧ b := begin intros [Ha, Hb, Hc], reverts [Hb, Ha], intros [Hb2, Ha2], apply (and.intro Ha2 Hb2), end theorem foo1 {A : Type} (a b c : A) (P : A → Prop) : P a → a = b → P b := begin intros [Hp, Heq], reverts [Heq, Hp], intro Heq, apply (eq.rec_on Heq), intro Pa, apply Pa end theorem foo2 {A : Type} (a b c : A) (P : A → Prop) : P a → a = b → P b := begin intros [Hp, Heq], apply (eq.rec_on Heq Hp) end print definition foo1 print definition foo2
e54c0b1b5cd0f2450245fc5a817bd60436297965
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/run/class3.lean
ac647a855d36cec58d9216f53738447dcfecc1db
[ "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
217
lean
open tactic section variable {A : Type} variable {B : Type} variable Ha : inhabited A variable Hb : inhabited B include Ha Hb theorem tst : inhabited (Prop × A × B) := by apply_instance end print tst
ae14f50a84d128bd7ecbad321ac829496a827b26
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/buffer/basic.lean
7ae8a6654b64e83c7dc1a6116ca412d5e9bc2e81
[ "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
1,974
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon Traversable instance for buffers. -/ import data.buffer import data.array.lemmas import control.traversable.instances namespace buffer open function variables {α : Type*} {xs : list α} instance : inhabited (buffer α) := ⟨nil⟩ @[ext] lemma ext : ∀ {b₁ b₂ : buffer α}, to_list b₁ = to_list b₂ → b₁ = b₂ | ⟨n₁, a₁⟩ ⟨n₂, a₂⟩ h := begin simp [to_list, to_array] at h, have e : n₁ = n₂ := by rw [←array.to_list_length a₁, ←array.to_list_length a₂, h], subst e, have h : a₁ == a₂.to_list.to_array := h ▸ a₁.to_list_to_array.symm, rw eq_of_heq (h.trans a₂.to_list_to_array) end instance (α) [decidable_eq α] : decidable_eq (buffer α) := by tactic.mk_dec_eq_instance @[simp] lemma to_list_append_list {b : buffer α} : to_list (append_list b xs) = to_list b ++ xs := by induction xs generalizing b; simp! [*]; cases b; simp! [to_list,to_array] @[simp] lemma append_list_mk_buffer : append_list mk_buffer xs = array.to_buffer (list.to_array xs) := by ext x : 1; simp [array.to_buffer,to_list,to_list_append_list]; induction xs; [refl,skip]; simp [to_array]; refl /-- The natural equivalence between lists and buffers, using `list.to_buffer` and `buffer.to_list`. -/ def list_equiv_buffer (α : Type*) : list α ≃ buffer α := begin refine { to_fun := list.to_buffer, inv_fun := buffer.to_list, .. }; simp [left_inverse,function.right_inverse], { intro x, induction x, refl, simp [list.to_buffer,append_list], rw ← x_ih, refl }, { intro x, cases x, simp [to_list,to_array,list.to_buffer], congr, simp, refl, apply array.to_list_to_array } end instance : traversable buffer := equiv.traversable list_equiv_buffer instance : is_lawful_traversable buffer := equiv.is_lawful_traversable list_equiv_buffer end buffer
4f1c86cb247de1cb9dc51b7ce4fe7381cb1f1aad
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/finset/pi.lean
cb86fab2dba10607ded8af0e8da042a77a488420
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
4,585
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.finset.basic import Mathlib.data.multiset.pi import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # The cartesian product of finsets -/ namespace finset /-! ### pi -/ /-- The empty dependent product function, defined on the empty set. The assumption `a ∈ ∅` is never satisfied. -/ def pi.empty {α : Type u_1} (β : α → Type u_2) (a : α) (h : a ∈ ∅) : β a := multiset.pi.empty β a h /-- Given a finset `s` of `α` and for all `a : α` a finset `t a` of `δ a`, then one can define the finset `s.pi t` of all functions defined on elements of `s` taking values in `t a` for `a ∈ s`. Note that the elements of `s.pi t` are only partially defined, on `s`. -/ def pi {α : Type u_1} {δ : α → Type u_2} [DecidableEq α] (s : finset α) (t : (a : α) → finset (δ a)) : finset ((a : α) → a ∈ s → δ a) := mk (multiset.pi (val s) fun (a : α) => val (t a)) sorry @[simp] theorem pi_val {α : Type u_1} {δ : α → Type u_2} [DecidableEq α] (s : finset α) (t : (a : α) → finset (δ a)) : val (pi s t) = multiset.pi (val s) fun (a : α) => val (t a) := rfl @[simp] theorem mem_pi {α : Type u_1} {δ : α → Type u_2} [DecidableEq α] {s : finset α} {t : (a : α) → finset (δ a)} {f : (a : α) → a ∈ s → δ a} : f ∈ pi s t ↔ ∀ (a : α) (h : a ∈ s), f a h ∈ t a := multiset.mem_pi (val s) (fun (a : α) => (fun (a : α) => val (t a)) a) f /-- Given a function `f` defined on a finset `s`, define a new function on the finset `s ∪ {a}`, equal to `f` on `s` and sending `a` to a given value `b`. This function is denoted `s.pi.cons a b f`. If `a` already belongs to `s`, the new function takes the value `b` at `a` anyway. -/ def pi.cons {α : Type u_1} {δ : α → Type u_2} [DecidableEq α] (s : finset α) (a : α) (b : δ a) (f : (a : α) → a ∈ s → δ a) (a' : α) (h : a' ∈ insert a s) : δ a' := multiset.pi.cons (val s) a b f a' sorry @[simp] theorem pi.cons_same {α : Type u_1} {δ : α → Type u_2} [DecidableEq α] (s : finset α) (a : α) (b : δ a) (f : (a : α) → a ∈ s → δ a) (h : a ∈ insert a s) : pi.cons s a b f a h = b := multiset.pi.cons_same (pi.cons._proof_1 s a a h) theorem pi.cons_ne {α : Type u_1} {δ : α → Type u_2} [DecidableEq α] {s : finset α} {a : α} {a' : α} {b : δ a} {f : (a : α) → a ∈ s → δ a} {h : a' ∈ insert a s} (ha : a ≠ a') : pi.cons s a b f a' h = f a' (or.resolve_left (iff.mp mem_insert h) (ne.symm ha)) := multiset.pi.cons_ne (pi.cons._proof_1 s a a' h) (ne.symm ha) theorem pi_cons_injective {α : Type u_1} {δ : α → Type u_2} [DecidableEq α] {a : α} {b : δ a} {s : finset α} (hs : ¬a ∈ s) : function.injective (pi.cons s a b) := sorry @[simp] theorem pi_empty {α : Type u_1} {δ : α → Type u_2} [DecidableEq α] {t : (a : α) → finset (δ a)} : pi ∅ t = singleton (pi.empty δ) := rfl @[simp] theorem pi_insert {α : Type u_1} {δ : α → Type u_2} [DecidableEq α] [(a : α) → DecidableEq (δ a)] {s : finset α} {t : (a : α) → finset (δ a)} {a : α} (ha : ¬a ∈ s) : pi (insert a s) t = finset.bUnion (t a) fun (b : δ a) => image (pi.cons s a b) (pi s t) := sorry theorem pi_singletons {α : Type u_1} [DecidableEq α] {β : Type u_2} (s : finset α) (f : α → β) : (pi s fun (a : α) => singleton (f a)) = singleton fun (a : α) (_x : a ∈ s) => f a := sorry theorem pi_const_singleton {α : Type u_1} [DecidableEq α] {β : Type u_2} (s : finset α) (i : β) : (pi s fun (_x : α) => singleton i) = singleton fun (_x : α) (_x : _x ∈ s) => i := pi_singletons s fun (_x : α) => i theorem pi_subset {α : Type u_1} {δ : α → Type u_2} [DecidableEq α] {s : finset α} (t₁ : (a : α) → finset (δ a)) (t₂ : (a : α) → finset (δ a)) (h : ∀ (a : α), a ∈ s → t₁ a ⊆ t₂ a) : pi s t₁ ⊆ pi s t₂ := fun (g : (a : α) → a ∈ s → δ a) (hg : g ∈ pi s t₁) => iff.mpr mem_pi fun (a : α) (ha : a ∈ s) => h a ha (iff.mp mem_pi hg a ha) theorem pi_disjoint_of_disjoint {α : Type u_1} [DecidableEq α] {δ : α → Type u_2} [(a : α) → DecidableEq (δ a)] {s : finset α} [DecidableEq ((a : α) → a ∈ s → δ a)] (t₁ : (a : α) → finset (δ a)) (t₂ : (a : α) → finset (δ a)) {a : α} (ha : a ∈ s) (h : disjoint (t₁ a) (t₂ a)) : disjoint (pi s t₁) (pi s t₂) := sorry
36a791153b1ea1804db0314677e2230a623d4111
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/field_theory/polynomial_galois_group.lean
47bb202fbf0aa8e7203501f78c3bc5ba9e1448c7
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,603
lean
/- Copyright (c) 2020 Thomas Browning, Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning, Patrick Lutz -/ import field_theory.galois /-! # Galois Groups of Polynomials In this file we introduce the Galois group of a polynomial, defined as the automorphism group of the splitting field. ## Main definitions - `gal p`: the Galois group of a polynomial p. - `restrict p E`: the restriction homomorphism `(E ≃ₐ[F] E) → gal p`. - `gal_action p E`: the action of `gal p` on the roots of `p` in `E`. ## Main results - `restrict_smul`: `restrict p E` is compatible with `gal_action p E`. - `gal_action_hom_injective`: the action of `gal p` on the roots of `p` in `E` is faithful. - `restrict_prod_inj`: `gal (p * q)` embeds as a subgroup of `gal p × gal q`. -/ noncomputable theory open_locale classical open finite_dimensional namespace polynomial variables {F : Type*} [field F] (p q : polynomial F) (E : Type*) [field E] [algebra F E] /-- The Galois group of a polynomial -/ @[derive [has_coe_to_fun, group, fintype]] def gal := p.splitting_field ≃ₐ[F] p.splitting_field namespace gal @[ext] lemma ext {σ τ : p.gal} (h : ∀ x ∈ p.root_set p.splitting_field, σ x = τ x) : σ = τ := begin refine alg_equiv.ext (λ x, (alg_hom.mem_equalizer σ.to_alg_hom τ.to_alg_hom x).mp ((set_like.ext_iff.mp _ x).mpr algebra.mem_top)), rwa [eq_top_iff, ←splitting_field.adjoin_roots, algebra.adjoin_le_iff], end instance [h : fact (p.splits (ring_hom.id F))] : unique p.gal := { default := 1, uniq := λ f, alg_equiv.ext (λ x, by { obtain ⟨y, rfl⟩ := algebra.mem_bot.mp ((set_like.ext_iff.mp ((is_splitting_field.splits_iff _ p).mp h.1) x).mp algebra.mem_top), rw [alg_equiv.commutes, alg_equiv.commutes] }) } /-- If `p` splits in `F` then the `p.gal` is trivial. -/ def unique_gal_of_splits (h : p.splits (ring_hom.id F)) : unique p.gal := { default := 1, uniq := λ f, alg_equiv.ext (λ x, by { obtain ⟨y, rfl⟩ := algebra.mem_bot.mp ((set_like.ext_iff.mp ((is_splitting_field.splits_iff _ p).mp h) x).mp algebra.mem_top), rw [alg_equiv.commutes, alg_equiv.commutes] }) } instance unique_gal_zero : unique (0 : polynomial F).gal := unique_gal_of_splits _ (splits_zero _) instance unique_gal_one : unique (1 : polynomial F).gal := unique_gal_of_splits _ (splits_one _) instance unique_gal_C (x : F) : unique (C x).gal := unique_gal_of_splits _ (splits_C _ _) instance unique_gal_X : unique (X : polynomial F).gal := unique_gal_of_splits _ (splits_X _) instance unique_gal_X_sub_C (x : F) : unique (X - C x).gal := unique_gal_of_splits _ (splits_X_sub_C _) instance unique_gal_X_pow (n : ℕ) : unique (X ^ n : polynomial F).gal := unique_gal_of_splits _ (splits_X_pow _ _) instance [h : fact (p.splits (algebra_map F E))] : algebra p.splitting_field E := (is_splitting_field.lift p.splitting_field p h.1).to_ring_hom.to_algebra instance [h : fact (p.splits (algebra_map F E))] : is_scalar_tower F p.splitting_field E := is_scalar_tower.of_algebra_map_eq (λ x, ((is_splitting_field.lift p.splitting_field p h.1).commutes x).symm) /-- The restriction homomorphism -/ def restrict [fact (p.splits (algebra_map F E))] : (E ≃ₐ[F] E) →* p.gal := alg_equiv.restrict_normal_hom p.splitting_field lemma restrict_surjective [fact (p.splits (algebra_map F E))] [normal F E] : function.surjective (restrict p E) := alg_equiv.restrict_normal_hom_surjective E section roots_action /-- The function from `roots p p.splitting_field` to `roots p E` -/ def map_roots [fact (p.splits (algebra_map F E))] : root_set p p.splitting_field → root_set p E := λ x, ⟨is_scalar_tower.to_alg_hom F p.splitting_field E x, begin have key := subtype.mem x, by_cases p = 0, { simp only [h, root_set_zero] at key, exact false.rec _ key }, { rw [mem_root_set h, aeval_alg_hom_apply, (mem_root_set h).mp key, alg_hom.map_zero] } end⟩ lemma map_roots_bijective [h : fact (p.splits (algebra_map F E))] : function.bijective (map_roots p E) := begin split, { exact λ _ _ h, subtype.ext (ring_hom.injective _ (subtype.ext_iff.mp h)) }, { intro y, have key := roots_map (is_scalar_tower.to_alg_hom F p.splitting_field E : p.splitting_field →+* E) ((splits_id_iff_splits _).mpr (is_splitting_field.splits p.splitting_field p)), rw [map_map, alg_hom.comp_algebra_map] at key, have hy := subtype.mem y, simp only [root_set, finset.mem_coe, multiset.mem_to_finset, key, multiset.mem_map] at hy, rcases hy with ⟨x, hx1, hx2⟩, exact ⟨⟨x, multiset.mem_to_finset.mpr hx1⟩, subtype.ext hx2⟩ } end /-- The bijection between `root_set p p.splitting_field` and `root_set p E` -/ def roots_equiv_roots [fact (p.splits (algebra_map F E))] : (root_set p p.splitting_field) ≃ (root_set p E) := equiv.of_bijective (map_roots p E) (map_roots_bijective p E) instance gal_action_aux : mul_action p.gal (root_set p p.splitting_field) := { smul := λ ϕ x, ⟨ϕ x, begin have key := subtype.mem x, --simp only [root_set, finset.mem_coe, multiset.mem_to_finset] at *, by_cases p = 0, { simp only [h, root_set_zero] at key, exact false.rec _ key }, { rw mem_root_set h, change aeval (ϕ.to_alg_hom x) p = 0, rw [aeval_alg_hom_apply, (mem_root_set h).mp key, alg_hom.map_zero] } end⟩, one_smul := λ _, by { ext, refl }, mul_smul := λ _ _ _, by { ext, refl } } instance gal_action [fact (p.splits (algebra_map F E))] : mul_action p.gal (root_set p E) := { smul := λ ϕ x, roots_equiv_roots p E (ϕ • ((roots_equiv_roots p E).symm x)), one_smul := λ _, by simp only [equiv.apply_symm_apply, one_smul], mul_smul := λ _ _ _, by simp only [equiv.apply_symm_apply, equiv.symm_apply_apply, mul_smul] } variables {p E} @[simp] lemma restrict_smul [fact (p.splits (algebra_map F E))] (ϕ : E ≃ₐ[F] E) (x : root_set p E) : ↑((restrict p E ϕ) • x) = ϕ x := begin let ψ := alg_equiv.of_injective_field (is_scalar_tower.to_alg_hom F p.splitting_field E), change ↑(ψ (ψ.symm _)) = ϕ x, rw alg_equiv.apply_symm_apply ψ, change ϕ (roots_equiv_roots p E ((roots_equiv_roots p E).symm x)) = ϕ x, rw equiv.apply_symm_apply (roots_equiv_roots p E), end variables (p E) /-- `gal_action` as a permutation representation -/ def gal_action_hom [fact (p.splits (algebra_map F E))] : p.gal →* equiv.perm (root_set p E) := { to_fun := λ ϕ, equiv.mk (λ x, ϕ • x) (λ x, ϕ⁻¹ • x) (λ x, inv_smul_smul ϕ x) (λ x, smul_inv_smul ϕ x), map_one' := by { ext1 x, exact mul_action.one_smul x }, map_mul' := λ x y, by { ext1 z, exact mul_action.mul_smul x y z } } lemma gal_action_hom_injective [fact (p.splits (algebra_map F E))] : function.injective (gal_action_hom p E) := begin rw monoid_hom.injective_iff, intros ϕ hϕ, let equalizer := alg_hom.equalizer ϕ.to_alg_hom (alg_hom.id F p.splitting_field), suffices : equalizer = ⊤, { exact alg_equiv.ext (λ x, (set_like.ext_iff.mp this x).mpr algebra.mem_top) }, rw [eq_top_iff, ←splitting_field.adjoin_roots, algebra.adjoin_le_iff], intros x hx, have key := equiv.perm.ext_iff.mp hϕ (roots_equiv_roots p E ⟨x, hx⟩), change roots_equiv_roots p E (ϕ • (roots_equiv_roots p E).symm (roots_equiv_roots p E ⟨x, hx⟩)) = roots_equiv_roots p E ⟨x, hx⟩ at key, rw equiv.symm_apply_apply at key, exact subtype.ext_iff.mp (equiv.injective (roots_equiv_roots p E) key), end end roots_action variables {p q} /-- The restriction homomorphism between Galois groups -/ def restrict_dvd (hpq : p ∣ q) : q.gal →* p.gal := if hq : q = 0 then 1 else @restrict F _ p _ _ _ ⟨splits_of_splits_of_dvd (algebra_map F q.splitting_field) hq (splitting_field.splits q) hpq⟩ lemma restrict_dvd_surjective (hpq : p ∣ q) (hq : q ≠ 0) : function.surjective (restrict_dvd hpq) := by simp only [restrict_dvd, dif_neg hq, restrict_surjective] variables (p q) /-- The Galois group of a product embeds into the product of the Galois groups -/ def restrict_prod : (p * q).gal →* p.gal × q.gal := monoid_hom.prod (restrict_dvd (dvd_mul_right p q)) (restrict_dvd (dvd_mul_left q p)) lemma restrict_prod_injective : function.injective (restrict_prod p q) := begin by_cases hpq : (p * q) = 0, { haveI : unique (p * q).gal := by { rw hpq, apply_instance }, exact λ f g h, eq.trans (unique.eq_default f) (unique.eq_default g).symm }, intros f g hfg, dsimp only [restrict_prod, restrict_dvd] at hfg, simp only [dif_neg hpq, monoid_hom.prod_apply, prod.mk.inj_iff] at hfg, suffices : alg_hom.equalizer f.to_alg_hom g.to_alg_hom = ⊤, { exact alg_equiv.ext (λ x, (set_like.ext_iff.mp this x).mpr algebra.mem_top) }, rw [eq_top_iff, ←splitting_field.adjoin_roots, algebra.adjoin_le_iff], intros x hx, rw [map_mul, polynomial.roots_mul] at hx, cases multiset.mem_add.mp (multiset.mem_to_finset.mp hx) with h h, { change f x = g x, haveI : fact (p.splits (algebra_map F (p * q).splitting_field)) := ⟨splits_of_splits_of_dvd _ hpq (splitting_field.splits (p * q)) (dvd_mul_right p q)⟩, have key : x = algebra_map (p.splitting_field) (p * q).splitting_field ((roots_equiv_roots p _).inv_fun ⟨x, multiset.mem_to_finset.mpr h⟩) := subtype.ext_iff.mp (equiv.apply_symm_apply (roots_equiv_roots p _) ⟨x, _⟩).symm, rw [key, ←alg_equiv.restrict_normal_commutes, ←alg_equiv.restrict_normal_commutes], exact congr_arg _ (alg_equiv.ext_iff.mp hfg.1 _) }, { change f x = g x, haveI : fact (q.splits (algebra_map F (p * q).splitting_field)) := ⟨splits_of_splits_of_dvd _ hpq (splitting_field.splits (p * q)) (dvd_mul_left q p)⟩, have key : x = algebra_map (q.splitting_field) (p * q).splitting_field ((roots_equiv_roots q _).inv_fun ⟨x, multiset.mem_to_finset.mpr h⟩) := subtype.ext_iff.mp (equiv.apply_symm_apply (roots_equiv_roots q _) ⟨x, _⟩).symm, rw [key, ←alg_equiv.restrict_normal_commutes, ←alg_equiv.restrict_normal_commutes], exact congr_arg _ (alg_equiv.ext_iff.mp hfg.2 _) }, { rwa [ne.def, mul_eq_zero, map_eq_zero, map_eq_zero, ←mul_eq_zero] } end lemma mul_splits_in_splitting_field_of_mul {p₁ q₁ p₂ q₂ : polynomial F} (hq₁ : q₁ ≠ 0) (hq₂ : q₂ ≠ 0) (h₁ : p₁.splits (algebra_map F q₁.splitting_field)) (h₂ : p₂.splits (algebra_map F q₂.splitting_field)) : (p₁ * p₂).splits (algebra_map F (q₁ * q₂).splitting_field) := begin apply splits_mul, { rw ← (splitting_field.lift q₁ (splits_of_splits_of_dvd _ (mul_ne_zero hq₁ hq₂) (splitting_field.splits _) (dvd_mul_right q₁ q₂))).comp_algebra_map, exact splits_comp_of_splits _ _ h₁, }, { rw ← (splitting_field.lift q₂ (splits_of_splits_of_dvd _ (mul_ne_zero hq₁ hq₂) (splitting_field.splits _) (dvd_mul_left q₂ q₁))).comp_algebra_map, exact splits_comp_of_splits _ _ h₂, }, end lemma splits_in_splitting_field_of_comp (hq : q.nat_degree ≠ 0) : p.splits (algebra_map F (p.comp q).splitting_field) := begin let P : polynomial F → Prop := λ r, r.splits (algebra_map F (r.comp q).splitting_field), have key1 : ∀ {r : polynomial F}, irreducible r → P r, { intros r hr, by_cases hr' : nat_degree r = 0, { exact splits_of_nat_degree_le_one _ (le_trans (le_of_eq hr') zero_le_one) }, obtain ⟨x, hx⟩ := exists_root_of_splits _ (splitting_field.splits (r.comp q)) (λ h, hr' ((mul_eq_zero.mp (nat_degree_comp.symm.trans (nat_degree_eq_of_degree_eq_some h))).resolve_right hq)), rw [←aeval_def, aeval_comp] at hx, have h_normal : normal F (r.comp q).splitting_field := splitting_field.normal (r.comp q), have qx_int := normal.is_integral h_normal (aeval x q), exact splits_of_splits_of_dvd _ (minpoly.ne_zero qx_int) (normal.splits h_normal _) (dvd_symm_of_irreducible (minpoly.irreducible qx_int) hr (minpoly.dvd F _ hx)) }, have key2 : ∀ {p₁ p₂ : polynomial F}, P p₁ → P p₂ → P (p₁ * p₂), { intros p₁ p₂ hp₁ hp₂, by_cases h₁ : p₁.comp q = 0, { cases comp_eq_zero_iff.mp h₁ with h h, { rw [h, zero_mul], exact splits_zero _ }, { exact false.rec _ (hq (by rw [h.2, nat_degree_C])) } }, by_cases h₂ : p₂.comp q = 0, { cases comp_eq_zero_iff.mp h₂ with h h, { rw [h, mul_zero], exact splits_zero _ }, { exact false.rec _ (hq (by rw [h.2, nat_degree_C])) } }, have key := mul_splits_in_splitting_field_of_mul h₁ h₂ hp₁ hp₂, rwa ← mul_comp at key }, exact wf_dvd_monoid.induction_on_irreducible p (splits_zero _) (λ _, splits_of_is_unit _) (λ _ _ _ h, key2 (key1 h)), end /-- The restriction homomorphism from the Galois group of a homomorphism -/ def restrict_comp (hq : q.nat_degree ≠ 0) : (p.comp q).gal →* p.gal := @restrict F _ p _ _ _ ⟨splits_in_splitting_field_of_comp p q hq⟩ lemma restrict_comp_surjective (hq : q.nat_degree ≠ 0) : function.surjective (restrict_comp p q hq) := by simp only [restrict_comp, restrict_surjective] variables {p q} lemma card_of_separable (hp : p.separable) : fintype.card p.gal = findim F p.splitting_field := begin haveI : is_galois F p.splitting_field := is_galois.of_separable_splitting_field hp, exact is_galois.card_aut_eq_findim F p.splitting_field, end lemma prime_degree_dvd_card [char_zero F] (p_irr : irreducible p) (p_deg : p.nat_degree.prime) : p.nat_degree ∣ fintype.card p.gal := begin rw gal.card_of_separable p_irr.separable, have hp : p.degree ≠ 0 := λ h, nat.prime.ne_zero p_deg (nat_degree_eq_zero_iff_degree_le_zero.mpr (le_of_eq h)), let α : p.splitting_field := root_of_splits (algebra_map F p.splitting_field) (splitting_field.splits p) hp, have hα : is_integral F α := (is_algebraic_iff_is_integral F).mp (algebra.is_algebraic_of_finite α), use finite_dimensional.findim F⟮α⟯ p.splitting_field, suffices : (minpoly F α).nat_degree = p.nat_degree, { rw [←finite_dimensional.findim_mul_findim F F⟮α⟯ p.splitting_field, intermediate_field.adjoin.findim hα, this] }, suffices : minpoly F α ∣ p, { have key := dvd_symm_of_irreducible (minpoly.irreducible hα) p_irr this, apply le_antisymm, { exact nat_degree_le_of_dvd this p_irr.ne_zero }, { exact nat_degree_le_of_dvd key (minpoly.ne_zero hα) } }, apply minpoly.dvd F α, rw [aeval_def, map_root_of_splits _ (splitting_field.splits p) hp], end end gal end polynomial
38a88c31e85ce222acf2d571df55003184066f71
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/number_theory/class_number/admissible_card_pow_degree.lean
c511c307293d36a55f369b3cf31805871f175d83
[ "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
13,912
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 data.polynomial.degree.card_pow_degree import field_theory.finite.basic import number_theory.class_number.admissible_absolute_value /-! # Admissible absolute values on polynomials This file defines an admissible absolute value `polynomial.card_pow_degree_is_admissible` which we use to show the class number of the ring of integers of a function field is finite. ## Main results * `polynomial.card_pow_degree_is_admissible` shows `card_pow_degree`, mapping `p : polynomial 𝔽_q` to `q ^ degree p`, is admissible -/ namespace polynomial open absolute_value real variables {Fq : Type*} [field Fq] [fintype Fq] /-- If `A` is a family of enough low-degree polynomials over a finite field, there is a pair of equal elements in `A`. -/ lemma exists_eq_polynomial {d : ℕ} {m : ℕ} (hm : fintype.card Fq ^ d ≤ m) (b : polynomial Fq) (hb : nat_degree b ≤ d) (A : fin m.succ → polynomial Fq) (hA : ∀ i, degree (A i) < degree b) : ∃ i₀ i₁, i₀ ≠ i₁ ∧ A i₁ = A i₀ := begin -- Since there are > q^d elements of A, and only q^d choices for the highest `d` coefficients, -- there must be two elements of A with the same coefficients at -- `0`, ... `degree b - 1` ≤ `d - 1`. -- In other words, the following map is not injective: set f : fin m.succ → (fin d → Fq) := λ i j, (A i).coeff j, have : fintype.card (fin d → Fq) < fintype.card (fin m.succ), { simpa using lt_of_le_of_lt hm (nat.lt_succ_self m) }, -- Therefore, the differences have all coefficients higher than `deg b - d` equal. obtain ⟨i₀, i₁, i_ne, i_eq⟩ := fintype.exists_ne_map_eq_of_card_lt f this, use [i₀, i₁, i_ne], ext j, -- The coefficients higher than `deg b` are the same because they are equal to 0. by_cases hbj : degree b ≤ j, { rw [coeff_eq_zero_of_degree_lt (lt_of_lt_of_le (hA _) hbj), coeff_eq_zero_of_degree_lt (lt_of_lt_of_le (hA _) hbj)] }, -- So we only need to look for the coefficients between `0` and `deg b`. rw not_le at hbj, apply congr_fun i_eq.symm ⟨j, _⟩, exact lt_of_lt_of_le (coe_lt_degree.mp hbj) hb end /-- If `A` is a family of enough low-degree polynomials over a finite field, there is a pair of elements in `A` (with different indices but not necessarily distinct), such that their difference has small degree. -/ lemma exists_approx_polynomial_aux {d : ℕ} {m : ℕ} (hm : fintype.card Fq ^ d ≤ m) (b : polynomial Fq) (A : fin m.succ → polynomial Fq) (hA : ∀ i, degree (A i) < degree b) : ∃ i₀ i₁, i₀ ≠ i₁ ∧ degree (A i₁ - A i₀) < ↑(nat_degree b - d) := begin have hb : b ≠ 0, { rintro rfl, specialize hA 0, rw degree_zero at hA, exact not_lt_of_le bot_le hA }, -- Since there are > q^d elements of A, and only q^d choices for the highest `d` coefficients, -- there must be two elements of A with the same coefficients at -- `degree b - 1`, ... `degree b - d`. -- In other words, the following map is not injective: set f : fin m.succ → (fin d → Fq) := λ i j, (A i).coeff (nat_degree b - j.succ), have : fintype.card (fin d → Fq) < fintype.card (fin m.succ), { simpa using lt_of_le_of_lt hm (nat.lt_succ_self m) }, -- Therefore, the differences have all coefficients higher than `deg b - d` equal. obtain ⟨i₀, i₁, i_ne, i_eq⟩ := fintype.exists_ne_map_eq_of_card_lt f this, use [i₀, i₁, i_ne], refine (degree_lt_iff_coeff_zero _ _).mpr (λ j hj, _), -- The coefficients higher than `deg b` are the same because they are equal to 0. by_cases hbj : degree b ≤ j, { refine coeff_eq_zero_of_degree_lt (lt_of_lt_of_le _ hbj), exact lt_of_le_of_lt (degree_sub_le _ _) (max_lt (hA _) (hA _)) }, -- So we only need to look for the coefficients between `deg b - d` and `deg b`. rw [coeff_sub, sub_eq_zero], rw [not_le, degree_eq_nat_degree hb, with_bot.coe_lt_coe] at hbj, have hj : nat_degree b - j.succ < d, { by_cases hd : nat_degree b < d, { exact lt_of_le_of_lt (nat.sub_le_self _ _) hd }, { rw not_lt at hd, have := lt_of_le_of_lt hj (nat.lt_succ_self j), rwa [nat.sub_lt_iff hd hbj] at this } }, have : j = b.nat_degree - (nat_degree b - j.succ).succ, { rw [← nat.succ_sub hbj, nat.succ_sub_succ, nat.sub_sub_self hbj.le] }, convert congr_fun i_eq.symm ⟨nat_degree b - j.succ, hj⟩ end /-- If `A` is a family of enough low-degree polynomials over a finite field, there is a pair of elements in `A` (with different indices but not necessarily distinct), such that the difference of their remainders is close together. -/ lemma exists_approx_polynomial {b : polynomial Fq} (hb : b ≠ 0) {ε : ℝ} (hε : 0 < ε) (A : fin (fintype.card Fq ^ nat_ceil (- log ε / log (fintype.card Fq))).succ → polynomial Fq) : ∃ i₀ i₁, i₀ ≠ i₁ ∧ (card_pow_degree (A i₁ % b - A i₀ % b) : ℝ) < card_pow_degree b • ε := begin have hbε : 0 < card_pow_degree b • ε, { rw [algebra.smul_def, ring_hom.eq_int_cast], exact mul_pos (int.cast_pos.mpr (absolute_value.pos _ hb)) hε }, have one_lt_q : 1 < fintype.card Fq := fintype.one_lt_card, have one_lt_q' : (1 : ℝ) < fintype.card Fq, { assumption_mod_cast }, have q_pos : 0 < fintype.card Fq, { linarith }, have q_pos' : (0 : ℝ) < fintype.card Fq, { assumption_mod_cast }, -- If `b` is already small enough, then the remainders are equal and we are done. by_cases le_b : b.nat_degree ≤ nat_ceil (-log ε / log ↑(fintype.card Fq)), { obtain ⟨i₀, i₁, i_ne, mod_eq⟩ := exists_eq_polynomial (le_refl _) b le_b (λ i, A i % b) (λ i, euclidean_domain.mod_lt (A i) hb), refine ⟨i₀, i₁, i_ne, _⟩, simp only at mod_eq, rwa [mod_eq, sub_self, absolute_value.map_zero, int.cast_zero] }, -- Otherwise, it suffices to choose two elements whose difference is of small enough degree. rw not_le at le_b, obtain ⟨i₀, i₁, i_ne, deg_lt⟩ := exists_approx_polynomial_aux (le_refl _) b (λ i, A i % b) (λ i, euclidean_domain.mod_lt (A i) hb), simp only at deg_lt, use [i₀, i₁, i_ne], -- Again, if the remainders are equal we are done. by_cases h : A i₁ % b = A i₀ % b, { rwa [h, sub_self, absolute_value.map_zero, int.cast_zero] }, have h' : A i₁ % b - A i₀ % b ≠ 0 := mt sub_eq_zero.mp h, -- If the remainders are not equal, we'll show their difference is of small degree. -- In particular, we'll show the degree is less than the following: suffices : (nat_degree (A i₁ % b - A i₀ % b) : ℝ) < b.nat_degree + log ε / log (fintype.card Fq), { rwa [← real.log_lt_log_iff (int.cast_pos.mpr (card_pow_degree.pos h')) hbε, card_pow_degree_nonzero _ h', card_pow_degree_nonzero _ hb, algebra.smul_def, ring_hom.eq_int_cast, int.cast_pow, int.cast_coe_nat, int.cast_pow, int.cast_coe_nat, log_mul (pow_ne_zero _ q_pos'.ne') hε.ne', ← rpow_nat_cast, ← rpow_nat_cast, log_rpow q_pos', log_rpow q_pos', ← lt_div_iff (log_pos one_lt_q'), add_div, mul_div_cancel _ (log_pos one_lt_q').ne'] }, -- And that result follows from manipulating the result from `exists_approx_polynomial_aux` -- to turn the `- ceil (- stuff)` into `+ stuff`. refine lt_of_lt_of_le (nat.cast_lt.mpr (with_bot.coe_lt_coe.mp _)) _, swap, { convert deg_lt, rw degree_eq_nat_degree h' }, rw [← sub_neg_eq_add, neg_div], refine le_trans _ (sub_le_sub_left (le_nat_ceil _) (b.nat_degree : ℝ)), rw ← neg_div, exact le_of_eq (nat.cast_sub le_b.le) end /-- If `x` is close to `y` and `y` is close to `z`, then `x` and `z` are at least as close. -/ lemma card_pow_degree_anti_archimedean {x y z : polynomial Fq} {a : ℤ} (hxy : card_pow_degree (x - y) < a) (hyz : card_pow_degree (y - z) < a) : card_pow_degree (x - z) < a := begin have ha : 0 < a := lt_of_le_of_lt (absolute_value.nonneg _ _) hxy, by_cases hxy' : x = y, { rwa hxy' }, by_cases hyz' : y = z, { rwa ← hyz' }, by_cases hxz' : x = z, { rwa [hxz', sub_self, absolute_value.map_zero] }, rw [← ne.def, ← sub_ne_zero] at hxy' hyz' hxz', refine lt_of_le_of_lt _ (max_lt hxy hyz), rw [card_pow_degree_nonzero _ hxz', card_pow_degree_nonzero _ hxy', card_pow_degree_nonzero _ hyz'], have : (1 : ℤ) ≤ fintype.card Fq, { exact_mod_cast (@fintype.one_lt_card Fq _ _).le }, simp only [int.cast_pow, int.cast_coe_nat, le_max_iff], refine or.imp (pow_le_pow this) (pow_le_pow this) _, rw [nat_degree_le_iff_degree_le, nat_degree_le_iff_degree_le, ← le_max_iff, ← degree_eq_nat_degree hxy', ← degree_eq_nat_degree hyz'], convert degree_add_le (x - y) (y - z) using 2, exact (sub_add_sub_cancel _ _ _).symm end /-- A slightly stronger version of `exists_partition` on which we perform induction on `n`: for all `ε > 0`, we can partition the remainders of any family of polynomials `A` into equivalence classes, where the equivalence(!) relation is "closer than `ε`". -/ lemma exists_partition_polynomial_aux (n : ℕ) {ε : ℝ} (hε : 0 < ε) {b : polynomial Fq} (hb : b ≠ 0) (A : fin n → polynomial Fq) : ∃ (t : fin n → fin (fintype.card Fq ^ nat_ceil (-log ε / log ↑(fintype.card Fq)))), ∀ (i₀ i₁ : fin n), t i₀ = t i₁ ↔ (card_pow_degree (A i₁ % b - A i₀ % b) : ℝ) < card_pow_degree b • ε := begin have hbε : 0 < card_pow_degree b • ε, { rw [algebra.smul_def, ring_hom.eq_int_cast], exact mul_pos (int.cast_pos.mpr (absolute_value.pos _ hb)) hε }, -- We go by induction on the size `A`. induction n with n ih, { refine ⟨fin_zero_elim, fin_zero_elim⟩ }, -- Show `anti_archimedean` also holds for real distances. have anti_archim' : ∀ {i j k} {ε : ℝ}, (card_pow_degree (A i % b - A j % b) : ℝ) < ε → (card_pow_degree (A j % b - A k % b) : ℝ) < ε → (card_pow_degree (A i % b - A k % b) : ℝ) < ε, { intros i j k ε, rw [← lt_ceil, ← lt_ceil, ← lt_ceil], exact card_pow_degree_anti_archimedean }, obtain ⟨t', ht'⟩ := ih (fin.tail A), -- We got rid of `A 0`, so determine the index `j` of the partition we'll re-add it to. suffices : ∃ j, ∀ i, t' i = j ↔ (card_pow_degree (A 0 % b - A i.succ % b) : ℝ) < card_pow_degree b • ε, { obtain ⟨j, hj⟩ := this, refine ⟨fin.cons j t', λ i₀ i₁, _⟩, refine fin.cases _ (λ i₀, _) i₀; refine fin.cases _ (λ i₁, _) i₁, { simpa using hbε }, { rw [fin.cons_succ, fin.cons_zero, eq_comm, absolute_value.map_sub], exact hj i₁ }, { rw [fin.cons_succ, fin.cons_zero], exact hj i₀ }, { rw [fin.cons_succ, fin.cons_succ], exact ht' i₀ i₁ } }, -- `exists_approx_polynomial` guarantees that we can insert `A 0` into some partition `j`, -- but not that `j` is uniquely defined (which is needed to keep the induction going). obtain ⟨j, hj⟩ : ∃ j, ∀ (i : fin n), t' i = j → (card_pow_degree (A 0 % b - A i.succ % b) : ℝ) < card_pow_degree b • ε, { by_contra this, push_neg at this, obtain ⟨j₀, j₁, j_ne, approx⟩ := exists_approx_polynomial hb hε (fin.cons (A 0) (λ j, A (fin.succ (classical.some (this j))))), revert j_ne approx, refine fin.cases _ (λ j₀, _) j₀; refine fin.cases (λ j_ne approx, _) (λ j₁ j_ne approx, _) j₁, { exact absurd rfl j_ne }, { rw [fin.cons_succ, fin.cons_zero, ← not_le, absolute_value.map_sub] at approx, have := (classical.some_spec (this j₁)).2, contradiction }, { rw [fin.cons_succ, fin.cons_zero, ← not_le] at approx, have := (classical.some_spec (this j₀)).2, contradiction }, { rw [fin.cons_succ, fin.cons_succ] at approx, rw [ne.def, fin.succ_inj] at j_ne, have : j₀ = j₁ := (classical.some_spec (this j₀)).1.symm.trans (((ht' (classical.some (this j₀)) (classical.some (this j₁))).mpr approx).trans (classical.some_spec (this j₁)).1), contradiction } }, -- However, if one of those partitions `j` is inhabited by some `i`, then this `j` works. by_cases exists_nonempty_j : ∃ j, (∃ i, t' i = j) ∧ ∀ i, t' i = j → (card_pow_degree (A 0 % b - A i.succ % b) : ℝ) < card_pow_degree b • ε, { obtain ⟨j, ⟨i, hi⟩, hj⟩ := exists_nonempty_j, refine ⟨j, λ i', ⟨hj i', λ hi', trans ((ht' _ _).mpr _) hi⟩⟩, apply anti_archim' _ hi', rw absolute_value.map_sub, exact hj _ hi }, -- And otherwise, we can just take any `j`, since those are empty. refine ⟨j, λ i, ⟨hj i, λ hi, _⟩⟩, have := exists_nonempty_j ⟨t' i, ⟨i, rfl⟩, λ i' hi', anti_archim' hi ((ht' _ _).mp hi')⟩, contradiction end /-- For all `ε > 0`, we can partition the remainders of any family of polynomials `A` into classes, where all remainders in a class are close together. -/ lemma exists_partition_polynomial (n : ℕ) {ε : ℝ} (hε : 0 < ε) {b : polynomial Fq} (hb : b ≠ 0) (A : fin n → polynomial Fq) : ∃ (t : fin n → fin (fintype.card Fq ^ nat_ceil (-log ε / log ↑(fintype.card Fq)))), ∀ (i₀ i₁ : fin n), t i₀ = t i₁ → (card_pow_degree (A i₁ % b - A i₀ % b) : ℝ) < card_pow_degree b • ε := begin obtain ⟨t, ht⟩ := exists_partition_polynomial_aux n hε hb A, exact ⟨t, λ i₀ i₁ hi, (ht i₀ i₁).mp hi⟩ end /-- `λ p, fintype.card Fq ^ degree p` is an admissible absolute value. We set `q ^ degree 0 = 0`. -/ noncomputable def card_pow_degree_is_admissible : is_admissible (card_pow_degree : absolute_value (polynomial Fq) ℤ) := { card := λ ε, fintype.card Fq ^ (nat_ceil (- log ε / log (fintype.card Fq))), exists_partition' := λ n ε hε b hb, exists_partition_polynomial n hε hb, .. @card_pow_degree_is_euclidean Fq _ _ } end polynomial
18258cda61c65459cf037379fc06cdc989d537ee
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/trace.lean
1eff304e71d4815f86dff83a342efa209f6137bb
[ "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
11,317
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, Patrick Massot, Casper Putz, Anne Baanen, Antoine Labelle -/ import linear_algebra.matrix.to_lin import linear_algebra.matrix.trace import linear_algebra.contraction import linear_algebra.tensor_product_basis import linear_algebra.free_module.strong_rank_condition import linear_algebra.free_module.finite.rank import linear_algebra.projection /-! # Trace of a linear map This file defines the trace of a linear map. See also `linear_algebra/matrix/trace.lean` for the trace of a matrix. ## Tags linear_map, trace, diagonal -/ noncomputable theory universes u v w namespace linear_map open_locale big_operators open_locale matrix open finite_dimensional open_locale tensor_product section variables (R : Type u) [comm_semiring R] {M : Type v} [add_comm_monoid M] [module R M] variables {ι : Type w} [decidable_eq ι] [fintype ι] variables {κ : Type*} [decidable_eq κ] [fintype κ] variables (b : basis ι R M) (c : basis κ R M) /-- The trace of an endomorphism given a basis. -/ def trace_aux : (M →ₗ[R] M) →ₗ[R] R := (matrix.trace_linear_map ι R R) ∘ₗ ↑(linear_map.to_matrix b b) -- Can't be `simp` because it would cause a loop. lemma trace_aux_def (b : basis ι R M) (f : M →ₗ[R] M) : trace_aux R b f = matrix.trace (linear_map.to_matrix b b f) := rfl theorem trace_aux_eq : trace_aux R b = trace_aux R c := linear_map.ext $ λ f, calc matrix.trace (linear_map.to_matrix b b f) = matrix.trace (linear_map.to_matrix b b ((linear_map.id.comp f).comp linear_map.id)) : by rw [linear_map.id_comp, linear_map.comp_id] ... = matrix.trace (linear_map.to_matrix c b linear_map.id ⬝ linear_map.to_matrix c c f ⬝ linear_map.to_matrix b c linear_map.id) : by rw [linear_map.to_matrix_comp _ c, linear_map.to_matrix_comp _ c] ... = matrix.trace (linear_map.to_matrix c c f ⬝ linear_map.to_matrix b c linear_map.id ⬝ linear_map.to_matrix c b linear_map.id) : by rw [matrix.mul_assoc, matrix.trace_mul_comm] ... = matrix.trace (linear_map.to_matrix c c ((f.comp linear_map.id).comp linear_map.id)) : by rw [linear_map.to_matrix_comp _ b, linear_map.to_matrix_comp _ c] ... = matrix.trace (linear_map.to_matrix c c f) : by rw [linear_map.comp_id, linear_map.comp_id] open_locale classical variables (R) (M) /-- Trace of an endomorphism independent of basis. -/ def trace : (M →ₗ[R] M) →ₗ[R] R := if H : ∃ (s : finset M), nonempty (basis s R M) then trace_aux R H.some_spec.some else 0 variables (R) {M} /-- Auxiliary lemma for `trace_eq_matrix_trace`. -/ theorem trace_eq_matrix_trace_of_finset {s : finset M} (b : basis s R M) (f : M →ₗ[R] M) : trace R M f = matrix.trace (linear_map.to_matrix b b f) := have ∃ (s : finset M), nonempty (basis s R M), from ⟨s, ⟨b⟩⟩, by { rw [trace, dif_pos this, ← trace_aux_def], congr' 1, apply trace_aux_eq } theorem trace_eq_matrix_trace (f : M →ₗ[R] M) : trace R M f = matrix.trace (linear_map.to_matrix b b f) := by rw [trace_eq_matrix_trace_of_finset R b.reindex_finset_range, ← trace_aux_def, ← trace_aux_def, trace_aux_eq R b] theorem trace_mul_comm (f g : M →ₗ[R] M) : trace R M (f * g) = trace R M (g * f) := if H : ∃ (s : finset M), nonempty (basis s R M) then let ⟨s, ⟨b⟩⟩ := H in by { simp_rw [trace_eq_matrix_trace R b, linear_map.to_matrix_mul], apply matrix.trace_mul_comm } else by rw [trace, dif_neg H, linear_map.zero_apply, linear_map.zero_apply] /-- The trace of an endomorphism is invariant under conjugation -/ @[simp] theorem trace_conj (g : M →ₗ[R] M) (f : (M →ₗ[R] M)ˣ) : trace R M (↑f * g * ↑f⁻¹) = trace R M g := by { rw trace_mul_comm, simp } end section variables {R : Type*} [comm_ring R] {M : Type*} [add_comm_group M] [module R M] variables (N : Type*) [add_comm_group N] [module R N] variables {ι : Type*} /-- The trace of a linear map correspond to the contraction pairing under the isomorphism `End(M) ≃ M* ⊗ M`-/ lemma trace_eq_contract_of_basis [finite ι] (b : basis ι R M) : (linear_map.trace R M) ∘ₗ (dual_tensor_hom R M M) = contract_left R M := begin classical, casesI nonempty_fintype ι, apply basis.ext (basis.tensor_product (basis.dual_basis b) b), rintros ⟨i, j⟩, simp only [function.comp_app, basis.tensor_product_apply, basis.coe_dual_basis, coe_comp], rw [trace_eq_matrix_trace R b, to_matrix_dual_tensor_hom], by_cases hij : i = j, { rw [hij], simp }, rw matrix.std_basis_matrix.trace_zero j i (1:R) hij, simp [finsupp.single_eq_pi_single, hij], end /-- The trace of a linear map correspond to the contraction pairing under the isomorphism `End(M) ≃ M* ⊗ M`-/ lemma trace_eq_contract_of_basis' [fintype ι] [decidable_eq ι] (b : basis ι R M) : (linear_map.trace R M) = (contract_left R M) ∘ₗ (dual_tensor_hom_equiv_of_basis b).symm.to_linear_map := by simp [linear_equiv.eq_comp_to_linear_map_symm, trace_eq_contract_of_basis b] variables (R M N) variables [module.free R M] [module.finite R M] [module.free R N] [module.finite R N] [nontrivial R] /-- When `M` is finite free, the trace of a linear map correspond to the contraction pairing under the isomorphism `End(M) ≃ M* ⊗ M`-/ @[simp] theorem trace_eq_contract : (linear_map.trace R M) ∘ₗ (dual_tensor_hom R M M) = contract_left R M := trace_eq_contract_of_basis (module.free.choose_basis R M) @[simp] theorem trace_eq_contract_apply (x : module.dual R M ⊗[R] M) : (linear_map.trace R M) ((dual_tensor_hom R M M) x) = contract_left R M x := by rw [←comp_apply, trace_eq_contract] open_locale classical /-- When `M` is finite free, the trace of a linear map correspond to the contraction pairing under the isomorphism `End(M) ≃ M* ⊗ M`-/ theorem trace_eq_contract' : (linear_map.trace R M) = (contract_left R M) ∘ₗ (dual_tensor_hom_equiv R M M).symm.to_linear_map := trace_eq_contract_of_basis' (module.free.choose_basis R M) /-- The trace of the identity endomorphism is the dimension of the free module -/ @[simp] theorem trace_one : trace R M 1 = (finrank R M : R) := begin have b := module.free.choose_basis R M, rw [trace_eq_matrix_trace R b, to_matrix_one, module.free.finrank_eq_card_choose_basis_index], simp, end /-- The trace of the identity endomorphism is the dimension of the free module -/ @[simp] theorem trace_id : trace R M id = (finrank R M : R) := by rw [←one_eq_id, trace_one] @[simp] theorem trace_transpose : trace R (module.dual R M) ∘ₗ module.dual.transpose = trace R M := begin let e := dual_tensor_hom_equiv R M M, have h : function.surjective e.to_linear_map := e.surjective, refine (cancel_right h).1 _, ext f m, simp [e], end theorem trace_prod_map : trace R (M × N) ∘ₗ prod_map_linear R M N M N R = (coprod id id : R × R →ₗ[R] R) ∘ₗ prod_map (trace R M) (trace R N) := begin let e := ((dual_tensor_hom_equiv R M M).prod (dual_tensor_hom_equiv R N N)), have h : function.surjective e.to_linear_map := e.surjective, refine (cancel_right h).1 _, ext, { simp only [dual_tensor_hom_equiv, tensor_product.algebra_tensor_module.curry_apply, to_fun_eq_coe, tensor_product.curry_apply, coe_restrict_scalars_eq_coe, coe_comp, linear_equiv.coe_to_linear_map, coe_inl, function.comp_app, linear_equiv.prod_apply, dual_tensor_hom_equiv_of_basis_apply, map_zero, prod_map_apply, coprod_apply, id_coe, id.def, add_zero, prod_map_linear_apply, dual_tensor_hom_prod_map_zero, trace_eq_contract_apply, contract_left_apply, fst_apply] }, { simp only [dual_tensor_hom_equiv, tensor_product.algebra_tensor_module.curry_apply, to_fun_eq_coe, tensor_product.curry_apply, coe_restrict_scalars_eq_coe, coe_comp, linear_equiv.coe_to_linear_map, coe_inr, function.comp_app, linear_equiv.prod_apply, dual_tensor_hom_equiv_of_basis_apply, map_zero, prod_map_apply, coprod_apply, id_coe, id.def, zero_add, prod_map_linear_apply, zero_prod_map_dual_tensor_hom, trace_eq_contract_apply, contract_left_apply, snd_apply], }, end variables {R M N} theorem trace_prod_map' (f : M →ₗ[R] M) (g : N →ₗ[R] N) : trace R (M × N) (prod_map f g) = trace R M f + trace R N g := begin have h := ext_iff.1 (trace_prod_map R M N) (f, g), simp only [coe_comp, function.comp_app, prod_map_apply, coprod_apply, id_coe, id.def, prod_map_linear_apply] at h, exact h, end variables (R M N) open tensor_product function theorem trace_tensor_product : compr₂ (map_bilinear R M N M N) (trace R (M ⊗ N)) = compl₁₂ (lsmul R R : R →ₗ[R] R →ₗ[R] R) (trace R M) (trace R N) := begin apply (compl₁₂_inj (show surjective (dual_tensor_hom R M M), from (dual_tensor_hom_equiv R M M).surjective) (show surjective (dual_tensor_hom R N N), from (dual_tensor_hom_equiv R N N).surjective)).1, ext f m g n, simp only [algebra_tensor_module.curry_apply, to_fun_eq_coe, tensor_product.curry_apply, coe_restrict_scalars_eq_coe, compl₁₂_apply, compr₂_apply, map_bilinear_apply, trace_eq_contract_apply, contract_left_apply, lsmul_apply, algebra.id.smul_eq_mul, map_dual_tensor_hom, dual_distrib_apply], end theorem trace_comp_comm : compr₂ (llcomp R M N M) (trace R M) = compr₂ (llcomp R N M N).flip (trace R N) := begin apply (compl₁₂_inj (show surjective (dual_tensor_hom R N M), from (dual_tensor_hom_equiv R N M).surjective) (show surjective (dual_tensor_hom R M N), from (dual_tensor_hom_equiv R M N).surjective)).1, ext g m f n, simp only [tensor_product.algebra_tensor_module.curry_apply, to_fun_eq_coe, linear_equiv.coe_to_linear_map, tensor_product.curry_apply, coe_restrict_scalars_eq_coe, compl₁₂_apply, compr₂_apply, flip_apply, llcomp_apply', comp_dual_tensor_hom, map_smul, trace_eq_contract_apply, contract_left_apply, smul_eq_mul, mul_comm], end variables {R M N} @[simp] theorem trace_transpose' (f : M →ₗ[R] M) : trace R _ (module.dual.transpose f) = trace R M f := by { rw [←comp_apply, trace_transpose] } theorem trace_tensor_product' (f : M →ₗ[R] M) (g : N →ₗ[R] N) : trace R (M ⊗ N) (map f g) = trace R M f * trace R N g := begin have h := ext_iff.1 (ext_iff.1 (trace_tensor_product R M N) f) g, simp only [compr₂_apply, map_bilinear_apply, compl₁₂_apply, lsmul_apply, algebra.id.smul_eq_mul] at h, exact h, end theorem trace_comp_comm' (f : M →ₗ[R] N) (g : N →ₗ[R] M) : trace R M (g ∘ₗ f) = trace R N (f ∘ₗ g) := begin have h := ext_iff.1 (ext_iff.1 (trace_comp_comm R M N) g) f, simp only [llcomp_apply', compr₂_apply, flip_apply] at h, exact h, end @[simp] theorem trace_conj' (f : M →ₗ[R] M) (e : M ≃ₗ[R] N) : trace R N (e.conj f) = trace R M f := by rw [e.conj_apply, trace_comp_comm', ←comp_assoc, linear_equiv.comp_coe, linear_equiv.self_trans_symm, linear_equiv.refl_to_linear_map, id_comp] theorem is_proj.trace {p : submodule R M} {f : M →ₗ[R] M} (h : is_proj p f) [module.free R p] [module.finite R p] [module.free R f.ker] [module.finite R f.ker] : trace R M f = (finrank R p : R) := by rw [h.eq_conj_prod_map, trace_conj', trace_prod_map', trace_id, map_zero, add_zero] end end linear_map
5d8dfd56b9e6e5505c7e359a1a7fcc7a3834f3b1
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/PPRoundtrip.lean
7677bc324c2f47bd59a2fdc11e8d1ea6dbb06496
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,794
lean
import Lean new_frontend open Lean open Lean.Elab open Lean.Elab.Term open Lean.Elab.Command open Lean.Format open Lean.Meta def checkM (stx : TermElabM Syntax) (optionsPerPos : OptionsPerPos := {}) : TermElabM Unit := do let opts ← getOptions; let stx ← stx; let e ← elabTermAndSynthesize stx none <* throwErrorIfErrors; let stx' ← liftMetaM $ delab Name.anonymous [] e optionsPerPos; let stx' ← liftCoreM $ PrettyPrinter.parenthesizeTerm stx'; let f' ← liftCoreM $ PrettyPrinter.formatTerm stx'; IO.println $ f'.pretty opts; let env ← getEnv; (match Parser.runParserCategory env `term (toString f') "<input>" with | Except.error e => throwErrorAt stx e | Except.ok stx'' => do let e' ← elabTermAndSynthesize stx'' none <* throwErrorIfErrors; unlessM (isDefEq e e') $ throwErrorAt stx (fmt "failed to round-trip" ++ line ++ fmt e ++ line ++ fmt e')) -- set_option trace.PrettyPrinter.parenthesize true set_option format.width 20 -- #eval checkM `(?m) -- fails round-trip #eval checkM `(Sort) #eval checkM `(Type) #eval checkM `(Type 0) #eval checkM `(Type 1) -- can't add a new universe variable inside a term... #eval checkM `(Type _) #eval checkM `(Type (_ + 2)) #eval checkM `(Nat) #eval checkM `(List Nat) #eval checkM `(id Nat) #eval checkM `(id (id (id Nat))) section set_option pp.explicit true #eval checkM `(List Nat) #eval checkM `(id Nat) end section set_option pp.universes true #eval checkM `(List Nat) #eval checkM `(id Nat) #eval checkM `(Sum Nat Nat) end #eval checkM `(id (id Nat)) (Std.RBMap.empty.insert 4 $ KVMap.empty.insert `pp.explicit true) -- specify the expected type of `a` in a way that is not erased by the delaborator def typeAs.{u} (α : Type u) (a : α) := () #eval checkM `(fun (a : Nat) => a) #eval checkM `(fun (a b : Nat) => a) #eval checkM `(fun (a : Nat) (b : Bool) => a) #eval checkM `(fun {a b : Nat} => a) -- implicit lambdas work as long as the expected type is preserved #eval checkM `(typeAs ({α : Type} → (a : α) → α) fun a => a) section set_option pp.explicit true #eval checkM `(fun {α : Type} [HasToString α] (a : α) => toString a) end #eval checkM `((α : Type) → α) #eval checkM `((α β : Type) → α) -- group #eval checkM `((α β : Type) → Type) -- don't group #eval checkM `((α : Type) → (a : α) → α) #eval checkM `((α : Type) → (a : α) → a = a) #eval checkM `({α : Type} → α) #eval checkM `({α : Type} → [HasToString α] → α) -- TODO: hide `ofNat` #eval checkM `(0) #eval checkM `(1) #eval checkM `(42) #eval checkM `("hi") set_option pp.structure_instance_type true in #eval checkM `({ type := Nat, val := 0 : PointedType }) #eval checkM `((1,2,3)) #eval checkM `((1,2).fst) #eval checkM `(1 < 2 || true) #eval checkM `(id (fun a => a) 0)
933895496bf9e911d2f222782eceee87f6c838d2
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/algebra/uniform_group.lean
2fbf010bd4a04bd511f6eb9c1d7392512fc4b069
[ "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
25,870
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl -/ import topology.uniform_space.uniform_convergence import topology.uniform_space.uniform_embedding import topology.uniform_space.complete_separated import topology.algebra.group import tactic.abel /-! # Uniform structure on topological groups This file defines uniform groups and its additive counterpart. These typeclasses should be preferred over using `[topological_space α] [topological_group α]` since every topological group naturally induces a uniform structure. ## Main declarations * `uniform_group` and `uniform_add_group`: Multiplicative and additive uniform groups, that i.e., groups with uniformly continuous `(*)` and `(⁻¹)` / `(+)` and `(-)`. ## Main results * `topological_add_group.to_uniform_space` and `topological_add_group_is_uniform` can be used to construct a canonical uniformity for a topological add group. * extension of ℤ-bilinear maps to complete groups (useful for ring completions) -/ noncomputable theory open_locale classical uniformity topological_space filter pointwise section uniform_group open filter set variables {α : Type*} {β : Type*} /-- A uniform group is a group in which multiplication and inversion are uniformly continuous. -/ class uniform_group (α : Type*) [uniform_space α] [group α] : Prop := (uniform_continuous_div : uniform_continuous (λp:α×α, p.1 / p.2)) /-- A uniform additive group is an additive group in which addition and negation are uniformly continuous.-/ class uniform_add_group (α : Type*) [uniform_space α] [add_group α] : Prop := (uniform_continuous_sub : uniform_continuous (λp:α×α, p.1 - p.2)) attribute [to_additive] uniform_group @[to_additive] theorem uniform_group.mk' {α} [uniform_space α] [group α] (h₁ : uniform_continuous (λp:α×α, p.1 * p.2)) (h₂ : uniform_continuous (λp:α, p⁻¹)) : uniform_group α := ⟨by simpa only [div_eq_mul_inv] using h₁.comp (uniform_continuous_fst.prod_mk (h₂.comp uniform_continuous_snd))⟩ variables [uniform_space α] [group α] [uniform_group α] @[to_additive] lemma uniform_continuous_div : uniform_continuous (λp:α×α, p.1 / p.2) := uniform_group.uniform_continuous_div @[to_additive] lemma uniform_continuous.div [uniform_space β] {f : β → α} {g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λx, f x / g x) := uniform_continuous_div.comp (hf.prod_mk hg) @[to_additive] lemma uniform_continuous.inv [uniform_space β] {f : β → α} (hf : uniform_continuous f) : uniform_continuous (λx, (f x)⁻¹) := have uniform_continuous (λx, 1 / f x), from uniform_continuous_const.div hf, by simp * at * @[to_additive] lemma uniform_continuous_inv : uniform_continuous (λx:α, x⁻¹) := uniform_continuous_id.inv @[to_additive] lemma uniform_continuous.mul [uniform_space β] {f : β → α} {g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λx, f x * g x) := have uniform_continuous (λx, f x / (g x)⁻¹), from hf.div hg.inv, by simp * at * @[to_additive] lemma uniform_continuous_mul : uniform_continuous (λp:α×α, p.1 * p.2) := uniform_continuous_fst.mul uniform_continuous_snd @[priority 10, to_additive] instance uniform_group.to_topological_group : topological_group α := { continuous_mul := uniform_continuous_mul.continuous, continuous_inv := uniform_continuous_inv.continuous } @[to_additive] instance [uniform_space β] [group β] [uniform_group β] : uniform_group (α × β) := ⟨((uniform_continuous_fst.comp uniform_continuous_fst).div (uniform_continuous_fst.comp uniform_continuous_snd)).prod_mk ((uniform_continuous_snd.comp uniform_continuous_fst).div (uniform_continuous_snd.comp uniform_continuous_snd))⟩ @[to_additive] lemma uniformity_translate_mul (a : α) : (𝓤 α).map (λx:α×α, (x.1 * a, x.2 * a)) = 𝓤 α := le_antisymm (uniform_continuous_id.mul uniform_continuous_const) (calc 𝓤 α = ((𝓤 α).map (λx:α×α, (x.1 * a⁻¹, x.2 * a⁻¹))).map (λx:α×α, (x.1 * a, x.2 * a)) : by simp [filter.map_map, (∘)]; exact filter.map_id.symm ... ≤ (𝓤 α).map (λx:α×α, (x.1 * a, x.2 * a)) : filter.map_mono (uniform_continuous_id.mul uniform_continuous_const)) @[to_additive] lemma uniform_embedding_translate_mul (a : α) : uniform_embedding (λx:α, x * a) := { comap_uniformity := begin rw [← uniformity_translate_mul a, comap_map] {occs := occurrences.pos [1]}, rintros ⟨p₁, p₂⟩ ⟨q₁, q₂⟩, simp [prod.eq_iff_fst_eq_snd_eq] {contextual := tt} end, inj := mul_left_injective a } namespace mul_opposite @[to_additive] instance : uniform_group αᵐᵒᵖ := ⟨uniform_continuous_op.comp ((uniform_continuous_unop.comp uniform_continuous_snd).inv.mul $ uniform_continuous_unop.comp uniform_continuous_fst)⟩ end mul_opposite namespace subgroup @[to_additive] instance (S : subgroup α) : uniform_group S := ⟨uniform_continuous_comap' (uniform_continuous_div.comp $ uniform_continuous_subtype_val.prod_map uniform_continuous_subtype_val)⟩ end subgroup section variables (α) @[to_additive] lemma uniformity_eq_comap_nhds_one : 𝓤 α = comap (λx:α×α, x.2 / x.1) (𝓝 (1:α)) := begin rw [nhds_eq_comap_uniformity, filter.comap_comap], refine le_antisymm (filter.map_le_iff_le_comap.1 _) _, { assume s hs, rcases mem_uniformity_of_uniform_continuous_invariant uniform_continuous_div hs with ⟨t, ht, hts⟩, refine mem_map.2 (mem_of_superset ht _), rintros ⟨a, b⟩, simpa [subset_def] using hts a b a }, { assume s hs, rcases mem_uniformity_of_uniform_continuous_invariant uniform_continuous_mul hs with ⟨t, ht, hts⟩, refine ⟨_, ht, _⟩, rintros ⟨a, b⟩, simpa [subset_def] using hts 1 (b / a) a } end @[to_additive] lemma uniformity_eq_comap_nhds_one_swapped : 𝓤 α = comap (λx:α×α, x.1 / x.2) (𝓝 (1:α)) := by { rw [← comap_swap_uniformity, uniformity_eq_comap_nhds_one, comap_comap, (∘)], refl } open mul_opposite @[to_additive] lemma uniformity_eq_comap_inv_mul_nhds_one : 𝓤 α = comap (λx:α×α, x.1⁻¹ * x.2) (𝓝 (1:α)) := begin rw [← comap_uniformity_mul_opposite, uniformity_eq_comap_nhds_one, ← op_one, ← comap_unop_nhds, comap_comap, comap_comap], simp [(∘)] end @[to_additive] lemma uniformity_eq_comap_inv_mul_nhds_one_swapped : 𝓤 α = comap (λx:α×α, x.2⁻¹ * x.1) (𝓝 (1:α)) := by { rw [← comap_swap_uniformity, uniformity_eq_comap_inv_mul_nhds_one, comap_comap, (∘)], refl } end @[to_additive] lemma filter.has_basis.uniformity_of_nhds_one {ι} {p : ι → Prop} {U : ι → set α} (h : (𝓝 (1 : α)).has_basis p U) : (𝓤 α).has_basis p (λ i, {x : α × α | x.2 / x.1 ∈ U i}) := by { rw uniformity_eq_comap_nhds_one, exact h.comap _ } @[to_additive] lemma filter.has_basis.uniformity_of_nhds_one_inv_mul {ι} {p : ι → Prop} {U : ι → set α} (h : (𝓝 (1 : α)).has_basis p U) : (𝓤 α).has_basis p (λ i, {x : α × α | x.1⁻¹ * x.2 ∈ U i}) := by { rw uniformity_eq_comap_inv_mul_nhds_one, exact h.comap _ } @[to_additive] lemma filter.has_basis.uniformity_of_nhds_one_swapped {ι} {p : ι → Prop} {U : ι → set α} (h : (𝓝 (1 : α)).has_basis p U) : (𝓤 α).has_basis p (λ i, {x : α × α | x.1 / x.2 ∈ U i}) := by { rw uniformity_eq_comap_nhds_one_swapped, exact h.comap _ } @[to_additive] lemma filter.has_basis.uniformity_of_nhds_one_inv_mul_swapped {ι} {p : ι → Prop} {U : ι → set α} (h : (𝓝 (1 : α)).has_basis p U) : (𝓤 α).has_basis p (λ i, {x : α × α | x.2⁻¹ * x.1 ∈ U i}) := by { rw uniformity_eq_comap_inv_mul_nhds_one_swapped, exact h.comap _ } @[to_additive] lemma group_separation_rel (x y : α) : (x, y) ∈ separation_rel α ↔ x / y ∈ closure ({1} : set α) := have embedding (λa, a * (y / x)), from (uniform_embedding_translate_mul (y / x)).embedding, show (x, y) ∈ ⋂₀ (𝓤 α).sets ↔ x / y ∈ closure ({1} : set α), begin rw [this.closure_eq_preimage_closure_image, uniformity_eq_comap_nhds_one α, sInter_comap_sets], simp [mem_closure_iff_nhds, inter_singleton_nonempty, sub_eq_add_neg, add_assoc] end @[to_additive] lemma uniform_continuous_of_tendsto_one {hom : Type*} [uniform_space β] [group β] [uniform_group β] [monoid_hom_class hom α β] {f : hom} (h : tendsto f (𝓝 1) (𝓝 1)) : uniform_continuous f := begin have : ((λx:β×β, x.2 / x.1) ∘ (λx:α×α, (f x.1, f x.2))) = (λx:α×α, f (x.2 / x.1)), { simp only [map_div] }, rw [uniform_continuous, uniformity_eq_comap_nhds_one α, uniformity_eq_comap_nhds_one β, tendsto_comap_iff, this], exact tendsto.comp h tendsto_comap end @[to_additive] lemma uniform_continuous_of_continuous_at_one {hom : Type*} [uniform_space β] [group β] [uniform_group β] [monoid_hom_class hom α β] (f : hom) (hf : continuous_at f 1) : uniform_continuous f := uniform_continuous_of_tendsto_one (by simpa using hf.tendsto) @[to_additive] lemma monoid_hom.uniform_continuous_of_continuous_at_one [uniform_space β] [group β] [uniform_group β] (f : α →* β) (hf : continuous_at f 1) : uniform_continuous f := uniform_continuous_of_continuous_at_one f hf /-- A homomorphism from a uniform group to a discrete uniform group is continuous if and only if its kernel is open. -/ @[to_additive "A homomorphism from a uniform additive group to a discrete uniform additive group is continuous if and only if its kernel is open."] lemma uniform_group.uniform_continuous_iff_open_ker {hom : Type*} [uniform_space β] [discrete_topology β] [group β] [uniform_group β] [monoid_hom_class hom α β] {f : hom} : uniform_continuous f ↔ is_open ((f : α →* β).ker : set α) := begin refine ⟨λ hf, _, λ hf, _⟩, { apply (is_open_discrete ({1} : set β)).preimage (uniform_continuous.continuous hf) }, { apply uniform_continuous_of_continuous_at_one, rw [continuous_at, nhds_discrete β, map_one, tendsto_pure], exact hf.mem_nhds (map_one f) } end @[to_additive] lemma uniform_continuous_monoid_hom_of_continuous {hom : Type*} [uniform_space β] [group β] [uniform_group β] [monoid_hom_class hom α β] {f : hom} (h : continuous f) : uniform_continuous f := uniform_continuous_of_tendsto_one $ suffices tendsto f (𝓝 1) (𝓝 (f 1)), by rwa map_one at this, h.tendsto 1 @[to_additive] lemma cauchy_seq.mul {ι : Type*} [semilattice_sup ι] {u v : ι → α} (hu : cauchy_seq u) (hv : cauchy_seq v) : cauchy_seq (u * v) := uniform_continuous_mul.comp_cauchy_seq (hu.prod hv) @[to_additive] lemma cauchy_seq.mul_const {ι : Type*} [semilattice_sup ι] {u : ι → α} {x : α} (hu : cauchy_seq u) : cauchy_seq (λ n, u n * x) := (uniform_continuous_id.mul uniform_continuous_const).comp_cauchy_seq hu @[to_additive] lemma cauchy_seq.const_mul {ι : Type*} [semilattice_sup ι] {u : ι → α} {x : α} (hu : cauchy_seq u) : cauchy_seq (λ n, x * u n) := (uniform_continuous_const.mul uniform_continuous_id).comp_cauchy_seq hu @[to_additive] lemma cauchy_seq.inv {ι : Type*} [semilattice_sup ι] {u : ι → α} (h : cauchy_seq u) : cauchy_seq (u⁻¹) := uniform_continuous_inv.comp_cauchy_seq h @[to_additive] lemma totally_bounded_iff_subset_finite_Union_nhds_one {s : set α} : totally_bounded s ↔ ∀ U ∈ 𝓝 (1 : α), ∃ (t : set α), t.finite ∧ s ⊆ ⋃ y ∈ t, y • U := (𝓝 (1 : α)).basis_sets.uniformity_of_nhds_one_inv_mul_swapped.totally_bounded_iff.trans $ by simp [← preimage_smul_inv, preimage] end uniform_group section topological_comm_group open filter variables (G : Type*) [comm_group G] [topological_space G] [topological_group G] /-- The right uniformity on a topological group. -/ @[to_additive "The right uniformity on a topological group"] def topological_group.to_uniform_space : uniform_space G := { uniformity := comap (λp:G×G, p.2 / p.1) (𝓝 1), refl := by refine map_le_iff_le_comap.1 (le_trans _ (pure_le_nhds 1)); simp [set.subset_def] {contextual := tt}, symm := begin suffices : tendsto (λp:G×G, (p.2 / p.1)⁻¹) (comap (λp:G×G, p.2 / p.1) (𝓝 1)) (𝓝 1⁻¹), { simpa [tendsto_comap_iff], }, exact tendsto.comp (tendsto.inv tendsto_id) tendsto_comap end, comp := begin intros D H, rw mem_lift'_sets, { rcases H with ⟨U, U_nhds, U_sub⟩, rcases exists_nhds_one_split U_nhds with ⟨V, ⟨V_nhds, V_sum⟩⟩, existsi ((λp:G×G, p.2 / p.1) ⁻¹' V), have H : (λp:G×G, p.2 / p.1) ⁻¹' V ∈ comap (λp:G×G, p.2 / p.1) (𝓝 (1 : G)), by existsi [V, V_nhds] ; refl, existsi H, have comp_rel_sub : comp_rel ((λp:G×G, p.2 / p.1) ⁻¹' V) ((λp, p.2 / p.1) ⁻¹' V) ⊆ (λp:G×G, p.2 / p.1) ⁻¹' U, begin intros p p_comp_rel, rcases p_comp_rel with ⟨z, ⟨Hz1, Hz2⟩⟩, simpa [sub_eq_add_neg, add_comm, add_left_comm] using V_sum _ Hz1 _ Hz2 end, exact set.subset.trans comp_rel_sub U_sub }, { exact monotone_comp_rel monotone_id monotone_id } end, is_open_uniformity := begin intro S, let S' := λ x, {p : G × G | p.1 = x → p.2 ∈ S}, show is_open S ↔ ∀ (x : G), x ∈ S → S' x ∈ comap (λp:G×G, p.2 / p.1) (𝓝 (1 : G)), rw [is_open_iff_mem_nhds], refine forall₂_congr (λ a ha, _), rw [← nhds_translation_div, mem_comap, mem_comap], refine exists₂_congr (λ t ht, _), show (λ (y : G), y / a) ⁻¹' t ⊆ S ↔ (λ (p : G × G), p.snd / p.fst) ⁻¹' t ⊆ S' a, split, { rintros h ⟨x, y⟩ hx rfl, exact h hx }, { rintros h x hx, exact @h (a, x) hx rfl } end } variables {G} @[to_additive] lemma topological_group.tendsto_uniformly_iff {ι α : Type*} (F : ι → α → G) (f : α → G) (p : filter ι) : @tendsto_uniformly α G ι (topological_group.to_uniform_space G) F f p ↔ ∀ u ∈ 𝓝 (1 : G), ∀ᶠ i in p, ∀ a, F i a / f a ∈ u := ⟨λ h u hu, h _ ⟨u, hu, λ _, id⟩, λ h v ⟨u, hu, hv⟩, mem_of_superset (h u hu) (λ i hi a, hv (by exact hi a))⟩ @[to_additive] lemma topological_group.tendsto_uniformly_on_iff {ι α : Type*} (F : ι → α → G) (f : α → G) (p : filter ι) (s : set α) : @tendsto_uniformly_on α G ι (topological_group.to_uniform_space G) F f p s ↔ ∀ u ∈ 𝓝 (1 : G), ∀ᶠ i in p, ∀ a ∈ s, F i a / f a ∈ u := ⟨λ h u hu, h _ ⟨u, hu, λ _, id⟩, λ h v ⟨u, hu, hv⟩, mem_of_superset (h u hu) (λ i hi a ha, hv (by exact hi a ha))⟩ @[to_additive] lemma topological_group.tendsto_locally_uniformly_iff {ι α : Type*} [topological_space α] (F : ι → α → G) (f : α → G) (p : filter ι) : @tendsto_locally_uniformly α G ι (topological_group.to_uniform_space G) _ F f p ↔ ∀ (u ∈ 𝓝 (1 : G)) (x : α), ∃ (t ∈ 𝓝 x), ∀ᶠ i in p, ∀ a ∈ t, F i a / f a ∈ u := ⟨λ h u hu, h _ ⟨u, hu, λ _, id⟩, λ h v ⟨u, hu, hv⟩ x, exists_imp_exists (by exact λ a, exists_imp_exists (λ ha hp, mem_of_superset hp (λ i hi a ha, hv (by exact hi a ha)))) (h u hu x)⟩ @[to_additive] lemma topological_group.tendsto_locally_uniformly_on_iff {ι α : Type*} [topological_space α] (F : ι → α → G) (f : α → G) (p : filter ι) (s : set α) : @tendsto_locally_uniformly_on α G ι (topological_group.to_uniform_space G) _ F f p s ↔ ∀ (u ∈ 𝓝 (1 : G)) (x ∈ s), ∃ (t ∈ 𝓝[s] x), ∀ᶠ i in p, ∀ a ∈ t, F i a / f a ∈ u := ⟨λ h u hu, h _ ⟨u, hu, λ _, id⟩, λ h v ⟨u, hu, hv⟩ x, exists_imp_exists (by exact λ a, exists_imp_exists (λ ha hp, mem_of_superset hp (λ i hi a ha, hv (by exact hi a ha)))) ∘ h u hu x⟩ end topological_comm_group section topological_comm_group universes u v w x open filter variables (G : Type*) [comm_group G] [topological_space G] [topological_group G] section local attribute [instance] topological_group.to_uniform_space @[to_additive] lemma uniformity_eq_comap_nhds_one' : 𝓤 G = comap (λp:G×G, p.2 / p.1) (𝓝 (1 : G)) := rfl variable {G} @[to_additive] lemma topological_group_is_uniform : uniform_group G := have tendsto ((λp:(G×G), p.1 / p.2) ∘ (λp:(G×G)×(G×G), (p.1.2 / p.1.1, p.2.2 / p.2.1))) (comap (λp:(G×G)×(G×G), (p.1.2 / p.1.1, p.2.2 / p.2.1)) ((𝓝 1).prod (𝓝 1))) (𝓝 (1 / 1)) := (tendsto_fst.div' tendsto_snd).comp tendsto_comap, begin constructor, rw [uniform_continuous, uniformity_prod_eq_prod, tendsto_map'_iff, uniformity_eq_comap_nhds_one' G, tendsto_comap_iff, prod_comap_comap_eq], simpa [(∘), div_eq_mul_inv, mul_comm, mul_left_comm] using this end open set @[to_additive] lemma topological_group.t2_space_iff_one_closed : t2_space G ↔ is_closed ({1} : set G) := begin haveI : uniform_group G := topological_group_is_uniform, rw [← separated_iff_t2, separated_space_iff, ← closure_eq_iff_is_closed], split; intro h, { apply subset.antisymm, { intros x x_in, have := group_separation_rel x 1, rw div_one at this, rw [← this, h] at x_in, change x = 1 at x_in, simp [x_in] }, { exact subset_closure } }, { ext p, cases p with x y, rw [group_separation_rel x, h, mem_singleton_iff, div_eq_one], refl } end @[to_additive] lemma topological_group.t2_space_of_one_sep (H : ∀ x : G, x ≠ 1 → ∃ U ∈ nhds (1 : G), x ∉ U) : t2_space G := begin rw [topological_group.t2_space_iff_one_closed, ← is_open_compl_iff, is_open_iff_mem_nhds], intros x x_not, have : x ≠ 1, from mem_compl_singleton_iff.mp x_not, rcases H x this with ⟨U, U_in, xU⟩, rw ← nhds_one_symm G at U_in, rcases U_in with ⟨W, W_in, UW⟩, rw ← nhds_translation_mul_inv, use [W, W_in], rw subset_compl_comm, suffices : x⁻¹ ∉ W, by simpa, exact λ h, xU (UW h) end end @[to_additive] lemma uniform_group.to_uniform_space_eq {G : Type*} [u : uniform_space G] [comm_group G] [uniform_group G] : topological_group.to_uniform_space G = u := begin ext : 1, show @uniformity G (topological_group.to_uniform_space G) = 𝓤 G, rw [uniformity_eq_comap_nhds_one' G, uniformity_eq_comap_nhds_one G] end end topological_comm_group open comm_group filter set function section variables {α : Type*} {β : Type*} {hom : Type*} variables [topological_space α] [comm_group α] [topological_group α] -- β is a dense subgroup of α, inclusion is denoted by e variables [topological_space β] [comm_group β] variables [monoid_hom_class hom β α] {e : hom} (de : dense_inducing e) include de @[to_additive] lemma tendsto_div_comap_self (x₀ : α) : tendsto (λt:β×β, t.2 / t.1) (comap (λp:β×β, (e p.1, e p.2)) $ 𝓝 (x₀, x₀)) (𝓝 1) := begin have comm : (λx:α×α, x.2/x.1) ∘ (λt:β×β, (e t.1, e t.2)) = e ∘ (λt:β×β, t.2 / t.1), { ext t, change e t.2 / e t.1 = e (t.2 / t.1), rwa ← map_div e t.2 t.1 }, have lim : tendsto (λ x : α × α, x.2/x.1) (𝓝 (x₀, x₀)) (𝓝 (e 1)), { simpa using (continuous_div'.comp (@continuous_swap α α _ _)).tendsto (x₀, x₀) }, simpa using de.tendsto_comap_nhds_nhds lim comm end end namespace dense_inducing variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables {G : Type*} -- β is a dense subgroup of α, inclusion is denoted by e -- δ is a dense subgroup of γ, inclusion is denoted by f variables [topological_space α] [add_comm_group α] [topological_add_group α] variables [topological_space β] [add_comm_group β] [topological_add_group β] variables [topological_space γ] [add_comm_group γ] [topological_add_group γ] variables [topological_space δ] [add_comm_group δ] [topological_add_group δ] variables [uniform_space G] [add_comm_group G] [uniform_add_group G] [separated_space G] [complete_space G] variables {e : β →+ α} (de : dense_inducing e) variables {f : δ →+ γ} (df : dense_inducing f) variables {φ : β →+ δ →+ G} local notation `Φ` := λ p : β × δ, φ p.1 p.2 variables (hφ : continuous Φ) include de df hφ variables {W' : set G} (W'_nhd : W' ∈ 𝓝 (0 : G)) include W'_nhd private lemma extend_Z_bilin_aux (x₀ : α) (y₁ : δ) : ∃ U₂ ∈ comap e (𝓝 x₀), ∀ x x' ∈ U₂, Φ (x' - x, y₁) ∈ W' := begin let Nx := 𝓝 x₀, let ee := λ u : β × β, (e u.1, e u.2), have lim1 : tendsto (λ a : β × β, (a.2 - a.1, y₁)) (comap e Nx ×ᶠ comap e Nx) (𝓝 (0, y₁)), { have := tendsto.prod_mk (tendsto_sub_comap_self de x₀) (tendsto_const_nhds : tendsto (λ (p : β × β), y₁) (comap ee $ 𝓝 (x₀, x₀)) (𝓝 y₁)), rw [nhds_prod_eq, prod_comap_comap_eq, ←nhds_prod_eq], exact (this : _) }, have lim2 : tendsto Φ (𝓝 (0, y₁)) (𝓝 0), by simpa using hφ.tendsto (0, y₁), have lim := lim2.comp lim1, rw tendsto_prod_self_iff at lim, simp_rw ball_mem_comm, exact lim W' W'_nhd end private lemma extend_Z_bilin_key (x₀ : α) (y₀ : γ) : ∃ U ∈ comap e (𝓝 x₀), ∃ V ∈ comap f (𝓝 y₀), ∀ x x' ∈ U, ∀ y y' ∈ V, Φ (x', y') - Φ (x, y) ∈ W' := begin let Nx := 𝓝 x₀, let Ny := 𝓝 y₀, let dp := dense_inducing.prod de df, let ee := λ u : β × β, (e u.1, e u.2), let ff := λ u : δ × δ, (f u.1, f u.2), have lim_φ : filter.tendsto Φ (𝓝 (0, 0)) (𝓝 0), { simpa using hφ.tendsto (0, 0) }, have lim_φ_sub_sub : tendsto (λ (p : (β × β) × (δ × δ)), Φ (p.1.2 - p.1.1, p.2.2 - p.2.1)) ((comap ee $ 𝓝 (x₀, x₀)) ×ᶠ (comap ff $ 𝓝 (y₀, y₀))) (𝓝 0), { have lim_sub_sub : tendsto (λ (p : (β × β) × δ × δ), (p.1.2 - p.1.1, p.2.2 - p.2.1)) ((comap ee (𝓝 (x₀, x₀))) ×ᶠ (comap ff (𝓝 (y₀, y₀)))) (𝓝 0 ×ᶠ 𝓝 0), { have := filter.prod_mono (tendsto_sub_comap_self de x₀) (tendsto_sub_comap_self df y₀), rwa prod_map_map_eq at this }, rw ← nhds_prod_eq at lim_sub_sub, exact tendsto.comp lim_φ lim_sub_sub }, rcases exists_nhds_zero_quarter W'_nhd with ⟨W, W_nhd, W4⟩, have : ∃ U₁ ∈ comap e (𝓝 x₀), ∃ V₁ ∈ comap f (𝓝 y₀), ∀ x x' ∈ U₁, ∀ y y' ∈ V₁, Φ (x'-x, y'-y) ∈ W, { have := tendsto_prod_iff.1 lim_φ_sub_sub W W_nhd, repeat { rw [nhds_prod_eq, ←prod_comap_comap_eq] at this }, rcases this with ⟨U, U_in, V, V_in, H⟩, rw [mem_prod_same_iff] at U_in V_in, rcases U_in with ⟨U₁, U₁_in, HU₁⟩, rcases V_in with ⟨V₁, V₁_in, HV₁⟩, existsi [U₁, U₁_in, V₁, V₁_in], intros x x_in x' x'_in y y_in y' y'_in, exact H _ _ (HU₁ (mk_mem_prod x_in x'_in)) (HV₁ (mk_mem_prod y_in y'_in)) }, rcases this with ⟨U₁, U₁_nhd, V₁, V₁_nhd, H⟩, obtain ⟨x₁, x₁_in⟩ : U₁.nonempty := ((de.comap_nhds_ne_bot _).nonempty_of_mem U₁_nhd), obtain ⟨y₁, y₁_in⟩ : V₁.nonempty := ((df.comap_nhds_ne_bot _).nonempty_of_mem V₁_nhd), have cont_flip : continuous (λ p : δ × β, φ.flip p.1 p.2), { show continuous (Φ ∘ prod.swap), from hφ.comp continuous_swap }, rcases (extend_Z_bilin_aux de df hφ W_nhd x₀ y₁) with ⟨U₂, U₂_nhd, HU⟩, rcases (extend_Z_bilin_aux df de cont_flip W_nhd y₀ x₁) with ⟨V₂, V₂_nhd, HV⟩, existsi [U₁ ∩ U₂, inter_mem U₁_nhd U₂_nhd, V₁ ∩ V₂, inter_mem V₁_nhd V₂_nhd], rintros x ⟨xU₁, xU₂⟩ x' ⟨x'U₁, x'U₂⟩ y ⟨yV₁, yV₂⟩ y' ⟨y'V₁, y'V₂⟩, have key_formula : φ x' y' - φ x y = φ(x' - x) y₁ + φ (x' - x) (y' - y₁) + φ x₁ (y' - y) + φ (x - x₁) (y' - y), { simp, abel }, rw key_formula, have h₁ := HU x xU₂ x' x'U₂, have h₂ := H x xU₁ x' x'U₁ y₁ y₁_in y' y'V₁, have h₃ := HV y yV₂ y' y'V₂, have h₄ := H x₁ x₁_in x xU₁ y yV₁ y' y'V₁, exact W4 h₁ h₂ h₃ h₄ end omit W'_nhd open dense_inducing /-- Bourbaki GT III.6.5 Theorem I: ℤ-bilinear continuous maps from dense images into a complete Hausdorff group extend by continuity. Note: Bourbaki assumes that α and β are also complete Hausdorff, but this is not necessary. -/ theorem extend_Z_bilin : continuous (extend (de.prod df) Φ) := begin refine continuous_extend_of_cauchy _ _, rintro ⟨x₀, y₀⟩, split, { apply ne_bot.map, apply comap_ne_bot, intros U h, rcases mem_closure_iff_nhds.1 ((de.prod df).dense (x₀, y₀)) U h with ⟨x, x_in, ⟨z, z_x⟩⟩, existsi z, cc }, { suffices : map (λ (p : (β × δ) × (β × δ)), Φ p.2 - Φ p.1) (comap (λ (p : (β × δ) × β × δ), ((e p.1.1, f p.1.2), (e p.2.1, f p.2.2))) (𝓝 (x₀, y₀) ×ᶠ 𝓝 (x₀, y₀))) ≤ 𝓝 0, by rwa [uniformity_eq_comap_nhds_zero G, prod_map_map_eq, ←map_le_iff_le_comap, filter.map_map, prod_comap_comap_eq], intros W' W'_nhd, have key := extend_Z_bilin_key de df hφ W'_nhd x₀ y₀, rcases key with ⟨U, U_nhd, V, V_nhd, h⟩, rw mem_comap at U_nhd, rcases U_nhd with ⟨U', U'_nhd, U'_sub⟩, rw mem_comap at V_nhd, rcases V_nhd with ⟨V', V'_nhd, V'_sub⟩, rw [mem_map, mem_comap, nhds_prod_eq], existsi (U' ×ˢ V') ×ˢ (U' ×ˢ V'), rw mem_prod_same_iff, simp only [exists_prop], split, { change U' ∈ 𝓝 x₀ at U'_nhd, change V' ∈ 𝓝 y₀ at V'_nhd, have := prod_mem_prod U'_nhd V'_nhd, tauto }, { intros p h', simp only [set.mem_preimage, set.prod_mk_mem_set_prod_eq] at h', rcases p with ⟨⟨x, y⟩, ⟨x', y'⟩⟩, apply h ; tauto } } end end dense_inducing
10f08a6c7f45144fe59938177ceb929a50db3cd9
bb31430994044506fa42fd667e2d556327e18dfe
/src/topology/continuous_function/zero_at_infty.lean
947c71539b09c6be09ff87c4264b66acfc6c62bc
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
22,934
lean
/- Copyright (c) 2022 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import topology.continuous_function.bounded import topology.continuous_function.cocompact_map /-! # Continuous functions vanishing at infinity The type of continuous functions vanishing at infinity. When the domain is compact `C(α, β) ≃ C₀(α, β)` via the identity map. When the codomain is a metric space, every continuous map which vanishes at infinity is a bounded continuous function. When the domain is a locally compact space, this type has nice properties. ## TODO * Create more intances of algebraic structures (e.g., `non_unital_semiring`) once the necessary type classes (e.g., `topological_ring`) are sufficiently generalized. * Relate the unitization of `C₀(α, β)` to the Alexandroff compactification. -/ universes u v w variables {F : Type*} {α : Type u} {β : Type v} {γ : Type w} [topological_space α] open_locale bounded_continuous_function topological_space open filter metric /-- `C₀(α, β)` is the type of continuous functions `α → β` which vanish at infinity from a topological space to a metric space with a zero element. When possible, instead of parametrizing results over `(f : C₀(α, β))`, you should parametrize over `(F : Type*) [zero_at_infty_continuous_map_class F α β] (f : F)`. When you extend this structure, make sure to extend `zero_at_infty_continuous_map_class`. -/ structure zero_at_infty_continuous_map (α : Type u) (β : Type v) [topological_space α] [has_zero β] [topological_space β] extends continuous_map α β : Type (max u v) := (zero_at_infty' : tendsto to_fun (cocompact α) (𝓝 0)) localized "notation [priority 2000] (name := zero_at_infty_continuous_map) `C₀(` α `, ` β `)` := zero_at_infty_continuous_map α β" in zero_at_infty localized "notation (name := zero_at_infty_continuous_map.arrow) α ` →C₀ ` β := zero_at_infty_continuous_map α β" in zero_at_infty section set_option old_structure_cmd true /-- `zero_at_infty_continuous_map_class F α β` states that `F` is a type of continuous maps which vanish at infinity. You should also extend this typeclass when you extend `zero_at_infty_continuous_map`. -/ class zero_at_infty_continuous_map_class (F : Type*) (α β : out_param $ Type*) [topological_space α] [has_zero β] [topological_space β] extends continuous_map_class F α β := (zero_at_infty (f : F) : tendsto f (cocompact α) (𝓝 0)) end export zero_at_infty_continuous_map_class (zero_at_infty) namespace zero_at_infty_continuous_map section basics variables [topological_space β] [has_zero β] [zero_at_infty_continuous_map_class F α β] instance : zero_at_infty_continuous_map_class C₀(α, β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by { obtain ⟨⟨_, _⟩, _⟩ := f, obtain ⟨⟨_, _⟩, _⟩ := g, congr' }, map_continuous := λ f, f.continuous_to_fun, zero_at_infty := λ f, f.zero_at_infty' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun C₀(α, β) (λ _, α → β) := fun_like.has_coe_to_fun instance : has_coe_t F C₀(α, β) := ⟨λ f, { to_fun := f, continuous_to_fun := map_continuous f, zero_at_infty' := zero_at_infty f }⟩ @[simp] lemma coe_to_continuous_fun (f : C₀(α, β)) : (f.to_continuous_map : α → β) = f := rfl @[ext] lemma ext {f g : C₀(α, β)} (h : ∀ x, f x = g x) : f = g := fun_like.ext _ _ h /-- Copy of a `zero_at_infinity_continuous_map` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : C₀(α, β)) (f' : α → β) (h : f' = f) : C₀(α, β) := { to_fun := f', continuous_to_fun := by { rw h, exact f.continuous_to_fun }, zero_at_infty' := by { simp_rw h, exact f.zero_at_infty' } } @[simp] lemma coe_copy (f : C₀(α, β)) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl lemma copy_eq (f : C₀(α, β)) (f' : α → β) (h : f' = f) : f.copy f' h = f := fun_like.ext' h lemma eq_of_empty [is_empty α] (f g : C₀(α, β)) : f = g := ext $ is_empty.elim ‹_› /-- A continuous function on a compact space is automatically a continuous function vanishing at infinity. -/ @[simps] def continuous_map.lift_zero_at_infty [compact_space α] : C(α, β) ≃ C₀(α, β) := { to_fun := λ f, { to_fun := f, continuous_to_fun := f.continuous, zero_at_infty' := by simp }, inv_fun := λ f, f, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, refl } } /-- A continuous function on a compact space is automatically a continuous function vanishing at infinity. This is not an instance to avoid type class loops. -/ @[simps] def zero_at_infty_continuous_map_class.of_compact {G : Type*} [continuous_map_class G α β] [compact_space α] : zero_at_infty_continuous_map_class G α β := { coe := λ g, g, coe_injective' := λ f g h, fun_like.coe_fn_eq.mp h, map_continuous := map_continuous, zero_at_infty := by simp } end basics /-! ### Algebraic structure Whenever `β` has suitable algebraic structure and a compatible topological structure, then `C₀(α, β)` inherits a corresponding algebraic structure. The primary exception to this is that `C₀(α, β)` will not have a multiplicative identity. -/ section algebraic_structure variables [topological_space β] (x : α) instance [has_zero β] : has_zero C₀(α, β) := ⟨⟨0, tendsto_const_nhds⟩⟩ instance [has_zero β] : inhabited C₀(α, β) := ⟨0⟩ @[simp] lemma coe_zero [has_zero β] : ⇑(0 : C₀(α, β)) = 0 := rfl lemma zero_apply [has_zero β] : (0 : C₀(α, β)) x = 0 := rfl instance [mul_zero_class β] [has_continuous_mul β] : has_mul C₀(α, β) := ⟨λ f g, ⟨f * g, by simpa only [mul_zero] using (zero_at_infty f).mul (zero_at_infty g)⟩⟩ @[simp] lemma coe_mul [mul_zero_class β] [has_continuous_mul β] (f g : C₀(α, β)) : ⇑(f * g) = f * g := rfl lemma mul_apply [mul_zero_class β] [has_continuous_mul β] (f g : C₀(α, β)) : (f * g) x = f x * g x := rfl instance [mul_zero_class β] [has_continuous_mul β] : mul_zero_class C₀(α, β) := fun_like.coe_injective.mul_zero_class _ coe_zero coe_mul instance [semigroup_with_zero β] [has_continuous_mul β] : semigroup_with_zero C₀(α, β) := fun_like.coe_injective.semigroup_with_zero _ coe_zero coe_mul instance [add_zero_class β] [has_continuous_add β] : has_add C₀(α, β) := ⟨λ f g, ⟨f + g, by simpa only [add_zero] using (zero_at_infty f).add (zero_at_infty g)⟩⟩ @[simp] lemma coe_add [add_zero_class β] [has_continuous_add β] (f g : C₀(α, β)) : ⇑(f + g) = f + g := rfl lemma add_apply [add_zero_class β] [has_continuous_add β] (f g : C₀(α, β)) : (f + g) x = f x + g x := rfl instance [add_zero_class β] [has_continuous_add β] : add_zero_class C₀(α, β) := fun_like.coe_injective.add_zero_class _ coe_zero coe_add section add_monoid variables [add_monoid β] [has_continuous_add β] (f g : C₀(α, β)) @[simp] lemma coe_nsmul_rec : ∀ n, ⇑(nsmul_rec n f) = n • f | 0 := by rw [nsmul_rec, zero_smul, coe_zero] | (n + 1) := by rw [nsmul_rec, succ_nsmul, coe_add, coe_nsmul_rec] instance has_nat_scalar : has_smul ℕ C₀(α, β) := ⟨λ n f, ⟨n • f, by simpa [coe_nsmul_rec] using zero_at_infty (nsmul_rec n f)⟩⟩ instance : add_monoid C₀(α, β) := fun_like.coe_injective.add_monoid _ coe_zero coe_add (λ _ _, rfl) end add_monoid instance [add_comm_monoid β] [has_continuous_add β] : add_comm_monoid C₀(α, β) := fun_like.coe_injective.add_comm_monoid _ coe_zero coe_add (λ _ _, rfl) section add_group variables [add_group β] [topological_add_group β] (f g : C₀(α, β)) instance : has_neg C₀(α, β) := ⟨λ f, ⟨-f, by simpa only [neg_zero] using (zero_at_infty f).neg⟩⟩ @[simp] lemma coe_neg : ⇑(-f) = -f := rfl lemma neg_apply : (-f) x = -f x := rfl instance : has_sub C₀(α, β) := ⟨λ f g, ⟨f - g, by simpa only [sub_zero] using (zero_at_infty f).sub (zero_at_infty g)⟩⟩ @[simp] lemma coe_sub : ⇑(f - g) = f - g := rfl lemma sub_apply : (f - g) x = f x - g x := rfl @[simp] lemma coe_zsmul_rec : ∀ z, ⇑(zsmul_rec z f) = z • f | (int.of_nat n) := by rw [zsmul_rec, int.of_nat_eq_coe, coe_nsmul_rec, coe_nat_zsmul] | -[1+ n] := by rw [zsmul_rec, zsmul_neg_succ_of_nat, coe_neg, coe_nsmul_rec] instance has_int_scalar : has_smul ℤ C₀(α, β) := ⟨λ n f, ⟨n • f, by simpa using zero_at_infty (zsmul_rec n f)⟩⟩ instance : add_group C₀(α, β) := fun_like.coe_injective.add_group _ coe_zero coe_add coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) end add_group instance [add_comm_group β] [topological_add_group β] : add_comm_group C₀(α, β) := fun_like.coe_injective.add_comm_group _ coe_zero coe_add coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) instance [has_zero β] {R : Type*} [has_zero R] [smul_with_zero R β] [has_continuous_const_smul R β] : has_smul R C₀(α, β) := ⟨λ r f, ⟨r • f, by simpa [smul_zero] using (zero_at_infty f).const_smul r⟩⟩ @[simp] lemma coe_smul [has_zero β] {R : Type*} [has_zero R] [smul_with_zero R β] [has_continuous_const_smul R β] (r : R) (f : C₀(α, β)) : ⇑(r • f) = r • f := rfl lemma smul_apply [has_zero β] {R : Type*} [has_zero R] [smul_with_zero R β] [has_continuous_const_smul R β] (r : R) (f : C₀(α, β)) (x : α) : (r • f) x = r • f x := rfl instance [has_zero β] {R : Type*} [has_zero R] [smul_with_zero R β] [smul_with_zero Rᵐᵒᵖ β] [has_continuous_const_smul R β] [is_central_scalar R β] : is_central_scalar R C₀(α, β) := ⟨λ r f, ext $ λ x, op_smul_eq_smul _ _⟩ instance [has_zero β] {R : Type*} [has_zero R] [smul_with_zero R β] [has_continuous_const_smul R β] : smul_with_zero R C₀(α, β) := function.injective.smul_with_zero ⟨_, coe_zero⟩ fun_like.coe_injective coe_smul instance [has_zero β] {R : Type*} [monoid_with_zero R] [mul_action_with_zero R β] [has_continuous_const_smul R β] : mul_action_with_zero R C₀(α, β) := function.injective.mul_action_with_zero ⟨_, coe_zero⟩ fun_like.coe_injective coe_smul instance [add_comm_monoid β] [has_continuous_add β] {R : Type*} [semiring R] [module R β] [has_continuous_const_smul R β] : module R C₀(α, β) := function.injective.module R ⟨_, coe_zero, coe_add⟩ fun_like.coe_injective coe_smul instance [non_unital_non_assoc_semiring β] [topological_semiring β] : non_unital_non_assoc_semiring C₀(α, β) := fun_like.coe_injective.non_unital_non_assoc_semiring _ coe_zero coe_add coe_mul (λ _ _, rfl) instance [non_unital_semiring β] [topological_semiring β] : non_unital_semiring C₀(α, β) := fun_like.coe_injective.non_unital_semiring _ coe_zero coe_add coe_mul (λ _ _, rfl) instance [non_unital_comm_semiring β] [topological_semiring β] : non_unital_comm_semiring C₀(α, β) := fun_like.coe_injective.non_unital_comm_semiring _ coe_zero coe_add coe_mul (λ _ _, rfl) instance [non_unital_non_assoc_ring β] [topological_ring β] : non_unital_non_assoc_ring C₀(α, β) := fun_like.coe_injective.non_unital_non_assoc_ring _ coe_zero coe_add coe_mul coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) instance [non_unital_ring β] [topological_ring β] : non_unital_ring C₀(α, β) := fun_like.coe_injective.non_unital_ring _ coe_zero coe_add coe_mul coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) instance [non_unital_comm_ring β] [topological_ring β] : non_unital_comm_ring C₀(α, β) := fun_like.coe_injective.non_unital_comm_ring _ coe_zero coe_add coe_mul coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) instance {R : Type*} [semiring R] [non_unital_non_assoc_semiring β] [topological_semiring β] [module R β] [has_continuous_const_smul R β] [is_scalar_tower R β β] : is_scalar_tower R C₀(α, β) C₀(α, β) := { smul_assoc := λ r f g, begin ext, simp only [smul_eq_mul, coe_mul, coe_smul, pi.mul_apply, pi.smul_apply], rw [←smul_eq_mul, ←smul_eq_mul, smul_assoc], end } instance {R : Type*} [semiring R] [non_unital_non_assoc_semiring β] [topological_semiring β] [module R β] [has_continuous_const_smul R β] [smul_comm_class R β β] : smul_comm_class R C₀(α, β) C₀(α, β) := { smul_comm := λ r f g, begin ext, simp only [smul_eq_mul, coe_smul, coe_mul, pi.smul_apply, pi.mul_apply], rw [←smul_eq_mul, ←smul_eq_mul, smul_comm], end } end algebraic_structure section uniform variables [uniform_space β] [uniform_space γ] [has_zero γ] [zero_at_infty_continuous_map_class F β γ] lemma uniform_continuous (f : F) : uniform_continuous (f : β → γ) := (map_continuous f).uniform_continuous_of_zero_at_infty (zero_at_infty f) end uniform /-! ### Metric structure When `β` is a metric space, then every element of `C₀(α, β)` is bounded, and so there is a natural inclusion map `zero_at_infty_continuous_map.to_bcf : C₀(α, β) → (α →ᵇ β)`. Via this map `C₀(α, β)` inherits a metric as the pullback of the metric on `α →ᵇ β`. Moreover, this map has closed range in `α →ᵇ β` and consequently `C₀(α, β)` is a complete space whenever `β` is complete. -/ section metric open metric set variables [metric_space β] [has_zero β] [zero_at_infty_continuous_map_class F α β] protected lemma bounded (f : F) : ∃ C, ∀ x y : α, dist ((f : α → β) x) (f y) ≤ C := begin obtain ⟨K : set α, hK₁, hK₂⟩ := mem_cocompact.mp (tendsto_def.mp (zero_at_infty (f : F)) _ (closed_ball_mem_nhds (0 : β) zero_lt_one)), obtain ⟨C, hC⟩ := (hK₁.image (map_continuous f)).bounded.subset_ball (0 : β), refine ⟨max C 1 + max C 1, (λ x y, _)⟩, have : ∀ x, f x ∈ closed_ball (0 : β) (max C 1), { intro x, by_cases hx : x ∈ K, { exact (mem_closed_ball.mp $ hC ⟨x, hx, rfl⟩).trans (le_max_left _ _) }, { exact (mem_closed_ball.mp $ mem_preimage.mp (hK₂ hx)).trans (le_max_right _ _) } }, exact (dist_triangle (f x) 0 (f y)).trans (add_le_add (mem_closed_ball.mp $ this x) (mem_closed_ball'.mp $ this y)), end lemma bounded_range (f : C₀(α, β)) : bounded (range f) := bounded_range_iff.2 f.bounded lemma bounded_image (f : C₀(α, β)) (s : set α) : bounded (f '' s) := f.bounded_range.mono $ image_subset_range _ _ @[priority 100] instance : bounded_continuous_map_class F α β := { map_bounded := λ f, zero_at_infty_continuous_map.bounded f, ..‹zero_at_infty_continuous_map_class F α β› } /-- Construct a bounded continuous function from a continuous function vanishing at infinity. -/ @[simps] def to_bcf (f : C₀(α, β)) : α →ᵇ β := ⟨f, map_bounded f⟩ section variables (α) (β) lemma to_bcf_injective : function.injective (to_bcf : C₀(α, β) → α →ᵇ β) := λ f g h, by { ext, simpa only using fun_like.congr_fun h x, } end variables {C : ℝ} {f g : C₀(α, β)} /-- The type of continuous functions vanishing at infinity, with the uniform distance induced by the inclusion `zero_at_infinity_continuous_map.to_bcf`, is a metric space. -/ noncomputable instance : metric_space C₀(α, β) := metric_space.induced _ (to_bcf_injective α β) (by apply_instance) @[simp] lemma dist_to_bcf_eq_dist {f g : C₀(α, β)} : dist f.to_bcf g.to_bcf = dist f g := rfl open bounded_continuous_function /-- Convergence in the metric on `C₀(α, β)` is uniform convergence. -/ lemma tendsto_iff_tendsto_uniformly {ι : Type*} {F : ι → C₀(α, β)} {f : C₀(α, β)} {l : filter ι} : tendsto F l (𝓝 f) ↔ tendsto_uniformly (λ i, F i) f l := by simpa only [metric.tendsto_nhds] using @bounded_continuous_function.tendsto_iff_tendsto_uniformly _ _ _ _ _ (λ i, (F i).to_bcf) f.to_bcf l lemma isometry_to_bcf : isometry (to_bcf : C₀(α, β) → α →ᵇ β) := by tauto lemma closed_range_to_bcf : is_closed (range (to_bcf : C₀(α, β) → α →ᵇ β)) := begin refine is_closed_iff_cluster_pt.mpr (λ f hf, _), rw cluster_pt_principal_iff at hf, have : tendsto f (cocompact α) (𝓝 0), { refine metric.tendsto_nhds.mpr (λ ε hε, _), obtain ⟨_, hg, g, rfl⟩ := hf (ball f (ε / 2)) (ball_mem_nhds f $ half_pos hε), refine (metric.tendsto_nhds.mp (zero_at_infty g) (ε / 2) (half_pos hε)).mp (eventually_of_forall $ λ x hx, _), calc dist (f x) 0 ≤ dist (g.to_bcf x) (f x) + dist (g x) 0 : dist_triangle_left _ _ _ ... < dist g.to_bcf f + ε / 2 : add_lt_add_of_le_of_lt (dist_coe_le_dist x) hx ... < ε : by simpa [add_halves ε] using add_lt_add_right hg (ε / 2) }, exact ⟨⟨f.to_continuous_map, this⟩, by {ext, refl}⟩, end /-- Continuous functions vanishing at infinity taking values in a complete space form a complete space. -/ instance [complete_space β] : complete_space C₀(α, β) := (complete_space_iff_is_complete_range isometry_to_bcf.uniform_inducing).mpr closed_range_to_bcf.is_complete end metric section norm /-! ### Normed space The norm structure on `C₀(α, β)` is the one induced by the inclusion `to_bcf : C₀(α, β) → (α →ᵇ b)`, viewed as an additive monoid homomorphism. Then `C₀(α, β)` is naturally a normed space over a normed field `𝕜` whenever `β` is as well. -/ section normed_space variables [normed_add_comm_group β] {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] noncomputable instance : normed_add_comm_group C₀(α, β) := normed_add_comm_group.induced C₀(α, β) (α →ᵇ β) (⟨to_bcf, rfl, λ x y, rfl⟩ : C₀(α, β) →+ (α →ᵇ β)) (to_bcf_injective α β) @[simp] lemma norm_to_bcf_eq_norm {f : C₀(α, β)} : ‖f.to_bcf‖ = ‖f‖ := rfl instance : normed_space 𝕜 C₀(α, β) := { norm_smul_le := λ k f, (norm_smul k f.to_bcf).le } end normed_space section normed_ring variables [non_unital_normed_ring β] noncomputable instance : non_unital_normed_ring C₀(α, β) := { norm_mul := λ f g, norm_mul_le f.to_bcf g.to_bcf, ..zero_at_infty_continuous_map.non_unital_ring, ..zero_at_infty_continuous_map.normed_add_comm_group } end normed_ring end norm section star /-! ### Star structure It is possible to equip `C₀(α, β)` with a pointwise `star` operation whenever there is a continuous `star : β → β` for which `star (0 : β) = 0`. We don't have quite this weak a typeclass, but `star_add_monoid` is close enough. The `star_add_monoid` and `normed_star_group` classes on `C₀(α, β)` are inherited from their counterparts on `α →ᵇ β`. Ultimately, when `β` is a C⋆-ring, then so is `C₀(α, β)`. -/ variables [topological_space β] [add_monoid β] [star_add_monoid β] [has_continuous_star β] instance : has_star C₀(α, β) := { star := λ f, { to_fun := λ x, star (f x), continuous_to_fun := (map_continuous f).star, zero_at_infty' := by simpa only [star_zero] using (continuous_star.tendsto (0 : β)).comp (zero_at_infty f) } } @[simp] lemma coe_star (f : C₀(α, β)) : ⇑(star f) = star f := rfl lemma star_apply (f : C₀(α, β)) (x : α) : (star f) x = star (f x) := rfl instance [has_continuous_add β] : star_add_monoid C₀(α, β) := { star_involutive := λ f, ext $ λ x, star_star (f x), star_add := λ f g, ext $ λ x, star_add (f x) (g x) } end star section normed_star variables [normed_add_comm_group β] [star_add_monoid β] [normed_star_group β] instance : normed_star_group C₀(α, β) := { norm_star := λ f, (norm_star f.to_bcf : _) } end normed_star section star_module variables {𝕜 : Type*} [has_zero 𝕜] [has_star 𝕜] [add_monoid β] [star_add_monoid β] [topological_space β] [has_continuous_star β] [smul_with_zero 𝕜 β] [has_continuous_const_smul 𝕜 β] [star_module 𝕜 β] instance : star_module 𝕜 C₀(α, β) := { star_smul := λ k f, ext $ λ x, star_smul k (f x) } end star_module section star_ring variables [non_unital_semiring β] [star_ring β] [topological_space β] [has_continuous_star β] [topological_semiring β] instance : star_ring C₀(α, β) := { star_mul := λ f g, ext $ λ x, star_mul (f x) (g x), ..zero_at_infty_continuous_map.star_add_monoid } end star_ring section cstar_ring instance [non_unital_normed_ring β] [star_ring β] [cstar_ring β] : cstar_ring C₀(α, β) := { norm_star_mul_self := λ f, @cstar_ring.norm_star_mul_self _ _ _ _ f.to_bcf } end cstar_ring /-! ### C₀ as a functor For each `β` with sufficient structure, there is a contravariant functor `C₀(-, β)` from the category of topological spaces with morphisms given by `cocompact_map`s. -/ variables {δ : Type*} [topological_space β] [topological_space γ] [topological_space δ] local notation α ` →co ` β := cocompact_map α β section variables [has_zero δ] /-- Composition of a continuous function vanishing at infinity with a cocompact map yields another continuous function vanishing at infinity. -/ def comp (f : C₀(γ, δ)) (g : β →co γ) : C₀(β, δ) := { to_continuous_map := (f : C(γ, δ)).comp g, zero_at_infty' := (zero_at_infty f).comp (cocompact_tendsto g) } @[simp] lemma coe_comp_to_continuous_fun (f : C₀(γ, δ)) (g : β →co γ) : ((f.comp g).to_continuous_map : β → δ) = f ∘ g := rfl @[simp] lemma comp_id (f : C₀(γ, δ)) : f.comp (cocompact_map.id γ) = f := ext (λ x, rfl) @[simp] lemma comp_assoc (f : C₀(γ, δ)) (g : β →co γ) (h : α →co β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma zero_comp (g : β →co γ) : (0 : C₀(γ, δ)).comp g = 0 := rfl end /-- Composition as an additive monoid homomorphism. -/ def comp_add_monoid_hom [add_monoid δ] [has_continuous_add δ] (g : β →co γ) : C₀(γ, δ) →+ C₀(β, δ) := { to_fun := λ f, f.comp g, map_zero' := zero_comp g, map_add' := λ f₁ f₂, rfl } /-- Composition as a semigroup homomorphism. -/ def comp_mul_hom [mul_zero_class δ] [has_continuous_mul δ] (g : β →co γ) : C₀(γ, δ) →ₙ* C₀(β, δ) := { to_fun := λ f, f.comp g, map_mul' := λ f₁ f₂, rfl } /-- Composition as a linear map. -/ def comp_linear_map [add_comm_monoid δ] [has_continuous_add δ] {R : Type*} [semiring R] [module R δ] [has_continuous_const_smul R δ] (g : β →co γ) : C₀(γ, δ) →ₗ[R] C₀(β, δ) := { to_fun := λ f, f.comp g, map_add' := λ f₁ f₂, rfl, map_smul' := λ r f, rfl } /-- Composition as a non-unital algebra homomorphism. -/ def comp_non_unital_alg_hom {R : Type*} [semiring R] [non_unital_non_assoc_semiring δ] [topological_semiring δ] [module R δ] [has_continuous_const_smul R δ] (g : β →co γ) : C₀(γ, δ) →ₙₐ[R] C₀(β, δ) := { to_fun := λ f, f.comp g, map_smul' := λ r f, rfl, map_zero' := rfl, map_add' := λ f₁ f₂, rfl, map_mul' := λ f₁ f₂, rfl } end zero_at_infty_continuous_map
7723870188c158f7571022bde73bb32bcab85d83
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/attr_at3.lean
150fce778e1b6a2cdff412a4d9d74e70ea44478b
[ "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
182
lean
namespace bla definition f (a : nat) := a + 1 attribute f [reducible] at foo print f end bla section open foo print bla.f end print bla.f namespace foo print bla.f end foo
6d11e1004cdc631c8255ead5e64eb4aa7dc277e9
947b78d97130d56365ae2ec264df196ce769371a
/stage0/src/Init/Data/Random.lean
76fe642730b9af4fc8af043030bd62bcb02e960e
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,043
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.System.IO import Init.Data.Int universes u /- Basic random number generator support based on the one available on the Haskell library -/ /- Interface for random number generators. -/ class RandomGen (g : Type u) := /- `range` returns the range of values returned by the generator. -/ (range : g → Nat × Nat) /- `next` operation returns a natural number that is uniformly distributed the range returned by `range` (including both end points), and a new generator. -/ (next : g → Nat × g) /- The 'split' operation allows one to obtain two distinct random number generators. This is very useful in functional programs (for example, when passing a random number generator down to recursive calls). -/ (split : g → g × g) /- "Standard" random number generator. -/ structure StdGen := (s1 : Nat) (s2 : Nat) instance StdGen.inhabited : Inhabited StdGen := ⟨{ s1 := 0, s2 := 0 }⟩ def stdRange := (1, 2147483562) instance : HasRepr StdGen := { repr := fun ⟨s1, s2⟩ => "⟨" ++ toString s1 ++ ", " ++ toString s2 ++ "⟩" } def stdNext : StdGen → Nat × StdGen | ⟨s1, s2⟩ => let k : Int := s1 / 53668; let s1' : Int := 40014 * ((s1 : Int) - k * 53668) - k * 12211; let s1'' : Int := if s1' < 0 then s1' + 2147483563 else s1'; let k' : Int := s2 / 52774; let s2' : Int := 40692 * ((s2 : Int) - k' * 52774) - k' * 3791; let s2'' : Int := if s2' < 0 then s2' + 2147483399 else s2'; let z : Int := s1'' - s2''; let z' : Int := if z < 1 then z + 2147483562 else z % 2147483562; (z'.toNat, ⟨s1''.toNat, s2''.toNat⟩) def stdSplit : StdGen → StdGen × StdGen | g@⟨s1, s2⟩ => let newS1 := if s1 = 2147483562 then 1 else s1 + 1; let newS2 := if s2 = 1 then 2147483398 else s2 - 1; let newG := (stdNext g).2; let leftG := StdGen.mk newS1 newG.2; let rightG := StdGen.mk newG.1 newS2; (leftG, rightG) instance : RandomGen StdGen := {range := fun _ => stdRange, next := stdNext, split := stdSplit} /-- Return a standard number generator. -/ def mkStdGen (s : Nat := 0) : StdGen := let q := s / 2147483562; let s1 := s % 2147483562; let s2 := q % 2147483398; ⟨s1 + 1, s2 + 1⟩ /- Auxiliary function for randomNatVal. Generate random values until we exceed the target magnitude. `genLo` and `genMag` are the generator lower bound and magnitude. The parameter `r` is the "remaining" magnitude. -/ private partial def randNatAux {gen : Type u} [RandomGen gen] (genLo genMag : Nat) : Nat → (Nat × gen) → Nat × gen | 0, (v, g) => (v, g) | r'@(r+1), (v, g) => let (x, g') := RandomGen.next g; let v' := v*genMag + (x - genLo); randNatAux (r' / genMag - 1) (v', g') /-- Generate a random natural number in the interval [lo, hi]. -/ def randNat {gen : Type u} [RandomGen gen] (g : gen) (lo hi : Nat) : Nat × gen := let lo' := if lo > hi then hi else lo; let hi' := if lo > hi then lo else hi; let (genLo, genHi) := RandomGen.range g; let genMag := genHi - genLo + 1; /- Probabilities of the most likely and least likely result will differ at most by a factor of (1 +- 1/q). Assuming the RandomGen is uniform, of course -/ let q := 1000; let k := hi' - lo' + 1; let tgtMag := k * q; let (v, g') := randNatAux genLo genMag tgtMag (0, g); let v' := lo' + (v % k); (v', g') /-- Generate a random Boolean. -/ def randBool {gen : Type u} [RandomGen gen] (g : gen) : Bool × gen := let (v, g') := randNat g 0 1; (v = 1, g') def IO.mkStdGenRef : IO (IO.Ref StdGen) := IO.mkRef mkStdGen @[init IO.mkStdGenRef] constant IO.stdGenRef : IO.Ref StdGen := arbitrary _ def IO.setRandSeed (n : Nat) : IO Unit := IO.stdGenRef.set (mkStdGen n) def IO.rand (lo hi : Nat) : IO Nat := do gen ← IO.stdGenRef.get; let (r, gen) := randNat gen lo hi; IO.stdGenRef.set gen; pure r
57cc420dd7c8db36a877b36b975698a64d1f1516
c76cc4eaee3c806716844e49b5175747d1aa170a
/src/solutions_sheet_one.lean
ffada619c840219ad2a7ac07385758fef638382a
[]
no_license
ImperialCollegeLondon/M40002
0fb55848adbb0d8bc4a65ca5d7ed6edd18764c28
a499db70323bd5ccae954c680ec9afbf15ffacca
refs/heads/master
1,674,878,059,748
1,607,624,828,000
1,607,624,828,000
309,696,750
3
0
null
null
null
null
UTF-8
Lean
false
false
1,499
lean
import tactic import data.real.basic import data.real.irrational -- Q1) what's the biggest element of {x ∈ ℝ | x < 1}? theorem soln1 : ∀ a ∈ {x : ℝ | x < 1}, ∃ b ∈ {x : ℝ | x < 1}, a < b := begin intro a, rintro (ha : a < 1), use (a + 1) / 2, split, { simp, linarith }, linarith, end open real -- Q2) Prove that for every positive intger n ≠ 3, √n - √3 is irrational theorem soln2 : ∀ n : ℕ, 0 < n ∧ n ≠ 3 → irrational (sqrt (n : ℝ) - sqrt 3) := begin rintros n ⟨hn0, hn3⟩ hq, rw set.mem_range at hq, cases hq with q hq, have hq1 := add_eq_of_eq_sub hq, apply_fun (λ x, x * x) at hq1, have h3 : (0 : ℝ) ≤ 3 := by norm_num, simp [mul_add, add_mul, h3] at hq1, have hq2 : (2 : ℝ) * q * sqrt 3 = n - q * q - 3, rw ← hq1, ring, let r : ℚ := n - q * q - 3, have hq3 : (2 : ℝ) * q * sqrt 3 = r, convert hq2, norm_cast, clear hq1, clear hq2, have s3 : irrational (sqrt ((3 : ℕ) : ℝ)), apply nat.prime.irrational_sqrt, norm_num, simp at s3, have temp : (2 : ℝ) * q * sqrt 3 = sqrt 3 * ((2 : ℚ) * q : ℚ), rw mul_comm ((2 : ℝ) * _), norm_cast, rw temp at hq3, apply irrational.mul_rat s3, swap, use r, exact hq3.symm, clear hq3 r s3 temp, intro h, rw mul_eq_zero at h, cases h, linarith, rw h at hq, simp at hq, symmetry' at hq, rw sub_eq_zero at hq, apply hn3, apply_fun (λ x, x * x) at hq, simp [h3] at hq, norm_cast at hq, end
d8cc65756a4e233922f665171a38825258b16bf4
dc253be9829b840f15d96d986e0c13520b085033
/move_to_lib.hlean
3c1acc93e56593b1c69cf39847960c5661558907
[ "Apache-2.0" ]
permissive
cmu-phil/Spectral
4ce68e5c1ef2a812ffda5260e9f09f41b85ae0ea
3b078f5f1de251637decf04bd3fc8aa01930a6b3
refs/heads/master
1,685,119,195,535
1,684,169,772,000
1,684,169,772,000
46,450,197
42
13
null
1,505,516,767,000
1,447,883,921,000
Lean
UTF-8
Lean
false
false
12,076
hlean
-- definitions, theorems and attributes which should be moved to files in the HoTT library import homotopy.sphere2 homotopy.cofiber homotopy.wedge hit.prop_trunc hit.set_quotient eq2 types.pointed2 algebra.graph algebra.category.functor.equivalence open eq nat int susp pointed sigma is_equiv equiv fiber algebra trunc pi group is_trunc function unit prod bool universe variable u definition AddAbGroup.struct2 [instance] (G : AddAbGroup) : add_ab_group (algebra._trans_of_Group_of_AbGroup_2 G) := AddAbGroup.struct G namespace eq /- move to init.equiv -/ variables {A₀₀ A₂₀ A₀₂ A₂₂ : Type} {f₁₀ : A₀₀ → A₂₀} {f₀₁ : A₀₀ → A₀₂} {f₂₁ : A₂₀ → A₂₂} {f₁₂ : A₀₂ → A₂₂} definition hhinverse' (f₁₀ : A₀₀ ≃ A₂₀) (f₁₂ : A₀₂ ≃ A₂₂) (p : hsquare f₁₀ f₁₂ f₀₁ f₂₁) : hsquare f₁₀⁻¹ᵉ f₁₂⁻¹ᵉ f₂₁ f₀₁ := p⁻¹ʰᵗʸʰ definition hvinverse' (f₀₁ : A₀₀ ≃ A₀₂) (f₂₁ : A₂₀ ≃ A₂₂) (p : hsquare f₁₀ f₁₂ f₀₁ f₂₁) : hsquare f₁₂ f₁₀ f₀₁⁻¹ᵉ f₂₁⁻¹ᵉ := p⁻¹ʰᵗʸᵛ definition transport_lemma {A : Type} {C : A → Type} {g₁ : A → A} {x y : A} (p : x = y) (f : Π⦃x⦄, C x → C (g₁ x)) (z : C x) : transport C (ap g₁ p)⁻¹ (f (transport C p z)) = f z := by induction p; reflexivity definition transport_lemma2 {A : Type} {C : A → Type} {g₁ : A → A} {x y : A} (p : x = y) (f : Π⦃x⦄, C x → C (g₁ x)) (z : C x) : transport C (ap g₁ p) (f z) = f (transport C p z) := by induction p; reflexivity variables {A A' B : Type} {a a₂ a₃ : A} {p p' : a = a₂} {p₂ : a₂ = a₃} {a' a₂' a₃' : A'} {b b₂ : B} end eq open eq namespace int definition maxm2_eq_minus_two {n : ℤ} (H : n < 0) : maxm2 n = -2 := begin induction exists_eq_neg_succ_of_nat H with n p, cases p, reflexivity end end int namespace nat -- definition rec_down_le_beta_lt (P : ℕ → Type) (s : ℕ) (H0 : Πn, s ≤ n → P n) -- (Hs : Πn, P (n+1) → P n) (n : ℕ) (Hn : n < s) : -- rec_down_le P s H0 Hs n = Hs n (rec_down_le P s H0 Hs (n+1)) := -- begin -- revert n Hn, induction s with s IH: intro n Hn, -- { exfalso, exact not_succ_le_zero n Hn }, -- { have Hn' : n ≤ s, from le_of_succ_le_succ Hn, -- --esimp [rec_down_le], -- exact sorry -- -- induction Hn' with s Hn IH, -- -- { }, -- -- { } -- } -- end end nat -- definition ppi_eq_equiv_internal : (k = l) ≃ (k ~* l) := -- calc (k = l) ≃ ppi.sigma_char P p₀ k = ppi.sigma_char P p₀ l -- : eq_equiv_fn_eq (ppi.sigma_char P p₀) k l -- ... ≃ Σ(p : k = l), -- pathover (λh, h pt = p₀) (respect_pt k) p (respect_pt l) -- : sigma_eq_equiv _ _ -- ... ≃ Σ(p : k = l), -- respect_pt k = ap (λh, h pt) p ⬝ respect_pt l -- : sigma_equiv_sigma_right -- (λp, eq_pathover_equiv_Fl p (respect_pt k) (respect_pt l)) -- ... ≃ Σ(p : k = l), -- respect_pt k = apd10 p pt ⬝ respect_pt l -- : sigma_equiv_sigma_right -- (λp, equiv_eq_closed_right _ (whisker_right _ (ap_eq_apd10 p _))) -- ... ≃ Σ(p : k ~ l), respect_pt k = p pt ⬝ respect_pt l -- : sigma_equiv_sigma_left' eq_equiv_homotopy -- ... ≃ Σ(p : k ~ l), p pt ⬝ respect_pt l = respect_pt k -- : sigma_equiv_sigma_right (λp, eq_equiv_eq_symm _ _) -- ... ≃ (k ~* l) : phomotopy.sigma_char k l namespace pointed open option sum definition option_equiv_sum (A : Type) : option A ≃ A ⊎ unit := begin fapply equiv.MK, { intro z, induction z with a, { exact inr star }, { exact inl a } }, { intro z, induction z with a b, { exact some a }, { exact none } }, { intro z, induction z with a b, { reflexivity }, { induction b, reflexivity } }, { intro z, induction z with a, all_goals reflexivity } end theorem is_trunc_add_point [instance] (n : ℕ₋₂) (A : Type) [HA : is_trunc (n.+2) A] : is_trunc (n.+2) A₊ := begin apply is_trunc_equiv_closed_rev _ (option_equiv_sum A), apply is_trunc_sum end end pointed open pointed namespace trunc open trunc_index sigma.ops -- TODO: redefine loopn_ptrunc_pequiv definition apn_ptrunc_functor (n : ℕ₋₂) (k : ℕ) {A B : Type*} (f : A →* B) : Ω→[k] (ptrunc_functor (n+k) f) ∘* (loopn_ptrunc_pequiv n k A)⁻¹ᵉ* ~* (loopn_ptrunc_pequiv n k B)⁻¹ᵉ* ∘* ptrunc_functor n (Ω→[k] f) := begin revert n, induction k with k IH: intro n, { reflexivity }, { exact sorry } end end trunc open trunc namespace sigma open sigma.ops -- open sigma.ops -- definition eq.rec_sigma {A : Type} {B : A → Type} {a₀ : A} {b₀ : B a₀} -- {P : Π(a : A) (b : B a), ⟨a₀, b₀⟩ = ⟨a, b⟩ → Type} (H : P a₀ b₀ idp) {a : A} {b : B a} -- (p : ⟨a₀, b₀⟩ = ⟨a, b⟩) : P a b p := -- sorry -- definition sigma_pathover_equiv_of_is_prop {A : Type} {B : A → Type} {C : Πa, B a → Type} -- {a a' : A} {p : a = a'} {b : B a} {b' : B a'} {c : C a b} {c' : C a' b'} -- [Πa b, is_prop (C a b)] : ⟨b, c⟩ =[p] ⟨b', c'⟩ ≃ b =[p] b' := -- begin -- fapply equiv.MK, -- { exact pathover_pr1 }, -- { intro q, induction q, apply pathover_idp_of_eq, exact sigma_eq idp !is_prop.elimo }, -- { intro q, induction q, -- have c = c', from !is_prop.elim, induction this, -- rewrite [▸*, is_prop_elimo_self (C a) c] }, -- { esimp, generalize ⟨b, c⟩, intro x q, } -- end definition sigma_equiv_of_is_embedding_left_fun [constructor] {X Y : Type} {P : Y → Type} {f : X → Y} (H : Πy, P y → fiber f y) (v : Σy, P y) : Σx, P (f x) := ⟨fiber.point (H v.1 v.2), transport P (point_eq (H v.1 v.2))⁻¹ v.2⟩ definition sigma_equiv_of_is_embedding_left [constructor] {X Y : Type} {P : Y → Type} (f : X → Y) (Hf : is_embedding f) (HP : Πx, is_prop (P (f x))) (H : Πy, P y → fiber f y) : (Σy, P y) ≃ Σx, P (f x) := begin apply equiv.MK (sigma_equiv_of_is_embedding_left_fun H) (sigma_functor f (λa, id)), { intro v, induction v with x p, esimp [sigma_equiv_of_is_embedding_left_fun], fapply sigma_eq, apply @is_injective_of_is_embedding _ _ f, exact point_eq (H (f x) p), apply is_prop.elimo }, { intro v, induction v with y p, esimp, fapply sigma_eq, exact point_eq (H y p), apply tr_pathover } end definition sigma_equiv_of_is_embedding_left_contr [constructor] {X Y : Type} {P : Y → Type} (f : X → Y) (Hf : is_embedding f) (HP : Πx, is_contr (P (f x))) (H : Πy, P y → fiber f y) : (Σy, P y) ≃ X := sigma_equiv_of_is_embedding_left f Hf _ H ⬝e sigma_equiv_of_is_contr_right _ _ end sigma open sigma namespace group definition group_homomorphism_of_add_group_homomorphism [constructor] {G₁ G₂ : AddGroup} (φ : G₁ →a G₂) : G₁ →g G₂ := φ -- definition is_equiv_isomorphism -- some extra instances for type class inference -- definition is_mul_hom_comm_homomorphism [instance] {G G' : AbGroup} (φ : G →g G') -- : @is_mul_hom G G' (@ab_group.to_group _ (AbGroup.struct G)) -- (@ab_group.to_group _ (AbGroup.struct G')) φ := -- homomorphism.struct φ -- definition is_mul_hom_comm_homomorphism1 [instance] {G G' : AbGroup} (φ : G →g G') -- : @is_mul_hom G G' _ -- (@ab_group.to_group _ (AbGroup.struct G')) φ := -- homomorphism.struct φ -- definition is_mul_hom_comm_homomorphism2 [instance] {G G' : AbGroup} (φ : G →g G') -- : @is_mul_hom G G' (@ab_group.to_group _ (AbGroup.struct G)) _ φ := -- homomorphism.struct φ -- definition interchange (G : AbGroup) (a b c d : G) : (a * b) * (c * d) = (a * c) * (b * d) := -- mul.comm4 a b c d open option definition add_point_AbGroup [unfold 3] {X : Type} (G : X → AbGroup) : X₊ → AbGroup | (some x) := G x | none := trivial_ab_group_lift -- definition trunc_isomorphism_of_equiv {A B : Type} [inf_group A] [inf_group B] (f : A ≃ B) -- (h : is_mul_hom f) : -- Group.mk (trunc 0 A) (group_trunc A) ≃g Group.mk (trunc 0 B) (group_trunc B) := -- begin -- apply isomorphism_of_equiv (trunc_equiv_trunc 0 f), intros x x', -- induction x with a, induction x' with a', apply ap tr, exact h a a' -- end end group open group namespace fiber /- if we need this: do pfiber_functor_pcompose and so on first -/ -- definition psquare_pfiber_functor [constructor] {A₁ A₂ A₃ A₄ B₁ B₂ B₃ B₄ : Type*} -- {f₁ : A₁ →* B₁} {f₂ : A₂ →* B₂} {f₃ : A₃ →* B₃} {f₄ : A₄ →* B₄} -- {g₁₂ : A₁ →* A₂} {g₃₄ : A₃ →* A₄} {g₁₃ : A₁ →* A₃} {g₂₄ : A₂ →* A₄} -- {h₁₂ : B₁ →* B₂} {h₃₄ : B₃ →* B₄} {h₁₃ : B₁ →* B₃} {h₂₄ : B₂ →* B₄} -- (H₁₂ : psquare g₁₂ h₁₂ f₁ f₂) (H₃₄ : psquare g₃₄ h₃₄ f₃ f₄) -- (H₁₃ : psquare g₁₃ h₁₃ f₁ f₃) (H₂₄ : psquare g₂₄ h₂₄ f₂ f₄) -- (G : psquare g₁₂ g₃₄ g₁₃ g₂₄) (H : psquare h₁₂ h₃₄ h₁₃ h₂₄) -- /- pcube H₁₂ H₃₄ H₁₃ H₂₄ G H -/ : -- psquare (pfiber_functor g₁₂ h₁₂ H₁₂) (pfiber_functor g₃₄ h₃₄ H₃₄) -- (pfiber_functor g₁₃ h₁₃ H₁₃) (pfiber_functor g₂₄ h₂₄ H₂₄) := -- begin -- fapply phomotopy.mk, -- { intro x, induction x with x p, induction B₁ with B₁ b₁₀, induction f₁ with f₁ f₁₀, esimp at *, -- induction p, esimp [fiber_functor], }, -- { } -- end end fiber open fiber namespace function variables {A B : Type} {f f' : A → B} open is_conn sigma.ops definition homotopy_group_isomorphism_of_is_embedding (n : ℕ) [H : is_succ n] {A B : Type*} (f : A →* B) [H2 : is_embedding f] : πg[n] A ≃g πg[n] B := begin apply isomorphism.mk (homotopy_group_homomorphism n f), induction H with n, apply is_equiv_of_equiv_of_homotopy (ptrunc_pequiv_ptrunc 0 (loopn_pequiv_loopn_of_is_embedding (n+1) f)), exact sorry end definition merely_constant_pmap {A B : Type*} {f : A →* B} (H : merely_constant f) (a : A) : merely (f a = pt) := tconcat (tconcat (H.2 a) (tinverse (H.2 pt))) (tr (respect_pt f)) definition merely_constant_of_is_conn {A B : Type*} (f : A →* B) [is_conn 0 A] : merely_constant f := ⟨pt, is_conn.elim -1 _ (tr (respect_pt f))⟩ end function open function namespace is_conn open unit trunc_index nat is_trunc pointed.ops sigma.ops prod.ops -- definition is_conn_pfiber_of_equiv_on_homotopy_groups (n : ℕ) {A B : pType.{u}} (f : A →* B) -- [H : is_conn 0 A] -- (H1 : Πk, k ≤ n → is_equiv (π→[k] f)) -- (H2 : is_surjective (π→[succ n] f)) : -- is_conn n (pfiber f) := -- _ -- definition is_conn_pelim [constructor] {k : ℕ} {X : Type*} (Y : Type*) (H : is_conn k X) : -- (X →* connect k Y) ≃ (X →* Y) := end is_conn namespace sphere -- definition constant_sphere_map_sphere {n m : ℕ} (H : n < m) (f : S n →* S m) : -- f ~* pconst (S n) (S m) := -- begin -- assert H : is_contr (Ω[n] (S m)), -- { apply homotopy_group_sphere_le, }, -- apply phomotopy_of_eq, -- apply inj !sphere_pmap_pequiv, -- apply @is_prop.elim -- end end sphere namespace paths variables {A : Type} {R : A → A → Type} {a₁ a₂ a₃ a₄ : A} definition mem_equiv_Exists (l : R a₁ a₂) (p : paths R a₃ a₄) : mem l p ≃ Exists (λa a' r, ⟨a₁, a₂, l⟩ = ⟨a, a', r⟩) p := sorry end paths
e1def7b68875133c4254a0b07717f2035a7a682c
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Meta/FunInfo.lean
9194fa7bd53f96b0672ea20cba3a653228af9ebf
[ "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
4,266
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.Basic import Lean.Meta.InferType namespace Lean.Meta @[inline] private def checkFunInfoCache (fn : Expr) (maxArgs? : Option Nat) (k : MetaM FunInfo) : MetaM FunInfo := do let t ← getTransparency match (← get).cache.funInfo.find? ⟨t, fn, maxArgs?⟩ with | some finfo => pure finfo | none => do let finfo ← k modify fun s => { s with cache := { s.cache with funInfo := s.cache.funInfo.insert ⟨t, fn, maxArgs?⟩ finfo } } pure finfo @[inline] private def whenHasVar {α} (e : Expr) (deps : α) (k : α → α) : α := if e.hasFVar then k deps else deps private def collectDeps (fvars : Array Expr) (e : Expr) : Array Nat := let rec visit (e : Expr) (deps : Array Nat) : Array Nat := match e with | .app f a => whenHasVar e deps (visit a ∘ visit f) | .forallE _ d b _ => whenHasVar e deps (visit b ∘ visit d) | .lam _ d b _ => whenHasVar e deps (visit b ∘ visit d) | .letE _ t v b _ => whenHasVar e deps (visit b ∘ visit v ∘ visit t) | .proj _ _ e => visit e deps | .mdata _ e => visit e deps | .fvar .. => match fvars.indexOf? e with | none => deps | some i => if deps.contains i.val then deps else deps.push i.val | _ => deps let deps := visit e #[] deps.qsort (fun i j => i < j) /-- Update `hasFwdDeps` fields using new `backDeps` -/ private def updateHasFwdDeps (pinfo : Array ParamInfo) (backDeps : Array Nat) : Array ParamInfo := if backDeps.size == 0 then pinfo else -- update hasFwdDeps fields pinfo.mapIdx fun i info => if info.hasFwdDeps then info else if backDeps.contains i then { info with hasFwdDeps := true } else info private def getFunInfoAux (fn : Expr) (maxArgs? : Option Nat) : MetaM FunInfo := checkFunInfoCache fn maxArgs? do let fnType ← inferType fn withTransparency TransparencyMode.default do forallBoundedTelescope fnType maxArgs? fun fvars type => do let mut paramInfo := #[] let mut higherOrderOutParams : FVarIdSet := {} for i in [:fvars.size] do let fvar := fvars[i]! let decl ← getFVarLocalDecl fvar let backDeps := collectDeps fvars decl.type let dependsOnHigherOrderOutParam := !higherOrderOutParams.isEmpty && Option.isSome (decl.type.find? fun e => e.isFVar && higherOrderOutParams.contains e.fvarId!) paramInfo := updateHasFwdDeps paramInfo backDeps paramInfo := paramInfo.push { backDeps, dependsOnHigherOrderOutParam binderInfo := decl.binderInfo isProp := (← isProp decl.type) isDecInst := (← forallTelescopeReducing decl.type fun _ type => return type.isAppOf ``Decidable) } if decl.binderInfo == .instImplicit then /- Collect higher order output parameters of this class -/ if let some className ← isClass? decl.type then if let some outParamPositions := getOutParamPositions? (← getEnv) className then unless outParamPositions.isEmpty do let args := decl.type.getAppArgs for i in [:args.size] do if outParamPositions.contains i then let arg := args[i]! if let some idx := fvars.indexOf? arg then if (← whnf (← inferType arg)).isForall then paramInfo := paramInfo.modify idx fun info => { info with higherOrderOutParam := true } higherOrderOutParams := higherOrderOutParams.insert arg.fvarId! let resultDeps := collectDeps fvars type paramInfo := updateHasFwdDeps paramInfo resultDeps return { resultDeps, paramInfo } def getFunInfo (fn : Expr) : MetaM FunInfo := getFunInfoAux fn none def getFunInfoNArgs (fn : Expr) (nargs : Nat) : MetaM FunInfo := getFunInfoAux fn (some nargs) def FunInfo.getArity (info : FunInfo) : Nat := info.paramInfo.size end Lean.Meta
4bcac42eb2204af871c5463264cf3b50ed60c651
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/algebra/monoid_algebra/degree.lean
a15a552b8fba11224d050d1de713583fe74b0b16
[ "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
6,478
lean
/- Copyright (c) 2022 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import algebra.monoid_algebra.basic /-! # Lemmas about the `sup` and `inf` of the support of `add_monoid_algebra` ## TODO The current plan is to state and prove lemmas about `finset.sup (finsupp.support f) D` with a "generic" degree/weight function `D` from the grading Type `A` to a somewhat ordered Type `B`. Next, the general lemmas get specialized for some yet-to-be-defined `degree`s. -/ variables {R A T B ι : Type*} namespace add_monoid_algebra open_locale classical big_operators /-! ### Results about the `finset.sup` and `finset.inf` of `finsupp.support` -/ section general_results_assuming_semilattice_sup variables [semilattice_sup B] [order_bot B] [semilattice_inf T] [order_top T] section semiring variables [semiring R] section explicit_degrees /-! In this section, we use `degb` and `degt` to denote "degree functions" on `A` with values in a type with *b*ot or *t*op respectively. -/ variables (degb : A → B) (degt : A → T) (f g : add_monoid_algebra R A) lemma sup_support_add_le : (f + g).support.sup degb ≤ (f.support.sup degb) ⊔ (g.support.sup degb) := (finset.sup_mono finsupp.support_add).trans_eq finset.sup_union lemma le_inf_support_add : f.support.inf degt ⊓ g.support.inf degt ≤ (f + g).support.inf degt := sup_support_add_le (λ a : A, order_dual.to_dual (degt a)) f g end explicit_degrees section add_only variables [has_add A] [has_add B] [has_add T] [covariant_class B B (+) (≤)] [covariant_class B B (function.swap (+)) (≤)] [covariant_class T T (+) (≤)] [covariant_class T T (function.swap (+)) (≤)] lemma sup_support_mul_le {degb : A → B} (degbm : ∀ {a b}, degb (a + b) ≤ degb a + degb b) (f g : add_monoid_algebra R A) : (f * g).support.sup degb ≤ f.support.sup degb + g.support.sup degb := begin refine (finset.sup_mono $ support_mul _ _).trans _, simp_rw [finset.sup_bUnion, finset.sup_singleton], refine (finset.sup_le $ λ fd fds, finset.sup_le $ λ gd gds, degbm.trans $ add_le_add _ _); exact finset.le_sup ‹_›, end lemma le_inf_support_mul {degt : A → T} (degtm : ∀ {a b}, degt a + degt b ≤ degt (a + b)) (f g : add_monoid_algebra R A) : f.support.inf degt + g.support.inf degt ≤ (f * g).support.inf degt := order_dual.of_dual_le_of_dual.mpr $ sup_support_mul_le (λ a b, order_dual.of_dual_le_of_dual.mp degtm) f g end add_only section add_monoids variables [add_monoid A] [add_monoid B] [covariant_class B B (+) (≤)] [covariant_class B B (function.swap (+)) (≤)] [add_monoid T] [covariant_class T T (+) (≤)] [covariant_class T T (function.swap (+)) (≤)] {degb : A → B} {degt : A → T} lemma sup_support_list_prod_le (degb0 : degb 0 ≤ 0) (degbm : ∀ a b, degb (a + b) ≤ degb a + degb b) : ∀ l : list (add_monoid_algebra R A), l.prod.support.sup degb ≤ (l.map (λ f : add_monoid_algebra R A, f.support.sup degb)).sum | [] := begin rw [list.map_nil, finset.sup_le_iff, list.prod_nil, list.sum_nil], exact λ a ha, by rwa [finset.mem_singleton.mp (finsupp.support_single_subset ha)] end | (f::fs) := begin rw [list.prod_cons, list.map_cons, list.sum_cons], exact (sup_support_mul_le degbm _ _).trans (add_le_add_left (sup_support_list_prod_le _) _) end lemma le_inf_support_list_prod (degt0 : 0 ≤ degt 0) (degtm : ∀ a b, degt a + degt b ≤ degt (a + b)) (l : list (add_monoid_algebra R A)) : (l.map (λ f : add_monoid_algebra R A, f.support.inf degt)).sum ≤ l.prod.support.inf degt := order_dual.of_dual_le_of_dual.mpr $ sup_support_list_prod_le (order_dual.of_dual_le_of_dual.mp degt0) (λ a b, order_dual.of_dual_le_of_dual.mp (degtm _ _)) l lemma sup_support_pow_le (degb0 : degb 0 ≤ 0) (degbm : ∀ a b, degb (a + b) ≤ degb a + degb b) (n : ℕ) (f : add_monoid_algebra R A) : (f ^ n).support.sup degb ≤ n • (f.support.sup degb) := begin rw [← list.prod_repeat, ←list.sum_repeat], refine (sup_support_list_prod_le degb0 degbm _).trans_eq _, rw list.map_repeat, end lemma le_inf_support_pow (degt0 : 0 ≤ degt 0) (degtm : ∀ a b, degt a + degt b ≤ degt (a + b)) (n : ℕ) (f : add_monoid_algebra R A) : n • (f.support.inf degt) ≤ (f ^ n).support.inf degt := order_dual.of_dual_le_of_dual.mpr $ sup_support_pow_le (order_dual.of_dual_le_of_dual.mp degt0) (λ a b, order_dual.of_dual_le_of_dual.mp (degtm _ _)) n f end add_monoids end semiring section commutative_lemmas variables [comm_semiring R] [add_comm_monoid A] [add_comm_monoid B] [covariant_class B B (+) (≤)] [covariant_class B B (function.swap (+)) (≤)] [add_comm_monoid T] [covariant_class T T (+) (≤)] [covariant_class T T (function.swap (+)) (≤)] {degb : A → B} {degt : A → T} lemma sup_support_multiset_prod_le (degb0 : degb 0 ≤ 0) (degbm : ∀ a b, degb (a + b) ≤ degb a + degb b) (m : multiset (add_monoid_algebra R A)) : m.prod.support.sup degb ≤ (m.map (λ f : add_monoid_algebra R A, f.support.sup degb)).sum := begin induction m using quot.induction_on, rw [multiset.quot_mk_to_coe'', multiset.coe_map, multiset.coe_sum, multiset.coe_prod], exact sup_support_list_prod_le degb0 degbm m, end lemma le_inf_support_multiset_prod (degt0 : 0 ≤ degt 0) (degtm : ∀ a b, degt a + degt b ≤ degt (a + b)) (m : multiset (add_monoid_algebra R A)) : (m.map (λ f : add_monoid_algebra R A, f.support.inf degt)).sum ≤ m.prod.support.inf degt := order_dual.of_dual_le_of_dual.mpr $ sup_support_multiset_prod_le (order_dual.of_dual_le_of_dual.mp degt0) (λ a b, order_dual.of_dual_le_of_dual.mp (degtm _ _)) m lemma sup_support_finset_prod_le (degb0 : degb 0 ≤ 0) (degbm : ∀ a b, degb (a + b) ≤ degb a + degb b) (s : finset ι) (f : ι → add_monoid_algebra R A) : (∏ i in s, f i).support.sup degb ≤ ∑ i in s, (f i).support.sup degb := (sup_support_multiset_prod_le degb0 degbm _).trans_eq $ congr_arg _ $ multiset.map_map _ _ _ lemma le_inf_support_finset_prod (degt0 : 0 ≤ degt 0) (degtm : ∀ a b, degt a + degt b ≤ degt (a + b)) (s : finset ι) (f : ι → add_monoid_algebra R A) : ∑ i in s, (f i).support.inf degt ≤ (∏ i in s, f i).support.inf degt := le_of_eq_of_le (by rw [multiset.map_map]; refl) (le_inf_support_multiset_prod degt0 degtm _) end commutative_lemmas end general_results_assuming_semilattice_sup end add_monoid_algebra
cfef148bc94c6ce6abd5c0d6f4e62a21cb75dcd9
e0b0b1648286e442507eb62344760d5cd8d13f2d
/tests/lean/run/KyleAlg.lean
3fa5330d0b9f434dffe6fc4c5aa286733c9e6c63
[ "Apache-2.0" ]
permissive
MULXCODE/lean4
743ed389e05e26e09c6a11d24607ad5a697db39b
4675817a9e89824eca37192364cd47a4027c6437
refs/heads/master
1,682,231,879,857
1,620,423,501,000
1,620,423,501,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,485
lean
import Lean /- from core: class OfNat (α : Type u) (n : Nat) where ofNat : α class Mul (α : Type u) where mul : α → α → α class Add (α : Type u) where add : α → α → α -/ class Inv (α : Type u) where inv : α → α postfix:max "⁻¹" => Inv.inv class One (α : Type u) where one : α export One (one) instance [One α] : OfNat α (nat_lit 1) where ofNat := one class Zero (α : Type u) where zero : α export Zero (zero) instance [Zero α] : OfNat α (nat_lit 0) where ofNat := zero class MulComm (α : Type u) [Mul α] : Prop where mulComm : {a b : α} → a * b = b * a export MulComm (mulComm) class MulAssoc (α : Type u) [Mul α] : Prop where mulAssoc : {a b c : α} → a * b * c = a * (b * c) export MulAssoc (mulAssoc) class OneUnit (α : Type u) [Mul α] [One α] : Prop where oneMul : {a : α} → 1 * a = a mulOne : {a : α} → a * 1 = a export OneUnit (oneMul mulOne) class AddComm (α : Type u) [Add α] : Prop where addComm : {a b : α} → a + b = b + a export AddComm (addComm) class AddAssoc (α : Type u) [Add α] : Prop where addAssoc : {a b c : α} → a + b + c = a + (b + c) export AddAssoc (addAssoc) class ZeroUnit (α : Type u) [Add α] [Zero α] : Prop where zeroAdd : {a : α} → 0 + a = a addZero : {a : α} → a + 0 = a export ZeroUnit (zeroAdd addZero) class InvMul (α : Type u) [Mul α] [One α] [Inv α] : Prop where invMul : {a : α} → a⁻¹ * a = 1 export InvMul (invMul) class NegAdd (α : Type u) [Add α] [Zero α] [Neg α] : Prop where negAdd : {a : α} → -a + a = 0 export NegAdd (negAdd) class ZeroMul (α : Type u) [Mul α] [Zero α] : Prop where zeroMul : {a : α} → 0 * a = 0 export ZeroMul (zeroMul) class Distrib (α : Type u) [Add α] [Mul α] : Prop where leftDistrib : {a b c : α} → a * (b + c) = a * b + a * c rightDistrib : {a b c : α} → (a + b) * c = a * c + b * c export Distrib (leftDistrib rightDistrib) class Domain (α : Type u) [Mul α] [Zero α] : Prop where eqZeroOrEqZeroOfMulEqZero : {a b : α} → a * b = 0 → a = 0 ∨ b = 0 export Domain (eqZeroOrEqZeroOfMulEqZero) class Semigroup (α : Type u) extends Mul α, MulAssoc α attribute [instance] Semigroup.mk class AddSemigroup (α : Type u) extends Add α, AddAssoc α attribute [instance] AddSemigroup.mk class Monoid (α : Type u) extends Semigroup α, One α, OneUnit α attribute [instance] Monoid.mk class AddMonoid (α : Type u) extends AddSemigroup α, Zero α, ZeroUnit α attribute [instance] AddMonoid.mk class CommSemigroup (α : Type u) extends Semigroup α, MulComm α attribute [instance] CommSemigroup.mk class CommMonoid (α : Type u) extends Monoid α, MulComm α attribute [instance] CommMonoid.mk class Group (α : Type u) extends Monoid α, Inv α, InvMul α attribute [instance] Group.mk class AddGroup (α : Type u) extends AddMonoid α, Neg α, NegAdd α attribute [instance] AddGroup.mk class Semiring (α : Type u) extends AddMonoid α, Monoid α, AddComm α, ZeroMul α, Distrib α attribute [instance] Semiring.mk class Ring (α : Type u) extends AddGroup α, Monoid α, AddComm α, Distrib α attribute [instance] Ring.mk class CommRing (α : Type u) extends Ring α, MulComm α attribute [instance] CommRing.mk class IntegralDomain (α : Type u) extends CommRing α, Domain α attribute [instance] IntegralDomain.mk section test1 variable (α : Type u) [h : CommMonoid α] example : Semigroup α := inferInstance example : Monoid α := inferInstance example : CommSemigroup α := inferInstance end test1 section test2 variable (β : Type u) [CommSemigroup β] [One β] [OneUnit β] example : Monoid β := inferInstance example : CommMonoid β := inferInstance example : Semigroup β := inferInstance end test2 section test3 variable (β : Type u) [Mul β] [One β] [MulAssoc β] [OneUnit β] example : Monoid β := inferInstance example : Semigroup β := inferInstance end test3 theorem negZero [AddGroup α] : -(0 : α) = 0 := by rw [←addZero (a := -(0 : α)), negAdd] theorem subZero [AddGroup α] {a : α} : a + -(0 : α) = a := by rw [←addZero (a := a), addAssoc, negZero, addZero] theorem negNeg [AddGroup α] {a : α} : -(-a) = a := by { rw [←addZero (a := - -a)]; rw [←negAdd (a := a)]; rw [←addAssoc]; rw [negAdd]; rw [zeroAdd]; } theorem addNeg [AddGroup α] {a : α} : a + -a = 0 := by { have h : - -a + -a = 0 := by { rw [negAdd] }; rw [negNeg] at h; exact h } theorem addIdemIffZero [AddGroup α] {a : α} : a + a = a ↔ a = 0 := by apply Iff.intro focus intro h have h' := congrArg (λ x => x + -a) h simp at h' rw [addAssoc, addNeg, addZero] at h' exact h' focus intro h subst a rw [addZero] instance [Ring α] : ZeroMul α := by { apply ZeroMul.mk; intro a; have h : 0 * a + 0 * a = 0 * a := by { rw [←rightDistrib, addZero] }; rw [addIdemIffZero (a := 0 * a)] at h; rw [h]; } example [Ring α] : Semiring α := inferInstance section prod instance [Mul α] [Mul β] : Mul (α × β) where mul p p' := (p.1 * p'.1, p.2 * p'.2) instance [Inv α] [Inv β] : Inv (α × β) where inv p := (p.1⁻¹, p.2⁻¹) instance [One α] [One β] : One (α × β) where one := (1, 1) theorem Product.ext : {p q : α × β} → p.1 = q.1 → p.2 = q.2 → p = q | (a, b), (c, d) => by simp; intro h; subst a; intro h; subst b; rfl instance [Semigroup α] [Semigroup β] : Semigroup (α × β) where mulAssoc := by intros apply Product.ext apply mulAssoc apply mulAssoc instance [Monoid α] [Monoid β] : Monoid (α × β) where oneMul := by intros apply Product.ext apply oneMul apply oneMul mulOne := by intros apply Product.ext apply mulOne apply mulOne instance [Group α] [Group β] : Group (α × β) where invMul := by intros apply Product.ext apply invMul apply invMul end prod def test1 {G : Type _} [Group G]: Group (G) := inferInstance def test2 {G : Type _} [Group G]: Group (G × G) := inferInstance def test3 {G : Type _} [Group G]: Group (G × G × G) := inferInstance def test4 {G : Type _} [Group G]: Group (G × G × G × G) := inferInstance def test5 {G : Type _} [Group G]: Group (G × G × G × G × G) := inferInstance def test6 {G : Type _} [Group G]: Group (G × G × G × G × G × G) := inferInstance def test7 {G : Type _} [Group G]: Group (G × G × G × G × G × G × G) := inferInstance def test8 {G : Type _} [Group G]: Group (G × G × G × G × G × G × G × G) := inferInstance namespace Lean unsafe def Expr.dagSizeUnsafe (e : Expr) : IO Nat := do let (_, s) ← visit e |>.run ({}, 0) return s.2 where visit (e : Expr) : StateRefT (Std.HashSet USize × Nat) IO Unit := do let addr := ptrAddrUnsafe e unless (← get).1.contains addr do modify fun (s, c) => (s.insert addr, c+1) match e with | Expr.proj _ _ s _ => visit s | Expr.forallE _ d b _ => visit d; visit b | Expr.lam _ d b _ => visit d; visit b | Expr.letE _ t v b _ => visit t; visit v; visit b | Expr.app f a _ => visit f; visit a | Expr.mdata _ b _ => visit b | _ => return () @[implementedBy Expr.dagSizeUnsafe] constant Expr.dagSize (e : Expr) : IO Nat def getDeclTypeValueDagSize (declName : Name) : CoreM Nat := do let info ← getConstInfo declName let n ← info.type.dagSize match info.value? with | none => return n | some v => return n + (← v.dagSize) #eval getDeclTypeValueDagSize `test2 #eval getDeclTypeValueDagSize `test3 #eval getDeclTypeValueDagSize `test4 #eval getDeclTypeValueDagSize `test5 #eval getDeclTypeValueDagSize `test6 #eval getDeclTypeValueDagSize `test7 #eval getDeclTypeValueDagSize `test8 def reduceAndGetDagSize (declName : Name) : MetaM Nat := do let c := mkConst declName [levelOne] let e ← Meta.reduce c trace[Meta.debug] "{e}" e.dagSize #eval reduceAndGetDagSize `test1 #eval reduceAndGetDagSize `test2 #eval reduceAndGetDagSize `test3 #eval reduceAndGetDagSize `test4 #eval reduceAndGetDagSize `test5 #eval reduceAndGetDagSize `test6 #eval reduceAndGetDagSize `test7 -- Use `set_option` to trace the reduced term set_option pp.all true in set_option trace.Meta.debug true in #eval reduceAndGetDagSize `test8
b474e973ff9b7ea2540330969ade4113ad6368d5
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/list/cycle.lean
4453b9a2cfbf88741433582997ed7dea0eee4468
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,210
lean
/- Copyright (c) 2021 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import data.list.rotate import data.finset.sort import data.fintype.list /-! # Cycles of a list Lists have an equivalence relation of whether they are rotational permutations of one another. This relation is defined as `is_rotated`. Based on this, we define the quotient of lists by the rotation relation, called `cycle`. We also define a representation of concrete cycles, available when viewing them in a goal state or via `#eval`, when over representatble types. For example, the cycle `(2 1 4 3)` will be shown as `c[1, 4, 3, 2]`. The representation of the cycle sorts the elements by the string value of the underlying element. This representation also supports cycles that can contain duplicates. -/ namespace list variables {α : Type*} [decidable_eq α] /-- Return the `z` such that `x :: z :: _` appears in `xs`, or `default` if there is no such `z`. -/ def next_or : Π (xs : list α) (x default : α), α | [] x default := default | [y] x default := default -- Handles the not-found and the wraparound case | (y :: z :: xs) x default := if x = y then z else next_or (z :: xs) x default @[simp] lemma next_or_nil (x d : α) : next_or [] x d = d := rfl @[simp] lemma next_or_singleton (x y d : α) : next_or [y] x d = d := rfl @[simp] lemma next_or_self_cons_cons (xs : list α) (x y d : α) : next_or (x :: y :: xs) x d = y := if_pos rfl lemma next_or_cons_of_ne (xs : list α) (y x d : α) (h : x ≠ y) : next_or (y :: xs) x d = next_or xs x d := begin cases xs with z zs, { refl }, { exact if_neg h } end /-- `next_or` does not depend on the default value, if the next value appears. -/ lemma next_or_eq_next_or_of_mem_of_ne (xs : list α) (x d d' : α) (x_mem : x ∈ xs) (x_ne : x ≠ xs.last (ne_nil_of_mem x_mem)) : next_or xs x d = next_or xs x d' := begin induction xs with y ys IH, { cases x_mem }, cases ys with z zs, { simp at x_mem x_ne, contradiction }, by_cases h : x = y, { rw [h, next_or_self_cons_cons, next_or_self_cons_cons] }, { rw [next_or, next_or, IH]; simpa [h] using x_mem } end lemma mem_of_next_or_ne {xs : list α} {x d : α} (h : next_or xs x d ≠ d) : x ∈ xs := begin induction xs with y ys IH, { simpa using h }, cases ys with z zs, { simpa using h }, { by_cases hx : x = y, { simp [hx] }, { rw [next_or_cons_of_ne _ _ _ _ hx] at h, simpa [hx] using IH h } } end lemma next_or_concat {xs : list α} {x : α} (d : α) (h : x ∉ xs) : next_or (xs ++ [x]) x d = d := begin induction xs with z zs IH, { simp }, { obtain ⟨hz, hzs⟩ := not_or_distrib.mp (mt (mem_cons_iff _ _ _).mp h), rw [cons_append, next_or_cons_of_ne _ _ _ _ hz, IH hzs] } end lemma next_or_mem {xs : list α} {x d : α} (hd : d ∈ xs) : next_or xs x d ∈ xs := begin revert hd, suffices : ∀ (xs' : list α) (h : ∀ x ∈ xs, x ∈ xs') (hd : d ∈ xs'), next_or xs x d ∈ xs', { exact this xs (λ _, id) }, intros xs' hxs' hd, induction xs with y ys ih, { exact hd }, cases ys with z zs, { exact hd }, rw next_or, split_ifs with h, { exact hxs' _ (mem_cons_of_mem _ (mem_cons_self _ _)) }, { exact ih (λ _ h, hxs' _ (mem_cons_of_mem _ h)) }, end /-- Given an element `x : α` of `l : list α` such that `x ∈ l`, get the next element of `l`. This works from head to tail, (including a check for last element) so it will match on first hit, ignoring later duplicates. For example: * `next [1, 2, 3] 2 _ = 3` * `next [1, 2, 3] 3 _ = 1` * `next [1, 2, 3, 2, 4] 2 _ = 3` * `next [1, 2, 3, 2] 2 _ = 3` * `next [1, 1, 2, 3, 2] 1 _ = 1` -/ def next (l : list α) (x : α) (h : x ∈ l) : α := next_or l x (l.nth_le 0 (length_pos_of_mem h)) /-- Given an element `x : α` of `l : list α` such that `x ∈ l`, get the previous element of `l`. This works from head to tail, (including a check for last element) so it will match on first hit, ignoring later duplicates. * `prev [1, 2, 3] 2 _ = 1` * `prev [1, 2, 3] 1 _ = 3` * `prev [1, 2, 3, 2, 4] 2 _ = 1` * `prev [1, 2, 3, 4, 2] 2 _ = 1` * `prev [1, 1, 2] 1 _ = 2` -/ def prev : Π (l : list α) (x : α) (h : x ∈ l), α | [] _ h := by simpa using h | [y] _ _ := y | (y :: z :: xs) x h := if hx : x = y then (last (z :: xs) (cons_ne_nil _ _)) else if x = z then y else prev (z :: xs) x (by simpa [hx] using h) variables (l : list α) (x : α) (h : x ∈ l) @[simp] lemma next_singleton (x y : α) (h : x ∈ [y]) : next [y] x h = y := rfl @[simp] lemma prev_singleton (x y : α) (h : x ∈ [y]) : prev [y] x h = y := rfl lemma next_cons_cons_eq' (y z : α) (h : x ∈ (y :: z :: l)) (hx : x = y) : next (y :: z :: l) x h = z := by rw [next, next_or, if_pos hx] @[simp] lemma next_cons_cons_eq (z : α) (h : x ∈ (x :: z :: l)) : next (x :: z :: l) x h = z := next_cons_cons_eq' l x x z h rfl lemma next_ne_head_ne_last (y : α) (h : x ∈ (y :: l)) (hy : x ≠ y) (hx : x ≠ last (y :: l) (cons_ne_nil _ _)) : next (y :: l) x h = next l x (by simpa [hy] using h) := begin rw [next, next, next_or_cons_of_ne _ _ _ _ hy, next_or_eq_next_or_of_mem_of_ne], { rwa last_cons at hx }, { simpa [hy] using h } end lemma next_cons_concat (y : α) (hy : x ≠ y) (hx : x ∉ l) (h : x ∈ y :: l ++ [x] := mem_append_right _ (mem_singleton_self x)) : next (y :: l ++ [x]) x h = y := begin rw [next, next_or_concat], { refl }, { simp [hy, hx] } end lemma next_last_cons (y : α) (h : x ∈ (y :: l)) (hy : x ≠ y) (hx : x = last (y :: l) (cons_ne_nil _ _)) (hl : nodup l) : next (y :: l) x h = y := begin rw [next, nth_le, ←init_append_last (cons_ne_nil y l), hx, next_or_concat], subst hx, intro H, obtain ⟨_ | k, hk, hk'⟩ := nth_le_of_mem H, { simpa [init_eq_take, nth_le_take', hy.symm] using hk' }, suffices : k.succ = l.length, { simpa [this] using hk }, cases l with hd tl, { simpa using hk }, { rw nodup_iff_nth_le_inj at hl, rw [length, nat.succ_inj'], apply hl, simpa [init_eq_take, nth_le_take', last_eq_nth_le] using hk' } end lemma prev_last_cons' (y : α) (h : x ∈ (y :: l)) (hx : x = y) : prev (y :: l) x h = last (y :: l) (cons_ne_nil _ _) := begin cases l; simp [prev, hx] end @[simp] lemma prev_last_cons (h : x ∈ (x :: l)) : prev (x :: l) x h = last (x :: l) (cons_ne_nil _ _) := prev_last_cons' l x x h rfl lemma prev_cons_cons_eq' (y z : α) (h : x ∈ (y :: z :: l)) (hx : x = y) : prev (y :: z :: l) x h = last (z :: l) (cons_ne_nil _ _) := by rw [prev, dif_pos hx] @[simp] lemma prev_cons_cons_eq (z : α) (h : x ∈ (x :: z :: l)) : prev (x :: z :: l) x h = last (z :: l) (cons_ne_nil _ _) := prev_cons_cons_eq' l x x z h rfl lemma prev_cons_cons_of_ne' (y z : α) (h : x ∈ (y :: z :: l)) (hy : x ≠ y) (hz : x = z) : prev (y :: z :: l) x h = y := begin cases l, { simp [prev, hy, hz] }, { rw [prev, dif_neg hy, if_pos hz] } end lemma prev_cons_cons_of_ne (y : α) (h : x ∈ (y :: x :: l)) (hy : x ≠ y) : prev (y :: x :: l) x h = y := prev_cons_cons_of_ne' _ _ _ _ _ hy rfl lemma prev_ne_cons_cons (y z : α) (h : x ∈ (y :: z :: l)) (hy : x ≠ y) (hz : x ≠ z) : prev (y :: z :: l) x h = prev (z :: l) x (by simpa [hy] using h) := begin cases l, { simpa [hy, hz] using h }, { rw [prev, dif_neg hy, if_neg hz] } end include h lemma next_mem : l.next x h ∈ l := next_or_mem (nth_le_mem _ _ _) lemma prev_mem : l.prev x h ∈ l := begin cases l with hd tl, { simpa using h }, induction tl with hd' tl hl generalizing hd, { simp }, { by_cases hx : x = hd, { simp only [hx, prev_cons_cons_eq], exact mem_cons_of_mem _ (last_mem _) }, { rw [prev, dif_neg hx], split_ifs with hm, { exact mem_cons_self _ _ }, { exact mem_cons_of_mem _ (hl _ _) } } } end lemma next_nth_le (l : list α) (h : nodup l) (n : ℕ) (hn : n < l.length) : next l (l.nth_le n hn) (nth_le_mem _ _ _) = l.nth_le ((n + 1) % l.length) (nat.mod_lt _ (n.zero_le.trans_lt hn)) := begin cases l with x l, { simpa using hn }, induction l with y l hl generalizing x n, { simp }, { cases n, { simp }, { have hn' : n.succ ≤ l.length.succ, { refine nat.succ_le_of_lt _, simpa [nat.succ_lt_succ_iff] using hn }, have hx': (x :: y :: l).nth_le n.succ hn ≠ x, { intro H, suffices : n.succ = 0, { simpa }, rw nodup_iff_nth_le_inj at h, refine h _ _ hn nat.succ_pos' _, simpa using H }, rcases hn'.eq_or_lt with hn''|hn'', { rw [next_last_cons], { simp [hn''] }, { exact hx' }, { simp [last_eq_nth_le, hn''] }, { exact nodup_of_nodup_cons h } }, { have : n < l.length := by simpa [nat.succ_lt_succ_iff] using hn'' , rw [next_ne_head_ne_last _ _ _ _ hx'], { simp [nat.mod_eq_of_lt (nat.succ_lt_succ (nat.succ_lt_succ this)), hl _ _ (nodup_of_nodup_cons h), nat.mod_eq_of_lt (nat.succ_lt_succ this)] }, { rw last_eq_nth_le, intro H, suffices : n.succ = l.length.succ, { exact absurd hn'' this.ge.not_lt }, rw nodup_iff_nth_le_inj at h, refine h _ _ hn _ _, { simp }, { simpa using H } } } } } end lemma prev_nth_le (l : list α) (h : nodup l) (n : ℕ) (hn : n < l.length) : prev l (l.nth_le n hn) (nth_le_mem _ _ _) = l.nth_le ((n + (l.length - 1)) % l.length) (nat.mod_lt _ (n.zero_le.trans_lt hn)) := begin cases l with x l, { simpa using hn }, induction l with y l hl generalizing n x, { simp }, { rcases n with _|_|n, { simpa [last_eq_nth_le, nat.mod_eq_of_lt (nat.succ_lt_succ l.length.lt_succ_self)] }, { simp only [mem_cons_iff, nodup_cons] at h, push_neg at h, simp [add_comm, prev_cons_cons_of_ne, h.left.left.symm] }, { rw [prev_ne_cons_cons], { convert hl _ _ (nodup_of_nodup_cons h) _ using 1, have : ∀ k hk, (y :: l).nth_le k hk = (x :: y :: l).nth_le (k + 1) (nat.succ_lt_succ hk), { intros, simpa }, rw [this], congr, simp only [nat.add_succ_sub_one, add_zero, length], simp only [length, nat.succ_lt_succ_iff] at hn, set k := l.length, rw [nat.succ_add, ←nat.add_succ, nat.add_mod_right, nat.succ_add, ←nat.add_succ _ k, nat.add_mod_right, nat.mod_eq_of_lt, nat.mod_eq_of_lt], { exact nat.lt_succ_of_lt hn }, { exact nat.succ_lt_succ (nat.lt_succ_of_lt hn) } }, { intro H, suffices : n.succ.succ = 0, { simpa }, rw nodup_iff_nth_le_inj at h, refine h _ _ hn nat.succ_pos' _, simpa using H }, { intro H, suffices : n.succ.succ = 1, { simpa }, rw nodup_iff_nth_le_inj at h, refine h _ _ hn (nat.succ_lt_succ nat.succ_pos') _, simpa using H } } } end lemma pmap_next_eq_rotate_one (h : nodup l) : l.pmap l.next (λ _ h, h) = l.rotate 1 := begin apply list.ext_le, { simp }, { intros, rw [nth_le_pmap, nth_le_rotate, next_nth_le _ h] } end lemma pmap_prev_eq_rotate_length_sub_one (h : nodup l) : l.pmap l.prev (λ _ h, h) = l.rotate (l.length - 1) := begin apply list.ext_le, { simp }, { intros n hn hn', rw [nth_le_rotate, nth_le_pmap, prev_nth_le _ h] } end lemma prev_next (l : list α) (h : nodup l) (x : α) (hx : x ∈ l) : prev l (next l x hx) (next_mem _ _ _) = x := begin obtain ⟨n, hn, rfl⟩ := nth_le_of_mem hx, simp only [next_nth_le, prev_nth_le, h, nat.mod_add_mod], cases l with hd tl, { simp }, { have : n < 1 + tl.length := by simpa [add_comm] using hn, simp [add_left_comm, add_comm, add_assoc, nat.mod_eq_of_lt this] } end lemma next_prev (l : list α) (h : nodup l) (x : α) (hx : x ∈ l) : next l (prev l x hx) (prev_mem _ _ _) = x := begin obtain ⟨n, hn, rfl⟩ := nth_le_of_mem hx, simp only [next_nth_le, prev_nth_le, h, nat.mod_add_mod], cases l with hd tl, { simp }, { have : n < 1 + tl.length := by simpa [add_comm] using hn, simp [add_left_comm, add_comm, add_assoc, nat.mod_eq_of_lt this] } end lemma prev_reverse_eq_next (l : list α) (h : nodup l) (x : α) (hx : x ∈ l) : prev l.reverse x (mem_reverse.mpr hx) = next l x hx := begin obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx, have lpos : 0 < l.length := k.zero_le.trans_lt hk, have key : l.length - 1 - k < l.length := (nat.sub_le _ _).trans_lt (sub_lt_self' lpos nat.succ_pos'), rw ←nth_le_pmap l.next (λ _ h, h) (by simpa using hk), simp_rw [←nth_le_reverse l k (key.trans_le (by simp)), pmap_next_eq_rotate_one _ h], rw ←nth_le_pmap l.reverse.prev (λ _ h, h), { simp_rw [pmap_prev_eq_rotate_length_sub_one _ (nodup_reverse.mpr h), rotate_reverse, length_reverse, nat.mod_eq_of_lt (sub_lt_self' lpos nat.succ_pos'), nat.sub_sub_self (nat.succ_le_of_lt lpos)], rw ←nth_le_reverse, { simp [nat.sub_sub_self (nat.le_pred_of_lt hk)] }, { simpa using (nat.sub_le _ _).trans_lt (sub_lt_self' lpos nat.succ_pos') } }, { simpa using (nat.sub_le _ _).trans_lt (sub_lt_self' lpos nat.succ_pos') } end lemma next_reverse_eq_prev (l : list α) (h : nodup l) (x : α) (hx : x ∈ l) : next l.reverse x (mem_reverse.mpr hx) = prev l x hx := begin convert (prev_reverse_eq_next l.reverse (nodup_reverse.mpr h) x (mem_reverse.mpr hx)).symm, exact (reverse_reverse l).symm end lemma is_rotated_next_eq {l l' : list α} (h : l ~r l') (hn : nodup l) {x : α} (hx : x ∈ l) : l.next x hx = l'.next x (h.mem_iff.mp hx) := begin obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx, obtain ⟨n, rfl⟩ := id h, rw [next_nth_le _ hn], simp_rw ←nth_le_rotate' _ n k, rw [next_nth_le _ (h.nodup_iff.mp hn), ←nth_le_rotate' _ n], simp [add_assoc] end lemma is_rotated_prev_eq {l l' : list α} (h : l ~r l') (hn : nodup l) {x : α} (hx : x ∈ l) : l.prev x hx = l'.prev x (h.mem_iff.mp hx) := begin rw [←next_reverse_eq_prev _ hn, ←next_reverse_eq_prev _ (h.nodup_iff.mp hn)], exact is_rotated_next_eq h.reverse (nodup_reverse.mpr hn) _ end end list open list /-- `cycle α` is the quotient of `list α` by cyclic permutation. Duplicates are allowed. -/ def cycle (α : Type*) : Type* := quotient (is_rotated.setoid α) namespace cycle variables {α : Type*} instance : has_coe (list α) (cycle α) := ⟨quot.mk _⟩ @[simp] lemma coe_eq_coe {l₁ l₂ : list α} : (l₁ : cycle α) = l₂ ↔ (l₁ ~r l₂) := @quotient.eq _ (is_rotated.setoid _) _ _ @[simp] lemma mk_eq_coe (l : list α) : quot.mk _ l = (l : cycle α) := rfl @[simp] lemma mk'_eq_coe (l : list α) : quotient.mk' l = (l : cycle α) := rfl instance : inhabited (cycle α) := ⟨(([] : list α) : cycle α)⟩ /-- For `x : α`, `s : cycle α`, `x ∈ s` indicates that `x` occurs at least once in `s`. -/ def mem (a : α) (s : cycle α) : Prop := quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ (e : l₁ ~r l₂), propext $ e.mem_iff) instance : has_mem α (cycle α) := ⟨mem⟩ @[simp] lemma mem_coe_iff {a : α} {l : list α} : a ∈ (l : cycle α) ↔ a ∈ l := iff.rfl instance [decidable_eq α] : decidable_eq (cycle α) := λ s₁ s₂, quotient.rec_on_subsingleton₂' s₁ s₂ (λ l₁ l₂, decidable_of_iff' _ quotient.eq') instance [decidable_eq α] (x : α) (s : cycle α) : decidable (x ∈ s) := quotient.rec_on_subsingleton' s (λ l, list.decidable_mem x l) /-- Reverse a `s : cycle α` by reversing the underlying `list`. -/ def reverse (s : cycle α) : cycle α := quot.map reverse (λ l₁ l₂ (e : l₁ ~r l₂), e.reverse) s @[simp] lemma reverse_coe (l : list α) : (l : cycle α).reverse = l.reverse := rfl @[simp] lemma mem_reverse_iff {a : α} {s : cycle α} : a ∈ s.reverse ↔ a ∈ s := quot.induction_on s (λ _, mem_reverse) @[simp] lemma reverse_reverse (s : cycle α) : s.reverse.reverse = s := quot.induction_on s (λ _, by simp) /-- The length of the `s : cycle α`, which is the number of elements, counting duplicates. -/ def length (s : cycle α) : ℕ := quot.lift_on s length (λ l₁ l₂ (e : l₁ ~r l₂), e.perm.length_eq) @[simp] lemma length_coe (l : list α) : length (l : cycle α) = l.length := rfl @[simp] lemma length_reverse (s : cycle α) : s.reverse.length = s.length := quot.induction_on s length_reverse /-- A `s : cycle α` that is at most one element. -/ def subsingleton (s : cycle α) : Prop := s.length ≤ 1 lemma length_subsingleton_iff {s : cycle α} : subsingleton s ↔ length s ≤ 1 := iff.rfl @[simp] lemma subsingleton_reverse_iff {s : cycle α} : s.reverse.subsingleton ↔ s.subsingleton := by simp [length_subsingleton_iff] lemma subsingleton.congr {s : cycle α} (h : subsingleton s) : ∀ ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s), x = y := begin induction s using quot.induction_on with l, simp only [length_subsingleton_iff, length_coe, mk_eq_coe, le_iff_lt_or_eq, nat.lt_add_one_iff, length_eq_zero, length_eq_one, nat.not_lt_zero, false_or] at h, rcases h with rfl|⟨z, rfl⟩; simp end /-- A `s : cycle α` that is made up of at least two unique elements. -/ def nontrivial (s : cycle α) : Prop := ∃ (x y : α) (h : x ≠ y), x ∈ s ∧ y ∈ s @[simp] lemma nontrivial_coe_nodup_iff {l : list α} (hl : l.nodup) : nontrivial (l : cycle α) ↔ 2 ≤ l.length := begin rw nontrivial, rcases l with (_ | ⟨hd, _ | ⟨hd', tl⟩⟩), { simp }, { simp }, { simp only [mem_cons_iff, exists_prop, mem_coe_iff, list.length, ne.def, nat.succ_le_succ_iff, zero_le, iff_true], refine ⟨hd, hd', _, by simp⟩, simp only [not_or_distrib, mem_cons_iff, nodup_cons] at hl, exact hl.left.left } end @[simp] lemma nontrivial_reverse_iff {s : cycle α} : s.reverse.nontrivial ↔ s.nontrivial := by simp [nontrivial] lemma length_nontrivial {s : cycle α} (h : nontrivial s) : 2 ≤ length s := begin obtain ⟨x, y, hxy, hx, hy⟩ := h, induction s using quot.induction_on with l, rcases l with (_ | ⟨hd, _ | ⟨hd', tl⟩⟩), { simpa using hx }, { simp only [mem_coe_iff, mk_eq_coe, mem_singleton] at hx hy, simpa [hx, hy] using hxy }, { simp [bit0] } end /-- The `s : cycle α` contains no duplicates. -/ def nodup (s : cycle α) : Prop := quot.lift_on s nodup (λ l₁ l₂ (e : l₁ ~r l₂), propext $ e.nodup_iff) @[simp] lemma nodup_coe_iff {l : list α} : nodup (l : cycle α) ↔ l.nodup := iff.rfl @[simp] lemma nodup_reverse_iff {s : cycle α} : s.reverse.nodup ↔ s.nodup := quot.induction_on s (λ _, nodup_reverse) lemma subsingleton.nodup {s : cycle α} (h : subsingleton s) : nodup s := begin induction s using quot.induction_on with l, cases l with hd tl, { simp }, { have : tl = [] := by simpa [subsingleton, length_eq_zero] using h, simp [this] } end lemma nodup.nontrivial_iff {s : cycle α} (h : nodup s) : nontrivial s ↔ ¬ subsingleton s := begin rw length_subsingleton_iff, induction s using quotient.induction_on', simp only [mk'_eq_coe, nodup_coe_iff] at h, simp [h, nat.succ_le_iff] end /-- The `s : cycle α` as a `multiset α`. -/ def to_multiset (s : cycle α) : multiset α := quotient.lift_on' s (λ l, (l : multiset α)) (λ l₁ l₂ (h : l₁ ~r l₂), multiset.coe_eq_coe.mpr h.perm) /-- The lift of `list.map`. -/ def map {β : Type*} (f : α → β) : cycle α → cycle β := quotient.map' (list.map f) $ λ l₁ l₂ h, h.map _ /-- The `multiset` of lists that can make the cycle. -/ def lists (s : cycle α) : multiset (list α) := quotient.lift_on' s (λ l, (l.cyclic_permutations : multiset (list α))) $ λ l₁ l₂ (h : l₁ ~r l₂), by simpa using h.cyclic_permutations.perm @[simp] lemma mem_lists_iff_coe_eq {s : cycle α} {l : list α} : l ∈ s.lists ↔ (l : cycle α) = s := begin induction s using quotient.induction_on', rw [lists, quotient.lift_on'_mk'], simp end section decidable variable [decidable_eq α] /-- Auxiliary decidability algorithm for lists that contain at least two unique elements. -/ def decidable_nontrivial_coe : Π (l : list α), decidable (nontrivial (l : cycle α)) | [] := is_false (by simp [nontrivial]) | [x] := is_false (by simp [nontrivial]) | (x :: y :: l) := if h : x = y then @decidable_of_iff' _ (nontrivial ((x :: l) : cycle α)) (by simp [h, nontrivial]) (decidable_nontrivial_coe (x :: l)) else is_true ⟨x, y, h, by simp, by simp⟩ instance {s : cycle α} : decidable (nontrivial s) := quot.rec_on_subsingleton s decidable_nontrivial_coe instance {s : cycle α} : decidable (nodup s) := quot.rec_on_subsingleton s (λ (l : list α), list.nodup_decidable l) instance fintype_nodup_cycle [fintype α] : fintype {s : cycle α // s.nodup} := fintype.of_surjective (λ (l : {l : list α // l.nodup}), ⟨l.val, by simpa using l.prop⟩) (λ ⟨s, hs⟩, begin induction s using quotient.induction_on', exact ⟨⟨s, hs⟩, by simp⟩ end) instance fintype_nodup_nontrivial_cycle [fintype α] : fintype {s : cycle α // s.nodup ∧ s.nontrivial} := fintype.subtype (((finset.univ : finset {s : cycle α // s.nodup}).map (function.embedding.subtype _)).filter cycle.nontrivial) (by simp) /-- The `s : cycle α` as a `finset α`. -/ def to_finset (s : cycle α) : finset α := s.to_multiset.to_finset /-- Given a `s : cycle α` such that `nodup s`, retrieve the next element after `x ∈ s`. -/ def next : Π (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s), α := λ s, quot.hrec_on s (λ l hn x hx, next l x hx) (λ l₁ l₂ (h : l₁ ~r l₂), function.hfunext (propext h.nodup_iff) (λ h₁ h₂ he, function.hfunext rfl (λ x y hxy, function.hfunext (propext (by simpa [eq_of_heq hxy] using h.mem_iff)) (λ hm hm' he', heq_of_eq (by simpa [eq_of_heq hxy] using is_rotated_next_eq h h₁ _))))) /-- Given a `s : cycle α` such that `nodup s`, retrieve the previous element before `x ∈ s`. -/ def prev : Π (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s), α := λ s, quot.hrec_on s (λ l hn x hx, prev l x hx) (λ l₁ l₂ (h : l₁ ~r l₂), function.hfunext (propext h.nodup_iff) (λ h₁ h₂ he, function.hfunext rfl (λ x y hxy, function.hfunext (propext (by simpa [eq_of_heq hxy] using h.mem_iff)) (λ hm hm' he', heq_of_eq (by simpa [eq_of_heq hxy] using is_rotated_prev_eq h h₁ _))))) @[simp] lemma prev_reverse_eq_next (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) : s.reverse.prev (nodup_reverse_iff.mpr hs) x (mem_reverse_iff.mpr hx) = s.next hs x hx := (quotient.induction_on' s prev_reverse_eq_next) hs x hx @[simp] lemma next_reverse_eq_prev (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) : s.reverse.next (nodup_reverse_iff.mpr hs) x (mem_reverse_iff.mpr hx) = s.prev hs x hx := by simp [←prev_reverse_eq_next] @[simp] lemma next_mem (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) : s.next hs x hx ∈ s := begin induction s using quot.induction_on, exact next_mem _ _ _ end lemma prev_mem (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) : s.prev hs x hx ∈ s := by { rw [←next_reverse_eq_prev, ←mem_reverse_iff], exact next_mem _ _ _ _ } @[simp] lemma prev_next (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) : s.prev hs (s.next hs x hx) (next_mem s hs x hx) = x := (quotient.induction_on' s prev_next) hs x hx @[simp] lemma next_prev (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) : s.next hs (s.prev hs x hx) (prev_mem s hs x hx) = x := (quotient.induction_on' s next_prev) hs x hx end decidable /-- We define a representation of concrete cycles, available when viewing them in a goal state or via `#eval`, when over representatble types. For example, the cycle `(2 1 4 3)` will be shown as `c[1, 4, 3, 2]`. The representation of the cycle sorts the elements by the string value of the underlying element. This representation also supports cycles that can contain duplicates. -/ instance [has_repr α] : has_repr (cycle α) := ⟨λ s, "c[" ++ string.intercalate ", " ((s.map repr).lists.sort (≤)).head ++ "]"⟩ end cycle
a1aa5144d304b35f34239057c9dd8b6aea684dea
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch2/ex0702.lean
95377e4f086e6bbda42986e2ef3f6bc4d8aa4ee0
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
53
lean
#check list.nil #check list.cons #check list.append
3cd24cb1c80c84ba49d169d697c843b8409b553d
682dc1c167e5900ba3168b89700ae1cf501cfa29
/src/basicmodal/semantics/semantics.lean
3468f5a12443c7210e2ef5ac647591fb744f2bf3
[]
no_license
paulaneeley/modal
834558c87f55cdd6d8a29bb46c12f4d1de3239bc
ee5d149d4ecb337005b850bddf4453e56a5daf04
refs/heads/master
1,675,911,819,093
1,609,785,144,000
1,609,785,144,000
270,388,715
13
1
null
null
null
null
UTF-8
Lean
false
false
2,344
lean
/- Copyright (c) 2021 Paula Neeley. All rights reserved. Author: Paula Neeley -/ import basicmodal.language basicmodal.syntax.syntax import logic.basic data.set.basic local attribute [instance] classical.prop_decidable open form ---------------------- Semantics ---------------------- -- Definition of relational frame structure frame := (states : Type) (h : inhabited states) (rel : states → states → Prop) -- Definition of forces def forces (f : frame) (v : nat → f.states → Prop) : f.states → form → Prop | x (bot) := false | x (var n) := v n x | x (and φ ψ) := (forces x φ) ∧ (forces x ψ) | x (impl φ ψ) := (forces x φ) → (forces x ψ) | x (box φ) := ∀ y, f.rel x y → forces y φ -- φ is valid in a model M = (f,v) def m_valid (φ : form) (f : frame) (v : nat → f.states → Prop) := ∀ x, forces f v x φ -- φ is valid in a frame f def f_valid (φ : form) (f : frame) := ∀ v x, forces f v x φ -- φ is valid in a class of frames F def F_valid (φ : form) (F : set (frame)) := ∀ f ∈ F, ∀ v x, forces f v x φ -- φ is universally valid (valid in all frames) def u_valid (φ : form) := ∀ f v x, forces f v x φ -- A context is true at a world in a model if each -- formula of the context is true at that world in that model def forces_ctx (f : frame) (v : nat → f.states → Prop) (Γ : ctx) := ∀ φ, ∀ x, φ ∈ Γ → forces f v x φ -- Global semantic consequence def global_sem_csq (Γ : ctx) (φ : form) := ∀ f v, forces_ctx f v Γ → ∀ x, forces f v x φ lemma not_forces_imp : ∀ f v x φ, (¬(forces f v x φ)) ↔ (forces f v x (¬φ)) := begin intros f v x φ, split, repeat {intros h1 h2, exact h1 h2}, end lemma forces_exists {f : frame} {v : nat → f.states → Prop} {x : f.states} {φ : form} : forces f v x (◇φ) ↔ ∃ y : f.states, (f.rel x y ∧ forces f v y φ) := begin split, intro h1, repeat {rw forces at h1}, have h2 := not_or_of_imp h1, cases h2, push_neg at h2, cases h2 with y h2, cases h2 with h2 h3, existsi (y : f.states), split, exact h2, have h4 := (not_forces_imp f v y (¬φ)).mp h3, repeat {rw forces at h4}, repeat {rw imp_false at h4}, rw not_not at h4, exact h4, exact false.elim h2, intro h1, cases h1 with y h1, cases h1 with h1 h2, intro h3, exact absurd h2 (h3 y h1) end
1dd8fe9825f4fa21861ab2c7d1ebe3d9a87e4235
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/stage0/src/Lean/Elab/Tactic/ElabTerm.lean
8e838484ce2ad2b41bcb13a8220f1bda6e716401
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,728
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.CollectMVars import Lean.Meta.Tactic.Apply import Lean.Meta.Tactic.Assert import Lean.Elab.Tactic.Basic import Lean.Elab.SyntheticMVars namespace Lean.Elab.Tactic open Meta /- `elabTerm` for Tactics and basic tactics that use it. -/ def elabTerm (stx : Syntax) (expectedType? : Option Expr) (mayPostpone := false) : TacticM Expr := withRef stx $ liftTermElabM $ Term.withoutErrToSorry do let e ← Term.elabTerm stx expectedType? Term.synthesizeSyntheticMVars mayPostpone instantiateMVars e def elabTermEnsuringType (stx : Syntax) (expectedType? : Option Expr) (mayPostpone := false) : TacticM Expr := do let e ← elabTerm stx expectedType? mayPostpone ensureHasType expectedType? e @[builtinTactic «exact»] def evalExact : Tactic := fun stx => match_syntax stx with | `(tactic| exact $e) => do let (g, gs) ← getMainGoal withMVarContext g do let decl ← getMVarDecl g let val ← elabTermEnsuringType e decl.type ensureHasNoMVars val assignExprMVar g val setGoals gs | _ => throwUnsupportedSyntax def elabTermWithHoles (stx : Syntax) (expectedType? : Option Expr) (tagSuffix : Name) (allowNaturalHoles := false) : TacticM (Expr × List MVarId) := do let val ← elabTermEnsuringType stx expectedType? let newMVarIds ← getMVarsNoDelayed val /- ignore let-rec auxiliary variables, they are synthesized automatically later -/ let newMVarIds ← newMVarIds.filterM fun mvarId => return !(← Term.isLetRecAuxMVar mvarId) let newMVarIds ← if allowNaturalHoles then pure newMVarIds.toList else let naturalMVarIds ← newMVarIds.filterM fun mvarId => return (← getMVarDecl mvarId).kind.isNatural let syntheticMVarIds ← newMVarIds.filterM fun mvarId => return !(← getMVarDecl mvarId).kind.isNatural Term.logUnassignedUsingErrorInfos naturalMVarIds pure syntheticMVarIds.toList tagUntaggedGoals (← getMainTag) tagSuffix newMVarIds pure (val, newMVarIds) /- If `allowNaturalHoles == true`, then we allow the resultant expression to contain unassigned "natural" metavariables. Recall that "natutal" metavariables are created for explicit holes `_` and implicit arguments. They are meant to be filled by typing constraints. "Synthetic" metavariables are meant to be filled by tactics and are usually created using the synthetic hole notation `?<hole-name>`. -/ def refineCore (stx : Syntax) (tagSuffix : Name) (allowNaturalHoles : Bool) : TacticM Unit := do let (g, gs) ← getMainGoal withMVarContext g do let decl ← getMVarDecl g let (val, gs') ← elabTermWithHoles stx decl.type tagSuffix allowNaturalHoles assignExprMVar g val setGoals (gs ++ gs') @[builtinTactic «refine»] def evalRefine : Tactic := fun stx => match_syntax stx with | `(tactic| refine $e) => refineCore e `refine (allowNaturalHoles := false) | _ => throwUnsupportedSyntax @[builtinTactic «refine!»] def evalRefineBang : Tactic := fun stx => match_syntax stx with | `(tactic| refine! $e) => refineCore e `refine (allowNaturalHoles := true) | _ => throwUnsupportedSyntax @[builtinTactic Lean.Parser.Tactic.apply] def evalApply : Tactic := fun stx => match_syntax stx with | `(tactic| apply $e) => do let (g, gs) ← getMainGoal let gs' ← withMVarContext g do let decl ← getMVarDecl g let val ← elabTerm e none true let gs' ← Meta.apply g val Term.synthesizeSyntheticMVarsNoPostponing pure gs' -- TODO: handle optParam and autoParam setGoals (gs' ++ gs) | _ => throwUnsupportedSyntax /-- Elaborate `stx`. If it a free variable, return it. Otherwise, assert it, and return the free variable. Note that, the main goal is updated when `Meta.assert` is used in the second case. -/ def elabAsFVar (stx : Syntax) (userName? : Option Name := none) : TacticM FVarId := do let (mvarId, others) ← getMainGoal withMVarContext mvarId do let e ← elabTerm stx none match e with | Expr.fvar fvarId _ => pure fvarId | _ => let type ← inferType e let intro (userName : Name) (preserveBinderNames : Bool) : TacticM FVarId := do let (fvarId, mvarId) ← liftMetaM do let mvarId ← Meta.assert mvarId userName type e Meta.intro1Core mvarId preserveBinderNames setGoals $ mvarId::others pure fvarId match userName? with | none => intro `h false | some userName => intro userName true end Lean.Elab.Tactic
591d6cd6940865d2147e41e05cdbc085318befa4
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/adjunction/fully_faithful.lean
2a44246edfb028777a7b3039f86f2e843417fce0
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
3,318
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.adjunction.basic import Mathlib.category_theory.conj import Mathlib.category_theory.yoneda import Mathlib.PostPort universes u₁ u₂ v₁ v₂ u₃ u₄ v₃ v₄ namespace Mathlib namespace category_theory /-- If the left adjoint is fully faithful, then the unit is an isomorphism. See * Lemma 4.5.13 from [Riehl][riehl2017] * https://math.stackexchange.com/a/2727177 * https://stacks.math.columbia.edu/tag/07RB (we only prove the forward direction!) -/ protected instance unit_is_iso_of_L_fully_faithful {C : Type u₁} [category C] {D : Type u₂} [category D] {L : C ⥤ D} {R : D ⥤ C} (h : L ⊣ R) [full L] [faithful L] : is_iso (adjunction.unit h) := nat_iso.is_iso_of_is_iso_app (adjunction.unit h) /-- If the right adjoint is fully faithful, then the counit is an isomorphism. See https://stacks.math.columbia.edu/tag/07RB (we only prove the forward direction!) -/ protected instance counit_is_iso_of_R_fully_faithful {C : Type u₁} [category C] {D : Type u₂} [category D] {L : C ⥤ D} {R : D ⥤ C} (h : L ⊣ R) [full R] [faithful R] : is_iso (adjunction.counit h) := nat_iso.is_iso_of_is_iso_app (adjunction.counit h) -- TODO also prove the converses? -- def L_full_of_unit_is_iso [is_iso (adjunction.unit h)] : full L := sorry -- def L_faithful_of_unit_is_iso [is_iso (adjunction.unit h)] : faithful L := sorry -- def R_full_of_counit_is_iso [is_iso (adjunction.counit h)] : full R := sorry -- def R_faithful_of_counit_is_iso [is_iso (adjunction.counit h)] : faithful R := sorry -- TODO also do the statements from Riehl 4.5.13 for full and faithful separately? -- TODO: This needs some lemmas describing the produced adjunction, probably in terms of `adj`, -- `iC` and `iD`. /-- If `C` is a full subcategory of `C'` and `D` is a full subcategory of `D'`, then we can restrict an adjunction `L' ⊣ R'` where `L' : C' ⥤ D'` and `R' : D' ⥤ C'` to `C` and `D`. The construction here is slightly more general, in that `C` is required only to have a full and faithful "inclusion" functor `iC : C ⥤ C'` (and similarly `iD : D ⥤ D'`) which commute (up to natural isomorphism) with the proposed restrictions. -/ def adjunction.restrict_fully_faithful {C : Type u₁} [category C] {D : Type u₂} [category D] {C' : Type u₃} [category C'] {D' : Type u₄} [category D'] (iC : C ⥤ C') (iD : D ⥤ D') {L' : C' ⥤ D'} {R' : D' ⥤ C'} (adj : L' ⊣ R') {L : C ⥤ D} {R : D ⥤ C} (comm1 : iC ⋙ L' ≅ L ⋙ iD) (comm2 : iD ⋙ R' ≅ R ⋙ iC) [full iC] [faithful iC] [full iD] [faithful iD] : L ⊣ R := adjunction.mk_of_hom_equiv (adjunction.core_hom_equiv.mk fun (X : C) (Y : D) => equiv.trans (equiv.trans (equiv.trans (equiv.trans (equiv_of_fully_faithful iD) (iso.hom_congr (iso.app (iso.symm comm1) X) (iso.refl (functor.obj iD Y)))) (adjunction.hom_equiv adj (functor.obj iC X) (functor.obj iD Y))) (iso.hom_congr (iso.refl (functor.obj iC X)) (iso.app comm2 Y))) (equiv.symm (equiv_of_fully_faithful iC)))
b1eeeeec94ae1589a655ec1e91bdbdc5ad5edabe
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/forall1.lean
ab5dd4a5a2e6ed5443871d36c871998b2a53b33b
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
70
lean
import Int. variable P : Int -> Bool axiom Ax (x : Int) : P x check Ax
bc128bef3b67daf25b976ab3834a2042afe096e6
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/compiler/thunk.lean
2b80fe043bb0075c5d62069ee7004acb3549d6d5
[ "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
297
lean
def compute (v : Nat) : Thunk Nat := ⟨fun _ => let xs := List.replicate 100000 v; xs.foldl Nat.add 0⟩ @[noinline] def test (t : Thunk Nat) (n : Nat) : Nat := n.repeat (fun r => t.get + r) 0 def main (xs : List String) : IO UInt32 := IO.println (toString (test (compute 1) 100000)) *> pure 0
ae03d477b535b16126b41266875ccfaa257c9d0e
1fbca480c1574e809ae95a3eda58188ff42a5e41
/src/util/data/minimum/basic.lean
2f210c0d708acbe9abae538c4a53447d28ac0700
[]
no_license
unitb/lean-lib
560eea0acf02b1fd4bcaac9986d3d7f1a4290e7e
439b80e606b4ebe4909a08b1d77f4f5c0ee3dee9
refs/heads/master
1,610,706,025,400
1,570,144,245,000
1,570,144,245,000
99,579,229
5
0
null
null
null
null
UTF-8
Lean
false
false
3,413
lean
import data.set import data.set.basic import util.meta.tactic.basic import util.data.order open nat universe variables u class has_minimum (α : Type u) extends partial_order α := (minimum : set α → α) (minimum_mem : ∀ s, s ≠ ∅ → minimum s ∈ s) (minimum_le : ∀ s x, x ∈ s → minimum s ≤ x) (le_minimum_of_forall_le : ∀ s x, s ≠ ∅ → (∀ y, y ∈ s → x ≤ y) → x ≤ minimum s) class has_maximum (α : Type u) extends partial_order α := (maximum : set α → α) (maximum_mem : ∀ s, s ≠ ∅ → maximum s ∈ s) (maximum_ge : ∀ s x, x ∈ s → x ≤ maximum s) (maximum_unique : ∀ s x, x ∈ s → (∀ y, y ∈ s → y ≤ x) → maximum s = x) notation `↓` binders `, ` r:(scoped P, has_minimum.minimum P) := r lemma min_eq_or_min_eq {α} [decidable_linear_order α] (x y : α) : min x y = x ∨ min x y = y := begin apply or.imp min_eq_left min_eq_right, apply le_total end section minimum parameters {α : Type u} parameters [has_minimum α] parameters {s : set α} parameters {x : α} lemma minimum_mem : s ≠ ∅ → has_minimum.minimum s ∈ s := @has_minimum.minimum_mem _ _ _ lemma minimum_le : x ∈ s → has_minimum.minimum s ≤ x := @has_minimum.minimum_le _ _ _ _ lemma le_minimum_of_forall_le : s ≠ ∅ → (∀ y, y ∈ s → x ≤ y) → x ≤ has_minimum.minimum s := @has_minimum.le_minimum_of_forall_le _ _ _ _ lemma minimum_unique (h₀ : x ∈ s) (h₁ : ∀ y, y ∈ s → x ≤ y) : has_minimum.minimum s = x := begin have h₂ := set.ne_empty_of_mem h₀, apply @le_antisymm α, { apply minimum_le h₀, }, { apply le_minimum_of_forall_le h₂ h₁, }, end lemma le_minimum_iff_forall_le (h : s ≠ ∅) (x : α) : x ≤ (↓ x, x ∈ s) ↔ (∀ y, y ∈ s → x ≤ y) := begin split ; intro h₀, { intros y h₁, revert h₀, apply indirect_le_left_of_le x, apply has_minimum.minimum_le _ _ h₁, }, { apply le_minimum_of_forall_le h h₀, }, end lemma minimum_le_iff_exists_le (h : s ≠ ∅) (x : α) : (↓ x, x ∈ s) ≤ x ↔ (∃ y, y ∈ s ∧ y ≤ x) := begin split ; intro h₀, { existsi (↓ (x : α), x ∈ s), refine ⟨_,h₀⟩, apply minimum_mem h, }, { cases h₀, apply indirect_le_right_of_le , apply has_minimum.minimum_le _ _ h₀_h.left, tauto, }, end end minimum section has_minimum parameters {α : Type u} parameters [partial_order α] parameters minimum : set α → α local notation `↓` binders ` | ` r:(scoped P, has_minimum.minimum P) := r parameters minimum_mem : ∀ (s : set α), s ≠ ∅ → minimum s ∈ s parameters h : ∀ (s : set α) (x : α), x ≤ minimum s ↔ ∀ y, y ∈ s → x ≤ y include minimum_mem h section lemmas variables s : set α variables x : α variables h₀ : x ∈ s include h₀ private lemma minimum_le : minimum s ≤ x := begin apply le_of_indirect_le_left, intros z h', rw h at h', apply h' _ h₀, end omit h₀ variables h₁ : s ≠ ∅ variables h₂ : ∀ (y : α), y ∈ s → x ≤ y include h₁ h₂ private lemma le_minimum_of_forall_le : x ≤ minimum s := begin rw h, apply h₂, end end lemmas def has_minimum_of_le_minimum_iff : has_minimum α := { (_ : partial_order α) with minimum := minimum , minimum_mem := @minimum_mem , minimum_le := @minimum_le , le_minimum_of_forall_le := @le_minimum_of_forall_le } end has_minimum
95c579d6d6df71a7c087d1045f3ea7f610771557
1446f520c1db37e157b631385707cc28a17a595e
/src/Init/Lean/Meta/ExprDefEq.lean
e860144e5a6c82208b9bdcacb4c79d66a424ca58
[ "Apache-2.0" ]
permissive
bdbabiak/lean4
cab06b8a2606d99a168dd279efdd404edb4e825a
3f4d0d78b2ce3ef541cb643bbe21496bd6b057ac
refs/heads/master
1,615,045,275,530
1,583,793,696,000
1,583,793,696,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
40,354
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Lean.ProjFns import Init.Lean.Meta.WHNF import Init.Lean.Meta.InferType import Init.Lean.Meta.FunInfo import Init.Lean.Meta.LevelDefEq import Init.Lean.Meta.Check import Init.Lean.Meta.Offset namespace Lean namespace Meta /-- Try to solve `a := (fun x => t) =?= b` by eta-expanding `b`. Remark: eta-reduction is not a good alternative even in a system without universe cumulativity like Lean. Example: ``` (fun x : A => f ?m) =?= f ``` The left-hand side of the constraint above it not eta-reduced because `?m` is a metavariable. -/ private def isDefEqEta (a b : Expr) : MetaM Bool := if a.isLambda && !b.isLambda then do bType ← inferType b; bType ← whnfD bType; match bType with | Expr.forallE n d _ c => let b' := Lean.mkLambda n c.binderInfo d (mkApp b (mkBVar 0)); commitWhen $ isExprDefEqAux a b' | _ => pure false else pure false /-- Return `true` if `e` is of the form `fun (x_1 ... x_n) => ?m x_1 ... x_n)`, and `?m` is unassigned. Remark: `n` may be 0. -/ def isEtaUnassignedMVar (e : Expr) : MetaM Bool := match e.etaExpanded? with | some (Expr.mvar mvarId _) => condM (isReadOnlyOrSyntheticOpaqueExprMVar mvarId) (pure false) (condM (isExprMVarAssigned mvarId) (pure false) (pure true)) | _ => pure false /- First pass for `isDefEqArgs`. We unify explicit arguments, *and* easy cases Here, we say a case is easy if it is of the form ?m =?= t or t =?= ?m where `?m` is unassigned. These easy cases are not just an optimization. When `?m` is a function, by assigning it to t, we make sure a unification constraint (in the explicit part) ``` ?m t =?= f s ``` is not higher-order. We also handle the eta-expanded cases: ``` fun x₁ ... xₙ => ?m x₁ ... xₙ =?= t t =?= fun x₁ ... xₙ => ?m x₁ ... xₙ This is important because type inference often produces eta-expanded terms, and without this extra case, we could introduce counter intuitive behavior. Pre: `paramInfo.size <= args₁.size = args₂.size` -/ private partial def isDefEqArgsFirstPass (paramInfo : Array ParamInfo) (args₁ args₂ : Array Expr) : Nat → Array Nat → MetaM (Option (Array Nat)) | i, postponed => if h : i < paramInfo.size then let info := paramInfo.get ⟨i, h⟩; let a₁ := args₁.get! i; let a₂ := args₂.get! i; if info.implicit || info.instImplicit then condM (isEtaUnassignedMVar a₁ <||> isEtaUnassignedMVar a₂) (condM (isExprDefEqAux a₁ a₂) (isDefEqArgsFirstPass (i+1) postponed) (pure none)) (isDefEqArgsFirstPass (i+1) (postponed.push i)) else condM (isExprDefEqAux a₁ a₂) (isDefEqArgsFirstPass (i+1) postponed) (pure none) else pure (some postponed) private partial def isDefEqArgsAux (args₁ args₂ : Array Expr) (h : args₁.size = args₂.size) : Nat → MetaM Bool | i => if h₁ : i < args₁.size then let a₁ := args₁.get ⟨i, h₁⟩; let a₂ := args₂.get ⟨i, h ▸ h₁⟩; condM (isExprDefEqAux a₁ a₂) (isDefEqArgsAux (i+1)) (pure false) else pure true private def isDefEqArgs (f : Expr) (args₁ args₂ : Array Expr) : MetaM Bool := if h : args₁.size = args₂.size then do finfo ← getFunInfoNArgs f args₁.size; (some postponed) ← isDefEqArgsFirstPass finfo.paramInfo args₁ args₂ 0 #[] | pure false; (isDefEqArgsAux args₁ args₂ h finfo.paramInfo.size) <&&> (postponed.allM $ fun i => do /- Second pass: unify implicit arguments. In the second pass, we make sure we are unfolding at least non reducible definitions (default setting). -/ let a₁ := args₁.get! i; let a₂ := args₂.get! i; let info := finfo.paramInfo.get! i; when info.instImplicit $ do { synthPending a₁; synthPending a₂; pure () }; withAtLeastTransparency TransparencyMode.default $ isExprDefEqAux a₁ a₂) else pure false /-- Check whether the types of the free variables at `fvars` are definitionally equal to the types at `ds₂`. Pre: `fvars.size == ds₂.size` This method also updates the set of local instances, and invokes the continuation `k` with the updated set. We can't use `withNewLocalInstances` because the `isDeq fvarType d₂` may use local instances. -/ @[specialize] partial def isDefEqBindingDomain (fvars : Array Expr) (ds₂ : Array Expr) : Nat → MetaM Bool → MetaM Bool | i, k => if h : i < fvars.size then do let fvar := fvars.get ⟨i, h⟩; fvarDecl ← getFVarLocalDecl fvar; let fvarType := fvarDecl.type; let d₂ := ds₂.get! i; condM (isExprDefEqAux fvarType d₂) (do c? ← isClass fvarType; match c? with | some className => withNewLocalInstance className fvar $ isDefEqBindingDomain (i+1) k | none => isDefEqBindingDomain (i+1) k) (pure false) else k /- Auxiliary function for `isDefEqBinding` for handling binders `forall/fun`. It accumulates the new free variables in `fvars`, and declare them at `lctx`. We use the domain types of `e₁` to create the new free variables. We store the domain types of `e₂` at `ds₂`. -/ private partial def isDefEqBindingAux : LocalContext → Array Expr → Expr → Expr → Array Expr → MetaM Bool | lctx, fvars, e₁, e₂, ds₂ => let process (n : Name) (d₁ d₂ b₁ b₂ : Expr) : MetaM Bool := do { let d₁ := d₁.instantiateRev fvars; let d₂ := d₂.instantiateRev fvars; fvarId ← mkFreshId; let lctx := lctx.mkLocalDecl fvarId n d₁; let fvars := fvars.push (mkFVar fvarId); isDefEqBindingAux lctx fvars b₁ b₂ (ds₂.push d₂) }; match e₁, e₂ with | Expr.forallE n d₁ b₁ _, Expr.forallE _ d₂ b₂ _ => process n d₁ d₂ b₁ b₂ | Expr.lam n d₁ b₁ _, Expr.lam _ d₂ b₂ _ => process n d₁ d₂ b₁ b₂ | _, _ => adaptReader (fun (ctx : Context) => { lctx := lctx, .. ctx }) $ isDefEqBindingDomain fvars ds₂ 0 $ isExprDefEqAux (e₁.instantiateRev fvars) (e₂.instantiateRev fvars) @[inline] private def isDefEqBinding (a b : Expr) : MetaM Bool := do lctx ← getLCtx; isDefEqBindingAux lctx #[] a b #[] private def checkTypesAndAssign (mvar : Expr) (v : Expr) : MetaM Bool := traceCtx `Meta.isDefEq.assign.checkTypes $ do -- must check whether types are definitionally equal or not, before assigning and returning true mvarType ← inferType mvar; vType ← inferType v; condM (withTransparency TransparencyMode.default $ isExprDefEqAux mvarType vType) (do trace! `Meta.isDefEq.assign.final (mvar ++ " := " ++ v); assignExprMVar mvar.mvarId! v; pure true) (do trace `Meta.isDefEq.assign.typeMismatch $ fun _ => mvar ++ " : " ++ mvarType ++ " := " ++ v ++ " : " ++ vType; pure false) /- Each metavariable is declared in a particular local context. We use the notation `C |- ?m : t` to denote a metavariable `?m` that was declared at the local context `C` with type `t` (see `MetavarDecl`). We also use `?m@C` as a shorthand for `C |- ?m : t` where `t` is the type of `?m`. The following method process the unification constraint ?m@C a₁ ... aₙ =?= t We say the unification constraint is a pattern IFF 1) `a₁ ... aₙ` are pairwise distinct free variables that are ​*not*​ let-variables. 2) `a₁ ... aₙ` are not in `C` 3) `t` only contains free variables in `C` and/or `{a₁, ..., aₙ}` 4) For every metavariable `?m'@C'` occurring in `t`, `C'` is a subprefix of `C` 5) `?m` does not occur in `t` Claim: we don't have to check free variable declarations. That is, if `t` contains a reference to `x : A := v`, we don't need to check `v`. Reason: The reference to `x` is a free variable, and it must be in `C` (by 1 and 3). If `x` is in `C`, then any metavariable occurring in `v` must have been defined in a strict subprefix of `C`. So, condition 4 and 5 are satisfied. If the conditions above have been satisfied, then the solution for the unification constrain is ?m := fun a₁ ... aₙ => t Now, we consider some workarounds/approximations. A1) Suppose `t` contains a reference to `x : A := v` and `x` is not in `C` (failed condition 3) (precise) solution: unfold `x` in `t`. A2) Suppose some `aᵢ` is in `C` (failed condition 2) (approximated) solution (when `config.foApprox` is set to true) : ignore condition and also use ?m := fun a₁ ... aₙ => t Here is an example where this approximation fails: Given `C` containing `a : nat`, consider the following two constraints ?m@C a =?= a ?m@C b =?= a If we use the approximation in the first constraint, we get ?m := fun x => x when we apply this solution to the second one we get a failure. IMPORTANT: When applying this approximation we need to make sure the abstracted term `fun a₁ ... aₙ => t` is type correct. The check can only be skipped in the pattern case described above. Consider the following example. Given the local context (α : Type) (a : α) we try to solve ?m α =?= @id α a If we use the approximation above we obtain: ?m := (fun α' => @id α' a) which is a type incorrect term. `a` has type `α` but it is expected to have type `α'`. The problem occurs because the right hand side contains a free variable `a` that depends on the free variable `α` being abstracted. Note that this dependency cannot occur in patterns. We can address this by type checking the term after abstraction. This is not a significant performance bottleneck because this case doesn't happen very often in practice (262 times when compiling stdlib on Jan 2018). The second example is trickier, but it also occurs less frequently (8 times when compiling stdlib on Jan 2018, and all occurrences were at Init/Control when we define monads and auxiliary combinators for them). We considered three options for the addressing the issue on the second example: A3) `a₁ ... aₙ` are not pairwise distinct (failed condition 1). In Lean3, we would try to approximate this case using an approach similar to A2. However, this approximation complicates the code, and is never used in the Lean3 stdlib and mathlib. A4) `t` contains a metavariable `?m'@C'` where `C'` is not a subprefix of `C`. If `?m'` is assigned, we substitute. If not, we create an auxiliary metavariable with a smaller scope. Actually, we let `elimMVarDeps` at `MetavarContext.lean` to perform this step. A5) If some `aᵢ` is not a free variable, then we use first-order unification (if `config.foApprox` is set to true) ?m a_1 ... a_i a_{i+1} ... a_{i+k} =?= f b_1 ... b_k reduces to ?M a_1 ... a_i =?= f a_{i+1} =?= b_1 ... a_{i+k} =?= b_k A6) If (m =?= v) is of the form ?m a_1 ... a_n =?= ?m b_1 ... b_k then we use first-order unification (if `config.foApprox` is set to true) -/ namespace CheckAssignment structure Context extends Meta.Context := (mvarId : MVarId) (mvarDecl : MetavarDecl) (fvars : Array Expr) (hasCtxLocals : Bool) inductive Exception | occursCheck | useFOApprox | outOfScopeFVar (fvarId : FVarId) | readOnlyMVarWithBiggerLCtx (mvarId : MVarId) | unknownExprMVar (mvarId : MVarId) | meta (ex : Meta.Exception) structure State extends Meta.State := (checkCache : ExprStructMap Expr := {}) abbrev CheckAssignmentM := ReaderT Context (EStateM Exception State) private def findCached? (e : Expr) : CheckAssignmentM (Option Expr) := do s ← get; pure $ s.checkCache.find? e private def cache (e r : Expr) : CheckAssignmentM Unit := modify $ fun s => { checkCache := s.checkCache.insert e r, .. s } instance : MonadCache Expr Expr CheckAssignmentM := { findCached? := findCached?, cache := cache } def liftMetaM {α} (x : MetaM α) : CheckAssignmentM α := fun ctx s => match x ctx.toContext s.toState with | EStateM.Result.ok a newS => EStateM.Result.ok a { toState := newS, .. s } | EStateM.Result.error ex newS => EStateM.Result.error (Exception.meta ex) { toState := newS, .. s } @[inline] private def visit (f : Expr → CheckAssignmentM Expr) (e : Expr) : CheckAssignmentM Expr := if !e.hasExprMVar && !e.hasFVar then pure e else checkCache e f @[specialize] def checkFVar (check : Expr → CheckAssignmentM Expr) (fvar : Expr) : CheckAssignmentM Expr := do ctx ← read; if ctx.mvarDecl.lctx.containsFVar fvar then pure fvar else do let lctx := ctx.lctx; match lctx.findFVar? fvar with | some (LocalDecl.ldecl _ _ _ _ v) => visit check v | _ => if ctx.fvars.contains fvar then pure fvar else throw $ Exception.outOfScopeFVar fvar.fvarId! @[inline] def getMCtx : CheckAssignmentM MetavarContext := do s ← get; pure s.mctx def mkAuxMVar (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) : CheckAssignmentM Expr := do s ← get; let mvarId := s.ngen.curr; modify $ fun s => { ngen := s.ngen.next, mctx := s.mctx.addExprMVarDecl mvarId Name.anonymous lctx localInsts type, .. s }; pure (mkMVar mvarId) @[specialize] def checkMVar (check : Expr → CheckAssignmentM Expr) (mvar : Expr) : CheckAssignmentM Expr := do let mvarId := mvar.mvarId!; ctx ← read; mctx ← getMCtx; if mvarId == ctx.mvarId then throw Exception.occursCheck else match mctx.getExprAssignment? mvarId with | some v => check v | none => match mctx.findDecl? mvarId with | none => throw $ Exception.unknownExprMVar mvarId | some mvarDecl => if ctx.hasCtxLocals then throw $ Exception.useFOApprox -- It is not a pattern, then we fail and fall back to FO unification else if mvarDecl.lctx.isSubPrefixOf ctx.mvarDecl.lctx ctx.fvars then /- The local context of `mvar` - free variables being abstracted is a subprefix of the metavariable being assigned. We "substract" variables being abstracted because we use `elimMVarDeps` -/ pure mvar else if mvarDecl.depth != mctx.depth || mvarDecl.kind.isSyntheticOpaque then throw $ Exception.readOnlyMVarWithBiggerLCtx mvarId else if ctx.config.ctxApprox && ctx.mvarDecl.lctx.isSubPrefixOf mvarDecl.lctx then do mvarType ← check mvarDecl.type; /- Create an auxiliary metavariable with a smaller context and "checked" type. Note that `mvarType` may be different from `mvarDecl.type`. Example: `mvarType` contains a metavariable that we also need to reduce the context. -/ newMVar ← mkAuxMVar ctx.mvarDecl.lctx ctx.mvarDecl.localInstances mvarType; modify $ fun s => { mctx := s.mctx.assignExpr mvarId newMVar, .. s }; pure newMVar else pure mvar /- Auxiliary function used to "fix" subterms of the form `?m x_1 ... x_n` where `x_i`s are free variables, and one of them is out-of-scope. See `Expr.app` case at `check`. If `ctxApprox` is true, then we solve this case by creating a fresh metavariable ?n with the correct scope, an assigning `?m := fun _ ... _ => ?n` -/ def assignToConstFun (mvar : Expr) (numArgs : Nat) (newMVar : Expr) : MetaM Bool := do mvarType ← inferType mvar; forallBoundedTelescope mvarType numArgs $ fun xs _ => if xs.size != numArgs then pure false else do v ← mkLambda xs newMVar; checkTypesAndAssign mvar v partial def check : Expr → CheckAssignmentM Expr | e@(Expr.mdata _ b _) => do b ← visit check b; pure $ e.updateMData! b | e@(Expr.proj _ _ s _) => do s ← visit check s; pure $ e.updateProj! s | e@(Expr.lam _ d b _) => do d ← visit check d; b ← visit check b; pure $ e.updateLambdaE! d b | e@(Expr.forallE _ d b _) => do d ← visit check d; b ← visit check b; pure $ e.updateForallE! d b | e@(Expr.letE _ t v b _) => do t ← visit check t; v ← visit check v; b ← visit check b; pure $ e.updateLet! t v b | e@(Expr.bvar _ _) => pure e | e@(Expr.sort _ _) => pure e | e@(Expr.const _ _ _) => pure e | e@(Expr.lit _ _) => pure e | e@(Expr.fvar _ _) => visit (checkFVar check) e | e@(Expr.mvar _ _) => visit (checkMVar check) e | Expr.localE _ _ _ _ => unreachable! | e@(Expr.app _ _ _) => e.withApp $ fun f args => do ctx ← read; if f.isMVar && ctx.config.ctxApprox && args.all Expr.isFVar then do f ← visit (checkMVar check) f; catch (do args ← args.mapM (visit check); pure $ mkAppN f args) (fun ex => match ex with | Exception.outOfScopeFVar _ => condM (liftMetaM $ isDelayedAssigned f.mvarId!) (throw ex) $ do eType ← liftMetaM $ inferType e; mvarType ← check eType; /- Create an auxiliary metavariable with a smaller context and "checked" type, assign `?f := fun _ => ?newMVar` Note that `mvarType` may be different from `eType`. -/ newMVar ← mkAuxMVar ctx.mvarDecl.lctx ctx.mvarDecl.localInstances mvarType; condM (liftMetaM $ assignToConstFun f args.size newMVar) (pure newMVar) (throw ex) | _ => throw ex) else do f ← visit check f; args ← args.mapM (visit check); pure $ mkAppN f args end CheckAssignment private def checkAssignmentFailure (mvarId : MVarId) (fvars : Array Expr) (v : Expr) (ex : CheckAssignment.Exception) : MetaM (Option Expr) := match ex with | CheckAssignment.Exception.occursCheck => do trace! `Meta.isDefEq.assign.occursCheck (mkMVar mvarId ++ " " ++ fvars ++ " := " ++ v); pure none | CheckAssignment.Exception.useFOApprox => pure none | CheckAssignment.Exception.outOfScopeFVar fvarId => do trace! `Meta.isDefEq.assign.outOfScopeFVar (mkFVar fvarId ++ " @ " ++ mkMVar mvarId ++ " " ++ fvars ++ " := " ++ v); pure none | CheckAssignment.Exception.readOnlyMVarWithBiggerLCtx nestedMVarId => do trace! `Meta.isDefEq.assign.readOnlyMVarWithBiggerLCtx (mkMVar nestedMVarId ++ " @ " ++ mkMVar mvarId ++ " " ++ fvars ++ " := " ++ v); pure none | CheckAssignment.Exception.unknownExprMVar mvarId => -- This case can only happen if the MetaM API is being misused throwEx $ Exception.unknownExprMVar mvarId | CheckAssignment.Exception.meta ex => throw ex namespace CheckAssignmentQuick @[inline] private def visit (f : Expr → Bool) (e : Expr) : Bool := if !e.hasExprMVar && !e.hasFVar then true else f e partial def check (hasCtxLocals ctxApprox : Bool) (mctx : MetavarContext) (lctx : LocalContext) (mvarDecl : MetavarDecl) (mvarId : MVarId) (fvars : Array Expr) : Expr → Bool | e@(Expr.mdata _ b _) => check b | e@(Expr.proj _ _ s _) => check s | e@(Expr.app f a _) => visit check f && visit check a | e@(Expr.lam _ d b _) => visit check d && visit check b | e@(Expr.forallE _ d b _) => visit check d && visit check b | e@(Expr.letE _ t v b _) => visit check t && visit check v && visit check b | e@(Expr.bvar _ _) => true | e@(Expr.sort _ _) => true | e@(Expr.const _ _ _) => true | e@(Expr.lit _ _) => true | e@(Expr.fvar fvarId _) => if mvarDecl.lctx.contains fvarId then true else match lctx.find? fvarId with | some (LocalDecl.ldecl _ _ _ _ v) => false -- need expensive CheckAssignment.check | _ => if fvars.any $ fun x => x.fvarId! == fvarId then true else false -- We could throw an exception here, but we would have to use ExceptM. So, we let CheckAssignment.check do it | e@(Expr.mvar mvarId' _) => do match mctx.getExprAssignment? mvarId' with | some _ => false -- use CheckAssignment.check to instantiate | none => if mvarId' == mvarId then false -- occurs check failed, use CheckAssignment.check to throw exception else match mctx.findDecl? mvarId' with | none => false | some mvarDecl' => if hasCtxLocals then false -- use CheckAssignment.check else if mvarDecl'.lctx.isSubPrefixOf mvarDecl.lctx fvars then true else if mvarDecl'.depth != mctx.depth || mvarDecl'.kind.isSyntheticOpaque then false -- use CheckAssignment.check else if ctxApprox && mvarDecl.lctx.isSubPrefixOf mvarDecl'.lctx then false -- use CheckAssignment.check else true | Expr.localE _ _ _ _ => unreachable! end CheckAssignmentQuick -- See checkAssignment def checkAssignmentAux (mvarId : MVarId) (mvarDecl : MetavarDecl) (fvars : Array Expr) (hasCtxLocals : Bool) (v : Expr) : MetaM (Option Expr) := fun ctx s => let checkCtx : CheckAssignment.Context := { mvarId := mvarId, mvarDecl := s.mctx.getDecl mvarId, fvars := fvars, hasCtxLocals := hasCtxLocals, toContext := ctx }; match (CheckAssignment.check v checkCtx).run { toState := s } with | EStateM.Result.ok e newS => EStateM.Result.ok (some e) newS.toState | EStateM.Result.error ex newS => checkAssignmentFailure mvarId fvars v ex ctx newS.toState /-- Auxiliary function for handling constraints of the form `?m a₁ ... aₙ =?= v`. It will check whether we can perform the assignment ``` ?m := fun fvars => t ``` The result is `none` if the assignment can't be performed. The result is `some newV` where `newV` is a possibly updated `v`. This method may need to unfold let-declarations. -/ def checkAssignment (mvarId : MVarId) (fvars : Array Expr) (v : Expr) : MetaM (Option Expr) := do if !v.hasExprMVar && !v.hasFVar then pure (some v) else do mvarDecl ← getMVarDecl mvarId; let hasCtxLocals := fvars.any $ fun fvar => mvarDecl.lctx.containsFVar fvar; ctx ← read; mctx ← getMCtx; if CheckAssignmentQuick.check hasCtxLocals ctx.config.ctxApprox mctx ctx.lctx mvarDecl mvarId fvars v then pure (some v) else do v ← instantiateMVars v; checkAssignmentAux mvarId mvarDecl fvars hasCtxLocals v private def processAssignmentFOApproxAux (mvar : Expr) (args : Array Expr) (v : Expr) : MetaM Bool := match v with | Expr.app f a _ => isExprDefEqAux args.back a <&&> isExprDefEqAux (mkAppRange mvar 0 (args.size - 1) args) f | _ => pure false /- Auxiliary method for applying first-order unification. It is an approximation. Remark: this method is trying to solve the unification constraint: ?m a₁ ... aₙ =?= v It is uses processAssignmentFOApproxAux, if it fails, it tries to unfold `v`. We have added support for unfolding here because we want to be able to solve unification problems such as ?m Unit =?= ITactic where `ITactic` is defined as def ITactic := Tactic Unit -/ private partial def processAssignmentFOApprox (mvar : Expr) (args : Array Expr) : Expr → MetaM Bool | v => do cfg ← getConfig; if !cfg.foApprox then pure false else do trace! `Meta.isDefEq.foApprox (mvar ++ " " ++ args ++ " := " ++ v); condM (commitWhen $ processAssignmentFOApproxAux mvar args v) (pure true) (do v? ← unfoldDefinition? v; match v? with | none => pure false | some v => processAssignmentFOApprox v) private partial def simpAssignmentArgAux : Expr → MetaM Expr | Expr.mdata _ e _ => simpAssignmentArgAux e | e@(Expr.fvar fvarId _) => do decl ← getLocalDecl fvarId; match decl.value? with | some value => simpAssignmentArgAux value | _ => pure e | e => pure e /- Auxiliary procedure for processing `?m a₁ ... aₙ =?= v`. We apply it to each `aᵢ`. It instantiates assigned metavariables if `aᵢ` is of the form `f[?n] b₁ ... bₘ`, and then removes metadata, and zeta-expand let-decls. -/ private def simpAssignmentArg (arg : Expr) : MetaM Expr := do arg ← if arg.getAppFn.hasExprMVar then instantiateMVars arg else pure arg; simpAssignmentArgAux arg private def processConstApprox (mvar : Expr) (numArgs : Nat) (v : Expr) : MetaM Bool := do cfg ← getConfig; if cfg.constApprox then do let mvarId := mvar.mvarId!; v? ← checkAssignment mvarId #[] v; match v? with | none => pure false | some v => do mvarDecl ← getMVarDecl mvarId; forallBoundedTelescope mvarDecl.type numArgs $ fun xs _ => if xs.size != numArgs then pure false else do v ← mkLambda xs v; checkTypesAndAssign mvar v else pure false private partial def processAssignmentAux (mvar : Expr) (mvarDecl : MetavarDecl) : Nat → Array Expr → Expr → MetaM Bool | i, args, v => do cfg ← getConfig; let useFOApprox (args : Array Expr) : MetaM Bool := processAssignmentFOApprox mvar args v <||> processConstApprox mvar args.size v; if h : i < args.size then do let arg := args.get ⟨i, h⟩; arg ← simpAssignmentArg arg; let args := args.set ⟨i, h⟩ arg; match arg with | Expr.fvar fvarId _ => if args.anyRange 0 i (fun prevArg => prevArg == arg) then useFOApprox args else if mvarDecl.lctx.contains fvarId && !cfg.quasiPatternApprox then useFOApprox args else processAssignmentAux (i+1) args v | _ => useFOApprox args else do v ← instantiateMVars v; -- enforce A4 if v.getAppFn == mvar then -- using A6 useFOApprox args else do let mvarId := mvar.mvarId!; v? ← checkAssignment mvarId args v; match v? with | none => useFOApprox args | some v => do trace `Meta.isDefEq.assign.beforeMkLambda $ fun _ => mvar ++ " " ++ args ++ " := " ++ v; v ← mkLambda args v; if args.any (fun arg => mvarDecl.lctx.containsFVar arg) then /- We need to type check `v` because abstraction using `mkLambda` may have produced a type incorrect term. See discussion at A2 -/ condM (isTypeCorrect v) (checkTypesAndAssign mvar v) (do trace `Meta.isDefEq.assign.typeError $ fun _ => mvar ++ " := " ++ v; useFOApprox args) else checkTypesAndAssign mvar v /-- Tries to solve `?m a₁ ... aₙ =?= v` by assigning `?m`. It assumes `?m` is unassigned. -/ private def processAssignment (mvarApp : Expr) (v : Expr) : MetaM Bool := traceCtx `Meta.isDefEq.assign $ do trace! `Meta.isDefEq.assign (mvarApp ++ " := " ++ v); let mvar := mvarApp.getAppFn; mvarDecl ← getMVarDecl mvar.mvarId!; processAssignmentAux mvar mvarDecl 0 mvarApp.getAppArgs v private def isDeltaCandidate (t : Expr) : MetaM (Option ConstantInfo) := match t.getAppFn with | Expr.const c _ _ => getConst c | _ => pure none /-- Auxiliary method for isDefEqDelta -/ private def isListLevelDefEq (us vs : List Level) : MetaM LBool := toLBoolM $ isListLevelDefEqAux us vs /-- Auxiliary method for isDefEqDelta -/ private def isDefEqLeft (fn : Name) (t s : Expr) : MetaM LBool := do trace! `Meta.isDefEq.delta.unfoldLeft fn; toLBoolM $ isExprDefEqAux t s /-- Auxiliary method for isDefEqDelta -/ private def isDefEqRight (fn : Name) (t s : Expr) : MetaM LBool := do trace! `Meta.isDefEq.delta.unfoldRight fn; toLBoolM $ isExprDefEqAux t s /-- Auxiliary method for isDefEqDelta -/ private def isDefEqLeftRight (fn : Name) (t s : Expr) : MetaM LBool := do trace! `Meta.isDefEq.delta.unfoldLeftRight fn; toLBoolM $ isExprDefEqAux t s /-- Try to solve `f a₁ ... aₙ =?= f b₁ ... bₙ` by solving `a₁ =?= b₁, ..., aₙ =?= bₙ`. Auxiliary method for isDefEqDelta -/ private def tryHeuristic (t s : Expr) : MetaM Bool := let tFn := t.getAppFn; let sFn := s.getAppFn; traceCtx `Meta.isDefEq.delta $ commitWhen $ do b ← isDefEqArgs tFn t.getAppArgs s.getAppArgs <&&> isListLevelDefEqAux tFn.constLevels! sFn.constLevels!; unless b $ trace! `Meta.isDefEq.delta ("heuristic failed " ++ t ++ " =?= " ++ s); pure b /-- Auxiliary method for isDefEqDelta -/ private abbrev unfold {α} (e : Expr) (failK : MetaM α) (successK : Expr → MetaM α) : MetaM α := do e? ← unfoldDefinition? e; match e? with | some e => successK e | none => failK /-- Auxiliary method for isDefEqDelta -/ private def unfoldBothDefEq (fn : Name) (t s : Expr) : MetaM LBool := match t, s with | Expr.const _ ls₁ _, Expr.const _ ls₂ _ => isListLevelDefEq ls₁ ls₂ | Expr.app _ _ _, Expr.app _ _ _ => condM (tryHeuristic t s) (pure LBool.true) (unfold t (unfold s (pure LBool.false) (fun s => isDefEqRight fn t s)) (fun t => unfold s (isDefEqLeft fn t s) (fun s => isDefEqLeftRight fn t s))) | _, _ => pure LBool.false private def sameHeadSymbol (t s : Expr) : Bool := match t.getAppFn, s.getAppFn with | Expr.const c₁ _ _, Expr.const c₂ _ _ => true | _, _ => false /-- - If headSymbol (unfold t) == headSymbol s, then unfold t - If headSymbol (unfold s) == headSymbol t, then unfold s - Otherwise unfold t and s if possible. Auxiliary method for isDefEqDelta -/ private def unfoldComparingHeadsDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := unfold t (unfold s (pure LBool.undef) -- `t` and `s` failed to be unfolded (fun s => isDefEqRight sInfo.name t s)) (fun tNew => if sameHeadSymbol tNew s then isDefEqLeft tInfo.name tNew s else unfold s (isDefEqLeft tInfo.name tNew s) (fun sNew => if sameHeadSymbol t sNew then isDefEqRight sInfo.name t sNew else isDefEqLeftRight tInfo.name tNew sNew)) /-- If `t` and `s` do not contain metavariables, then use kernel definitional equality heuristics. Otherwise, use `unfoldComparingHeadsDefEq`. Auxiliary method for isDefEqDelta -/ private def unfoldDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := if !t.hasExprMVar && !s.hasExprMVar then /- If `t` and `s` do not contain metavariables, we simulate strategy used in the kernel. -/ if tInfo.hints.lt sInfo.hints then unfold t (unfoldComparingHeadsDefEq tInfo sInfo t s) $ fun t => isDefEqLeft tInfo.name t s else if sInfo.hints.lt tInfo.hints then unfold s (unfoldComparingHeadsDefEq tInfo sInfo t s) $ fun s => isDefEqRight sInfo.name t s else unfoldComparingHeadsDefEq tInfo sInfo t s else unfoldComparingHeadsDefEq tInfo sInfo t s /-- When `TransparencyMode` is set to `default` or `all`. If `t` is reducible and `s` is not ==> `isDefEqLeft (unfold t) s` If `s` is reducible and `t` is not ==> `isDefEqRight t (unfold s)` Otherwise, use `unfoldDefEq` Auxiliary method for isDefEqDelta -/ private def unfoldReducibeDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := condM shouldReduceReducibleOnly (unfoldDefEq tInfo sInfo t s) (do tReducible ← isReducible tInfo.name; sReducible ← isReducible sInfo.name; if tReducible && !sReducible then unfold t (unfoldDefEq tInfo sInfo t s) $ fun t => isDefEqLeft tInfo.name t s else if !tReducible && sReducible then unfold s (unfoldDefEq tInfo sInfo t s) $ fun s => isDefEqRight sInfo.name t s else unfoldDefEq tInfo sInfo t s) /-- If `t` is a projection function application and `s` is not ==> `isDefEqRight t (unfold s)` If `s` is a projection function application and `t` is not ==> `isDefEqRight (unfold t) s` Otherwise, use `unfoldReducibeDefEq` Auxiliary method for isDefEqDelta -/ private def unfoldNonProjFnDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := do env ← getEnv; let tProj? := env.isProjectionFn tInfo.name; let sProj? := env.isProjectionFn sInfo.name; if tProj? && !sProj? then unfold s (unfoldDefEq tInfo sInfo t s) $ fun s => isDefEqRight sInfo.name t s else if !tProj? && sProj? then unfold t (unfoldDefEq tInfo sInfo t s) $ fun t => isDefEqLeft tInfo.name t s else unfoldReducibeDefEq tInfo sInfo t s /-- isDefEq by lazy delta reduction. This method implements many different heuristics: 1- If only `t` can be unfolded => then unfold `t` and continue 2- If only `s` can be unfolded => then unfold `s` and continue 3- If `t` and `s` can be unfolded and they have the same head symbol, then a) First try to solve unification by unifying arguments. b) If it fails, unfold both and continue. Implemented by `unfoldBothDefEq` 4- If `t` is a projection function application and `s` is not => then unfold `s` and continue. 5- If `s` is a projection function application and `t` is not => then unfold `t` and continue. Remark: 4&5 are implemented by `unfoldNonProjFnDefEq` 6- If `t` is reducible and `s` is not => then unfold `t` and continue. 7- If `s` is reducible and `t` is not => then unfold `s` and continue Remark: 6&7 are implemented by `unfoldReducibeDefEq` 8- If `t` and `s` do not contain metavariables, then use heuristic used in the Kernel. Implemented by `unfoldDefEq` 9- If `headSymbol (unfold t) == headSymbol s`, then unfold t and continue. 10- If `headSymbol (unfold s) == headSymbol t`, then unfold s 11- Otherwise, unfold `t` and `s` and continue. Remark: 9&10&11 are implemented by `unfoldComparingHeadsDefEq` -/ private def isDefEqDelta (t s : Expr) : MetaM LBool := do tInfo? ← isDeltaCandidate t.getAppFn; sInfo? ← isDeltaCandidate s.getAppFn; match tInfo?, sInfo? with | none, none => pure LBool.undef | some tInfo, none => unfold t (pure LBool.undef) $ fun t => isDefEqLeft tInfo.name t s | none, some sInfo => unfold s (pure LBool.undef) $ fun s => isDefEqRight sInfo.name t s | some tInfo, some sInfo => if tInfo.name == sInfo.name then unfoldBothDefEq tInfo.name t s else unfoldNonProjFnDefEq tInfo sInfo t s private def isAssigned : Expr → MetaM Bool | Expr.mvar mvarId _ => isExprMVarAssigned mvarId | _ => pure false private def isDelayedAssignedHead (tFn : Expr) (t : Expr) : MetaM Bool := match tFn with | Expr.mvar mvarId _ => do condM (isDelayedAssigned mvarId) (do tNew ← instantiateMVars t; pure $ tNew != t) (pure false) | _ => pure false private def isSynthetic : Expr → MetaM Bool | Expr.mvar mvarId _ => do mvarDecl ← getMVarDecl mvarId; match mvarDecl.kind with | MetavarKind.synthetic => pure true | MetavarKind.syntheticOpaque => pure true | MetavarKind.natural => pure false | _ => pure false private def isAssignable : Expr → MetaM Bool | Expr.mvar mvarId _ => do b ← isReadOnlyOrSyntheticOpaqueExprMVar mvarId; pure (!b) | _ => pure false private def etaEq (t s : Expr) : Bool := match t.etaExpanded? with | some t => t == s | none => false private def isLetFVar (fvarId : FVarId) : MetaM Bool := do decl ← getLocalDecl fvarId; pure decl.isLet private partial def isDefEqQuick : Expr → Expr → MetaM LBool | Expr.lit l₁ _, Expr.lit l₂ _ => pure (l₁ == l₂).toLBool | Expr.sort u _, Expr.sort v _ => toLBoolM $ isLevelDefEqAux u v | t@(Expr.lam _ _ _ _), s@(Expr.lam _ _ _ _) => if t == s then pure LBool.true else toLBoolM $ isDefEqBinding t s | t@(Expr.forallE _ _ _ _), s@(Expr.forallE _ _ _ _) => if t == s then pure LBool.true else toLBoolM $ isDefEqBinding t s | Expr.mdata _ t _, s => isDefEqQuick t s | t, Expr.mdata _ s _ => isDefEqQuick t s | Expr.fvar fvarId₁ _, Expr.fvar fvarId₂ _ => condM (isLetFVar fvarId₁ <||> isLetFVar fvarId₂) (pure LBool.undef) (pure (fvarId₁ == fvarId₂).toLBool) | t, s => cond (t == s) (pure LBool.true) $ cond (etaEq t s || etaEq s t) (pure LBool.true) $ -- t =?= (fun xs => t xs) let tFn := t.getAppFn; let sFn := s.getAppFn; cond (!tFn.isMVar && !sFn.isMVar) (pure LBool.undef) $ condM (isAssigned tFn) (do t ← instantiateMVars t; isDefEqQuick t s) $ condM (isAssigned sFn) (do s ← instantiateMVars s; isDefEqQuick t s) $ condM (isDelayedAssignedHead tFn t) (do t ← instantiateMVars t; isDefEqQuick t s) $ condM (isDelayedAssignedHead sFn s) (do s ← instantiateMVars s; isDefEqQuick t s) $ condM (isSynthetic tFn <&&> synthPending tFn) (do t ← instantiateMVars t; isDefEqQuick t s) $ condM (isSynthetic sFn <&&> synthPending sFn) (do s ← instantiateMVars s; isDefEqQuick t s) $ do tAssign? ← isAssignable tFn; sAssign? ← isAssignable sFn; trace! `Meta.isDefEq (t ++ (if tAssign? then " [assignable]" else " [nonassignable]") ++ " =?= " ++ s ++ (if sAssign? then " [assignable]" else " [nonassignable]")); let assign (t s : Expr) : MetaM LBool := toLBoolM $ processAssignment t s; cond (tAssign? && !sAssign?) (assign t s) $ cond (!tAssign? && sAssign?) (assign s t) $ cond (!tAssign? && !sAssign?) (if tFn.isMVar || sFn.isMVar then do ctx ← read; if ctx.config.isDefEqStuckEx then do trace! `Meta.isDefEq.stuck (t ++ " =?= " ++ s); throwEx $ Exception.isExprDefEqStuck t s else pure LBool.false else pure LBool.undef) $ do -- Both `t` and `s` are terms of the form `?m ...` tMVarDecl ← getMVarDecl tFn.mvarId!; sMVarDecl ← getMVarDecl sFn.mvarId!; if s.isMVar && !t.isMVar then /- Solve `?m t =?= ?n` by trying first `?n := ?m t`. Reason: this assignment is precise. -/ condM (commitWhen (processAssignment s t)) (pure LBool.true) $ assign t s else condM (commitWhen (processAssignment t s)) (pure LBool.true) $ assign s t private def isDefEqProofIrrel (t s : Expr) : MetaM LBool := do status ← isProofQuick t; match status with | LBool.false => pure LBool.undef | LBool.true => do tType ← inferType t; sType ← inferType s; toLBoolM $ isExprDefEqAux tType sType | LBool.undef => do tType ← inferType t; condM (isProp tType) (do sType ← inferType s; toLBoolM $ isExprDefEqAux tType sType) (pure LBool.undef) @[inline] def whenUndefDo (x : MetaM LBool) (k : MetaM Bool) : MetaM Bool := do status ← x; match status with | LBool.true => pure true | LBool.false => pure false | LBool.undef => k @[specialize] private partial def isDefEqWHNF (t s : Expr) (k : Expr → Expr → MetaM Bool) : MetaM Bool := do t' ← whnfCore t; s' ← whnfCore s; if t == t' && s == s' then k t' s' else whenUndefDo (isDefEqQuick t' s') $ k t' s' @[specialize] private def unstuckMVar (e : Expr) (successK : Expr → MetaM Bool) (failK : MetaM Bool): MetaM Bool := do s? ← WHNF.getStuckMVar getConst whnf e; match s? with | some s => condM (synthPending s) (do e ← instantiateMVars e; successK e) failK | none => failK private def isDefEqOnFailure (t s : Expr) : MetaM Bool := unstuckMVar t (fun t => isExprDefEqAux t s) $ unstuckMVar s (fun s => isExprDefEqAux t s) $ pure false /- Remove unnecessary let-decls -/ private def consumeLet : Expr → Expr | e@(Expr.letE _ _ _ b _) => if b.hasLooseBVars then e else consumeLet b | e => e partial def isExprDefEqAuxImpl : Expr → Expr → MetaM Bool | t, s => do let t := consumeLet t; let s := consumeLet s; trace `Meta.isDefEq.step $ fun _ => t ++ " =?= " ++ s; whenUndefDo (isDefEqQuick t s) $ whenUndefDo (isDefEqProofIrrel t s) $ isDefEqWHNF t s $ fun t s => do condM (isDefEqEta t s <||> isDefEqEta s t) (pure true) $ whenUndefDo (isDefEqOffset t s) $ do whenUndefDo (isDefEqDelta t s) $ match t, s with | Expr.const c us _, Expr.const d vs _ => if c == d then isListLevelDefEqAux us vs else pure false | Expr.app _ _ _, Expr.app _ _ _ => let tFn := t.getAppFn; condM (commitWhen (isExprDefEqAux tFn s.getAppFn <&&> isDefEqArgs tFn t.getAppArgs s.getAppArgs)) (pure true) (isDefEqOnFailure t s) | _, _ => isDefEqOnFailure t s @[init] def setIsExprDefEqAuxRef : IO Unit := isExprDefEqAuxRef.set isExprDefEqAuxImpl @[init] private def regTraceClasses : IO Unit := do registerTraceClass `Meta.isDefEq; registerTraceClass `Meta.isDefEq.foApprox; registerTraceClass `Meta.isDefEq.delta; registerTraceClass `Meta.isDefEq.step; registerTraceClass `Meta.isDefEq.assign end Meta end Lean
31918a854743517e7ef1e9ac8e834fc894d182ef
46125763b4dbf50619e8846a1371029346f4c3db
/src/topology/maps.lean
ab49f0d21ef1bc162d3a4918cf918a90a42cd5e7
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
15,712
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, Patrick Massot -/ import topology.order /-! # Specific classes of maps between topological spaces This file introduces the following properties of a map `f : X → Y` between topological spaces: * `is_open_map f` means the image of an open set under `f` is open. * `is_closed_map f` means the image of a closed set under `f` is closed. (Open and closed maps need not be continuous.) * `inducing f` means the topology on `X` is the one induced via `f` from the topology on `Y`. These behave like embeddings except they need not be injective. Instead, points of `X` which are identified by `f` are also indistinguishable in the topology on `X`. * `embedding f` means `f` is inducing and also injective. Equivalently, `f` identifies `X` with a subspace of `Y`. * `open_embedding f` means `f` is an embedding with open image, so it identifies `X` with an open subspace of `Y`. Equivalently, `f` is an embedding and an open map. * `closed_embedding f` similarly means `f` is an embedding with closed image, so it identifies `X` with a closed subspace of `Y`. Equivalently, `f` is an embedding and a closed map. * `quotient_map f` is the dual condition to `embedding f`: `f` is surjective and the topology on `Y` is the one coinduced via `f` from the topology on `X`. Equivalently, `f` identifies `Y` with a quotient of `X`. Quotient maps are also sometimes known as identification maps. ## References * <https://en.wikipedia.org/wiki/Open_and_closed_maps> * <https://en.wikipedia.org/wiki/Embedding#General_topology> * <https://en.wikipedia.org/wiki/Quotient_space_(topology)#Quotient_map> ## Tags open map, closed map, embedding, quotient map, identification map -/ open set filter lattice open_locale topological_space variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} section inducing structure inducing [tα : topological_space α] [tβ : topological_space β] (f : α → β) : Prop := (induced : tα = tβ.induced f) variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] lemma inducing_id : inducing (@id α) := ⟨induced_id.symm⟩ protected lemma inducing.comp {g : β → γ} {f : α → β} (hg : inducing g) (hf : inducing f) : inducing (g ∘ f) := ⟨by rw [hf.induced, hg.induced, induced_compose]⟩ lemma inducing_of_inducing_compose {f : α → β} {g : β → γ} (hf : continuous f) (hg : continuous g) (hgf : inducing (g ∘ f)) : inducing f := ⟨le_antisymm (by rwa ← continuous_iff_le_induced) (by { rw [hgf.induced, ← continuous_iff_le_induced], apply hg.comp continuous_induced_dom })⟩ lemma inducing_open {f : α → β} {s : set α} (hf : inducing f) (h : is_open (range f)) (hs : is_open s) : is_open (f '' s) := let ⟨t, ht, h_eq⟩ := by rw [hf.induced] at hs; exact hs in have is_open (t ∩ range f), from is_open_inter ht h, h_eq ▸ by rwa [image_preimage_eq_inter_range] lemma inducing_is_closed {f : α → β} {s : set α} (hf : inducing f) (h : is_closed (range f)) (hs : is_closed s) : is_closed (f '' s) := let ⟨t, ht, h_eq⟩ := by rw [hf.induced, is_closed_induced_iff] at hs; exact hs in have is_closed (t ∩ range f), from is_closed_inter ht h, h_eq.symm ▸ by rwa [image_preimage_eq_inter_range] lemma inducing.nhds_eq_comap {f : α → β} (hf : inducing f) : ∀ (a : α), 𝓝 a = comap f (𝓝 $ f a) := (induced_iff_nhds_eq f).1 hf.induced lemma inducing.map_nhds_eq {f : α → β} (hf : inducing f) (a : α) (h : range f ∈ 𝓝 (f a)) : (𝓝 a).map f = 𝓝 (f a) := hf.induced.symm ▸ map_nhds_induced_eq h lemma inducing.tendsto_nhds_iff {ι : Type*} {f : ι → β} {g : β → γ} {a : filter ι} {b : β} (hg : inducing g) : tendsto f a (𝓝 b) ↔ tendsto (g ∘ f) a (𝓝 (g b)) := by rw [tendsto, tendsto, hg.induced, nhds_induced, ← map_le_iff_le_comap, filter.map_map] lemma inducing.continuous_iff {f : α → β} {g : β → γ} (hg : inducing g) : continuous f ↔ continuous (g ∘ f) := by simp [continuous_iff_continuous_at, continuous_at, inducing.tendsto_nhds_iff hg] lemma inducing.continuous {f : α → β} (hf : inducing f) : continuous f := hf.continuous_iff.mp continuous_id end inducing section embedding /-- A function between topological spaces is an embedding if it is injective, and for all `s : set α`, `s` is open iff it is the preimage of an open set. -/ structure embedding [tα : topological_space α] [tβ : topological_space β] (f : α → β) extends inducing f : Prop := (inj : function.injective f) variables [topological_space α] [topological_space β] [topological_space γ] lemma embedding.mk' (f : α → β) (inj : function.injective f) (induced : ∀a, comap f (𝓝 (f a)) = 𝓝 a) : embedding f := ⟨⟨(induced_iff_nhds_eq f).2 (λ a, (induced a).symm)⟩, inj⟩ lemma embedding_id : embedding (@id α) := ⟨inducing_id, assume a₁ a₂ h, h⟩ lemma embedding.comp {g : β → γ} {f : α → β} (hg : embedding g) (hf : embedding f) : embedding (g ∘ f) := { inj:= assume a₁ a₂ h, hf.inj $ hg.inj h, ..hg.to_inducing.comp hf.to_inducing } lemma embedding_of_embedding_compose {f : α → β} {g : β → γ} (hf : continuous f) (hg : continuous g) (hgf : embedding (g ∘ f)) : embedding f := { induced := (inducing_of_inducing_compose hf hg hgf.to_inducing).induced, inj := assume a₁ a₂ h, hgf.inj $ by simp [h, (∘)] } lemma embedding_open {f : α → β} {s : set α} (hf : embedding f) (h : is_open (range f)) (hs : is_open s) : is_open (f '' s) := inducing_open hf.1 h hs lemma embedding_is_closed {f : α → β} {s : set α} (hf : embedding f) (h : is_closed (range f)) (hs : is_closed s) : is_closed (f '' s) := inducing_is_closed hf.1 h hs lemma embedding.map_nhds_eq {f : α → β} (hf : embedding f) (a : α) (h : range f ∈ 𝓝 (f a)) : (𝓝 a).map f = 𝓝 (f a) := inducing.map_nhds_eq hf.1 a h lemma embedding.tendsto_nhds_iff {ι : Type*} {f : ι → β} {g : β → γ} {a : filter ι} {b : β} (hg : embedding g) : tendsto f a (𝓝 b) ↔ tendsto (g ∘ f) a (𝓝 (g b)) := by rw [tendsto, tendsto, hg.induced, nhds_induced, ← map_le_iff_le_comap, filter.map_map] lemma embedding.continuous_iff {f : α → β} {g : β → γ} (hg : embedding g) : continuous f ↔ continuous (g ∘ f) := inducing.continuous_iff hg.1 lemma embedding.continuous {f : α → β} (hf : embedding f) : continuous f := inducing.continuous hf.1 lemma embedding.closure_eq_preimage_closure_image {e : α → β} (he : embedding e) (s : set α) : closure s = e ⁻¹' closure (e '' s) := by { ext x, rw [set.mem_preimage, ← closure_induced he.inj, he.induced] } end embedding /-- A function between topological spaces is a quotient map if it is surjective, and for all `s : set β`, `s` is open iff its preimage is an open set. -/ def quotient_map {α : Type*} {β : Type*} [tα : topological_space α] [tβ : topological_space β] (f : α → β) : Prop := function.surjective f ∧ tβ = tα.coinduced f namespace quotient_map variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] protected lemma id : quotient_map (@id α) := ⟨assume a, ⟨a, rfl⟩, coinduced_id.symm⟩ protected lemma comp {g : β → γ} {f : α → β} (hg : quotient_map g) (hf : quotient_map f) : quotient_map (g ∘ f) := ⟨function.surjective_comp hg.left hf.left, by rw [hg.right, hf.right, coinduced_compose]⟩ protected lemma of_quotient_map_compose {f : α → β} {g : β → γ} (hf : continuous f) (hg : continuous g) (hgf : quotient_map (g ∘ f)) : quotient_map g := ⟨assume b, let ⟨a, h⟩ := hgf.left b in ⟨f a, h⟩, le_antisymm (by rw [hgf.right, ← continuous_iff_coinduced_le]; apply continuous_coinduced_rng.comp hf) (by rwa ← continuous_iff_coinduced_le)⟩ protected lemma continuous_iff {f : α → β} {g : β → γ} (hf : quotient_map f) : continuous g ↔ continuous (g ∘ f) := by rw [continuous_iff_coinduced_le, continuous_iff_coinduced_le, hf.right, coinduced_compose] protected lemma continuous {f : α → β} (hf : quotient_map f) : continuous f := hf.continuous_iff.mp continuous_id end quotient_map /-- A map `f : α → β` is said to be an *open map*, if the image of any open `U : set α` is open in `β`. -/ def is_open_map [topological_space α] [topological_space β] (f : α → β) := ∀ U : set α, is_open U → is_open (f '' U) namespace is_open_map variables [topological_space α] [topological_space β] [topological_space γ] open function protected lemma id : is_open_map (@id α) := assume s hs, by rwa [image_id] protected lemma comp {g : β → γ} {f : α → β} (hg : is_open_map g) (hf : is_open_map f) : is_open_map (g ∘ f) := by intros s hs; rw [image_comp]; exact hg _ (hf _ hs) lemma is_open_range {f : α → β} (hf : is_open_map f) : is_open (range f) := by { rw ← image_univ, exact hf _ is_open_univ } lemma image_mem_nhds {f : α → β} (hf : is_open_map f) {x : α} {s : set α} (hx : s ∈ 𝓝 x) : f '' s ∈ 𝓝 (f x) := let ⟨t, hts, ht, hxt⟩ := mem_nhds_sets_iff.1 hx in mem_sets_of_superset (mem_nhds_sets (hf t ht) (mem_image_of_mem _ hxt)) (image_subset _ hts) lemma nhds_le {f : α → β} (hf : is_open_map f) (a : α) : 𝓝 (f a) ≤ (𝓝 a).map f := le_map $ λ s, hf.image_mem_nhds lemma of_inverse {f : α → β} {f' : β → α} (h : continuous f') (l_inv : left_inverse f f') (r_inv : right_inverse f f') : is_open_map f := assume s hs, have f' ⁻¹' s = f '' s, by ext x; simp [mem_image_iff_of_inverse r_inv l_inv], this ▸ h s hs lemma to_quotient_map {f : α → β} (open_map : is_open_map f) (cont : continuous f) (surj : function.surjective f) : quotient_map f := ⟨ surj, begin ext s, show is_open s ↔ is_open (f ⁻¹' s), split, { exact cont s }, { assume h, rw ← @image_preimage_eq _ _ _ s surj, exact open_map _ h } end⟩ end is_open_map lemma is_open_map_iff_nhds_le [topological_space α] [topological_space β] {f : α → β} : is_open_map f ↔ ∀(a:α), 𝓝 (f a) ≤ (𝓝 a).map f := begin refine ⟨λ hf, hf.nhds_le, λ h s hs, is_open_iff_mem_nhds.2 _⟩, rintros b ⟨a, ha, rfl⟩, exact h _ (filter.image_mem_map $ mem_nhds_sets hs ha) end section is_closed_map variables [topological_space α] [topological_space β] def is_closed_map (f : α → β) := ∀ U : set α, is_closed U → is_closed (f '' U) end is_closed_map namespace is_closed_map variables [topological_space α] [topological_space β] [topological_space γ] open function protected lemma id : is_closed_map (@id α) := assume s hs, by rwa image_id protected lemma comp {g : β → γ} {f : α → β} (hg : is_closed_map g) (hf : is_closed_map f) : is_closed_map (g ∘ f) := by { intros s hs, rw image_comp, exact hg _ (hf _ hs) } lemma of_inverse {f : α → β} {f' : β → α} (h : continuous f') (l_inv : left_inverse f f') (r_inv : right_inverse f f') : is_closed_map f := assume s hs, have f' ⁻¹' s = f '' s, by ext x; simp [mem_image_iff_of_inverse r_inv l_inv], this ▸ continuous_iff_is_closed.mp h s hs end is_closed_map section open_embedding variables [topological_space α] [topological_space β] [topological_space γ] /-- An open embedding is an embedding with open image. -/ structure open_embedding (f : α → β) extends embedding f : Prop := (open_range : is_open $ range f) lemma open_embedding.open_iff_image_open {f : α → β} (hf : open_embedding f) {s : set α} : is_open s ↔ is_open (f '' s) := ⟨embedding_open hf.to_embedding hf.open_range, λ h, begin convert ←hf.to_embedding.continuous _ h, apply preimage_image_eq _ hf.inj end⟩ lemma open_embedding.is_open_map {f : α → β} (hf : open_embedding f) : is_open_map f := λ s, hf.open_iff_image_open.mp lemma open_embedding.continuous {f : α → β} (hf : open_embedding f) : continuous f := hf.to_embedding.continuous lemma open_embedding.open_iff_preimage_open {f : α → β} (hf : open_embedding f) {s : set β} (hs : s ⊆ range f) : is_open s ↔ is_open (f ⁻¹' s) := begin convert ←hf.open_iff_image_open.symm, rwa [image_preimage_eq_inter_range, inter_eq_self_of_subset_left] end lemma open_embedding_of_embedding_open {f : α → β} (h₁ : embedding f) (h₂ : is_open_map f) : open_embedding f := ⟨h₁, by convert h₂ univ is_open_univ; simp⟩ lemma open_embedding_of_continuous_injective_open {f : α → β} (h₁ : continuous f) (h₂ : function.injective f) (h₃ : is_open_map f) : open_embedding f := begin refine open_embedding_of_embedding_open ⟨⟨_⟩, h₂⟩ h₃, apply le_antisymm (continuous_iff_le_induced.mp h₁) _, intro s, change is_open _ ≤ is_open _, rw is_open_induced_iff, refine λ hs, ⟨f '' s, h₃ s hs, _⟩, rw preimage_image_eq _ h₂ end lemma open_embedding_id : open_embedding (@id α) := ⟨embedding_id, by convert is_open_univ; apply range_id⟩ lemma open_embedding.comp {g : β → γ} {f : α → β} (hg : open_embedding g) (hf : open_embedding f) : open_embedding (g ∘ f) := ⟨hg.1.comp hf.1, show is_open (range (g ∘ f)), by rw [range_comp, ←hg.open_iff_image_open]; exact hf.2⟩ end open_embedding section closed_embedding variables [topological_space α] [topological_space β] [topological_space γ] /-- A closed embedding is an embedding with closed image. -/ structure closed_embedding (f : α → β) extends embedding f : Prop := (closed_range : is_closed $ range f) variables {f : α → β} lemma closed_embedding.continuous (hf : closed_embedding f) : continuous f := hf.to_embedding.continuous lemma closed_embedding.closed_iff_image_closed (hf : closed_embedding f) {s : set α} : is_closed s ↔ is_closed (f '' s) := ⟨embedding_is_closed hf.to_embedding hf.closed_range, λ h, begin convert ←continuous_iff_is_closed.mp hf.continuous _ h, apply preimage_image_eq _ hf.inj end⟩ lemma closed_embedding.is_closed_map (hf : closed_embedding f) : is_closed_map f := λ s, hf.closed_iff_image_closed.mp lemma closed_embedding.closed_iff_preimage_closed (hf : closed_embedding f) {s : set β} (hs : s ⊆ range f) : is_closed s ↔ is_closed (f ⁻¹' s) := begin convert ←hf.closed_iff_image_closed.symm, rwa [image_preimage_eq_inter_range, inter_eq_self_of_subset_left] end lemma closed_embedding_of_embedding_closed (h₁ : embedding f) (h₂ : is_closed_map f) : closed_embedding f := ⟨h₁, by convert h₂ univ is_closed_univ; simp⟩ lemma closed_embedding_of_continuous_injective_closed (h₁ : continuous f) (h₂ : function.injective f) (h₃ : is_closed_map f) : closed_embedding f := begin refine closed_embedding_of_embedding_closed ⟨⟨_⟩, h₂⟩ h₃, apply le_antisymm (continuous_iff_le_induced.mp h₁) _, intro s', change is_open _ ≤ is_open _, rw [←is_closed_compl_iff, ←is_closed_compl_iff], generalize : -s' = s, rw is_closed_induced_iff, refine λ hs, ⟨f '' s, h₃ s hs, _⟩, rw preimage_image_eq _ h₂ end lemma closed_embedding_id : closed_embedding (@id α) := ⟨embedding_id, by convert is_closed_univ; apply range_id⟩ lemma closed_embedding.comp {g : β → γ} {f : α → β} (hg : closed_embedding g) (hf : closed_embedding f) : closed_embedding (g ∘ f) := ⟨hg.to_embedding.comp hf.to_embedding, show is_closed (range (g ∘ f)), by rw [range_comp, ←hg.closed_iff_image_closed]; exact hf.closed_range⟩ end closed_embedding
53ef1b2116dd8dfc2af824cb0d87fd8fb468cc86
b32d3853770e6eaf06817a1b8c52064baaed0ef1
/src/super/debug.lean
afebaae8531a4f35d1d2dc39014ece9cca7b73c7
[]
no_license
gebner/super2
4d58b7477b6f7d945d5d866502982466db33ab0b
9bc5256c31750021ab97d6b59b7387773e54b384
refs/heads/master
1,635,021,682,021
1,634,886,326,000
1,634,886,326,000
225,600,688
4
2
null
1,598,209,306,000
1,575,371,550,000
Lean
UTF-8
Lean
false
false
500
lean
import super.utils namespace super def debugging_enabled : bool := tt open tactic @[inline] def if_debug {α} (debug no_debug : α) := by do to_expr ```(if debugging_enabled then debug else no_debug) >>= whnf >>= exact @[inline] def when_debug {m} [monad m] (tac : m unit) : m unit := if_debug tac (pure ()) @[inline] def check_result_when_debug {m} [monad m] {α} (tac : α → m unit) (wrapped : m α) : m α := if_debug (do res ← wrapped, monad_lift (tac res), pure res) wrapped end super
3b11610e9e44ad7006272001ab59573d1ee08e66
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/normed_space/star/basic.lean
5051945464265810fd5ed81274552c42cc5510df
[ "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
8,973
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.self_adjoint import algebra.star.unitary /-! # Normed star rings and algebras A normed star group is a normed group with a compatible `star` which is isometric. A C⋆-ring is a normed star group 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 group is a normed group with a compatible `star` which is isometric. -/ class normed_star_group (E : Type*) [seminormed_add_comm_group E] [star_add_monoid E] : Prop := (norm_star : ∀ x : E, ∥x⋆∥ = ∥x∥) export normed_star_group (norm_star) attribute [simp] norm_star variables {𝕜 E α : Type*} section normed_star_group variables [seminormed_add_comm_group E] [star_add_monoid E] [normed_star_group E] @[simp] lemma nnnorm_star (x : E) : ∥star x∥₊ = ∥x∥₊ := subtype.ext $ norm_star _ /-- The `star` map in a normed star group is a normed group homomorphism. -/ def star_normed_add_group_hom : normed_add_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) := show isometry star_add_equiv, by exact add_monoid_hom_class.isometry_of_norm star_add_equiv (show ∀ x, ∥x⋆∥ = ∥x∥, from norm_star) @[priority 100] instance normed_star_group.to_has_continuous_star : has_continuous_star E := ⟨star_isometry.continuous⟩ end normed_star_group instance ring_hom_isometric.star_ring_end [normed_comm_ring E] [star_ring E] [normed_star_group E] : ring_hom_isometric (star_ring_end E) := ⟨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*) [non_unital_normed_ring E] [star_ring E] : Prop := (norm_star_mul_self : ∀ {x : E}, ∥x⋆ * x∥ = ∥x∥ * ∥x∥) instance : cstar_ring ℝ := { norm_star_mul_self := λ x, by simp only [star, id.def, norm_mul] } namespace cstar_ring section non_unital variables [non_unital_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_group : normed_star_group 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] lemma nnnorm_star_mul_self {x : E} : ∥x⋆ * x∥₊ = ∥x∥₊ * ∥x∥₊ := subtype.ext norm_star_mul_self end non_unital section prod_pi variables {ι R₁ R₂ : Type*} {R : ι → Type*} variables [non_unital_normed_ring R₁] [star_ring R₁] [cstar_ring R₁] variables [non_unital_normed_ring R₂] [star_ring R₂] [cstar_ring R₂] variables [Π i, non_unital_normed_ring (R i)] [Π i, star_ring (R i)] /-- This instance exists to short circuit type class resolution because of problems with inference involving Π-types. -/ instance _root_.pi.star_ring' : star_ring (Π i, R i) := infer_instance variables [fintype ι] [Π i, cstar_ring (R i)] instance _root_.prod.cstar_ring : cstar_ring (R₁ × R₂) := { norm_star_mul_self := λ x, begin unfold norm, simp only [prod.fst_mul, prod.fst_star, prod.snd_mul, prod.snd_star, norm_star_mul_self, ←sq], refine le_antisymm _ _, { refine max_le _ _; rw [sq_le_sq, abs_of_nonneg (norm_nonneg _)], exact (le_max_left _ _).trans (le_abs_self _), exact (le_max_right _ _).trans (le_abs_self _) }, { rw le_max_iff, rcases le_total (∥x.fst∥) (∥x.snd∥) with (h | h); simp [h] } end } instance _root_.pi.cstar_ring : cstar_ring (Π i, R i) := { norm_star_mul_self := λ x, begin simp only [norm, pi.mul_apply, pi.star_apply, nnnorm_star_mul_self, ←sq], norm_cast, exact (finset.comp_sup_eq_sup_comp_of_is_total (λ x : nnreal, x ^ 2) (λ x y h, by simpa only [sq] using mul_le_mul' h h) (by simp)).symm, end } instance _root_.pi.cstar_ring' : cstar_ring (ι → R₁) := pi.cstar_ring end prod_pi section unital variables [normed_ring E] [star_ring E] [cstar_ring E] @[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 unital end cstar_ring lemma is_self_adjoint.nnnorm_pow_two_pow [normed_ring E] [star_ring E] [cstar_ring E] {x : E} (hx : is_self_adjoint x) (n : ℕ) : ∥x ^ 2 ^ n∥₊ = ∥x∥₊ ^ (2 ^ n) := begin induction n with k hk, { simp only [pow_zero, pow_one] }, { rw [pow_succ, pow_mul', sq], nth_rewrite 0 ←(self_adjoint.mem_iff.mp hx), rw [←star_pow, cstar_ring.nnnorm_star_mul_self, ←sq, hk, pow_mul'] }, end lemma self_adjoint.nnnorm_pow_two_pow [normed_ring E] [star_ring E] [cstar_ring E] (x : self_adjoint E) (n : ℕ) : ∥x ^ 2 ^ n∥₊ = ∥x∥₊ ^ (2 ^ n) := x.prop.nnnorm_pow_two_pow _ section starₗᵢ variables [comm_semiring 𝕜] [star_ring 𝕜] variables [seminormed_add_comm_group E] [star_add_monoid E] [normed_star_group 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' := 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ₗᵢ
218a18ff6d521890e63757289960c2f6c6477b35
c45b34bfd44d8607a2e8762c926e3cfaa7436201
/uexp/src/uexp/TDP_test.lean
6765107cc60a6db3e71165807405e14afcd773db
[ "BSD-2-Clause" ]
permissive
Shamrock-Frost/Cosette
b477c442c07e45082348a145f19ebb35a7f29392
24cbc4adebf627f13f5eac878f04ffa20d1209af
refs/heads/master
1,619,721,304,969
1,526,082,841,000
1,526,082,841,000
121,695,605
1
0
null
1,518,737,210,000
1,518,737,210,000
null
UTF-8
Lean
false
false
1,650
lean
import .TDP import .cosette_tactics open list io example {p q r s} {f : Tuple p → Tuple q → Tuple r → Tuple s → usr} : (∑ (a : Tuple p) (b : Tuple q) (c : Tuple r) (d : Tuple s), f a b c d) = (∑ (c : Tuple r) (a : Tuple p) (d : Tuple s) (b : Tuple q), f a b c d) := begin TDP' tactic.ac_refl, end example {p} {R S: Tuple p → usr} : (∑ (a b: Tuple p), R a * S b * S b) = (∑ (a b: Tuple p), R b * S a * S a) := begin TDP' tactic.ac_refl, end example {p} {R: Tuple p → usr} {b t: Tuple p}: (∑ (a: Tuple p), (a ≃ t) * R a * R b) = R t * R b := begin normalize_sig_body, removal_step, ac_refl, end example {p q} {R S: Tuple p → usr} {t: Tuple p} : (∑ (a b: Tuple p) (c: Tuple q), (a ≃ b) * R a * R b) = (∑ (t: Tuple p) (c: Tuple q), R t * R t) := begin normalize_sig_body, removal_step, refl, end example {r p} {R: Tuple r → usr} : (∑ (a1 a2 a3: Tuple r) (b c: Tuple p), (a2 ≃ a1) * (a2 ≃ a3) * (c ≃ b) * (R a1)) = (∑ (a: Tuple r)(b: Tuple p), R a) := begin remove_dup_sigs, refl, end example {p} {R: Tuple p → usr} {b t: Tuple p}: R t * R b = (∑ (a: Tuple p), (a ≃ t) * R a * R b) := begin apply ueq_symm, remove_dup_sigs, ac_refl, end example {r p} {R: Tuple r → usr} {k: Tuple (r++r)}: (∑ (a1 a2 a3: Tuple r) (b c: Tuple p), (k ≃ (pair a3 a2)) * (c ≃ b) * (R a1)) = (∑ (a: Tuple r)(b: Tuple p), R a) := begin remove_dup_sigs, ac_refl end example {r} {R: Tuple r → usr}: (∑ (a1), (∑ (a2: Tuple r), (a2 ≃ a1) * R a2 ) * R a1) = (∑ (t: Tuple r), R t * R t) := begin --remove_dup_sigs, simp, TDP, end
a6e0855ba8ed9c3858140c7b3d151501ccc2aee3
7cef822f3b952965621309e88eadf618da0c8ae9
/src/data/array/lemmas.lean
ded639b3c34ab1ba38fec729922dcadfdb73abf2
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
9,466
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, Mario Carneiro -/ import data.list.basic category.traversable.equiv data.vector2 universes u w namespace d_array variables {n : ℕ} {α : fin n → Type u} instance [∀ i, inhabited (α i)] : inhabited (d_array n α) := ⟨⟨λ _, default _⟩⟩ end d_array namespace array instance {n α} [inhabited α] : inhabited (array n α) := d_array.inhabited theorem to_list_of_heq {n₁ n₂ α} {a₁ : array n₁ α} {a₂ : array n₂ α} (hn : n₁ = n₂) (ha : a₁ == a₂) : a₁.to_list = a₂.to_list := by congr; assumption /- rev_list -/ section rev_list variables {n : ℕ} {α : Type u} {a : array n α} theorem rev_list_reverse_aux : ∀ i (h : i ≤ n) (t : list α), (a.iterate_aux (λ _, (::)) i h []).reverse_core t = a.rev_iterate_aux (λ _, (::)) i h t | 0 h t := rfl | (i+1) h t := rev_list_reverse_aux i _ _ @[simp] theorem rev_list_reverse : a.rev_list.reverse = a.to_list := rev_list_reverse_aux _ _ _ @[simp] theorem to_list_reverse : a.to_list.reverse = a.rev_list := by rw [←rev_list_reverse, list.reverse_reverse] end rev_list /- mem -/ section mem variables {n : ℕ} {α : Type u} {v : α} {a : array n α} theorem mem.def : v ∈ a ↔ ∃ i, a.read i = v := iff.rfl theorem mem_rev_list_aux : ∀ {i} (h : i ≤ n), (∃ (j : fin n), j.1 < i ∧ read a j = v) ↔ v ∈ a.iterate_aux (λ _, (::)) i h [] | 0 _ := ⟨λ ⟨i, n, _⟩, absurd n i.val.not_lt_zero, false.elim⟩ | (i+1) h := let IH := mem_rev_list_aux (le_of_lt h) in ⟨λ ⟨j, ji1, e⟩, or.elim (lt_or_eq_of_le $ nat.le_of_succ_le_succ ji1) (λ ji, list.mem_cons_of_mem _ $ IH.1 ⟨j, ji, e⟩) (λ je, by simp [d_array.iterate_aux]; apply or.inl; unfold read at e; have H : j = ⟨i, h⟩ := fin.eq_of_veq je; rwa [←H, e]), λ m, begin simp [d_array.iterate_aux, list.mem] at m, cases m with e m', exact ⟨⟨i, h⟩, nat.lt_succ_self _, eq.symm e⟩, exact let ⟨j, ji, e⟩ := IH.2 m' in ⟨j, nat.le_succ_of_le ji, e⟩ end⟩ @[simp] theorem mem_rev_list : v ∈ a.rev_list ↔ v ∈ a := iff.symm $ iff.trans (exists_congr $ λ j, iff.symm $ show j.1 < n ∧ read a j = v ↔ read a j = v, from and_iff_right j.2) (mem_rev_list_aux _) @[simp] theorem mem_to_list : v ∈ a.to_list ↔ v ∈ a := by rw ←rev_list_reverse; exact list.mem_reverse.trans mem_rev_list end mem /- foldr -/ section foldr variables {n : ℕ} {α : Type u} {β : Type w} {b : β} {f : α → β → β} {a : array n α} theorem rev_list_foldr_aux : ∀ {i} (h : i ≤ n), (d_array.iterate_aux a (λ _, (::)) i h []).foldr f b = d_array.iterate_aux a (λ _, f) i h b | 0 h := rfl | (j+1) h := congr_arg (f (read a ⟨j, h⟩)) (rev_list_foldr_aux _) theorem rev_list_foldr : a.rev_list.foldr f b = a.foldl b f := rev_list_foldr_aux _ end foldr /- foldl -/ section foldl variables {n : ℕ} {α : Type u} {β : Type w} {b : β} {f : β → α → β} {a : array n α} theorem to_list_foldl : a.to_list.foldl f b = a.foldl b (function.swap f) := by rw [←rev_list_reverse, list.foldl_reverse, rev_list_foldr] end foldl /- length -/ section length variables {n : ℕ} {α : Type u} theorem rev_list_length_aux (a : array n α) (i h) : (a.iterate_aux (λ _, (::)) i h []).length = i := by induction i; simp [*, d_array.iterate_aux] @[simp] theorem rev_list_length (a : array n α) : a.rev_list.length = n := rev_list_length_aux a _ _ @[simp] theorem to_list_length (a : array n α) : a.to_list.length = n := by rw[←rev_list_reverse, list.length_reverse, rev_list_length] end length /- nth -/ section nth variables {n : ℕ} {α : Type u} {a : array n α} theorem to_list_nth_le_aux (i : ℕ) (ih : i < n) : ∀ j {jh t h'}, (∀ k tl, j + k = i → list.nth_le t k tl = a.read ⟨i, ih⟩) → (a.rev_iterate_aux (λ _, (::)) j jh t).nth_le i h' = a.read ⟨i, ih⟩ | 0 _ _ _ al := al i _ $ zero_add _ | (j+1) jh t h' al := to_list_nth_le_aux j $ λ k tl hjk, show list.nth_le (a.read ⟨j, jh⟩ :: t) k tl = a.read ⟨i, ih⟩, from match k, hjk, tl with | 0, e, tl := match i, e, ih with ._, rfl, _ := rfl end | k'+1, _, tl := by simp[list.nth_le]; exact al _ _ (by simp [*]) end theorem to_list_nth_le (i : ℕ) (h h') : list.nth_le a.to_list i h' = a.read ⟨i, h⟩ := to_list_nth_le_aux _ _ _ (λ k tl, absurd tl k.not_lt_zero) @[simp] theorem to_list_nth_le' (a : array n α) (i : fin n) (h') : list.nth_le a.to_list i.1 h' = a.read i := by cases i; apply to_list_nth_le theorem to_list_nth {i v} : list.nth a.to_list i = some v ↔ ∃ h, a.read ⟨i, h⟩ = v := begin rw list.nth_eq_some, have ll := to_list_length a, split; intro h; cases h with h e; subst v, { exact ⟨ll ▸ h, (to_list_nth_le _ _ _).symm⟩ }, { exact ⟨ll.symm ▸ h, to_list_nth_le _ _ _⟩ } end theorem write_to_list {i v} : (a.write i v).to_list = a.to_list.update_nth i.1 v := list.ext_le (by simp) $ λ j h₁ h₂, begin have h₃ : j < n, {simpa using h₁}, rw [to_list_nth_le _ h₃], refine let ⟨_, e⟩ := list.nth_eq_some.1 _ in e.symm, by_cases ij : i.1 = j, { subst j, rw [show fin.mk i.val h₃ = i, from fin.eq_of_veq rfl, array.read_write, list.nth_update_nth_of_lt], simp [h₃] }, { rw [list.nth_update_nth_ne _ _ ij, a.read_write_of_ne, to_list_nth.2 ⟨h₃, rfl⟩], exact fin.ne_of_vne ij } end end nth /- enum -/ section enum variables {n : ℕ} {α : Type u} {a : array n α} theorem mem_to_list_enum {i v} : (i, v) ∈ a.to_list.enum ↔ ∃ h, a.read ⟨i, h⟩ = v := by simp [list.mem_iff_nth, to_list_nth, and.comm, and.assoc, and.left_comm] end enum /- to_array -/ section to_array variables {n : ℕ} {α : Type u} @[simp] theorem to_list_to_array (a : array n α) : a.to_list.to_array == a := heq_of_heq_of_eq (@@eq.drec_on (λ m (e : a.to_list.length = m), (d_array.mk (λ v, a.to_list.nth_le v.1 v.2)) == (@d_array.mk m (λ _, α) $ λ v, a.to_list.nth_le v.1 $ e.symm ▸ v.2)) a.to_list_length heq.rfl) $ d_array.ext $ λ ⟨i, h⟩, to_list_nth_le i h _ @[simp] theorem to_array_to_list (l : list α) : l.to_array.to_list = l := list.ext_le (to_list_length _) $ λ n h1 h2, to_list_nth_le _ _ _ end to_array /- push_back -/ section push_back variables {n : ℕ} {α : Type u} {v : α} {a : array n α} lemma push_back_rev_list_aux : ∀ i h h', d_array.iterate_aux (a.push_back v) (λ _, (::)) i h [] = d_array.iterate_aux a (λ _, (::)) i h' [] | 0 h h' := rfl | (i+1) h h' := begin simp [d_array.iterate_aux], refine ⟨_, push_back_rev_list_aux _ _ _⟩, dsimp [read, d_array.read, push_back], rw [dif_neg], refl, exact ne_of_lt h', end @[simp] theorem push_back_rev_list : (a.push_back v).rev_list = v :: a.rev_list := begin unfold push_back rev_list foldl iterate d_array.iterate, dsimp [d_array.iterate_aux, read, d_array.read, push_back], rw [dif_pos (eq.refl n)], apply congr_arg, apply push_back_rev_list_aux end @[simp] theorem push_back_to_list : (a.push_back v).to_list = a.to_list ++ [v] := by rw [←rev_list_reverse, ←rev_list_reverse, push_back_rev_list, list.reverse_cons] end push_back /- foreach -/ section foreach variables {n : ℕ} {α : Type u} {i : fin n} {f : fin n → α → α} {a : array n α} theorem read_foreach_aux : ∀ i h (b : array n α) (j : fin n), j.1 < i → (d_array.iterate_aux a (λ i v a', write a' i (f i v)) i h b).read j = f j (a.read j) | 0 hi a ⟨j, hj⟩ ji := absurd ji (nat.not_lt_zero _) | (i+1) hi a ⟨j, hj⟩ ji := begin dsimp [d_array.iterate_aux], dsimp at ji, by_cases e : (⟨i, hi⟩ : fin _) = ⟨j, hj⟩, { rw [e], simp, refl }, { rw [read_write_of_ne _ _ e, read_foreach_aux _ _ _ ⟨j, hj⟩], exact (lt_or_eq_of_le (nat.le_of_lt_succ ji)).resolve_right (ne.symm $ mt (@fin.eq_of_veq _ ⟨i, hi⟩ ⟨j, hj⟩) e) } end @[simp] theorem read_foreach : (foreach a f).read i = f i (a.read i) := read_foreach_aux _ _ _ _ i.2 end foreach /- map -/ section map variables {n : ℕ} {α : Type u} {i : fin n} {f : α → α} {a : array n α} theorem read_map : (map f a).read i = f (a.read i) := read_foreach end map /- map₂ -/ section map₂ variables {n : ℕ} {α : Type u} {i : fin n} {f : α → α → α} {a₁ a₂ : array n α} @[simp] theorem read_map₂ : (map₂ f a₁ a₂).read i = f (a₁.read i) (a₂.read i) := read_foreach end map₂ end array namespace equiv def d_array_equiv_fin {n : ℕ} (α : fin n → Type*) : d_array n α ≃ (∀ i, α i) := ⟨d_array.read, d_array.mk, λ ⟨f⟩, rfl, λ f, rfl⟩ def array_equiv_fin (n : ℕ) (α : Type*) : array n α ≃ (fin n → α) := d_array_equiv_fin _ def vector_equiv_fin (α : Type*) (n : ℕ) : vector α n ≃ (fin n → α) := ⟨vector.nth, vector.of_fn, vector.of_fn_nth, λ f, funext $ vector.nth_of_fn f⟩ def vector_equiv_array (α : Type*) (n : ℕ) : vector α n ≃ array n α := (vector_equiv_fin _ _).trans (array_equiv_fin _ _).symm end equiv namespace array open function variable {n : ℕ} instance : traversable (array n) := @equiv.traversable (flip vector n) _ (λ α, equiv.vector_equiv_array α n) _ instance : is_lawful_traversable (array n) := @equiv.is_lawful_traversable (flip vector n) _ (λ α, equiv.vector_equiv_array α n) _ _ end array
2dc3e49c0ccf7129382868c15d99ca43cded8919
2c41ae31b2b771ad5646ad880201393f5269a7f0
/Lean/Qualities/KeyPersonnel.lean
5a3aaeb0d673eafcf1bdcdac9a5114a6e4a8df00
[]
no_license
kevinsullivan/Boehm
926f25bc6f1a8b6bd47d333d936fdfc278228312
55208395bff20d48a598b7fa33a4d55a2447a9cf
refs/heads/master
1,586,127,134,302
1,488,252,326,000
1,488,252,326,000
32,836,930
0
0
null
null
null
null
UTF-8
Lean
false
false
571
lean
-- KeyPersonnel /- [KeyPersonnel] is parameterized by an instance of type [SystemType], and it's a sub-attribute to [Efficient]. -/ import SystemModel.System inductive KeyPersonnel (sys_type: SystemType): Prop | intro : (exists keyPersonnel: sys_type ^.Contexts -> sys_type ^.Phases -> sys_type ^.Stakeholders -> @SystemInstance sys_type -> Prop, forall c: sys_type ^.Contexts, forall p: sys_type ^.Phases, forall s: sys_type ^.Stakeholders, forall st: @SystemInstance sys_type, keyPersonnel c p s st) -> KeyPersonnel
0959bd1eefbb8996182ab947bc21e2fbc89e3a94
9028d228ac200bbefe3a711342514dd4e4458bff
/src/data/equiv/mul_add.lean
ce813e1f8e06043c327d93b8249ffb848d6180e9
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,134
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Callum Sutton, Yury Kudryashov -/ import data.equiv.basic import deprecated.group import algebra.group.hom /-! # Multiplicative and additive equivs In this file we define two extensions of `equiv` called `add_equiv` and `mul_equiv`, which are datatypes representing isomorphisms of `add_monoid`s/`add_group`s and `monoid`s/`group`s. We also introduce the corresponding groups of automorphisms `add_aut` and `mul_aut`. ## Notations The extended equivs all have coercions to functions, and the coercions are the canonical notation when treating the isomorphisms as maps. ## Implementation notes The fields for `mul_equiv`, `add_equiv` now avoid the unbundled `is_mul_hom` and `is_add_hom`, as these are deprecated. Definition of multiplication in the groups of automorphisms agrees with function composition, multiplication in `equiv.perm`, and multiplication in `category_theory.End`, not with `category_theory.comp`. ## Tags equiv, mul_equiv, add_equiv, mul_aut, add_aut -/ variables {A : Type*} {B : Type*} {M : Type*} {N : Type*} {P : Type*} {G : Type*} {H : Type*} set_option old_structure_cmd true /-- add_equiv α β is the type of an equiv α ≃ β which preserves addition. -/ structure add_equiv (A B : Type*) [has_add A] [has_add B] extends A ≃ B, add_hom A B /-- The `equiv` underlying an `add_equiv`. -/ add_decl_doc add_equiv.to_equiv /-- The `add_hom` underlying a `add_equiv`. -/ add_decl_doc add_equiv.to_add_hom /-- `mul_equiv α β` is the type of an equiv `α ≃ β` which preserves multiplication. -/ @[to_additive] structure mul_equiv (M N : Type*) [has_mul M] [has_mul N] extends M ≃ N, mul_hom M N /-- The `equiv` underlying a `mul_equiv`. -/ add_decl_doc mul_equiv.to_equiv /-- The `mul_hom` underlying a `mul_equiv`. -/ add_decl_doc mul_equiv.to_mul_hom infix ` ≃* `:25 := mul_equiv infix ` ≃+ `:25 := add_equiv namespace mul_equiv @[to_additive] instance [has_mul M] [has_mul N] : has_coe_to_fun (M ≃* N) := ⟨_, mul_equiv.to_fun⟩ variables [has_mul M] [has_mul N] [has_mul P] @[simp, to_additive] lemma to_fun_apply {f : M ≃* N} {m : M} : f.to_fun m = f m := rfl @[simp, to_additive] lemma to_equiv_apply {f : M ≃* N} {m : M} : f.to_equiv m = f m := rfl /-- A multiplicative isomorphism preserves multiplication (canonical form). -/ @[simp, to_additive] lemma map_mul (f : M ≃* N) : ∀ x y, f (x * y) = f x * f y := f.map_mul' /-- A multiplicative isomorphism preserves multiplication (deprecated). -/ @[to_additive] instance (h : M ≃* N) : is_mul_hom h := ⟨h.map_mul⟩ /-- Makes a multiplicative isomorphism from a bijection which preserves multiplication. -/ @[to_additive "Makes an additive isomorphism from a bijection which preserves addition."] def mk' (f : M ≃ N) (h : ∀ x y, f (x * y) = f x * f y) : M ≃* N := ⟨f.1, f.2, f.3, f.4, h⟩ @[to_additive] protected lemma bijective (e : M ≃* N) : function.bijective e := e.to_equiv.bijective @[to_additive] protected lemma injective (e : M ≃* N) : function.injective e := e.to_equiv.injective @[to_additive] protected lemma surjective (e : M ≃* N) : function.surjective e := e.to_equiv.surjective /-- The identity map is a multiplicative isomorphism. -/ @[refl, to_additive "The identity map is an additive isomorphism."] def refl (M : Type*) [has_mul M] : M ≃* M := { map_mul' := λ _ _, rfl, ..equiv.refl _} instance : inhabited (M ≃* M) := ⟨refl M⟩ /-- The inverse of an isomorphism is an isomorphism. -/ @[symm, to_additive "The inverse of an isomorphism is an isomorphism."] def symm (h : M ≃* N) : N ≃* M := { map_mul' := λ n₁ n₂, h.injective $ begin have : ∀ x, h (h.to_equiv.symm.to_fun x) = x := h.to_equiv.apply_symm_apply, simp only [this, h.map_mul] end, .. h.to_equiv.symm} @[simp, to_additive] theorem to_equiv_symm (f : M ≃* N) : f.symm.to_equiv = f.to_equiv.symm := rfl @[simp, to_additive] theorem coe_mk (f : M → N) (g h₁ h₂ h₃) : ⇑(mul_equiv.mk f g h₁ h₂ h₃) = f := rfl @[simp, to_additive] theorem coe_symm_mk (f : M → N) (g h₁ h₂ h₃) : ⇑(mul_equiv.mk f g h₁ h₂ h₃).symm = g := rfl /-- Transitivity of multiplication-preserving isomorphisms -/ @[trans, to_additive "Transitivity of addition-preserving isomorphisms"] def trans (h1 : M ≃* N) (h2 : N ≃* P) : (M ≃* P) := { map_mul' := λ x y, show h2 (h1 (x * y)) = h2 (h1 x) * h2 (h1 y), by rw [h1.map_mul, h2.map_mul], ..h1.to_equiv.trans h2.to_equiv } /-- e.right_inv in canonical form -/ @[simp, to_additive] lemma apply_symm_apply (e : M ≃* N) : ∀ y, e (e.symm y) = y := e.to_equiv.apply_symm_apply /-- e.left_inv in canonical form -/ @[simp, to_additive] lemma symm_apply_apply (e : M ≃* N) : ∀ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply @[simp, to_additive] theorem refl_apply (m : M) : refl M m = m := rfl @[simp, to_additive] theorem trans_apply (e₁ : M ≃* N) (e₂ : N ≃* P) (m : M) : e₁.trans e₂ m = e₂ (e₁ m) := rfl @[simp, to_additive] theorem apply_eq_iff_eq (e : M ≃* N) {x y : M} : e x = e y ↔ x = y := e.injective.eq_iff @[to_additive] lemma apply_eq_iff_symm_apply (e : M ≃* N) {x : M} {y : N} : e x = y ↔ x = e.symm y := e.to_equiv.apply_eq_iff_eq_symm_apply @[to_additive] lemma symm_apply_eq (e : M ≃* N) {x y} : e.symm x = y ↔ x = e y := e.to_equiv.symm_apply_eq @[to_additive] lemma eq_symm_apply (e : M ≃* N) {x y} : y = e.symm x ↔ e y = x := e.to_equiv.eq_symm_apply /-- a multiplicative equiv of monoids sends 1 to 1 (and is hence a monoid isomorphism) -/ @[simp, to_additive] lemma map_one {M N} [monoid M] [monoid N] (h : M ≃* N) : h 1 = 1 := by rw [←mul_one (h 1), ←h.apply_symm_apply 1, ←h.map_mul, one_mul] @[simp, to_additive] lemma map_eq_one_iff {M N} [monoid M] [monoid N] (h : M ≃* N) {x : M} : h x = 1 ↔ x = 1 := h.map_one ▸ h.to_equiv.apply_eq_iff_eq @[to_additive] lemma map_ne_one_iff {M N} [monoid M] [monoid N] (h : M ≃* N) {x : M} : h x ≠ 1 ↔ x ≠ 1 := ⟨mt h.map_eq_one_iff.2, mt h.map_eq_one_iff.1⟩ /-- A bijective `monoid` homomorphism is an isomorphism -/ @[to_additive "A bijective `add_monoid` homomorphism is an isomorphism"] noncomputable def of_bijective {M N} [monoid M] [monoid N] (f : M →* N) (hf : function.bijective f) : M ≃* N := { map_mul' := f.map_mul', ..equiv.of_bijective f hf } /-- Extract the forward direction of a multiplicative equivalence as a multiplication-preserving function. -/ @[to_additive "Extract the forward direction of an additive equivalence as an addition-preserving function."] def to_monoid_hom {M N} [monoid M] [monoid N] (h : M ≃* N) : (M →* N) := { map_one' := h.map_one, .. h } @[simp, to_additive] lemma to_monoid_hom_apply {M N} [monoid M] [monoid N] (e : M ≃* N) (x : M) : e.to_monoid_hom x = e x := rfl /-- A multiplicative equivalence of groups preserves inversion. -/ @[simp, to_additive] lemma map_inv [group G] [group H] (h : G ≃* H) (x : G) : h x⁻¹ = (h x)⁻¹ := h.to_monoid_hom.map_inv x /-- A multiplicative bijection between two monoids is a monoid hom (deprecated -- use to_monoid_hom). -/ @[to_additive] instance is_monoid_hom {M N} [monoid M] [monoid N] (h : M ≃* N) : is_monoid_hom h := ⟨h.map_one⟩ /-- A multiplicative bijection between two groups is a group hom (deprecated -- use to_monoid_hom). -/ @[to_additive] instance is_group_hom {G H} [group G] [group H] (h : G ≃* H) : is_group_hom h := { map_mul := h.map_mul } /-- Two multiplicative isomorphisms agree if they are defined by the same underlying function. -/ @[ext, to_additive "Two additive isomorphisms agree if they are defined by the same underlying function."] lemma ext {f g : mul_equiv M N} (h : ∀ x, f x = g x) : f = g := begin have h₁ : f.to_equiv = g.to_equiv := equiv.ext h, cases f, cases g, congr, { exact (funext h) }, { exact congr_arg equiv.inv_fun h₁ } end @[to_additive] lemma to_monoid_hom_injective {M N} [monoid M] [monoid N] : function.injective (to_monoid_hom : (M ≃* N) → M →* N) := λ f g h, mul_equiv.ext (monoid_hom.ext_iff.1 h) attribute [ext] add_equiv.ext end mul_equiv /-- An additive equivalence of additive groups preserves subtraction. -/ lemma add_equiv.map_sub [add_group A] [add_group B] (h : A ≃+ B) (x y : A) : h (x - y) = h x - h y := h.to_add_monoid_hom.map_sub x y instance add_equiv.inhabited {M : Type*} [has_add M] : inhabited (M ≃+ M) := ⟨add_equiv.refl M⟩ /-- The group of multiplicative automorphisms. -/ @[to_additive "The group of additive automorphisms."] def mul_aut (M : Type*) [has_mul M] := M ≃* M attribute [reducible] mul_aut add_aut namespace mul_aut variables (M) [has_mul M] /-- The group operation on multiplicative automorphisms is defined by `λ g h, mul_equiv.trans h g`. This means that multiplication agrees with composition, `(g*h)(x) = g (h x)`. -/ instance : group (mul_aut M) := by refine_struct { mul := λ g h, mul_equiv.trans h g, one := mul_equiv.refl M, inv := mul_equiv.symm }; intros; ext; try { refl }; apply equiv.left_inv instance : inhabited (mul_aut M) := ⟨1⟩ @[simp] lemma coe_mul (e₁ e₂ : mul_aut M) : ⇑(e₁ * e₂) = e₁ ∘ e₂ := rfl @[simp] lemma coe_one : ⇑(1 : mul_aut M) = id := rfl lemma mul_def (e₁ e₂ : mul_aut M) : e₁ * e₂ = e₂.trans e₁ := rfl lemma one_def : (1 : mul_aut M) = mul_equiv.refl _ := rfl lemma inv_def (e₁ : mul_aut M) : e₁⁻¹ = e₁.symm := rfl @[simp] lemma mul_apply (e₁ e₂ : mul_aut M) (m : M) : (e₁ * e₂) m = e₁ (e₂ m) := rfl @[simp] lemma one_apply (m : M) : (1 : mul_aut M) m = m := rfl @[simp] lemma apply_inv_self (e : mul_aut M) (m : M) : e (e⁻¹ m) = m := mul_equiv.apply_symm_apply _ _ @[simp] lemma inv_apply_self (e : mul_aut M) (m : M) : e⁻¹ (e m) = m := mul_equiv.apply_symm_apply _ _ /-- Monoid hom from the group of multiplicative automorphisms to the group of permutations. -/ def to_perm : mul_aut M →* equiv.perm M := by refine_struct { to_fun := mul_equiv.to_equiv }; intros; refl /-- group conjugation as a group homomorphism into the automorphism group. `conj g h = g * h * g⁻¹` -/ def conj [group G] : G →* mul_aut G := { to_fun := λ g, { to_fun := λ h, g * h * g⁻¹, inv_fun := λ h, g⁻¹ * h * g, left_inv := λ _, by simp [mul_assoc], right_inv := λ _, by simp [mul_assoc], map_mul' := by simp [mul_assoc] }, map_mul' := λ _ _, by ext; simp [mul_assoc], map_one' := by ext; simp [mul_assoc] } @[simp] lemma conj_apply [group G] (g h : G) : conj g h = g * h * g⁻¹ := rfl @[simp] lemma conj_symm_apply [group G] (g h : G) : (conj g).symm h = g⁻¹ * h * g := rfl @[simp] lemma conj_inv_apply {G : Type*} [group G] (g h : G) : (conj g)⁻¹ h = g⁻¹ * h * g := rfl end mul_aut namespace add_aut variables (A) [has_add A] /-- The group operation on additive automorphisms is defined by `λ g h, mul_equiv.trans h g`. This means that multiplication agrees with composition, `(g*h)(x) = g (h x)`. -/ instance group : group (add_aut A) := by refine_struct { mul := λ g h, add_equiv.trans h g, one := add_equiv.refl A, inv := add_equiv.symm }; intros; ext; try { refl }; apply equiv.left_inv instance : inhabited (add_aut A) := ⟨1⟩ @[simp] lemma coe_mul (e₁ e₂ : add_aut A) : ⇑(e₁ * e₂) = e₁ ∘ e₂ := rfl @[simp] lemma coe_one : ⇑(1 : add_aut A) = id := rfl lemma mul_def (e₁ e₂ : add_aut A) : e₁ * e₂ = e₂.trans e₁ := rfl lemma one_def : (1 : add_aut A) = add_equiv.refl _ := rfl lemma inv_def (e₁ : add_aut A) : e₁⁻¹ = e₁.symm := rfl @[simp] lemma mul_apply (e₁ e₂ : add_aut A) (a : A) : (e₁ * e₂) a = e₁ (e₂ a) := rfl @[simp] lemma one_apply (a : A) : (1 : add_aut A) a = a := rfl @[simp] lemma apply_inv_self (e : add_aut A) (a : A) : e⁻¹ (e a) = a := add_equiv.apply_symm_apply _ _ @[simp] lemma inv_apply_self (e : add_aut A) (a : A) : e (e⁻¹ a) = a := add_equiv.apply_symm_apply _ _ /-- Monoid hom from the group of multiplicative automorphisms to the group of permutations. -/ def to_perm : add_aut A →* equiv.perm A := by refine_struct { to_fun := add_equiv.to_equiv }; intros; refl end add_aut /-- A group is isomorphic to its group of units. -/ @[to_additive to_add_units "An additive group is isomorphic to its group of additive units"] def to_units {G} [group G] : G ≃* units G := { to_fun := λ x, ⟨x, x⁻¹, mul_inv_self _, inv_mul_self _⟩, inv_fun := coe, left_inv := λ x, rfl, right_inv := λ u, units.ext rfl, map_mul' := λ x y, units.ext rfl } namespace units variables [monoid M] [monoid N] [monoid P] /-- A multiplicative equivalence of monoids defines a multiplicative equivalence of their groups of units. -/ def map_equiv (h : M ≃* N) : units M ≃* units N := { inv_fun := map h.symm.to_monoid_hom, left_inv := λ u, ext $ h.left_inv u, right_inv := λ u, ext $ h.right_inv u, .. map h.to_monoid_hom } /-- Left multiplication by a unit of a monoid is a permutation of the underlying type. -/ @[to_additive "Left addition of an additive unit is a permutation of the underlying type."] def mul_left (u : units M) : equiv.perm M := { to_fun := λx, u * x, inv_fun := λx, ↑u⁻¹ * x, left_inv := u.inv_mul_cancel_left, right_inv := u.mul_inv_cancel_left } @[simp, to_additive] lemma coe_mul_left (u : units M) : ⇑u.mul_left = (*) u := rfl @[simp, to_additive] lemma mul_left_symm (u : units M) : u.mul_left.symm = u⁻¹.mul_left := equiv.ext $ λ x, rfl /-- Right multiplication by a unit of a monoid is a permutation of the underlying type. -/ @[to_additive "Right addition of an additive unit is a permutation of the underlying type."] def mul_right (u : units M) : equiv.perm M := { to_fun := λx, x * u, inv_fun := λx, x * ↑u⁻¹, left_inv := λ x, mul_inv_cancel_right x u, right_inv := λ x, inv_mul_cancel_right x u } @[simp, to_additive] lemma coe_mul_right (u : units M) : ⇑u.mul_right = λ x : M, x * u := rfl @[simp, to_additive] lemma mul_right_symm (u : units M) : u.mul_right.symm = u⁻¹.mul_right := equiv.ext $ λ x, rfl end units namespace equiv section group variables [group G] /-- Left multiplication in a `group` is a permutation of the underlying type. -/ @[to_additive "Left addition in an `add_group` is a permutation of the underlying type."] protected def mul_left (a : G) : perm G := (to_units a).mul_left @[simp, to_additive] lemma coe_mul_left (a : G) : ⇑(equiv.mul_left a) = (*) a := rfl @[simp, to_additive] lemma mul_left_symm (a : G) : (equiv.mul_left a).symm = equiv.mul_left a⁻¹ := ext $ λ x, rfl /-- Right multiplication in a `group` is a permutation of the underlying type. -/ @[to_additive "Right addition in an `add_group` is a permutation of the underlying type."] protected def mul_right (a : G) : perm G := (to_units a).mul_right @[simp, to_additive] lemma coe_mul_right (a : G) : ⇑(equiv.mul_right a) = λ x, x * a := rfl @[simp, to_additive] lemma mul_right_symm (a : G) : (equiv.mul_right a).symm = equiv.mul_right a⁻¹ := ext $ λ x, rfl variable (G) /-- Inversion on a `group` is a permutation of the underlying type. -/ @[to_additive "Negation on an `add_group` is a permutation of the underlying type."] protected def inv : perm G := { to_fun := λa, a⁻¹, inv_fun := λa, a⁻¹, left_inv := assume a, inv_inv a, right_inv := assume a, inv_inv a } variable {G} @[simp, to_additive] lemma coe_inv : ⇑(equiv.inv G) = has_inv.inv := rfl @[simp, to_additive] lemma inv_symm : (equiv.inv G).symm = equiv.inv G := rfl end group section point_reflection variables [add_comm_group A] (x y : A) /-- Point reflection in `x` as a permutation. -/ def point_reflection (x : A) : perm A := (equiv.neg A).trans (equiv.add_left (x + x)) lemma point_reflection_apply : point_reflection x y = x + x - y := rfl @[simp] lemma point_reflection_self : point_reflection x x = x := add_sub_cancel _ _ lemma point_reflection_involutive : function.involutive (point_reflection x : A → A) := λ y, by simp only [point_reflection_apply, sub_sub_cancel] @[simp] lemma point_reflection_symm : (point_reflection x).symm = point_reflection x := by { ext y, rw [symm_apply_eq, point_reflection_involutive x y] } /-- `x` is the only fixed point of `point_reflection x`. This lemma requires `x + x = y + y ↔ x = y`. There is no typeclass to use here, so we add it as an explicit argument. -/ lemma point_reflection_fixed_iff_of_bit0_injective {x y : A} (h : function.injective (bit0 : A → A)) : point_reflection x y = y ↔ y = x := sub_eq_iff_eq_add.trans $ h.eq_iff.trans eq_comm end point_reflection end equiv section type_tags /-- Reinterpret `G ≃+ H` as `multiplicative G ≃* multiplicative H`. -/ def add_equiv.to_multiplicative [add_monoid G] [add_monoid H] : (G ≃+ H) ≃ (multiplicative G ≃* multiplicative H) := { to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative, f.symm.to_add_monoid_hom.to_multiplicative, f.3, f.4, f.5⟩, inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, }, } /-- Reinterpret `G ≃* H` as `additive G ≃+ additive H`. -/ def mul_equiv.to_additive [monoid G] [monoid H] : (G ≃* H) ≃ (additive G ≃+ additive H) := { to_fun := λ f, ⟨f.to_monoid_hom.to_additive, f.symm.to_monoid_hom.to_additive, f.3, f.4, f.5⟩, inv_fun := λ f, ⟨f.to_add_monoid_hom, f.symm.to_add_monoid_hom, f.3, f.4, f.5⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, }, } /-- Reinterpret `additive G ≃+ H` as `G ≃* multiplicative H`. -/ def add_equiv.to_multiplicative' [monoid G] [add_monoid H] : (additive G ≃+ H) ≃ (G ≃* multiplicative H) := { to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative', f.symm.to_add_monoid_hom.to_multiplicative'', f.3, f.4, f.5⟩, inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, }, } /-- Reinterpret `G ≃* multiplicative H` as `additive G ≃+ H` as. -/ def mul_equiv.to_additive' [monoid G] [add_monoid H] : (G ≃* multiplicative H) ≃ (additive G ≃+ H) := add_equiv.to_multiplicative'.symm /-- Reinterpret `G ≃+ additive H` as `multiplicative G ≃* H`. -/ def add_equiv.to_multiplicative'' [add_monoid G] [monoid H] : (G ≃+ additive H) ≃ (multiplicative G ≃* H) := { to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative'', f.symm.to_add_monoid_hom.to_multiplicative', f.3, f.4, f.5⟩, inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, }, } /-- Reinterpret `multiplicative G ≃* H` as `G ≃+ additive H` as. -/ def mul_equiv.to_additive'' [add_monoid G] [monoid H] : (multiplicative G ≃* H) ≃ (G ≃+ additive H) := add_equiv.to_multiplicative''.symm end type_tags
cf8ae6bb31b4ab4740558e9f1e3d1bede24ff21f
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/analysis/analytic/basic.lean
9f0a2852094b4696dd3c2111f45919ad0e01ec4f
[ "Apache-2.0" ]
permissive
DanielFabian/mathlib
efc3a50b5dde303c59eeb6353ef4c35a345d7112
f520d07eba0c852e96fe26da71d85bf6d40fcc2a
refs/heads/master
1,668,739,922,971
1,595,201,756,000
1,595,201,756,000
279,469,476
0
0
null
1,594,696,604,000
1,594,696,604,000
null
UTF-8
Lean
false
false
37,970
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.calculus.times_cont_diff import tactic.omega import analysis.special_functions.pow /-! # Analytic functions A function is analytic in one dimension around `0` if it can be written as a converging power series `Σ pₙ zⁿ`. This definition can be extended to any dimension (even in infinite dimension) by requiring that `pₙ` is a continuous `n`-multilinear map. In general, `pₙ` is not unique (in two dimensions, taking `p₂ (x, y) (x', y') = x y'` or `y x'` gives the same map when applied to a vector `(x, y) (x, y)`). A way to guarantee uniqueness is to take a symmetric `pₙ`, but this is not always possible in nonzero characteristic (in characteristic 2, the previous example has no symmetric representative). Therefore, we do not insist on symmetry or uniqueness in the definition, and we only require the existence of a converging series. The general framework is important to say that the exponential map on bounded operators on a Banach space is analytic, as well as the inverse on invertible operators. ## Main definitions Let `p` be a formal multilinear series from `E` to `F`, i.e., `p n` is a multilinear map on `E^n` for `n : ℕ`. * `p.radius`: the largest `r : ennreal` such that `∥p n∥ * r^n` grows subexponentially, defined as a liminf. * `p.le_radius_of_bound`, `p.bound_of_lt_radius`, `p.geometric_bound_of_lt_radius`: relating the value of the radius with the growth of `∥p n∥ * r^n`. * `p.partial_sum n x`: the sum `∑_{i = 0}^{n-1} pᵢ xⁱ`. * `p.sum x`: the sum `∑'_{i = 0}^{∞} pᵢ xⁱ`. Additionally, let `f` be a function from `E` to `F`. * `has_fpower_series_on_ball f p x r`: on the ball of center `x` with radius `r`, `f (x + y) = ∑'_n pₙ yⁿ`. * `has_fpower_series_at f p x`: on some ball of center `x` with positive radius, holds `has_fpower_series_on_ball f p x r`. * `analytic_at 𝕜 f x`: there exists a power series `p` such that holds `has_fpower_series_at f p x`. We develop the basic properties of these notions, notably: * If a function admits a power series, it is continuous (see `has_fpower_series_on_ball.continuous_on` and `has_fpower_series_at.continuous_at` and `analytic_at.continuous_at`). * In a complete space, the sum of a formal power series with positive radius is well defined on the disk of convergence, see `formal_multilinear_series.has_fpower_series_on_ball`. * If a function admits a power series in a ball, then it is analytic at any point `y` of this ball, and the power series there can be expressed in terms of the initial power series `p` as `p.change_origin y`. See `has_fpower_series_on_ball.change_origin`. It follows in particular that the set of points at which a given function is analytic is open, see `is_open_analytic_at`. ## Implementation details We only introduce the radius of convergence of a power series, as `p.radius`. For a power series in finitely many dimensions, there is a finer (directional, coordinate-dependent) notion, describing the polydisk of convergence. This notion is more specific, and not necessary to build the general theory. We do not define it here. -/ noncomputable theory variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {G : Type*} [normed_group G] [normed_space 𝕜 G] open_locale topological_space classical big_operators open filter /-! ### The radius of a formal multilinear series -/ namespace formal_multilinear_series /-- The radius of a formal multilinear series is the largest `r` such that the sum `Σ pₙ yⁿ` converges for all `∥y∥ < r`. -/ def radius (p : formal_multilinear_series 𝕜 E F) : ennreal := liminf at_top (λ n, 1/((nnnorm (p n)) ^ (1 / (n : ℝ)) : nnreal)) /--If `∥pₙ∥ rⁿ` is bounded in `n`, then the radius of `p` is at least `r`. -/ lemma le_radius_of_bound (p : formal_multilinear_series 𝕜 E F) (C : nnreal) {r : nnreal} (h : ∀ (n : ℕ), nnnorm (p n) * r^n ≤ C) : (r : ennreal) ≤ p.radius := begin have L : tendsto (λ n : ℕ, (r : ennreal) / ((C + 1)^(1/(n : ℝ)) : nnreal)) at_top (𝓝 ((r : ennreal) / ((C + 1)^(0 : ℝ) : nnreal))), { apply ennreal.tendsto.div tendsto_const_nhds, { simp }, { rw ennreal.tendsto_coe, apply tendsto_const_nhds.nnrpow (tendsto_const_div_at_top_nhds_0_nat 1), simp }, { simp } }, have A : ∀ n : ℕ , 0 < n → (r : ennreal) ≤ ((C + 1)^(1/(n : ℝ)) : nnreal) * (1 / (nnnorm (p n) ^ (1/(n:ℝ)) : nnreal)), { assume n npos, simp only [one_div_eq_inv, mul_assoc, mul_one, eq.symm ennreal.mul_div_assoc], rw [ennreal.le_div_iff_mul_le _ _, ← nnreal.pow_nat_rpow_nat_inv r npos, ← ennreal.coe_mul, ennreal.coe_le_coe, ← nnreal.mul_rpow, mul_comm], { exact nnreal.rpow_le_rpow (le_trans (h n) (le_add_right (le_refl _))) (by simp) }, { simp }, { simp } }, have B : ∀ᶠ (n : ℕ) in at_top, (r : ennreal) / ((C + 1)^(1/(n : ℝ)) : nnreal) ≤ 1 / (nnnorm (p n) ^ (1/(n:ℝ)) : nnreal), { apply eventually_at_top.2 ⟨1, λ n hn, _⟩, rw [ennreal.div_le_iff_le_mul, mul_comm], { apply A n hn }, { simp }, { simp } }, have D : liminf at_top (λ n : ℕ, (r : ennreal) / ((C + 1)^(1/(n : ℝ)) : nnreal)) ≤ p.radius := liminf_le_liminf B, rw liminf_eq_of_tendsto filter.at_top_ne_bot L at D, simpa using D end /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` is bounded. -/ lemma bound_of_lt_radius (p : formal_multilinear_series 𝕜 E F) {r : nnreal} (h : (r : ennreal) < p.radius) : ∃ (C : nnreal), ∀ n, nnnorm (p n) * r^n ≤ C := begin obtain ⟨N, hN⟩ : ∃ (N : ℕ), ∀ n, n ≥ N → (r : ennreal) < 1 / ↑(nnnorm (p n) ^ (1 / (n : ℝ))) := eventually.exists_forall_of_at_top (eventually_lt_of_lt_liminf h), obtain ⟨D, hD⟩ : ∃D, ∀ x ∈ (↑((finset.range N.succ).image (λ i, nnnorm (p i) * r^i))), x ≤ D := finset.bdd_above _, refine ⟨max D 1, λ n, _⟩, cases le_or_lt n N with hn hn, { refine le_trans _ (le_max_left D 1), apply hD, have : n ∈ finset.range N.succ := list.mem_range.mpr (nat.lt_succ_iff.mpr hn), exact finset.mem_image_of_mem _ this }, { by_cases hpn : nnnorm (p n) = 0, { simp [hpn] }, have A : nnnorm (p n) ^ (1 / (n : ℝ)) ≠ 0, by simp [nnreal.rpow_eq_zero_iff, hpn], have B : r < (nnnorm (p n) ^ (1 / (n : ℝ)))⁻¹, { have := hN n (le_of_lt hn), rwa [ennreal.div_def, ← ennreal.coe_inv A, one_mul, ennreal.coe_lt_coe] at this }, rw [nnreal.lt_inv_iff_mul_lt A, mul_comm] at B, have : (nnnorm (p n) ^ (1 / (n : ℝ)) * r) ^ n ≤ 1 := pow_le_one n (zero_le (nnnorm (p n) ^ (1 / ↑n) * r)) (le_of_lt B), rw [mul_pow, one_div_eq_inv, nnreal.rpow_nat_inv_pow_nat _ (lt_of_le_of_lt (zero_le _) hn)] at this, exact le_trans this (le_max_right _ _) }, end /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` tends to zero exponentially. -/ lemma geometric_bound_of_lt_radius (p : formal_multilinear_series 𝕜 E F) {r : nnreal} (h : (r : ennreal) < p.radius) : ∃ a C, a < 1 ∧ ∀ n, nnnorm (p n) * r^n ≤ C * a^n := begin obtain ⟨t, rt, tp⟩ : ∃ (t : nnreal), (r : ennreal) < t ∧ (t : ennreal) < p.radius := ennreal.lt_iff_exists_nnreal_btwn.1 h, rw ennreal.coe_lt_coe at rt, have tpos : t ≠ 0 := ne_of_gt (lt_of_le_of_lt (zero_le _) rt), obtain ⟨C, hC⟩ : ∃ (C : nnreal), ∀ n, nnnorm (p n) * t^n ≤ C := p.bound_of_lt_radius tp, refine ⟨r / t, C, nnreal.div_lt_one_of_lt rt, λ n, _⟩, calc nnnorm (p n) * r ^ n = (nnnorm (p n) * t ^ n) * (r / t) ^ n : by { field_simp [tpos], ac_refl } ... ≤ C * (r / t) ^ n : mul_le_mul_of_nonneg_right (hC n) (zero_le _) end /-- The radius of the sum of two formal series is at least the minimum of their two radii. -/ lemma min_radius_le_radius_add (p q : formal_multilinear_series 𝕜 E F) : min p.radius q.radius ≤ (p + q).radius := begin refine le_of_forall_ge_of_dense (λ r hr, _), cases r, { simpa using hr }, obtain ⟨Cp, hCp⟩ : ∃ (C : nnreal), ∀ n, nnnorm (p n) * r^n ≤ C := p.bound_of_lt_radius (lt_of_lt_of_le hr (min_le_left _ _)), obtain ⟨Cq, hCq⟩ : ∃ (C : nnreal), ∀ n, nnnorm (q n) * r^n ≤ C := q.bound_of_lt_radius (lt_of_lt_of_le hr (min_le_right _ _)), have : ∀ n, nnnorm ((p + q) n) * r^n ≤ Cp + Cq, { assume n, calc nnnorm (p n + q n) * r ^ n ≤ (nnnorm (p n) + nnnorm (q n)) * r ^ n : mul_le_mul_of_nonneg_right (norm_add_le (p n) (q n)) (zero_le (r ^ n)) ... ≤ Cp + Cq : by { rw add_mul, exact add_le_add (hCp n) (hCq n) } }, exact (p + q).le_radius_of_bound _ this end lemma radius_neg (p : formal_multilinear_series 𝕜 E F) : (-p).radius = p.radius := by simp [formal_multilinear_series.radius, nnnorm_neg] /-- Given a formal multilinear series `p` and a vector `x`, then `p.sum x` is the sum `Σ pₙ xⁿ`. A priori, it only behaves well when `∥x∥ < p.radius`. -/ protected def sum (p : formal_multilinear_series 𝕜 E F) (x : E) : F := tsum (λn:ℕ, p n (λ(i : fin n), x)) /-- Given a formal multilinear series `p` and a vector `x`, then `p.partial_sum n x` is the sum `Σ pₖ xᵏ` for `k ∈ {0,..., n-1}`. -/ def partial_sum (p : formal_multilinear_series 𝕜 E F) (n : ℕ) (x : E) : F := ∑ k in finset.range n, p k (λ(i : fin k), x) /-- The partial sums of a formal multilinear series are continuous. -/ lemma partial_sum_continuous (p : formal_multilinear_series 𝕜 E F) (n : ℕ) : continuous (p.partial_sum n) := continuous_finset_sum (finset.range n) $ λ k hk, (p k).cont.comp (continuous_pi (λ i, continuous_id)) end formal_multilinear_series /-! ### Expanding a function as a power series -/ section variables {f g : E → F} {p pf pg : formal_multilinear_series 𝕜 E F} {x : E} {r r' : ennreal} /-- Given a function `f : E → F` and a formal multilinear series `p`, we say that `f` has `p` as a power series on the ball of radius `r > 0` around `x` if `f (x + y) = ∑' pₙ yⁿ` for all `∥y∥ < r`. -/ structure has_fpower_series_on_ball (f : E → F) (p : formal_multilinear_series 𝕜 E F) (x : E) (r : ennreal) : Prop := (r_le : r ≤ p.radius) (r_pos : 0 < r) (has_sum : ∀ {y}, y ∈ emetric.ball (0 : E) r → has_sum (λn:ℕ, p n (λ(i : fin n), y)) (f (x + y))) /-- Given a function `f : E → F` and a formal multilinear series `p`, we say that `f` has `p` as a power series around `x` if `f (x + y) = ∑' pₙ yⁿ` for all `y` in a neighborhood of `0`. -/ def has_fpower_series_at (f : E → F) (p : formal_multilinear_series 𝕜 E F) (x : E) := ∃ r, has_fpower_series_on_ball f p x r variable (𝕜) /-- Given a function `f : E → F`, we say that `f` is analytic at `x` if it admits a convergent power series expansion around `x`. -/ def analytic_at (f : E → F) (x : E) := ∃ (p : formal_multilinear_series 𝕜 E F), has_fpower_series_at f p x variable {𝕜} lemma has_fpower_series_on_ball.has_fpower_series_at (hf : has_fpower_series_on_ball f p x r) : has_fpower_series_at f p x := ⟨r, hf⟩ lemma has_fpower_series_at.analytic_at (hf : has_fpower_series_at f p x) : analytic_at 𝕜 f x := ⟨p, hf⟩ lemma has_fpower_series_on_ball.analytic_at (hf : has_fpower_series_on_ball f p x r) : analytic_at 𝕜 f x := hf.has_fpower_series_at.analytic_at lemma has_fpower_series_on_ball.radius_pos (hf : has_fpower_series_on_ball f p x r) : 0 < p.radius := lt_of_lt_of_le hf.r_pos hf.r_le lemma has_fpower_series_at.radius_pos (hf : has_fpower_series_at f p x) : 0 < p.radius := let ⟨r, hr⟩ := hf in hr.radius_pos lemma has_fpower_series_on_ball.mono (hf : has_fpower_series_on_ball f p x r) (r'_pos : 0 < r') (hr : r' ≤ r) : has_fpower_series_on_ball f p x r' := ⟨le_trans hr hf.1, r'_pos, λ y hy, hf.has_sum (emetric.ball_subset_ball hr hy)⟩ lemma has_fpower_series_on_ball.add (hf : has_fpower_series_on_ball f pf x r) (hg : has_fpower_series_on_ball g pg x r) : has_fpower_series_on_ball (f + g) (pf + pg) x r := { r_le := le_trans (le_min_iff.2 ⟨hf.r_le, hg.r_le⟩) (pf.min_radius_le_radius_add pg), r_pos := hf.r_pos, has_sum := λ y hy, (hf.has_sum hy).add (hg.has_sum hy) } lemma has_fpower_series_at.add (hf : has_fpower_series_at f pf x) (hg : has_fpower_series_at g pg x) : has_fpower_series_at (f + g) (pf + pg) x := begin rcases hf with ⟨rf, hrf⟩, rcases hg with ⟨rg, hrg⟩, have P : 0 < min rf rg, by simp [hrf.r_pos, hrg.r_pos], exact ⟨min rf rg, (hrf.mono P (min_le_left _ _)).add (hrg.mono P (min_le_right _ _))⟩ end lemma analytic_at.add (hf : analytic_at 𝕜 f x) (hg : analytic_at 𝕜 g x) : analytic_at 𝕜 (f + g) x := let ⟨pf, hpf⟩ := hf, ⟨qf, hqf⟩ := hg in (hpf.add hqf).analytic_at lemma has_fpower_series_on_ball.neg (hf : has_fpower_series_on_ball f pf x r) : has_fpower_series_on_ball (-f) (-pf) x r := { r_le := by { rw pf.radius_neg, exact hf.r_le }, r_pos := hf.r_pos, has_sum := λ y hy, (hf.has_sum hy).neg } lemma has_fpower_series_at.neg (hf : has_fpower_series_at f pf x) : has_fpower_series_at (-f) (-pf) x := let ⟨rf, hrf⟩ := hf in hrf.neg.has_fpower_series_at lemma analytic_at.neg (hf : analytic_at 𝕜 f x) : analytic_at 𝕜 (-f) x := let ⟨pf, hpf⟩ := hf in hpf.neg.analytic_at lemma has_fpower_series_on_ball.sub (hf : has_fpower_series_on_ball f pf x r) (hg : has_fpower_series_on_ball g pg x r) : has_fpower_series_on_ball (f - g) (pf - pg) x r := hf.add hg.neg lemma has_fpower_series_at.sub (hf : has_fpower_series_at f pf x) (hg : has_fpower_series_at g pg x) : has_fpower_series_at (f - g) (pf - pg) x := hf.add hg.neg lemma analytic_at.sub (hf : analytic_at 𝕜 f x) (hg : analytic_at 𝕜 g x) : analytic_at 𝕜 (f - g) x := hf.add hg.neg lemma has_fpower_series_on_ball.coeff_zero (hf : has_fpower_series_on_ball f pf x r) (v : fin 0 → E) : pf 0 v = f x := begin have v_eq : v = (λ i, 0), by { ext i, apply fin_zero_elim i }, have zero_mem : (0 : E) ∈ emetric.ball (0 : E) r, by simp [hf.r_pos], have : ∀ i ≠ 0, pf i (λ j, 0) = 0, { assume i hi, have : 0 < i := bot_lt_iff_ne_bot.mpr hi, apply continuous_multilinear_map.map_coord_zero _ (⟨0, this⟩ : fin i), refl }, have A := has_sum_unique (hf.has_sum zero_mem) (has_sum_single _ this), simpa [v_eq] using A.symm, end lemma has_fpower_series_at.coeff_zero (hf : has_fpower_series_at f pf x) (v : fin 0 → E) : pf 0 v = f x := let ⟨rf, hrf⟩ := hf in hrf.coeff_zero v /-- If a function admits a power series expansion, then it is exponentially close to the partial sums of this power series on strict subdisks of the disk of convergence. -/ lemma has_fpower_series_on_ball.uniform_geometric_approx {r' : nnreal} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ennreal) < r) : ∃ (a C : nnreal), a < 1 ∧ (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * a ^ n) := begin obtain ⟨a, C, ha, hC⟩ : ∃ a C, a < 1 ∧ ∀ n, nnnorm (p n) * r' ^n ≤ C * a^n := p.geometric_bound_of_lt_radius (lt_of_lt_of_le h hf.r_le), refine ⟨a, C / (1 - a), ha, λ y hy n, _⟩, have yr' : ∥y∥ < r', by { rw ball_0_eq at hy, exact hy }, have : y ∈ emetric.ball (0 : E) r, { rw [emetric.mem_ball, edist_eq_coe_nnnorm], apply lt_trans _ h, rw [ennreal.coe_lt_coe, ← nnreal.coe_lt_coe], exact yr' }, simp only [nnreal.coe_sub (le_of_lt ha), nnreal.coe_sub, nnreal.coe_div, nnreal.coe_one], rw [← dist_eq_norm, dist_comm, dist_eq_norm, ← mul_div_right_comm], apply norm_sub_le_of_geometric_bound_of_has_sum ha _ (hf.has_sum this), assume n, calc ∥(p n) (λ (i : fin n), y)∥ ≤ ∥p n∥ * (∏ i : fin n, ∥y∥) : continuous_multilinear_map.le_op_norm _ _ ... = nnnorm (p n) * (nnnorm y)^n : by simp ... ≤ nnnorm (p n) * r' ^ n : mul_le_mul_of_nonneg_left (pow_le_pow_of_le_left (nnreal.coe_nonneg _) (le_of_lt yr') _) (nnreal.coe_nonneg _) ... ≤ C * a ^ n : by exact_mod_cast hC n, end /-- If a function admits a power series expansion at `x`, then it is the uniform limit of the partial sums of this power series on strict subdisks of the disk of convergence, i.e., `f (x + y)` is the uniform limit of `p.partial_sum n y` there. -/ lemma has_fpower_series_on_ball.tendsto_uniformly_on {r' : nnreal} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ennreal) < r) : tendsto_uniformly_on (λ n y, p.partial_sum n y) (λ y, f (x + y)) at_top (metric.ball (0 : E) r') := begin rcases hf.uniform_geometric_approx h with ⟨a, C, ha, hC⟩, refine metric.tendsto_uniformly_on_iff.2 (λ ε εpos, _), have L : tendsto (λ n, (C : ℝ) * a^n) at_top (𝓝 ((C : ℝ) * 0)) := tendsto_const_nhds.mul (tendsto_pow_at_top_nhds_0_of_lt_1 (a.2) ha), rw mul_zero at L, apply ((tendsto_order.1 L).2 ε εpos).mono (λ n hn, _), assume y hy, rw dist_eq_norm, exact lt_of_le_of_lt (hC y hy n) hn end /-- If a function admits a power series expansion at `x`, then it is the locally uniform limit of the partial sums of this power series on the disk of convergence, i.e., `f (x + y)` is the locally uniform limit of `p.partial_sum n y` there. -/ lemma has_fpower_series_on_ball.tendsto_locally_uniformly_on (hf : has_fpower_series_on_ball f p x r) : tendsto_locally_uniformly_on (λ n y, p.partial_sum n y) (λ y, f (x + y)) at_top (emetric.ball (0 : E) r) := begin assume u hu x hx, rcases ennreal.lt_iff_exists_nnreal_btwn.1 hx with ⟨r', xr', hr'⟩, have : emetric.ball (0 : E) r' ∈ 𝓝 x := mem_nhds_sets emetric.is_open_ball xr', refine ⟨emetric.ball (0 : E) r', mem_nhds_within_of_mem_nhds this, _⟩, simpa [metric.emetric_ball_nnreal] using hf.tendsto_uniformly_on hr' u hu end /-- If a function admits a power series expansion at `x`, then it is the uniform limit of the partial sums of this power series on strict subdisks of the disk of convergence, i.e., `f y` is the uniform limit of `p.partial_sum n (y - x)` there. -/ lemma has_fpower_series_on_ball.tendsto_uniformly_on' {r' : nnreal} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ennreal) < r) : tendsto_uniformly_on (λ n y, p.partial_sum n (y - x)) f at_top (metric.ball (x : E) r') := begin convert (hf.tendsto_uniformly_on h).comp (λ y, y - x), { ext z, simp }, { ext z, simp [dist_eq_norm] } end /-- If a function admits a power series expansion at `x`, then it is the locally uniform limit of the partial sums of this power series on the disk of convergence, i.e., `f y` is the locally uniform limit of `p.partial_sum n (y - x)` there. -/ lemma has_fpower_series_on_ball.tendsto_locally_uniformly_on' (hf : has_fpower_series_on_ball f p x r) : tendsto_locally_uniformly_on (λ n y, p.partial_sum n (y - x)) f at_top (emetric.ball (x : E) r) := begin have A : continuous_on (λ (y : E), y - x) (emetric.ball (x : E) r) := (continuous_id.sub continuous_const).continuous_on, convert (hf.tendsto_locally_uniformly_on).comp (λ (y : E), y - x) _ A, { ext z, simp }, { assume z, simp [edist_eq_coe_nnnorm, edist_eq_coe_nnnorm_sub] } end /-- If a function admits a power series expansion on a disk, then it is continuous there. -/ lemma has_fpower_series_on_ball.continuous_on (hf : has_fpower_series_on_ball f p x r) : continuous_on f (emetric.ball x r) := begin apply hf.tendsto_locally_uniformly_on'.continuous_on _ at_top_ne_bot, exact λ n, ((p.partial_sum_continuous n).comp (continuous_id.sub continuous_const)).continuous_on end lemma has_fpower_series_at.continuous_at (hf : has_fpower_series_at f p x) : continuous_at f x := let ⟨r, hr⟩ := hf in hr.continuous_on.continuous_at (emetric.ball_mem_nhds x (hr.r_pos)) lemma analytic_at.continuous_at (hf : analytic_at 𝕜 f x) : continuous_at f x := let ⟨p, hp⟩ := hf in hp.continuous_at /-- In a complete space, the sum of a converging power series `p` admits `p` as a power series. This is not totally obvious as we need to check the convergence of the series. -/ lemma formal_multilinear_series.has_fpower_series_on_ball [complete_space F] (p : formal_multilinear_series 𝕜 E F) (h : 0 < p.radius) : has_fpower_series_on_ball p.sum p 0 p.radius := { r_le := le_refl _, r_pos := h, has_sum := λ y hy, begin rw zero_add, replace hy : (nnnorm y : ennreal) < p.radius, by { convert hy, exact (edist_eq_coe_nnnorm _).symm }, obtain ⟨a, C, ha, hC⟩ : ∃ a C, a < 1 ∧ ∀ n, nnnorm (p n) * (nnnorm y)^n ≤ C * a^n := p.geometric_bound_of_lt_radius hy, refine (summable_of_norm_bounded (λ n, (C : ℝ) * a ^ n) ((summable_geometric_of_lt_1 a.2 ha).mul_left _) (λ n, _)).has_sum, calc ∥(p n) (λ (i : fin n), y)∥ ≤ ∥p n∥ * (∏ i : fin n, ∥y∥) : continuous_multilinear_map.le_op_norm _ _ ... = nnnorm (p n) * (nnnorm y)^n : by simp ... ≤ C * a ^ n : by exact_mod_cast hC n end } lemma has_fpower_series_on_ball.sum [complete_space F] (h : has_fpower_series_on_ball f p x r) {y : E} (hy : y ∈ emetric.ball (0 : E) r) : f (x + y) = p.sum y := begin have A := h.has_sum hy, have B := (p.has_fpower_series_on_ball h.radius_pos).has_sum (lt_of_lt_of_le hy h.r_le), simpa using has_sum_unique A B end /-- The sum of a converging power series is continuous in its disk of convergence. -/ lemma formal_multilinear_series.continuous_on [complete_space F] : continuous_on p.sum (emetric.ball 0 p.radius) := begin by_cases h : 0 < p.radius, { exact (p.has_fpower_series_on_ball h).continuous_on }, { simp at h, simp [h, continuous_on_empty] } end end /-! ### Changing origin in a power series If a function is analytic in a disk `D(x, R)`, then it is analytic in any disk contained in that one. Indeed, one can write $$ f (x + y + z) = \sum_{n} p_n (y + z)^n = \sum_{n, k} \choose n k p_n y^{n-k} z^k = \sum_{k} (\sum_{n} \choose n k p_n y^{n-k}) z^k. $$ The corresponding power series has thus a `k`-th coefficient equal to `\sum_{n} \choose n k p_n y^{n-k}`. In the general case where `pₙ` is a multilinear map, this has to be interpreted suitably: instead of having a binomial coefficient, one should sum over all possible subsets `s` of `fin n` of cardinal `k`, and attribute `z` to the indices in `s` and `y` to the indices outside of `s`. In this paragraph, we implement this. The new power series is called `p.change_origin y`. Then, we check its convergence and the fact that its sum coincides with the original sum. The outcome of this discussion is that the set of points where a function is analytic is open. -/ namespace formal_multilinear_series variables (p : formal_multilinear_series 𝕜 E F) {x y : E} {r : nnreal} /-- Changing the origin of a formal multilinear series `p`, so that `p.sum (x+y) = (p.change_origin x).sum y` when this makes sense. Here, we don't use the bracket notation `⟨n, s, hs⟩` in place of the argument `i` in the lambda, as this leads to a bad definition with auxiliary `_match` statements, but we will try to use pattern matching in lambdas as much as possible in the proofs below to increase readability. -/ def change_origin (x : E) : formal_multilinear_series 𝕜 E F := λ k, tsum (λi, (p i.1).restr i.2.1 i.2.2 x : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → (E [×k]→L[𝕜] F)) /-- Auxiliary lemma controlling the summability of the sequence appearing in the definition of `p.change_origin`, first version. -/ -- Note here and below it is necessary to use `@` and provide implicit arguments using `_`, -- so that it is possible to use pattern matching in the lambda. -- Overall this seems a good trade-off in readability. lemma change_origin_summable_aux1 (h : (nnnorm x + r : ennreal) < p.radius) : @summable ℝ _ _ _ ((λ ⟨n, s⟩, ∥p n∥ * ∥x∥ ^ (n - s.card) * r ^ s.card) : (Σ (n : ℕ), finset (fin n)) → ℝ) := begin obtain ⟨a, C, ha, hC⟩ : ∃ a C, a < 1 ∧ ∀ n, nnnorm (p n) * (nnnorm x + r) ^ n ≤ C * a^n := p.geometric_bound_of_lt_radius h, let Bnnnorm : (Σ (n : ℕ), finset (fin n)) → nnreal := λ ⟨n, s⟩, nnnorm (p n) * (nnnorm x) ^ (n - s.card) * r ^ s.card, have : ((λ ⟨n, s⟩, ∥p n∥ * ∥x∥ ^ (n - s.card) * r ^ s.card) : (Σ (n : ℕ), finset (fin n)) → ℝ) = (λ b, (Bnnnorm b : ℝ)), by { ext ⟨n, s⟩, simp [Bnnnorm, nnreal.coe_pow, coe_nnnorm] }, rw [this, nnreal.summable_coe, ← ennreal.tsum_coe_ne_top_iff_summable], apply ne_of_lt, calc (∑' b, ↑(Bnnnorm b)) = (∑' n, (∑' s, ↑(Bnnnorm ⟨n, s⟩))) : by exact ennreal.tsum_sigma' _ ... ≤ (∑' n, (((nnnorm (p n) * (nnnorm x + r)^n) : nnreal) : ennreal)) : begin refine ennreal.tsum_le_tsum (λ n, _), rw [tsum_fintype, ← ennreal.coe_finset_sum, ennreal.coe_le_coe], apply le_of_eq, calc ∑ s : finset (fin n), Bnnnorm ⟨n, s⟩ = ∑ s : finset (fin n), nnnorm (p n) * ((nnnorm x) ^ (n - s.card) * r ^ s.card) : by simp [← mul_assoc] ... = nnnorm (p n) * (nnnorm x + r) ^ n : by { rw [add_comm, ← finset.mul_sum, ← fin.sum_pow_mul_eq_add_pow], congr, ext1 s, ring } end ... ≤ (∑' (n : ℕ), (C * a ^ n : ennreal)) : tsum_le_tsum (λ n, by exact_mod_cast hC n) ennreal.summable ennreal.summable ... < ⊤ : by simp [ennreal.mul_eq_top, ha, ennreal.tsum_mul_left, ennreal.tsum_geometric, ennreal.lt_top_iff_ne_top] end /-- Auxiliary lemma controlling the summability of the sequence appearing in the definition of `p.change_origin`, second version. -/ lemma change_origin_summable_aux2 (h : (nnnorm x + r : ennreal) < p.radius) : @summable ℝ _ _ _ ((λ ⟨k, n, s, hs⟩, ∥(p n).restr s hs x∥ * ↑r ^ k) : (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ) := begin let γ : ℕ → Type* := λ k, (Σ (n : ℕ), {s : finset (fin n) // s.card = k}), let Bnorm : (Σ (n : ℕ), finset (fin n)) → ℝ := λ ⟨n, s⟩, ∥p n∥ * ∥x∥ ^ (n - s.card) * r ^ s.card, have SBnorm : summable Bnorm := p.change_origin_summable_aux1 h, let Anorm : (Σ (n : ℕ), finset (fin n)) → ℝ := λ ⟨n, s⟩, ∥(p n).restr s rfl x∥ * r ^ s.card, have SAnorm : summable Anorm, { refine summable_of_norm_bounded _ SBnorm (λ i, _), rcases i with ⟨n, s⟩, suffices H : ∥(p n).restr s rfl x∥ * (r : ℝ) ^ s.card ≤ (∥p n∥ * ∥x∥ ^ (n - finset.card s) * r ^ s.card), { have : ∥(r: ℝ)∥ = r, by rw [real.norm_eq_abs, abs_of_nonneg (nnreal.coe_nonneg _)], simpa [Anorm, Bnorm, this] using H }, exact mul_le_mul_of_nonneg_right ((p n).norm_restr s rfl x) (pow_nonneg (nnreal.coe_nonneg _) _) }, let e : (Σ (n : ℕ), finset (fin n)) ≃ (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) := { to_fun := λ ⟨n, s⟩, ⟨s.card, n, s, rfl⟩, inv_fun := λ ⟨k, n, s, hs⟩, ⟨n, s⟩, left_inv := λ ⟨n, s⟩, rfl, right_inv := λ ⟨k, n, s, hs⟩, by { induction hs, refl } }, rw ← e.summable_iff, convert SAnorm, ext ⟨n, s⟩, refl end /-- An auxiliary definition for `change_origin_radius`. -/ def change_origin_summable_aux_j (k : ℕ) : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) := λ ⟨n, s, hs⟩, ⟨k, n, s, hs⟩ lemma change_origin_summable_aux_j_injective (k : ℕ) : function.injective (change_origin_summable_aux_j k) := begin rintros ⟨_, ⟨_, _⟩⟩ ⟨_, ⟨_, _⟩⟩ a, simp only [change_origin_summable_aux_j, true_and, eq_self_iff_true, heq_iff_eq, sigma.mk.inj_iff] at a, rcases a with ⟨rfl, a⟩, simpa using a, end /-- Auxiliary lemma controlling the summability of the sequence appearing in the definition of `p.change_origin`, third version. -/ lemma change_origin_summable_aux3 (k : ℕ) (h : (nnnorm x : ennreal) < p.radius) : @summable ℝ _ _ _ (λ ⟨n, s, hs⟩, ∥(p n).restr s hs x∥ : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ) := begin obtain ⟨r, rpos, hr⟩ : ∃ (r : nnreal), 0 < r ∧ ((nnnorm x + r) : ennreal) < p.radius := ennreal.lt_iff_exists_add_pos_lt.mp h, have S : @summable ℝ _ _ _ ((λ ⟨n, s, hs⟩, ∥(p n).restr s hs x∥ * (r : ℝ) ^ k) : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ), { convert summable.summable_comp_of_injective (p.change_origin_summable_aux2 hr) (change_origin_summable_aux_j_injective k), -- again, cleanup that could be done by `tidy`: ext ⟨_, ⟨_, _⟩⟩, refl }, have : (r : ℝ)^k ≠ 0, by simp [pow_ne_zero, nnreal.coe_eq_zero, ne_of_gt rpos], apply (summable_mul_right_iff this).2, convert S, -- again, cleanup that could be done by `tidy`: ext ⟨_, ⟨_, _⟩⟩, refl, end -- FIXME this causes a deterministic timeout with `-T50000` /-- The radius of convergence of `p.change_origin x` is at least `p.radius - ∥x∥`. In other words, `p.change_origin x` is well defined on the largest ball contained in the original ball of convergence.-/ lemma change_origin_radius : p.radius - nnnorm x ≤ (p.change_origin x).radius := begin by_cases h : p.radius ≤ nnnorm x, { have : radius p - ↑(nnnorm x) = 0 := ennreal.sub_eq_zero_of_le h, rw this, exact zero_le _ }, replace h : (nnnorm x : ennreal) < p.radius, by simpa using h, refine le_of_forall_ge_of_dense (λ r hr, _), cases r, { simpa using hr }, rw [ennreal.lt_sub_iff_add_lt, add_comm] at hr, let A : (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ := λ ⟨k, n, s, hs⟩, ∥(p n).restr s hs x∥ * (r : ℝ) ^ k, have SA : summable A := p.change_origin_summable_aux2 hr, have A_nonneg : ∀ i, 0 ≤ A i, { rintros ⟨k, n, s, hs⟩, change 0 ≤ ∥(p n).restr s hs x∥ * (r : ℝ) ^ k, refine mul_nonneg (norm_nonneg _) (pow_nonneg (nnreal.coe_nonneg _) _) }, have tsum_nonneg : 0 ≤ tsum A := tsum_nonneg A_nonneg, apply le_radius_of_bound _ (nnreal.of_real (tsum A)) (λ k, _), rw [← nnreal.coe_le_coe, nnreal.coe_mul, nnreal.coe_pow, coe_nnnorm, nnreal.coe_of_real _ tsum_nonneg], calc ∥change_origin p x k∥ * ↑r ^ k = ∥@tsum (E [×k]→L[𝕜] F) _ _ _ (λ i, (p i.1).restr i.2.1 i.2.2 x : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → (E [×k]→L[𝕜] F))∥ * ↑r ^ k : rfl ... ≤ tsum (λ i, ∥(p i.1).restr i.2.1 i.2.2 x∥ : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ) * ↑r ^ k : begin apply mul_le_mul_of_nonneg_right _ (pow_nonneg (nnreal.coe_nonneg _) _), apply norm_tsum_le_tsum_norm, convert p.change_origin_summable_aux3 k h, ext a, tidy end ... = tsum (λ i, ∥(p i.1).restr i.2.1 i.2.2 x∥ * ↑r ^ k : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ) : by { rw tsum_mul_right, convert p.change_origin_summable_aux3 k h, tidy } ... = tsum (A ∘ change_origin_summable_aux_j k) : by { congr, tidy } ... ≤ tsum A : tsum_comp_le_tsum_of_inj SA A_nonneg (change_origin_summable_aux_j_injective k) end -- From this point on, assume that the space is complete, to make sure that series that converge -- in norm also converge in `F`. variable [complete_space F] /-- The `k`-th coefficient of `p.change_origin` is the sum of a summable series. -/ lemma change_origin_has_sum (k : ℕ) (h : (nnnorm x : ennreal) < p.radius) : @has_sum (E [×k]→L[𝕜] F) _ _ _ ((λ i, (p i.1).restr i.2.1 i.2.2 x) : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → (E [×k]→L[𝕜] F)) (p.change_origin x k) := begin apply summable.has_sum, apply summable_of_summable_norm, convert p.change_origin_summable_aux3 k h, tidy end /-- Summing the series `p.change_origin x` at a point `y` gives back `p (x + y)`-/ theorem change_origin_eval (h : (nnnorm x + nnnorm y : ennreal) < p.radius) : has_sum ((λk:ℕ, p.change_origin x k (λ (i : fin k), y))) (p.sum (x + y)) := begin /- The series on the left is a series of series. If we order the terms differently, we get back to `p.sum (x + y)`, in which the `n`-th term is expanded by multilinearity. In the proof below, the term on the left is the sum of a series of terms `A`, the sum on the right is the sum of a series of terms `B`, and we show that they correspond to each other by reordering to conclude the proof. -/ have radius_pos : 0 < p.radius := lt_of_le_of_lt (zero_le _) h, -- `A` is the terms of the series whose sum gives the series for `p.change_origin` let A : (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // s.card = k}) → F := λ ⟨k, n, s, hs⟩, (p n).restr s hs x (λ(i : fin k), y), -- `B` is the terms of the series whose sum gives `p (x + y)`, after expansion by multilinearity. let B : (Σ (n : ℕ), finset (fin n)) → F := λ ⟨n, s⟩, (p n).restr s rfl x (λ (i : fin s.card), y), let Bnorm : (Σ (n : ℕ), finset (fin n)) → ℝ := λ ⟨n, s⟩, ∥p n∥ * ∥x∥ ^ (n - s.card) * ∥y∥ ^ s.card, have SBnorm : summable Bnorm, by convert p.change_origin_summable_aux1 h, have SB : summable B, { refine summable_of_norm_bounded _ SBnorm _, rintros ⟨n, s⟩, calc ∥(p n).restr s rfl x (λ (i : fin s.card), y)∥ ≤ ∥(p n).restr s rfl x∥ * ∥y∥ ^ s.card : begin convert ((p n).restr s rfl x).le_op_norm (λ (i : fin s.card), y), simp [(finset.prod_const (∥y∥))], end ... ≤ (∥p n∥ * ∥x∥ ^ (n - s.card)) * ∥y∥ ^ s.card : mul_le_mul_of_nonneg_right ((p n).norm_restr _ _ _) (pow_nonneg (norm_nonneg _) _) }, -- Check that indeed the sum of `B` is `p (x + y)`. have has_sum_B : has_sum B (p.sum (x + y)), { have K1 : ∀ n, has_sum (λ (s : finset (fin n)), B ⟨n, s⟩) (p n (λ (i : fin n), x + y)), { assume n, have : (p n) (λ (i : fin n), y + x) = ∑ s : finset (fin n), p n (finset.piecewise s (λ (i : fin n), y) (λ (i : fin n), x)) := (p n).map_add_univ (λ i, y) (λ i, x), simp [add_comm y x] at this, rw this, exact has_sum_fintype _ }, have K2 : has_sum (λ (n : ℕ), (p n) (λ (i : fin n), x + y)) (p.sum (x + y)), { have : x + y ∈ emetric.ball (0 : E) p.radius, { apply lt_of_le_of_lt _ h, rw [edist_eq_coe_nnnorm, ← ennreal.coe_add, ennreal.coe_le_coe], exact norm_add_le x y }, simpa using (p.has_fpower_series_on_ball radius_pos).has_sum this }, exact has_sum.sigma_of_has_sum K2 K1 SB }, -- Deduce that the sum of `A` is also `p (x + y)`, as the terms `A` and `B` are the same up to -- reordering have has_sum_A : has_sum A (p.sum (x + y)), { let e : (Σ (n : ℕ), finset (fin n)) ≃ (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) := { to_fun := λ ⟨n, s⟩, ⟨s.card, n, s, rfl⟩, inv_fun := λ ⟨k, n, s, hs⟩, ⟨n, s⟩, left_inv := λ ⟨n, s⟩, rfl, right_inv := λ ⟨k, n, s, hs⟩, by { induction hs, refl } }, have : A ∘ e = B, by { ext ⟨⟩, refl }, rw ← e.has_sum_iff, convert has_sum_B }, -- Summing `A ⟨k, c⟩` with fixed `k` and varying `c` is exactly the `k`-th term in the series -- defining `p.change_origin`, by definition have J : ∀k, has_sum (λ c, A ⟨k, c⟩) (p.change_origin x k (λ(i : fin k), y)), { assume k, have : (nnnorm x : ennreal) < radius p := lt_of_le_of_lt (le_add_right (le_refl _)) h, convert continuous_multilinear_map.has_sum_eval (p.change_origin_has_sum k this) (λ(i : fin k), y), ext i, tidy }, exact has_sum_A.sigma J end end formal_multilinear_series section variables [complete_space F] {f : E → F} {p : formal_multilinear_series 𝕜 E F} {x y : E} {r : ennreal} /-- If a function admits a power series expansion `p` on a ball `B (x, r)`, then it also admits a power series on any subball of this ball (even with a different center), given by `p.change_origin`. -/ theorem has_fpower_series_on_ball.change_origin (hf : has_fpower_series_on_ball f p x r) (h : (nnnorm y : ennreal) < r) : has_fpower_series_on_ball f (p.change_origin y) (x + y) (r - nnnorm y) := { r_le := begin apply le_trans _ p.change_origin_radius, exact ennreal.sub_le_sub hf.r_le (le_refl _) end, r_pos := by simp [h], has_sum := begin assume z hz, have A : (nnnorm y : ennreal) + nnnorm z < r, { have : edist z 0 < r - ↑(nnnorm y) := hz, rwa [edist_eq_coe_nnnorm, ennreal.lt_sub_iff_add_lt, add_comm] at this }, convert p.change_origin_eval (lt_of_lt_of_le A hf.r_le), have : y + z ∈ emetric.ball (0 : E) r := calc edist (y + z) 0 ≤ ↑(nnnorm y) + ↑(nnnorm z) : by { rw [edist_eq_coe_nnnorm, ← ennreal.coe_add, ennreal.coe_le_coe], exact norm_add_le y z } ... < r : A, simpa only [add_assoc] using hf.sum this end } lemma has_fpower_series_on_ball.analytic_at_of_mem (hf : has_fpower_series_on_ball f p x r) (h : y ∈ emetric.ball x r) : analytic_at 𝕜 f y := begin have : (nnnorm (y - x) : ennreal) < r, by simpa [edist_eq_coe_nnnorm_sub] using h, have := hf.change_origin this, rw [add_sub_cancel'_right] at this, exact this.analytic_at end variables (𝕜 f) lemma is_open_analytic_at : is_open {x | analytic_at 𝕜 f x} := begin rw is_open_iff_forall_mem_open, assume x hx, rcases hx with ⟨p, r, hr⟩, refine ⟨emetric.ball x r, λ y hy, hr.analytic_at_of_mem hy, emetric.is_open_ball, _⟩, simp only [edist_self, emetric.mem_ball, hr.r_pos] end variables {𝕜 f} end
591f731072173be8ed3b40cabd27878b4d2c549c
c062f1c97fdef9ac746f08754e7d766fd6789aa9
/algebra/lattice/bounded_lattice.lean
f0fa6c4671ef9b43ef252b7bff5363eb99beda08
[]
no_license
emberian/library_dev
00c7a985b21bdebe912f4127a363f2874e1e7555
f3abd7db0238edc18a397540e361a1da2f51503c
refs/heads/master
1,624,153,474,804
1,490,147,180,000
1,490,147,180,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,923
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 Defines bounded lattice type class hierarchy. Includes the Prop and fun instances. -/ import .basic universes u v variable {α : Type u} namespace lattice /- Bounded lattices -/ class bounded_lattice (α : Type u) extends lattice α, order_top α, order_bot α instance semilattice_inf_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_top α := { bl with le_top := take x, le_top } instance semilattice_inf_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_bot α := { bl with bot_le := take x, bot_le } instance semilattice_sup_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_top α := { bl with le_top := take x, le_top } instance semilattice_sup_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_bot α := { bl with bot_le := take x, bot_le } /- Prop instance -/ instance bounded_lattice_Prop : bounded_lattice Prop := { lattice.bounded_lattice . le := λa b, a → b, le_refl := take _, id, le_trans := take a b c f g, g ∘ f, le_antisymm := take a b Hab Hba, propext ⟨Hab, Hba⟩, sup := or, le_sup_left := @or.inl, le_sup_right := @or.inr, sup_le := take a b c, or.rec, inf := and, inf_le_left := @and.left, inf_le_right := @and.right, le_inf := take a b c Hab Hac Ha, and.intro (Hab Ha) (Hac Ha), top := true, le_top := take a Ha, true.intro, bot := false, bot_le := @false.elim } section logic variable [weak_order α] lemma monotone_and {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) : monotone (λx, p x ∧ q x) := take a b h, and.imp (m_p h) (m_q h) lemma monotone_or {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) : monotone (λx, p x ∨ q x) := take a b h, or.imp (m_p h) (m_q h) end logic /- Function lattices -/ /- TODO: * build up the lattice hierarchy for `fun`-functor piecewise. semilattic_*, bounded_lattice, lattice ... * can this be generalized to the dependent function space? -/ instance bounded_lattice_fun {α : Type u} {β : Type v} [bounded_lattice β] : bounded_lattice (α → β) := { weak_order_fun with sup := λf g a, sup (f a) (g a), le_sup_left := take f g a, le_sup_left, le_sup_right := take f g a, le_sup_right, sup_le := take f g h Hfg Hfh a, sup_le (Hfg a) (Hfh a), inf := λf g a, inf (f a) (g a), inf_le_left := take f g a, inf_le_left, inf_le_right := take f g a, inf_le_right, le_inf := take f g h Hfg Hfh a, le_inf (Hfg a) (Hfh a), top := λa, top, le_top := take f a, le_top, bot := λa, bot, bot_le := take f a, bot_le } end lattice
1456dc6490a67c83d7c9262b1665dbbbce3b9752
e0b0b1648286e442507eb62344760d5cd8d13f2d
/stage0/src/Lean/Meta/Tactic/Cases.lean
8a2a51dad4cda3dba21ab840c95c57b35345c1fe
[ "Apache-2.0" ]
permissive
MULXCODE/lean4
743ed389e05e26e09c6a11d24607ad5a697db39b
4675817a9e89824eca37192364cd47a4027c6437
refs/heads/master
1,682,231,879,857
1,620,423,501,000
1,620,423,501,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,408
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.AppBuilder import Lean.Meta.Tactic.Induction import Lean.Meta.Tactic.Injection import Lean.Meta.Tactic.Assert import Lean.Meta.Tactic.Subst namespace Lean.Meta private def throwInductiveTypeExpected {α} (type : Expr) : MetaM α := do throwError "failed to compile pattern matching, inductive type expected{indentExpr type}" def getInductiveUniverseAndParams (type : Expr) : MetaM (List Level × Array Expr) := do let type ← whnfD type matchConstInduct type.getAppFn (fun _ => throwInductiveTypeExpected type) fun val us => let I := type.getAppFn let Iargs := type.getAppArgs let params := Iargs.extract 0 val.numParams pure (us, params) private def mkEqAndProof (lhs rhs : Expr) : MetaM (Expr × Expr) := do let lhsType ← inferType lhs let rhsType ← inferType rhs let u ← getLevel lhsType if (← isDefEq lhsType rhsType) then pure (mkApp3 (mkConst `Eq [u]) lhsType lhs rhs, mkApp2 (mkConst `Eq.refl [u]) lhsType lhs) else pure (mkApp4 (mkConst `HEq [u]) lhsType lhs rhsType rhs, mkApp2 (mkConst `HEq.refl [u]) lhsType lhs) private partial def withNewEqs {α} (targets targetsNew : Array Expr) (k : Array Expr → Array Expr → MetaM α) : MetaM α := let rec loop (i : Nat) (newEqs : Array Expr) (newRefls : Array Expr) := do if h : i < targets.size then let (newEqType, newRefl) ← mkEqAndProof targets[i] targetsNew[i] withLocalDeclD `h newEqType fun newEq => do loop (i+1) (newEqs.push newEq) (newRefls.push newRefl) else k newEqs newRefls loop 0 #[] #[] def generalizeTargets (mvarId : MVarId) (motiveType : Expr) (targets : Array Expr) : MetaM MVarId := withMVarContext mvarId do checkNotAssigned mvarId `generalizeTargets let (typeNew, eqRefls) ← forallTelescopeReducing motiveType fun targetsNew _ => do unless targetsNew.size == targets.size do throwError "invalid number of targets #{targets.size}, motive expects #{targetsNew.size}" withNewEqs targets targetsNew fun eqs eqRefls => do let type ← getMVarType mvarId let typeNew ← mkForallFVars eqs type let typeNew ← mkForallFVars targetsNew typeNew pure (typeNew, eqRefls) let mvarNew ← mkFreshExprSyntheticOpaqueMVar typeNew (← getMVarTag mvarId) assignExprMVar mvarId (mkAppN (mkAppN mvarNew targets) eqRefls) pure mvarNew.mvarId! structure GeneralizeIndicesSubgoal where mvarId : MVarId indicesFVarIds : Array FVarId fvarId : FVarId numEqs : Nat /-- Similar to `generalizeTargets` but customized for the `casesOn` motive. Given a metavariable `mvarId` representing the ``` Ctx, h : I A j, D |- T ``` where `fvarId` is `h`s id, and the type `I A j` is an inductive datatype where `A` are parameters, and `j` the indices. Generate the goal ``` Ctx, h : I A j, D, j' : J, h' : I A j' |- j == j' -> h == h' -> T ``` Remark: `(j == j' -> h == h')` is a "telescopic" equality. Remark: `j` is sequence of terms, and `j'` a sequence of free variables. The result contains the fields - `mvarId`: the new goal - `indicesFVarIds`: `j'` ids - `fvarId`: `h'` id - `numEqs`: number of equations in the target -/ def generalizeIndices (mvarId : MVarId) (fvarId : FVarId) : MetaM GeneralizeIndicesSubgoal := withMVarContext mvarId do let lctx ← getLCtx let localInsts ← getLocalInstances checkNotAssigned mvarId `generalizeIndices let fvarDecl ← getLocalDecl fvarId let type ← whnf fvarDecl.type type.withApp fun f args => matchConstInduct f (fun _ => throwTacticEx `generalizeIndices mvarId "inductive type expected") fun val _ => do unless val.numIndices > 0 do throwTacticEx `generalizeIndices mvarId "indexed inductive type expected" unless args.size == val.numIndices + val.numParams do throwTacticEx `generalizeIndices mvarId "ill-formed inductive datatype" let indices := args.extract (args.size - val.numIndices) args.size let IA := mkAppN f (args.extract 0 val.numParams) -- `I A` let IAType ← inferType IA forallTelescopeReducing IAType fun newIndices _ => do let newType := mkAppN IA newIndices withLocalDeclD fvarDecl.userName newType fun h' => withNewEqs indices newIndices fun newEqs newRefls => do let (newEqType, newRefl) ← mkEqAndProof fvarDecl.toExpr h' let newRefls := newRefls.push newRefl withLocalDeclD `h newEqType fun newEq => do let newEqs := newEqs.push newEq /- auxType `forall (j' : J) (h' : I A j'), j == j' -> h == h' -> target -/ let target ← getMVarType mvarId let tag ← getMVarTag mvarId let auxType ← mkForallFVars newEqs target let auxType ← mkForallFVars #[h'] auxType let auxType ← mkForallFVars newIndices auxType let newMVar ← mkFreshExprMVarAt lctx localInsts auxType MetavarKind.syntheticOpaque tag /- assign mvarId := newMVar indices h refls -/ assignExprMVar mvarId (mkAppN (mkApp (mkAppN newMVar indices) fvarDecl.toExpr) newRefls) let (indicesFVarIds, newMVarId) ← introNP newMVar.mvarId! newIndices.size let (fvarId, newMVarId) ← intro1P newMVarId pure { mvarId := newMVarId, indicesFVarIds := indicesFVarIds, fvarId := fvarId, numEqs := newEqs.size } structure CasesSubgoal extends InductionSubgoal where ctorName : Name namespace Cases structure Context where inductiveVal : InductiveVal casesOnVal : DefinitionVal nminors : Nat := inductiveVal.ctors.length majorDecl : LocalDecl majorTypeFn : Expr majorTypeArgs : Array Expr majorTypeIndices : Array Expr := majorTypeArgs.extract (majorTypeArgs.size - inductiveVal.numIndices) majorTypeArgs.size private def mkCasesContext? (majorFVarId : FVarId) : MetaM (Option Context) := do let env ← getEnv if !env.contains `Eq || !env.contains `HEq then pure none else let majorDecl ← getLocalDecl majorFVarId let majorType ← whnf majorDecl.type majorType.withApp fun f args => matchConstInduct f (fun _ => pure none) fun ival _ => if args.size != ival.numIndices + ival.numParams then pure none else match env.find? (Name.mkStr ival.name "casesOn") with | ConstantInfo.defnInfo cval => pure $ some { inductiveVal := ival, casesOnVal := cval, majorDecl := majorDecl, majorTypeFn := f, majorTypeArgs := args } | _ => pure none /- We say the major premise has independent indices IF 1- its type is *not* an indexed inductive family, OR 2- its type is an indexed inductive family, but all indices are distinct free variables, and all local declarations different from the major and its indices do not depend on the indices. -/ private def hasIndepIndices (ctx : Context) : MetaM Bool := do if ctx.majorTypeIndices.isEmpty then pure true else if ctx.majorTypeIndices.any $ fun idx => !idx.isFVar then /- One of the indices is not a free variable. -/ pure false else if ctx.majorTypeIndices.size.any fun i => i.any fun j => ctx.majorTypeIndices[i] == ctx.majorTypeIndices[j] then /- An index ocurrs more than once -/ pure false else let lctx ← getLCtx let mctx ← getMCtx pure $ lctx.all fun decl => decl.fvarId == ctx.majorDecl.fvarId || -- decl is the major ctx.majorTypeIndices.any (fun index => decl.fvarId == index.fvarId!) || -- decl is one of the indices mctx.findLocalDeclDependsOn decl (fun fvarId => ctx.majorTypeIndices.all $ fun idx => idx.fvarId! != fvarId) -- or does not depend on any index private def elimAuxIndices (s₁ : GeneralizeIndicesSubgoal) (s₂ : Array CasesSubgoal) : MetaM (Array CasesSubgoal) := let indicesFVarIds := s₁.indicesFVarIds s₂.mapM fun s => do indicesFVarIds.foldlM (init := s) fun s indexFVarId => match s.subst.get indexFVarId with | Expr.fvar indexFVarId' _ => (do let mvarId ← clear s.mvarId indexFVarId'; pure { s with mvarId := mvarId, subst := s.subst.erase indexFVarId }) <|> (pure s) | _ => pure s /- Convert `s` into an array of `CasesSubgoal`, by attaching the corresponding constructor name, and adding the substitution `majorFVarId -> ctor_i us params fields` into each subgoal. -/ private def toCasesSubgoals (s : Array InductionSubgoal) (ctorNames : Array Name) (majorFVarId : FVarId) (us : List Level) (params : Array Expr) : Array CasesSubgoal := s.mapIdx fun i s => let ctorName := ctorNames[i] let ctorApp := mkAppN (mkAppN (mkConst ctorName us) params) s.fields let s := { s with subst := s.subst.insert majorFVarId ctorApp } { ctorName := ctorName, toInductionSubgoal := s } /- 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 ← assert mvarId eqDecl.userName aEqb prf clear mvarId eqDecl.fvarId partial def unifyEqs (numEqs : Nat) (mvarId : MVarId) (subst : FVarSubst) (caseName? : Option Name := none): MetaM (Option (MVarId × FVarSubst)) := do if numEqs == 0 then pure (some (mvarId, subst)) else let (eqFVarId, mvarId) ← intro1 mvarId withMVarContext mvarId do let eqDecl ← getLocalDecl eqFVarId if eqDecl.type.isHEq then let mvarId ← heqToEq mvarId eqDecl unifyEqs numEqs mvarId subst caseName? 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 /- TODO: support for acyclicity (e.g., `xs ≠ x :: xs`) -/ /- Remark: `substCore` fails if the equation is of the form `x = x` -/ if let some (substNew, mvarId) ← observing? (substCore mvarId eqFVarId symm subst) then unifyEqs (numEqs - 1) mvarId substNew caseName? else if (← isDefEq a b) then /- Skip equality -/ unifyEqs (numEqs - 1) (← clear mvarId eqFVarId) subst caseName? 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 => pure none -- this alternative has been solved | InjectionResultCore.subgoal mvarId numEqsNew => unifyEqs (numEqs - 1 + numEqsNew) mvarId subst caseName? 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 ← assert mvarId eqDecl.userName aEqb' prf let mvarId ← clear mvarId eqFVarId unifyEqs numEqs mvarId subst caseName? 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 ← getLocalDecl aFVarId let bDecl ← getLocalDecl bFVarId 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 -/ unifyEqs (numEqs - 1) (← clear mvarId eqFVarId) subst caseName? else injection a b private def unifyCasesEqs (numEqs : Nat) (subgoals : Array CasesSubgoal) : MetaM (Array CasesSubgoal) := subgoals.foldlM (init := #[]) fun subgoals s => do match (← unifyEqs numEqs s.mvarId s.subst s.ctorName) with | none => pure subgoals | some (mvarId, subst) => pure $ subgoals.push { s with mvarId := mvarId, subst := subst, fields := s.fields.map (subst.apply ·) } private def inductionCasesOn (mvarId : MVarId) (majorFVarId : FVarId) (givenNames : Array AltVarNames) (ctx : Context) : MetaM (Array CasesSubgoal) := do withMVarContext mvarId do let majorType ← inferType (mkFVar majorFVarId) let (us, params) ← getInductiveUniverseAndParams majorType let casesOn := mkCasesOnName ctx.inductiveVal.name let ctors := ctx.inductiveVal.ctors.toArray let s ← induction mvarId majorFVarId casesOn givenNames return toCasesSubgoals s ctors majorFVarId us params def cases (mvarId : MVarId) (majorFVarId : FVarId) (givenNames : Array AltVarNames := #[]) : MetaM (Array CasesSubgoal) := withMVarContext mvarId do checkNotAssigned mvarId `cases let context? ← mkCasesContext? majorFVarId match context? with | none => throwTacticEx `cases mvarId "not applicable to the given hypothesis" | some ctx => /- Remark: if caller does not need a `FVarSubst` (variable substitution), and `hasIndepIndices ctx` is true, then we can also use the simple case. This is a minor optimization, and we currently do not even allow callers to specify whether they want the `FVarSubst` or not. -/ if ctx.inductiveVal.numIndices == 0 then -- Simple case inductionCasesOn mvarId majorFVarId givenNames ctx else let s₁ ← generalizeIndices mvarId majorFVarId trace[Meta.Tactic.cases] "after generalizeIndices\n{MessageData.ofGoal s₁.mvarId}" let s₂ ← inductionCasesOn s₁.mvarId s₁.fvarId givenNames ctx let s₂ ← elimAuxIndices s₁ s₂ unifyCasesEqs s₁.numEqs s₂ end Cases def cases (mvarId : MVarId) (majorFVarId : FVarId) (givenNames : Array AltVarNames := #[]) : MetaM (Array CasesSubgoal) := Cases.cases mvarId majorFVarId givenNames builtin_initialize registerTraceClass `Meta.Tactic.cases end Lean.Meta
5bbb4309352c384d783f256a94ea8cb274479a5b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/integration.lean
ac763e3ca7fc6a53be621739990fb5830c368f0e
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
5,062
lean
/- Copyright (c) 2021 Benjamin Davidson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Benjamin Davidson -/ import analysis.special_functions.integrals open interval_integral real open_locale real /-! ### Simple functions -/ /- constants -/ example : ∫ x : ℝ in 8..11, (1 : ℝ) = 3 := by norm_num example : ∫ x : ℝ in 5..19, (12 : ℝ) = 168 := by norm_num /- the identity function -/ example : ∫ x : ℝ in (-1)..4, x = 15 / 2 := by norm_num example : ∫ x : ℝ in 4..5, x * 2 = 9 := by norm_num /- inverse -/ example : ∫ x : ℝ in 2..3, x⁻¹ = log (3 / 2) := by norm_num /- natural powers -/ example : ∫ x : ℝ in 2..4, x ^ (3 : ℕ) = 60 := by norm_num /- trigonometric functions -/ example : ∫ x in 0..π, sin x = 2 := by norm_num example : ∫ x in 0..π/4, cos x = sqrt 2 / 2 := by simp example : ∫ x in 0..π, 2 * sin x = 4 := by norm_num example : ∫ x in 0..π/2, cos x / 2 = 1 / 2 := by simp example : ∫ x : ℝ in 0..1, 1 / (1 + x ^ 2) = π / 4 := by simp example : ∫ x in 0..2*π, sin x ^ 2 = π := by simp [mul_div_cancel_left] example : ∫ x in 0..π/2, cos x ^ 2 / 2 = π / 8 := by norm_num [div_div] example : ∫ x in 0..π, cos x ^ 2 - sin x ^ 2 = 0 := by simp [integral_cos_sq_sub_sin_sq] example : ∫ x in 0..π/2, sin x ^ 3 = 2 / 3 := by norm_num example : ∫ x in 0..π/2, cos x ^ 3 = 2 / 3 := by norm_num example : ∫ x in 0..π, sin x * cos x = 0 := by simp example : ∫ x in 0..π, sin x ^ 2 * cos x ^ 2 = π / 8 := by simpa using sin_nat_mul_pi 4 /- the exponential function -/ example : ∫ x in 0..2, -exp x = 1 - exp 2 := by simp /- the logarithmic function -/ example : ∫ x in 1..2, log x = 2 * log 2 - 1 := by { norm_num, ring } /- linear combinations (e.g. polynomials) -/ example : ∫ x : ℝ in 0..2, 6*x^5 + 3*x^4 + x^3 - 2*x^2 + x - 7 = 1048 / 15 := by norm_num example : ∫ x : ℝ in 0..1, exp x + 9 * x^8 + x^3 - x/2 + (1 + x^2)⁻¹ = exp 1 + π / 4 := by norm_num /-! ### Functions composed with multiplication by and/or addition of a constant -/ /- many examples are computable by `norm_num` -/ example : ∫ x in 0..2, -exp (-x) = exp (-2) - 1 := by norm_num example : ∫ x in 1..2, exp (5*x - 5) = 1/5 * (exp 5 - 1) := by norm_num example : ∫ x in 0..π, cos (x/2) = 2 := by norm_num example : ∫ x in 0..π/4, sin (2*x) = 1/2 := by norm_num [mul_div_left_comm, mul_one_div] example (ω φ : ℝ) : ω * ∫ θ in 0..π, sin (ω*θ + φ) = cos φ - cos (ω*π + φ) := by simp /- some examples may require a bit of algebraic massaging -/ example {L : ℝ} (h : L ≠ 0) : ∫ x in 0..2/L*π, sin (L/2 * x) = 4 / L := begin norm_num [div_ne_zero h, ← mul_assoc], field_simp [h, mul_div_cancel], norm_num, end /- you may need to provide `norm_num` with the composition lemma you are invoking if it has a difficult time recognizing the function you are trying to integrate -/ example : ∫ x : ℝ in 0..2, 3 * (x + 1) ^ 2 = 26 := by norm_num [integral_comp_add_right (λ x, x ^ 2)] example : ∫ x : ℝ in -1..0, (1 + (x + 1) ^ 2)⁻¹ = π / 4 := by simp [integral_comp_add_right (λ x, (1 + x ^ 2)⁻¹)] /-! ### Compositions of functions (aka "change of variables" or "integration by substitution") -/ /- `interval_integral.integral_comp_mul_deriv` can be used to simplify integrals of the form `∫ x in a..b, (g ∘ f) x * f' x`, where `f'` is the derivative of `f`, to `∫ x in f a..f b, g x` -/ example {a b : ℝ} : ∫ x in a..b, exp (exp x) * exp x = ∫ x in exp a..exp b, exp x := integral_comp_mul_deriv (λ x hx, has_deriv_at_exp x) continuous_on_exp continuous_exp /- if it is known (to mathlib), the integral of `g` can then be evaluated using `simp`/`norm_num` -/ example : ∫ x in 0..1, exp (exp x) * exp x = exp (exp 1) - exp 1 := by rw integral_comp_mul_deriv (λ x hx, has_deriv_at_exp x) continuous_on_exp continuous_exp; simp /- a more detailed example -/ example : ∫ x in 0..2, exp (x ^ 2) * (2 * x) = exp 4 - 1 := begin -- let g := exp x, f := x ^ 2, f' := 2 * x rw integral_comp_mul_deriv (λ x hx, _), -- simplify to ∫ x in f 0..f 2, g x { norm_num }, -- compute the integral { exact continuous_on_const.mul continuous_on_id }, -- show that f' is continuous on [0, 2] { exact continuous_exp }, -- show that g is continuous { simpa using has_deriv_at_pow 2 x }, -- show that f' = derivative of f on [0, 2] end /- alternatively, `interval_integral.integral_deriv_comp_mul_deriv` can be used to compute integrals of this same form, provided that you also know that `g` is the derivative of some function -/ example : ∫ x : ℝ in 0..1, exp (x ^ 2) * (2 * x) = exp 1 - 1 := begin rw integral_deriv_comp_mul_deriv (λ x hx, _) (λ x hx, has_deriv_at_exp (x^2)) _ continuous_exp, { simp }, { simpa using has_deriv_at_pow 2 x }, { exact continuous_on_const.mul continuous_on_id }, end
8aeea375b904d98bad0783308f25b3716e9eed39
0845ae2ca02071debcfd4ac24be871236c01784f
/library/init/lean/compiler/ir/livevars.lean
26c8a53c834f743f93124bca5f7448bee83a6122
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
6,932
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.lean.compiler.ir.basic import init.lean.compiler.ir.freevars import init.control.reader import init.control.conditional namespace Lean namespace IR /- Remark: in the paper "Counting Immutable Beans" the concepts of free and live variables coincide because the paper does *not* consider join points. For example, consider the function body `B` ``` let x := ctor_0; jmp block_1 x ``` in a context where we have the join point `block_1` defined as ``` block_1 (x : obj) : obj := let z := ctor_0 x y; ret z `` The variable `y` is live in the function body `B` since it occurs in `block_1` which is "invoked" by `B`. -/ namespace IsLive /- We use `State Context` instead of `ReaderT Context Id` because we remove non local joint points from `Context` whenever we visit them instead of maintaining a set of visited non local join points. Remark: we don't need to track local join points because we assume there is no variable or join point shadowing in our IR. -/ abbrev M := State LocalContext @[inline] def visitVar (w : Index) (x : VarId) : M Bool := pure (HasIndex.visitVar w x) @[inline] def visitJP (w : Index) (x : JoinPointId) : M Bool := pure (HasIndex.visitJP w x) @[inline] def visitArg (w : Index) (a : Arg) : M Bool := pure (HasIndex.visitArg w a) @[inline] def visitArgs (w : Index) (as : Array Arg) : M Bool := pure (HasIndex.visitArgs w as) @[inline] def visitExpr (w : Index) (e : Expr) : M Bool := pure (HasIndex.visitExpr w e) partial def visitFnBody (w : Index) : FnBody → M Bool | (FnBody.vdecl x _ v b) := visitExpr w v <||> visitFnBody b | (FnBody.jdecl j ys v b) := visitFnBody v <||> visitFnBody b | (FnBody.set x _ y b) := visitVar w x <||> visitArg w y <||> visitFnBody b | (FnBody.uset x _ y b) := visitVar w x <||> visitVar w y <||> visitFnBody b | (FnBody.sset x _ _ y _ b) := visitVar w x <||> visitVar w y <||> visitFnBody b | (FnBody.setTag x _ b) := visitVar w x <||> visitFnBody b | (FnBody.inc x _ _ b) := visitVar w x <||> visitFnBody b | (FnBody.dec x _ _ b) := visitVar w x <||> visitFnBody b | (FnBody.del x b) := visitVar w x <||> visitFnBody b | (FnBody.mdata _ b) := visitFnBody b | (FnBody.jmp j ys) := visitArgs w ys <||> do { ctx ← get; match ctx.getJPBody j with | some b => -- `j` is not a local join point since we assume we cannot shadow join point declarations. -- Instead of marking the join points that we have already been visited, we permanently remove `j` from the context. set (ctx.eraseJoinPointDecl j) *> visitFnBody b | none => -- `j` must be a local join point. So do nothing since we have already visite its body. pure false } | (FnBody.ret x) := visitArg w x | (FnBody.case _ x alts) := visitVar w x <||> alts.anyM (fun alt => visitFnBody alt.body) | (FnBody.unreachable) := pure false end IsLive /- Return true if `x` is live in the function body `b` in the context `ctx`. Remark: the context only needs to contain all (free) join point declarations. Recall that we say that a join point `j` is free in `b` if `b` contains `FnBody.jmp j ys` and `j` is not local. -/ def FnBody.hasLiveVar (b : FnBody) (ctx : LocalContext) (x : VarId) : Bool := (IsLive.visitFnBody x.idx b).run' ctx abbrev LiveVarSet := VarIdSet abbrev JPLiveVarMap := RBMap JoinPointId LiveVarSet (fun j₁ j₂ => j₁.idx < j₂.idx) instance LiveVarSet.inhabited : Inhabited LiveVarSet := ⟨{}⟩ namespace LiveVars abbrev Collector := LiveVarSet → LiveVarSet @[inline] private def skip : Collector := fun s => s @[inline] private def collectVar (x : VarId) : Collector := fun s => s.insert x private def collectArg : Arg → Collector | (Arg.var x) := collectVar x | irrelevant := skip @[specialize] private def collectArray {α : Type} (as : Array α) (f : α → Collector) : Collector := fun s => as.foldl (fun s a => f a s) s private def collectArgs (as : Array Arg) : Collector := collectArray as collectArg private def accumulate (s' : LiveVarSet) : Collector := fun s => s'.fold (fun s x => s.insert x) s private def collectJP (m : JPLiveVarMap) (j : JoinPointId) : Collector := match m.find j with | some xs => accumulate xs | none => skip -- unreachable for well-formed code private def bindVar (x : VarId) : Collector := fun s => s.erase x private def bindParams (ps : Array Param) : Collector := fun s => ps.foldl (fun s p => s.erase p.x) s def collectExpr : Expr → Collector | (Expr.ctor _ ys) := collectArgs ys | (Expr.reset _ x) := collectVar x | (Expr.reuse x _ _ ys) := collectVar x ∘ collectArgs ys | (Expr.proj _ x) := collectVar x | (Expr.uproj _ x) := collectVar x | (Expr.sproj _ _ x) := collectVar x | (Expr.fap _ ys) := collectArgs ys | (Expr.pap _ ys) := collectArgs ys | (Expr.ap x ys) := collectVar x ∘ collectArgs ys | (Expr.box _ x) := collectVar x | (Expr.unbox x) := collectVar x | (Expr.lit v) := skip | (Expr.isShared x) := collectVar x | (Expr.isTaggedPtr x) := collectVar x partial def collectFnBody : FnBody → JPLiveVarMap → Collector | (FnBody.vdecl x _ v b) m := collectExpr v ∘ collectFnBody b m ∘ bindVar x | (FnBody.jdecl j ys v b) m := let jLiveVars := (collectFnBody v m ∘ bindParams ys) {}; let m := m.insert j jLiveVars; collectFnBody b m | (FnBody.set x _ y b) m := collectVar x ∘ collectArg y ∘ collectFnBody b m | (FnBody.setTag x _ b) m := collectVar x ∘ collectFnBody b m | (FnBody.uset x _ y b) m := collectVar x ∘ collectVar y ∘ collectFnBody b m | (FnBody.sset x _ _ y _ b) m := collectVar x ∘ collectVar y ∘ collectFnBody b m | (FnBody.inc x _ _ b) m := collectVar x ∘ collectFnBody b m | (FnBody.dec x _ _ b) m := collectVar x ∘ collectFnBody b m | (FnBody.del x b) m := collectVar x ∘ collectFnBody b m | (FnBody.mdata _ b) m := collectFnBody b m | (FnBody.ret x) m := collectArg x | (FnBody.case _ x alts) m := collectVar x ∘ collectArray alts (fun alt => collectFnBody alt.body m) | (FnBody.unreachable) m := skip | (FnBody.jmp j xs) m := collectJP m j ∘ collectArgs xs def updateJPLiveVarMap (j : JoinPointId) (ys : Array Param) (v : FnBody) (m : JPLiveVarMap) : JPLiveVarMap := let jLiveVars := (collectFnBody v m ∘ bindParams ys) {}; m.insert j jLiveVars end LiveVars def updateLiveVars (e : Expr) (v : LiveVarSet) : LiveVarSet := LiveVars.collectExpr e v def collectLiveVars (b : FnBody) (m : JPLiveVarMap) (v : LiveVarSet := {}) : LiveVarSet := LiveVars.collectFnBody b m v export LiveVars (updateJPLiveVarMap) end IR end Lean
053ac1524452e4bbe50318bef72f882d6817f494
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Meta/Tactic/Acyclic.lean
58de1b70cec9081b6cf8df8dc7a4fba386bea320
[ "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
1,939
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.MatchUtil import Lean.Meta.Tactic.Simp.Main namespace Lean.MVarId open Meta private def isTarget (lhs rhs : Expr) : MetaM Bool := do if !lhs.isFVar || !lhs.occurs rhs then return false else return (← whnf rhs).isConstructorApp (← getEnv) /-- Close the given goal if `h` is a proof for an equality such as `as = a :: as`. Inductive datatypes in Lean are acyclic. -/ def acyclic (mvarId : MVarId) (h : Expr) : MetaM Bool := mvarId.withContext do let type ← whnfD (← inferType h) trace[Meta.Tactic.acyclic] "type: {type}" let some (_, lhs, rhs) := type.eq? | return false if (← isTarget lhs rhs) then go h lhs rhs else if (← isTarget rhs lhs) then go (← mkEqSymm h) rhs lhs else return false where go (h lhs rhs : Expr) : MetaM Bool := do try let sizeOf_lhs ← mkAppM ``sizeOf #[lhs] let sizeOf_rhs ← mkAppM ``sizeOf #[rhs] let sizeOfEq ← mkLT sizeOf_lhs sizeOf_rhs let hlt ← mkFreshExprSyntheticOpaqueMVar sizeOfEq -- TODO: we only need the `sizeOf` simp theorems match (← simpTarget hlt.mvarId! { config.arith := true, simpTheorems := #[ (← getSimpTheorems) ] }) with | some _ => return false | none => let heq ← mkCongrArg sizeOf_lhs.appFn! (← mkEqSymm h) let hlt_self ← mkAppM ``Nat.lt_of_lt_of_eq #[hlt, heq] let hlt_irrelf ← mkAppM ``Nat.lt_irrefl #[sizeOf_lhs] mvarId.assign (← mkFalseElim (← mvarId.getType) (mkApp hlt_irrelf hlt_self)) trace[Meta.Tactic.acyclic] "succeeded" return true catch ex => trace[Meta.Tactic.acyclic] "failed with\n{ex.toMessageData}" return false builtin_initialize registerTraceClass `Meta.Tactic.acyclic end Lean.MVarId
5e035fe51e2ef7cf7362da508a658bd727456ee3
c9e78e68dc955b2325401aec3a6d3240cd8b83f4
/src/justification.lean
b13d4b735384e959a4be5fb6b12dff980d89c315
[]
no_license
loganrjmurphy/lean-strategies
4b8dd54771bb421c929a8bcb93a528ce6c1a70f1
832ea28077701b977b4fc59ed9a8ce6911654e59
refs/heads/master
1,682,732,168,860
1,621,444,295,000
1,621,444,295,000
278,458,841
3
0
null
1,613,755,728,000
1,594,324,763,000
Lean
UTF-8
Lean
false
false
3,426
lean
import data.set variables {α β: Type} def Property (α : Type) : Type := α → Prop structure Claim (α : Type) := (X : set α) (P : Property α) @[instance] def claim_default {α : Type} : inhabited (Claim α) := ⟨Claim.mk ∅ (λ x, true)⟩ @[reducible] def meaning {α : Type} (C : Claim α) : Prop := ∀ x ∈ C.X, C.P x notation ⟦C⟧ := meaning C structure Strategy (α : Type) := (parent : Claim α) (decomp : Claim α → list (Claim α)) @[instance] def strat_default {α : Type} : inhabited (Strategy α) := ⟨Strategy.mk (default (Claim α)) (λ c, [])⟩ def deductive (α : Type) (S : Strategy α) : Prop := let subclaims := (S.decomp) S.parent in (∀ clm ∈ subclaims, ⟦clm⟧) → ⟦S.parent⟧ namespace property @[reducible] def decomposition (Ps : list (Property α)) (Clm : Claim α) : list (Claim α) := list.map (Claim.mk Clm.X) Ps structure input (α : Type) := (Clm : Claim α) (Props : list (Property α)) @[instance] def input_default {α : Type} : inhabited (input α) := ⟨input.mk (default (Claim α)) []⟩ namespace input @[reducible] def length (Γ : input α) : ℕ := Γ.Props.length lemma len_decomp (Γ : input α) : Γ.length = (decomposition Γ.Props Γ.Clm).length := by {rw decomposition, simp} @[reducible] def subsets (Γ : input α) : fin (Γ.length) → set α := λ i, set_of (Γ.Props.nth_le i.1 i.2) end input def justified (Γ : input α) : Prop := (⋂ i, Γ.subsets i) ⊆ {x | Γ.Clm.P x} @[reducible] def strategy (Γ : input α) : Strategy α := { parent := Γ.Clm, decomp := property.decomposition Γ.Props } theorem deductive_of_justfd : Π {Γ : property.input α}, justified Γ → deductive α (property.strategy Γ) := begin intro Γ, rw [justified,deductive, meaning,strategy], simp only [fin.val_eq_coe], intros H1 H2 x xMem, apply H1, simp only [set.mem_Inter, set.mem_set_of_eq], intro i, replace H2 := H2 ((decomposition Γ.Props Γ.Clm).nth_le i.1 (fin.cast (input.len_decomp Γ) i).2), simp at H2, apply H2, apply list.nth_le_mem, assumption, end end property /- namespace domain @[reducible] def to_claim {α : Type} (P : Property α) (X : set α) : Claim α := Claim.mk X P @[reducible] def preimages {α β: Type} (f : α → β) (Clm : Claim α) (bs : list (set β)) : list (set α) := list.map (set.preimage f) bs @[reducible] def decomposition {α β: Type} (f : α → β) (sets_range : list (set β)) (Clm : Claim α) : list (Claim α) := (preimages f Clm sets_range).map (to_claim Clm.P) structure auxiliary (α β : Type) := (Clm : Claim α) (f : α → β) (range_sets : list (set β)) def set_of_list : list α → set α | [] := ∅ | (h::t) := {h} ∪ set_of_list t def complete (Γ : auxiliary α β) : Prop := ∀ b : β, ∃ s ∈ Γ.range_sets, b ∈ s def to_strategy (Γ : auxiliary α β) : strategy α := strategy.mk (Γ.Clm) (domain.decomposition Γ.f Γ.range_sets) theorem deductive_of_justfd_comp (Γ : auxiliary α β) : complete Γ → deductive α (to_strategy Γ) := begin rw [complete, deductive, meaning, to_strategy], simp only [fin.val_eq_coe], intros H1 H2 x xMem, unfold decomposition at H2,simp at H2, unfold to_claim at H2, have H3 : ∃ s ∈ Γ.range_sets, Γ.f x ∈ s, from H1 (Γ.f x), rcases H3 with ⟨s,H3,H4⟩, replace H2 := H2 s H3, apply H2, assumption, end end domain -/
9a1b968e6471529283943d571cd9c840fc46bffc
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/set_theory/cardinal.lean
0bd2c464ad97f39ec4d192a4abee10fa2f4b73e7
[ "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
51,959
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, Floris van Doorn -/ import data.set.countable import set_theory.schroeder_bernstein import data.fintype.card import data.nat.enat /-! # Cardinal Numbers We define cardinal numbers as a quotient of types under the equivalence relation of equinumerity. ## Main definitions * `cardinal` the type of cardinal numbers (in a given universe). * `cardinal.mk α` or `#α` is the cardinality of `α`. The notation `#` lives in the locale `cardinal`. * There is an instance that `cardinal` forms a `canonically_ordered_comm_semiring`. * Addition `c₁ + c₂` is defined by `cardinal.add_def α β : #α + #β = #(α ⊕ β)`. * Multiplication `c₁ * c₂` is defined by `cardinal.mul_def : #α * #β = #(α * β)`. * The order `c₁ ≤ c₂` is defined by `cardinal.le_def α β : #α ≤ #β ↔ nonempty (α ↪ β)`. * Exponentiation `c₁ ^ c₂` is defined by `cardinal.power_def α β : #α ^ #β = #(β → α)`. * `cardinal.omega` the cardinality of `ℕ`. This definition is universe polymorphic: `cardinal.omega.{u} : cardinal.{u}` (contrast with `ℕ : Type`, which lives in a specific universe). In some cases the universe level has to be given explicitly. * `cardinal.min (I : nonempty ι) (c : ι → cardinal)` is the minimal cardinal in the range of `c`. * `cardinal.succ c` is the successor cardinal, the smallest cardinal larger than `c`. * `cardinal.sum` is the sum of a collection of cardinals. * `cardinal.sup` is the supremum of a collection of cardinals. * `cardinal.powerlt c₁ c₂` or `c₁ ^< c₂` is defined as `sup_{γ < β} α^γ`. ## Main Statements * Cantor's theorem: `cardinal.cantor c : c < 2 ^ c`. * König's theorem: `cardinal.sum_lt_prod` ## 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`. The operation `cardinal.lift` lifts cardinal numbers to a higher level. * Cardinal arithmetic specifically for infinite cardinals (like `κ * κ = κ`) is in the file `set_theory/cardinal_ordinal.lean`. * There is an instance `has_pow cardinal`, but this will only fire if Lean already knows that both the base and the exponent live in the same universe. As a workaround, you can add ``` local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow ``` to a file. This notation will work even if Lean doesn't know yet that the base and the exponent live in the same universe (but no exponents in other types can be used). ## References * <https://en.wikipedia.org/wiki/Cardinal_number> ## Tags cardinal number, cardinal arithmetic, cardinal exponentiation, omega, Cantor's theorem, König's theorem -/ 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 le_def (α β : Type u) : mk α ≤ mk β ↔ nonempty (α ↪ β) := iff.rfl 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.of_injective 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 } protected lemma eq_congr : α ≃ β → # α = # β := λ h, quot.sound ⟨h⟩ noncomputable 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, decidable_le := classical.dec_rel _ } -- short-circuit type class inference noncomputable instance : distrib_lattice cardinal.{u} := by apply_instance 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 α β γ⟩ protected theorem eq_zero_or_eq_zero_of_mul_eq_zero {a b : cardinal.{u}} : a * b = 0 → a = 0 ∨ b = 0 := begin refine quotient.induction_on b _, refine quotient.induction_on a _, intros a b h, contrapose h, simp_rw [not_or_distrib, ← ne.def] at h, have := @prod.nonempty a b (ne_zero_iff_nonempty.mp h.1) (ne_zero_iff_nonempty.mp h.2), exact ne_zero_iff_nonempty.mpr this end 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 protected theorem zero_le : ∀(a : cardinal), 0 ≤ a := by rintro ⟨α⟩; exact ⟨embedding.of_not_nonempty $ λ ⟨a⟩, a.elim⟩ protected 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₂⟩ protected theorem add_le_add_left (a) {b c : cardinal} : b ≤ c → a + b ≤ a + c := cardinal.add_le_add (le_refl _) protected 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.of_injective f hf) (equiv.refl _)).trans $ (equiv.set.sum_compl (range f)), ⟨⟦↥(range f)ᶜ⟧, quotient.sound ⟨this.symm⟩⟩, λ ⟨c, e⟩, add_zero a ▸ e.symm ▸ cardinal.add_le_add_left _ (cardinal.zero_le _)⟩ instance : order_bot cardinal.{u} := { bot := 0, bot_le := cardinal.zero_le, ..cardinal.linear_order } instance : canonically_ordered_comm_semiring cardinal.{u} := { add_le_add_left := λ a b h c, cardinal.add_le_add_left _ h, lt_of_add_lt_add_left := λ a b c, lt_imp_lt_of_le_imp_le (cardinal.add_le_add_left _), le_iff_exists_add := @cardinal.le_iff_exists_add, eq_zero_or_eq_zero_of_mul_eq_zero := @cardinal.eq_zero_or_eq_zero_of_mul_eq_zero, ..cardinal.order_bot, ..cardinal.comm_semiring, ..cardinal.linear_order } noncomputable instance : canonically_linear_ordered_add_monoid cardinal.{u} := { .. (infer_instance : canonically_ordered_add_monoid cardinal.{u}), .. cardinal.linear_order } @[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 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⟩ end order_properties 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 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 [← nonpos_iff_eq_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 suffices : nonempty (Π i, (f i).out) ↔ ∀ i, nonempty (f i).out, { simpa [← ne_zero_iff_nonempty, prod] }, exact classical.nonempty_pi 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 [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⟩⟩, by simpa only [fintype.card_fin] using fintype.card_le_of_injective f hf, λ h, ⟨(fin.cast_le h).to_embedding⟩⟩ @[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 card_le_of {α : Type u} {n : ℕ} (H : ∀ s : finset α, s.card ≤ n) : # α ≤ n := begin refine lt_succ.1 (lt_of_not_ge $ λ hn, _), rw [← cardinal.nat_succ, ← cardinal.lift_mk_fin n.succ] at hn, cases hn with f, refine not_lt_of_le (H $ finset.univ.map f) _, rw [finset.card_map, ← fintype.card, fintype.card_ulift, fintype.card_fin], exact n.lt_succ_self end 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 ⟨⟨coe, λ a b, fin.ext⟩⟩ @[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 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 (self_le_add_right _ _) h, lt_of_le_of_lt (self_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 (canonically_ordered_semiring.mul_le_mul (le_refl a) hb) h }, { rw [← _root_.one_mul b], refine lt_of_le_of_lt (canonically_ordered_semiring.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 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 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 /-- This function sends finite cardinals to the corresponding natural, and infinite cardinals to 0. -/ noncomputable def to_nat : zero_hom cardinal ℕ := ⟨λ c, if h : c < omega.{v} then classical.some (lt_omega.1 h) else 0, begin have h : 0 < omega := nat_lt_omega 0, rw [dif_pos h, ← cardinal.nat_cast_inj, ← classical.some_spec (lt_omega.1 h), nat.cast_zero], end⟩ lemma to_nat_apply_of_lt_omega {c : cardinal} (h : c < omega) : c.to_nat = classical.some (lt_omega.1 h) := dif_pos h @[simp] lemma to_nat_apply_of_omega_le {c : cardinal} (h : omega ≤ c) : c.to_nat = 0 := dif_neg (not_lt_of_le h) @[simp] lemma cast_to_nat_of_lt_omega {c : cardinal} (h : c < omega) : ↑c.to_nat = c := by rw [to_nat_apply_of_lt_omega h, ← classical.some_spec (lt_omega.1 h)] @[simp] lemma to_nat_cast (n : ℕ) : cardinal.to_nat n = n := begin rw [to_nat_apply_of_lt_omega (nat_lt_omega n), ← nat_cast_inj], exact (classical.some_spec (lt_omega.1 (nat_lt_omega n))).symm, end /-- `to_nat` has a right-inverse: coercion. -/ lemma to_nat_right_inverse : function.right_inverse (coe : ℕ → cardinal) to_nat := to_nat_cast lemma to_nat_surjective : surjective to_nat := to_nat_right_inverse.surjective @[simp] lemma mk_to_nat_of_infinite [h : infinite α] : (mk α).to_nat = 0 := dif_neg (not_lt_of_le (infinite_iff.1 h)) @[simp] lemma mk_to_nat_eq_card [fintype α] : (mk α).to_nat = fintype.card α := by simp [fintype_card] @[simp] lemma zero_to_nat : cardinal.to_nat 0 = 0 := by rw [← to_nat_cast 0, nat.cast_zero] @[simp] lemma one_to_nat : cardinal.to_nat 1 = 1 := by rw [← to_nat_cast 1, nat.cast_one] /-- This function sends finite cardinals to the corresponding natural, and infinite cardinals to `⊤`. -/ noncomputable def to_enat : cardinal →+ enat := { to_fun := λ c, if c < omega.{v} then c.to_nat else ⊤, map_zero' := by simp [if_pos (lt_trans zero_lt_one one_lt_omega)], map_add' := λ x y, begin by_cases hx : x < omega, { obtain ⟨x0, rfl⟩ := lt_omega.1 hx, by_cases hy : y < omega, { obtain ⟨y0, rfl⟩ := lt_omega.1 hy, simp only [add_lt_omega hx hy, hx, hy, to_nat_cast, if_true], rw [← nat.cast_add, to_nat_cast, enat.coe_add] }, { rw [if_neg hy, if_neg, enat.add_top], contrapose! hy, apply lt_of_le_of_lt (le_add_left (le_refl y)) hy } }, { rw [if_neg hx, if_neg, enat.top_add], contrapose! hx, apply lt_of_le_of_lt (le_add_right (le_refl x)) hx }, end } @[simp] lemma to_enat_apply_of_lt_omega {c : cardinal} (h : c < omega) : c.to_enat = c.to_nat := if_pos h @[simp] lemma to_enat_apply_of_omega_le {c : cardinal} (h : omega ≤ c) : c.to_enat = ⊤ := if_neg (not_lt_of_le h) @[simp] lemma to_enat_cast (n : ℕ) : cardinal.to_enat n = n := by rw [to_enat_apply_of_lt_omega (nat_lt_omega n), to_nat_cast] @[simp] lemma mk_to_enat_of_infinite [h : infinite α] : (mk α).to_enat = ⊤ := to_enat_apply_of_omega_le (infinite_iff.1 h) lemma to_enat_surjective : surjective to_enat := begin intro x, exact enat.cases_on x ⟨omega, to_enat_apply_of_omega_le (le_refl omega)⟩ (λ n, ⟨n, to_enat_cast n⟩), end @[simp] lemma mk_to_enat_eq_coe_card [fintype α] : (mk α).to_enat = fintype.card α := by simp [fintype_card] 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, 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_set {α : Type u} : mk (set α) = 2 ^ mk α := begin rw [← prop_eq_two, cardinal.power_def (ulift Prop) α, cardinal.eq], exact ⟨equiv.arrow_congr (equiv.refl _) equiv.ulift.symm⟩, end @[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.of_injective 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.of_injective 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.of_injective 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_eq_nat_iff_finset {α} {s : set α} {n : ℕ} : mk s = n ↔ ∃ t : finset α, (t : set α) = s ∧ t.card = n := begin split, { intro h, have : # s < omega, by { rw h, exact nat_lt_omega n }, refine ⟨(lt_omega_iff_finite.1 this).to_finset, finite.coe_to_finset _, nat_cast_inj.1 _⟩, rwa [finset_card, finite.coe_to_finset] }, { rintro ⟨t, rfl, rfl⟩, exact finset_card.symm } end 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 ▸ self_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 lemma equiv.cardinal_eq {α β} : α ≃ β → cardinal.mk α = cardinal.mk β := cardinal.eq_congr
8f2034a634153414cba9b6296cf131556a50daf8
e61a235b8468b03aee0120bf26ec615c045005d2
/stage0/src/Init/Data/Queue/Basic.lean
5faa6573f64a8c273927cf074476bb240da4f6c6
[ "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
965
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam Simple queue implemented using two lists. Note: this is only a temporary placeholder. -/ prelude import Init.Data.Array import Init.Data.Int universes u v w structure Queue (α : Type u) := (eList dList : List α := []) namespace Queue variable {α : Type u} def empty : Queue α := { eList := [], dList := [] } def isEmpty (q : Queue α) : Bool := q.dList.isEmpty && q.eList.isEmpty def enqueue (v : α) (q : Queue α) : Queue α := { q with eList := v::q.eList } def enqueueAll (vs : List α) (q : Queue α) : Queue α := { q with eList := vs ++ q.eList } def dequeue? (q : Queue α) : Option (α × Queue α) := match q.dList with | d::ds => some (d, { q with dList := ds }) | [] => match q.eList.reverse with | [] => none | d::ds => some (d, { eList := [], dList := ds }) end Queue
b54c806244287fd608781677eb33feb1ad6d616e
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/geometry/algebra/lie_group.lean
08476506d460fe17ece98bd554bab96e0fe38484
[ "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
11,380
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Nicolò Cavalleri. -/ import geometry.manifold.times_cont_mdiff /-! # Lie groups A Lie group is a group that is also a smooth manifold, in which the group operations of multiplication and inversion are smooth maps. Smoothness of the group multiplication means that multiplication is a smooth mapping of the product manifold `G` × `G` into `G`. Note that, since a manifold here is not second-countable and Hausdorff a Lie group here is not guaranteed to be second-countable (even though it can be proved it is Hausdorff). Note also that Lie groups here are not necessarily finite dimensional. ## Main definitions and statements * `lie_add_group I G` : a Lie additive group where `G` is a manifold on the model with corners `I`. * `lie_group I G` : a Lie multiplicative group where `G` is a manifold on the model with corners `I`. * `lie_add_group_morphism I I' G G'` : morphism of addittive Lie groups * `lie_group_morphism I I' G G'` : morphism of Lie groups * `lie_add_group_core I G` : allows to define a Lie additive group without first proving it is a topological additive group. * `lie_group_core I G` : allows to define a Lie group without first proving it is a topological group. * `reals_lie_group` : real numbers are a Lie group ## Implementation notes A priori, a Lie group here is a manifold with corners. The definition of Lie group cannot require `I : model_with_corners 𝕜 E E` with the same space as the model space and as the model vector space, as one might hope, beause in the product situation, the model space is `model_prod E E'` and the model vector space is `E × E'`, which are not the same, so the definition does not apply. Hence the definition should be more general, allowing `I : model_with_corners 𝕜 E H`. -/ noncomputable theory section lie_group set_option default_priority 100 /-- A Lie (additive) group is a group and a smooth manifold at the same time in which the addition and negation operations are smooth. -/ class lie_add_group {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {H : Type*} [topological_space H] {E : Type*} [normed_group E] [normed_space 𝕜 E] (I : model_with_corners 𝕜 E H) (G : Type*) [add_group G] [topological_space G] [topological_add_group G] [charted_space H G] extends smooth_manifold_with_corners I G : Prop := (smooth_add : smooth (I.prod I) I (λ p : G×G, p.1 + p.2)) (smooth_neg : smooth I I (λ a:G, -a)) /-- A Lie group is a group and a smooth manifold at the same time in which the multiplication and inverse operations are smooth. -/ @[to_additive] class lie_group {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {H : Type*} [topological_space H] {E : Type*} [normed_group E] [normed_space 𝕜 E] (I : model_with_corners 𝕜 E H) (G : Type*) [group G] [topological_space G] [topological_group G] [charted_space H G] extends smooth_manifold_with_corners I G : Prop := (smooth_mul : smooth (I.prod I) I (λ p : G×G, p.1 * p.2)) (smooth_inv : smooth I I (λ a:G, a⁻¹)) section lie_group variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {H : Type*} [topological_space H] {E : Type*} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E H} {F : Type*} [normed_group F] [normed_space 𝕜 F] {J : model_with_corners 𝕜 F F} {G : Type*} [topological_space G] [charted_space H G] [group G] [topological_group G] [lie_group I G] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {M : Type*} [topological_space M] [charted_space H' M] [smooth_manifold_with_corners I' M] {E'' : Type*} [normed_group E''] [normed_space 𝕜 E''] {H'' : Type*} [topological_space H''] {I'' : model_with_corners 𝕜 E'' H''} {M' : Type*} [topological_space M'] [charted_space H'' M'] [smooth_manifold_with_corners I'' M'] @[to_additive] lemma smooth_mul : smooth (I.prod I) I (λ p : G×G, p.1 * p.2) := lie_group.smooth_mul @[to_additive] lemma smooth.mul {f : M → G} {g : M → G} (hf : smooth I' I f) (hg : smooth I' I g) : smooth I' I (f * g) := smooth_mul.comp (hf.prod_mk hg) localized "notation `L_add` := left_add" in lie_group localized "notation `R_add` := right_add" in lie_group localized "notation `L` := left_mul" in lie_group localized "notation `R` := right_mul" in lie_group @[to_additive] lemma smooth_left_mul {a : G} : smooth I I (left_mul a) := smooth_mul.comp (smooth_const.prod_mk smooth_id) @[to_additive] lemma smooth_right_mul {a : G} : smooth I I (right_mul a) := smooth_mul.comp (smooth_id.prod_mk smooth_const) @[to_additive] lemma smooth_on.mul {f : M → G} {g : M → G} {s : set M} (hf : smooth_on I' I f s) (hg : smooth_on I' I g s) : smooth_on I' I (f * g) s := (smooth_mul.comp_smooth_on (hf.prod_mk hg) : _) lemma smooth_pow : ∀ n : ℕ, smooth I I (λ a : G, a ^ n) | 0 := by { simp only [pow_zero], exact smooth_const } | (k+1) := show smooth I I (λ (a : G), a * a ^ k), from smooth_id.mul (smooth_pow _) @[to_additive] lemma smooth_inv : smooth I I (λ x : G, x⁻¹) := lie_group.smooth_inv @[to_additive] lemma smooth.inv {f : M → G} (hf : smooth I' I f) : smooth I' I (λx, (f x)⁻¹) := smooth_inv.comp hf @[to_additive] lemma smooth_on.inv {f : M → G} {s : set M} (hf : smooth_on I' I f s) : smooth_on I' I (λx, (f x)⁻¹) s := smooth_inv.comp_smooth_on hf end lie_group section prod_lie_group /- Instance of product group -/ @[to_additive] instance {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {H : Type*} [topological_space H] {E : Type*} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E H} {G : Type*} [topological_space G] [charted_space H G] [group G] [topological_group G] [h : lie_group I G] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {G' : Type*} [topological_space G'] [charted_space H' G'] [group G'] [topological_group G'] [h' : lie_group I' G'] : lie_group (I.prod I') (G×G') := { smooth_mul := ((smooth_fst.comp smooth_fst).smooth.mul (smooth_fst.comp smooth_snd)).prod_mk ((smooth_snd.comp smooth_fst).smooth.mul (smooth_snd.comp smooth_snd)), smooth_inv := smooth_fst.inv.prod_mk smooth_snd.inv, } end prod_lie_group section lie_add_group_morphism variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] /-- Morphism of additive Lie groups. -/ structure lie_add_group_morphism (I : model_with_corners 𝕜 E E) (I' : model_with_corners 𝕜 E' E') (G : Type*) [topological_space G] [charted_space E G] [smooth_manifold_with_corners I G] [add_group G] [topological_add_group G] [lie_add_group I G] (G' : Type*) [topological_space G'] [charted_space E' G'] [smooth_manifold_with_corners I' G'] [add_group G'] [topological_add_group G'] [lie_add_group I' G'] extends add_monoid_hom G G' := (smooth_to_fun : smooth I I' to_fun) /-- Morphism of Lie groups. -/ @[to_additive] structure lie_group_morphism (I : model_with_corners 𝕜 E E) (I' : model_with_corners 𝕜 E' E') (G : Type*) [topological_space G] [charted_space E G] [smooth_manifold_with_corners I G] [group G] [topological_group G] [lie_group I G] (G' : Type*) [topological_space G'] [charted_space E' G'] [smooth_manifold_with_corners I' G'] [group G'] [topological_group G'] [lie_group I' G'] extends monoid_hom G G' := (smooth_to_fun : smooth I I' to_fun) variables {I : model_with_corners 𝕜 E E} {I' : model_with_corners 𝕜 E' E'} {G : Type*} [topological_space G] [charted_space E G] [smooth_manifold_with_corners I G] [group G] [topological_group G] [lie_group I G] {G' : Type*} [topological_space G'] [charted_space E' G'] [smooth_manifold_with_corners I' G'] [group G'] [topological_group G'] [lie_group I' G'] @[to_additive] instance : has_one (lie_group_morphism I I' G G') := ⟨⟨1, smooth_const⟩⟩ @[to_additive] instance : inhabited (lie_group_morphism I I' G G') := ⟨1⟩ @[to_additive] instance : has_coe_to_fun (lie_group_morphism I I' G G') := ⟨_, λ a, a.to_fun⟩ end lie_add_group_morphism end lie_group section lie_group_core /-- Sometimes one might want to define a Lie additive group `G` without having proved previously that `G` is a topological additive group. In such case it is possible to use `lie_add_group_core` that does not require such instance, and then get a Lie group by invoking `to_lie_add_group`. -/ structure lie_add_group_core {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] (I : model_with_corners 𝕜 E E) (G : Type*) [add_group G] [topological_space G] [charted_space E G] [smooth_manifold_with_corners I G] : Prop := (smooth_add : smooth (I.prod I) I (λ p : G×G, p.1 + p.2)) (smooth_neg : smooth I I (λ a:G, -a)) /-- Sometimes one might want to define a Lie group `G` without having proved previously that `G` is a topological group. In such case it is possible to use `lie_group_core` that does not require such instance, and then get a Lie group by invoking `to_lie_group` defined below. -/ @[to_additive] structure lie_group_core {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] (I : model_with_corners 𝕜 E E) (G : Type*) [group G] [topological_space G] [charted_space E G] [smooth_manifold_with_corners I G] : Prop := (smooth_mul : smooth (I.prod I) I (λ p : G×G, p.1 * p.2)) (smooth_inv : smooth I I (λ a:G, a⁻¹)) variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E E} {F : Type*} [normed_group F] [normed_space 𝕜 F] {J : model_with_corners 𝕜 F F} {G : Type*} [topological_space G] [charted_space E G] [smooth_manifold_with_corners I G] [group G] namespace lie_group_core variables (c : lie_group_core I G) @[to_additive] protected lemma to_topological_group : topological_group G := { continuous_mul := c.smooth_mul.continuous, continuous_inv := c.smooth_inv.continuous, } @[to_additive] protected lemma to_lie_group : @lie_group 𝕜 _ _ _ E _ _ I G _ _ c.to_topological_group _ := { smooth_mul := c.smooth_mul, smooth_inv := c.smooth_inv, } end lie_group_core end lie_group_core /-! ### Real numbers are a Lie group -/ section real_numbers_lie_group instance normed_group_lie_group {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] : lie_add_group (model_with_corners_self 𝕜 E) E := { smooth_add := begin rw smooth_iff, refine ⟨continuous_add, λ x y, _⟩, simp only [prod.mk.eta] with mfld_simps, rw times_cont_diff_on_univ, exact times_cont_diff_add, end, smooth_neg := begin rw smooth_iff, refine ⟨continuous_neg, λ x y, _⟩, simp only [prod.mk.eta] with mfld_simps, rw times_cont_diff_on_univ, exact times_cont_diff_neg, end } instance reals_lie_group : lie_add_group (model_with_corners_self ℝ ℝ) ℝ := by apply_instance end real_numbers_lie_group
c94588fa3aff82a1bdd51bd827964872e6bcbe6b
618003631150032a5676f229d13a079ac875ff77
/src/tactic/default.lean
bdc0ae670103407dc97b56ba5dc3f5dda96b3398
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
903
lean
/- This file imports many useful tactics ("the kitchen sink"). You can use `import tactic` at the beginning of your file to get everything. (Although you may want to strip things down when you're polishing.) Because this file imports some complicated tactics, it has many transitive dependencies (which of course may not use `import tactic`, and must import selectively). As (non-exhaustive) examples, these includes things like: * algebra.group_power * algebra.ordered_ring * data.rat * data.nat.prime * data.list.perm * data.set.lattice * data.equiv.encodable * order.complete_lattice -/ import tactic.abel import tactic.ring_exp import tactic.noncomm_ring import tactic.linarith import tactic.omega import tactic.tfae import tactic.apply_fun import tactic.interval_cases import tactic.reassoc_axiom -- most likely useful only for category_theory import tactic.slice import tactic.subtype_instance
f1fa47f6d282e5a793af40c396c114319d496f84
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/data/nat/examples/partial_sum.lean
4c0a3cadbda3ec5571c215770727019a019041c6
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
1,161
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ import data.nat open nat definition partial_sum : nat → nat | 0 := 0 | (succ n) := succ n + partial_sum n example : partial_sum 5 = 15 := rfl example : partial_sum 6 = 21 := rfl lemma two_mul_partial_sum_eq : ∀ n, 2 * partial_sum n = (succ n) * n | 0 := by reflexivity | (succ n) := calc 2 * (succ n + partial_sum n) = 2 * succ n + 2 * partial_sum n : left_distrib ... = 2 * succ n + succ n * n : two_mul_partial_sum_eq ... = 2 * succ n + n * succ n : mul.comm ... = (2 + n) * succ n : right_distrib ... = (n + 2) * succ n : add.comm ... = (succ (succ n)) * succ n : rfl theorem partial_sum_eq : ∀ n, partial_sum n = ((n + 1) * n) / 2 := take n, have h₁ : (2 * partial_sum n) / 2 = ((succ n) * n) / 2, by rewrite two_mul_partial_sum_eq, have h₂ : (2:nat) > 0, from dec_trivial, by rewrite [nat.mul_div_cancel_left _ h₂ at h₁]; exact h₁
a3197fea09eca0909741c4d2e46798f2440cb49a
618003631150032a5676f229d13a079ac875ff77
/src/data/finmap.lean
405221b0939cbc99291afc6c03632b47d10c470b
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
18,200
lean
/- Copyright (c) 2018 Sean Leather. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sean Leather, Mario Carneiro Finite maps over `multiset`. -/ import data.list.alist import data.finset import data.pfun universes u v w open list variables {α : Type u} {β : α → Type v} namespace multiset /-- Multiset of keys of an association multiset. -/ def keys (s : multiset (sigma β)) : multiset α := s.map sigma.fst @[simp] theorem coe_keys {l : list (sigma β)} : keys (l : multiset (sigma β)) = (l.keys : multiset α) := rfl /-- `nodupkeys s` means that `s` has no duplicate keys. -/ def nodupkeys (s : multiset (sigma β)) : Prop := quot.lift_on s list.nodupkeys (λ s t p, propext $ perm_nodupkeys p) @[simp] theorem coe_nodupkeys {l : list (sigma β)} : @nodupkeys α β l ↔ l.nodupkeys := iff.rfl end multiset /-- `finmap β` is the type of finite maps over a multiset. It is effectively a quotient of `alist β` by permutation of the underlying list. -/ structure finmap (β : α → Type v) : Type (max u v) := (entries : multiset (sigma β)) (nodupkeys : entries.nodupkeys) /-- The quotient map from `alist` to `finmap`. -/ def alist.to_finmap (s : alist β) : finmap β := ⟨s.entries, s.nodupkeys⟩ local notation `⟦`:max a `⟧`:0 := alist.to_finmap a theorem alist.to_finmap_eq {s₁ s₂ : alist β} : ⟦s₁⟧ = ⟦s₂⟧ ↔ s₁.entries ~ s₂.entries := by cases s₁; cases s₂; simp [alist.to_finmap] @[simp] theorem alist.to_finmap_entries (s : alist β) : ⟦s⟧.entries = s.entries := rfl def list.to_finmap [decidable_eq α] (s : list (sigma β)) : finmap β := alist.to_finmap (list.to_alist s) namespace finmap open alist /-- Lift a permutation-respecting function on `alist` to `finmap`. -/ @[elab_as_eliminator] def lift_on {γ} (s : finmap β) (f : alist β → γ) (H : ∀ a b : alist β, a.entries ~ b.entries → f a = f b) : γ := begin refine (quotient.lift_on s.1 (λ l, (⟨_, λ nd, f ⟨l, nd⟩⟩ : roption γ)) (λ l₁ l₂ p, roption.ext' (perm_nodupkeys p) _) : roption γ).get _, { exact λ h₁ h₂, H _ _ (by exact p) }, { have := s.nodupkeys, rcases s.entries with ⟨l⟩, exact id } end @[simp] theorem lift_on_to_finmap {γ} (s : alist β) (f : alist β → γ) (H) : lift_on ⟦s⟧ f H = f s := by cases s; refl /-- Lift a permutation-respecting function on 2 `alist`s to 2 `finmap`s. -/ @[elab_as_eliminator] def lift_on₂ {γ} (s₁ s₂ : finmap β) (f : alist β → alist β → γ) (H : ∀ a₁ b₁ a₂ b₂ : alist β, a₁.entries ~ a₂.entries → b₁.entries ~ b₂.entries → f a₁ b₁ = f a₂ b₂) : γ := lift_on s₁ (λ l₁, lift_on s₂ (f l₁) (λ b₁ b₂ p, H _ _ _ _ (perm.refl _) p)) (λ a₁ a₂ p, have H' : f a₁ = f a₂ := funext (λ _, H _ _ _ _ p (perm.refl _)), by simp only [H']) @[simp] theorem lift_on₂_to_finmap {γ} (s₁ s₂ : alist β) (f : alist β → alist β → γ) (H) : lift_on₂ ⟦s₁⟧ ⟦s₂⟧ f H = f s₁ s₂ := by cases s₁; cases s₂; refl @[elab_as_eliminator] theorem induction_on {C : finmap β → Prop} (s : finmap β) (H : ∀ (a : alist β), C ⟦a⟧) : C s := by rcases s with ⟨⟨a⟩, h⟩; exact H ⟨a, h⟩ @[elab_as_eliminator] theorem induction_on₂ {C : finmap β → finmap β → Prop} (s₁ s₂ : finmap β) (H : ∀ (a₁ a₂ : alist β), C ⟦a₁⟧ ⟦a₂⟧) : C s₁ s₂ := induction_on s₁ $ λ l₁, induction_on s₂ $ λ l₂, H l₁ l₂ @[elab_as_eliminator] theorem induction_on₃ {C : finmap β → finmap β → finmap β → Prop} (s₁ s₂ s₃ : finmap β) (H : ∀ (a₁ a₂ a₃ : alist β), C ⟦a₁⟧ ⟦a₂⟧ ⟦a₃⟧) : C s₁ s₂ s₃ := induction_on₂ s₁ s₂ $ λ l₁ l₂, induction_on s₃ $ λ l₃, H l₁ l₂ l₃ @[ext] theorem ext : ∀ {s t : finmap β}, s.entries = t.entries → s = t | ⟨l₁, h₁⟩ ⟨l₂, h₂⟩ H := by congr' @[simp] theorem ext_iff {s t : finmap β} : s.entries = t.entries ↔ s = t := ⟨ext, congr_arg _⟩ /-- The predicate `a ∈ s` means that `s` has a value associated to the key `a`. -/ instance : has_mem α (finmap β) := ⟨λ a s, a ∈ s.entries.keys⟩ theorem mem_def {a : α} {s : finmap β} : a ∈ s ↔ a ∈ s.entries.keys := iff.rfl @[simp] theorem mem_to_finmap {a : α} {s : alist β} : a ∈ ⟦s⟧ ↔ a ∈ s := iff.rfl /-- The set of keys of a finite map. -/ def keys (s : finmap β) : finset α := ⟨s.entries.keys, induction_on s keys_nodup⟩ @[simp] theorem keys_val (s : alist β) : (keys ⟦s⟧).val = s.keys := rfl @[simp] theorem keys_ext {s₁ s₂ : alist β} : keys ⟦s₁⟧ = keys ⟦s₂⟧ ↔ s₁.keys ~ s₂.keys := by simp [keys, alist.keys] theorem mem_keys {a : α} {s : finmap β} : a ∈ s.keys ↔ a ∈ s := induction_on s $ λ s, alist.mem_keys /-- The empty map. -/ instance : has_emptyc (finmap β) := ⟨⟨0, nodupkeys_nil⟩⟩ instance : inhabited (finmap β) := ⟨∅⟩ @[simp] theorem empty_to_finmap : (⟦∅⟧ : finmap β) = ∅ := rfl @[simp] theorem to_finmap_nil [decidable_eq α] : (list.to_finmap [] : finmap β) = ∅ := rfl theorem not_mem_empty {a : α} : a ∉ (∅ : finmap β) := multiset.not_mem_zero a @[simp] theorem keys_empty : (∅ : finmap β).keys = ∅ := rfl /-- The singleton map. -/ def singleton (a : α) (b : β a) : finmap β := ⟦ alist.singleton a b ⟧ @[simp] theorem keys_singleton (a : α) (b : β a) : (singleton a b).keys = {a} := rfl @[simp] lemma mem_singleton (x y : α) (b : β y) : x ∈ singleton y b ↔ x = y := by simp only [singleton]; erw [mem_cons_eq,mem_nil_iff,or_false] variables [decidable_eq α] instance has_decidable_eq [∀ a, decidable_eq (β a)] : decidable_eq (finmap β) | s₁ s₂ := decidable_of_iff _ ext_iff /-- Look up the value associated to a key in a map. -/ def lookup (a : α) (s : finmap β) : option (β a) := lift_on s (lookup a) (λ s t, perm_lookup) @[simp] theorem lookup_to_finmap (a : α) (s : alist β) : lookup a ⟦s⟧ = s.lookup a := rfl @[simp] theorem lookup_list_to_finmap (a : α) (s : list (sigma β)) : lookup a s.to_finmap = s.lookup a := by rw [list.to_finmap,lookup_to_finmap,lookup_to_alist] @[simp] theorem lookup_empty (a) : lookup a (∅ : finmap β) = none := rfl theorem lookup_is_some {a : α} {s : finmap β} : (s.lookup a).is_some ↔ a ∈ s := induction_on s $ λ s, alist.lookup_is_some theorem lookup_eq_none {a} {s : finmap β} : lookup a s = none ↔ a ∉ s := induction_on s $ λ s, alist.lookup_eq_none @[simp] lemma lookup_singleton_eq {a : α} {b : β a} : (singleton a b).lookup a = some b := by rw [singleton,lookup_to_finmap,alist.singleton,alist.lookup,lookup_cons_eq] instance (a : α) (s : finmap β) : decidable (a ∈ s) := decidable_of_iff _ lookup_is_some /-- Replace a key with a given value in a finite map. If the key is not present it does nothing. -/ def replace (a : α) (b : β a) (s : finmap β) : finmap β := lift_on s (λ t, ⟦replace a b t⟧) $ λ s₁ s₂ p, to_finmap_eq.2 $ perm_replace p @[simp] theorem replace_to_finmap (a : α) (b : β a) (s : alist β) : replace a b ⟦s⟧ = ⟦s.replace a b⟧ := by simp [replace] @[simp] theorem keys_replace (a : α) (b : β a) (s : finmap β) : (replace a b s).keys = s.keys := induction_on s $ λ s, by simp @[simp] theorem mem_replace {a a' : α} {b : β a} {s : finmap β} : a' ∈ replace a b s ↔ a' ∈ s := induction_on s $ λ s, by simp /-- Fold a commutative function over the key-value pairs in the map -/ def foldl {δ : Type w} (f : δ → Π a, β a → δ) (H : ∀ d a₁ b₁ a₂ b₂, f (f d a₁ b₁) a₂ b₂ = f (f d a₂ b₂) a₁ b₁) (d : δ) (m : finmap β) : δ := m.entries.foldl (λ d s, f d s.1 s.2) (λ d s t, H _ _ _ _ _) d def any (f : Π x, β x → bool) (s : finmap β) : bool := s.foldl (λ x y z, x ∨ f y z) (by simp [or_assoc]; intros; congr' 2; rw or_comm) ff def all (f : Π x, β x → bool) (s : finmap β) : bool := s.foldl (λ x y z, x ∧ f y z) (by simp [and_assoc]; intros; congr' 2; rw and_comm) ff /-- Erase a key from the map. If the key is not present it does nothing. -/ def erase (a : α) (s : finmap β) : finmap β := lift_on s (λ t, ⟦erase a t⟧) $ λ s₁ s₂ p, to_finmap_eq.2 $ perm_erase p @[simp] theorem erase_to_finmap (a : α) (s : alist β) : erase a ⟦s⟧ = ⟦s.erase a⟧ := by simp [erase] @[simp] theorem keys_erase_to_finset (a : α) (s : alist β) : keys ⟦s.erase a⟧ = (keys ⟦s⟧).erase a := by simp [finset.erase, keys, alist.erase, keys_kerase] @[simp] theorem keys_erase (a : α) (s : finmap β) : (erase a s).keys = s.keys.erase a := induction_on s $ λ s, by simp @[simp] theorem mem_erase {a a' : α} {s : finmap β} : a' ∈ erase a s ↔ a' ≠ a ∧ a' ∈ s := induction_on s $ λ s, by simp theorem not_mem_erase_self {a : α} {s : finmap β} : ¬ a ∈ erase a s := by rw [mem_erase,not_and_distrib,not_not]; left; refl @[simp] theorem lookup_erase (a) (s : finmap β) : lookup a (erase a s) = none := induction_on s $ lookup_erase a @[simp] theorem lookup_erase_ne {a a'} {s : finmap β} (h : a ≠ a') : lookup a (erase a' s) = lookup a s := induction_on s $ λ s, lookup_erase_ne h theorem erase_erase {a a' : α} {s : finmap β} : erase a (erase a' s) = erase a' (erase a s) := induction_on s $ λ s, ext (by simp [alist.erase_erase]) lemma mem_iff {a : α} {s : finmap β} : a ∈ s ↔ ∃ b, s.lookup a = some b := induction_on s $ λ s, iff.trans list.mem_keys $ exists_congr $ λ b, (mem_lookup_iff s.nodupkeys).symm lemma mem_of_lookup_eq_some {a : α} {b : β a} {s : finmap β} (h : s.lookup a = some b) : a ∈ s := mem_iff.mpr ⟨_,h⟩ /- sub -/ def sdiff (s s' : finmap β) : finmap β := s'.foldl (λ s x _, s.erase x) (λ a₀ a₁ _ a₂ _, erase_erase) s instance : has_sdiff (finmap β) := ⟨ sdiff ⟩ /- insert -/ /-- Insert a key-value pair into a finite map, replacing any existing pair with the same key. -/ def insert (a : α) (b : β a) (s : finmap β) : finmap β := lift_on s (λ t, ⟦insert a b t⟧) $ λ s₁ s₂ p, to_finmap_eq.2 $ perm_insert p @[simp] theorem insert_to_finmap (a : α) (b : β a) (s : alist β) : insert a b ⟦s⟧ = ⟦s.insert a b⟧ := by simp [insert] theorem insert_entries_of_neg {a : α} {b : β a} {s : finmap β} : a ∉ s → (insert a b s).entries = ⟨a, b⟩ :: s.entries := induction_on s $ λ s h, by simp [insert_entries_of_neg (mt mem_to_finmap.1 h)] @[simp] theorem mem_insert {a a' : α} {b' : β a'} {s : finmap β} : a ∈ insert a' b' s ↔ a = a' ∨ a ∈ s := induction_on s mem_insert @[simp] theorem lookup_insert {a} {b : β a} (s : finmap β) : lookup a (insert a b s) = some b := induction_on s $ λ s, by simp only [insert_to_finmap, lookup_to_finmap, lookup_insert] @[simp] theorem lookup_insert_of_ne {a a'} {b : β a} (s : finmap β) (h : a' ≠ a) : lookup a' (insert a b s) = lookup a' s := induction_on s $ λ s, by simp only [insert_to_finmap, lookup_to_finmap, lookup_insert_ne h] @[simp] theorem insert_insert {a} {b b' : β a} (s : finmap β) : (s.insert a b).insert a b' = s.insert a b' := induction_on s $ λ s, by simp only [insert_to_finmap, insert_insert] theorem insert_insert_of_ne {a a'} {b : β a} {b' : β a'} (s : finmap β) (h : a ≠ a') : (s.insert a b).insert a' b' = (s.insert a' b').insert a b := induction_on s $ λ s, by simp only [insert_to_finmap,alist.to_finmap_eq,insert_insert_of_ne _ h] theorem to_finmap_cons (a : α) (b : β a) (xs : list (sigma β)) : list.to_finmap (⟨a,b⟩ :: xs) = insert a b xs.to_finmap := rfl theorem mem_list_to_finmap (a : α) (xs : list (sigma β)) : a ∈ xs.to_finmap ↔ (∃ b : β a, sigma.mk a b ∈ xs) := by { induction xs with x xs; [skip, cases x]; simp only [to_finmap_cons, *, not_mem_empty, exists_or_distrib, list.not_mem_nil, finmap.to_finmap_nil, iff_self, exists_false, mem_cons_iff, mem_insert, exists_and_distrib_left]; apply or_congr _ iff.rfl, conv { to_lhs, rw ← and_true (a = x_fst) }, apply and_congr_right, rintro ⟨⟩, simp only [exists_eq, iff_self, heq_iff_eq] } @[simp] theorem insert_singleton_eq {a : α} {b b' : β a} : insert a b (singleton a b') = singleton a b := by simp only [singleton, finmap.insert_to_finmap, alist.insert_singleton_eq] /- extract -/ /-- Erase a key from the map, and return the corresponding value, if found. -/ def extract (a : α) (s : finmap β) : option (β a) × finmap β := lift_on s (λ t, prod.map id to_finmap (extract a t)) $ λ s₁ s₂ p, by simp [perm_lookup p, to_finmap_eq, perm_erase p] @[simp] theorem extract_eq_lookup_erase (a : α) (s : finmap β) : extract a s = (lookup a s, erase a s) := induction_on s $ λ s, by simp [extract] /- union -/ /-- `s₁ ∪ s₂` is the key-based union of two finite maps. It is left-biased: if there exists an `a ∈ s₁`, `lookup a (s₁ ∪ s₂) = lookup a s₁`. -/ def union (s₁ s₂ : finmap β) : finmap β := lift_on₂ s₁ s₂ (λ s₁ s₂, ⟦s₁ ∪ s₂⟧) $ λ s₁ s₂ s₃ s₄ p₁₃ p₂₄, to_finmap_eq.mpr $ perm_union p₁₃ p₂₄ instance : has_union (finmap β) := ⟨union⟩ @[simp] theorem mem_union {a} {s₁ s₂ : finmap β} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := induction_on₂ s₁ s₂ $ λ _ _, mem_union @[simp] theorem union_to_finmap (s₁ s₂ : alist β) : ⟦s₁⟧ ∪ ⟦s₂⟧ = ⟦s₁ ∪ s₂⟧ := by simp [(∪), union] theorem keys_union {s₁ s₂ : finmap β} : (s₁ ∪ s₂).keys = s₁.keys ∪ s₂.keys := induction_on₂ s₁ s₂ $ λ s₁ s₂, finset.ext' $ by simp [keys] @[simp] theorem lookup_union_left {a} {s₁ s₂ : finmap β} : a ∈ s₁ → lookup a (s₁ ∪ s₂) = lookup a s₁ := induction_on₂ s₁ s₂ $ λ s₁ s₂, lookup_union_left @[simp] theorem lookup_union_right {a} {s₁ s₂ : finmap β} : a ∉ s₁ → lookup a (s₁ ∪ s₂) = lookup a s₂ := induction_on₂ s₁ s₂ $ λ s₁ s₂, lookup_union_right theorem lookup_union_left_of_not_in {a} {s₁ s₂ : finmap β} : a ∉ s₂ → lookup a (s₁ ∪ s₂) = lookup a s₁ := begin intros h, by_cases h' : a ∈ s₁, { rw lookup_union_left h' }, { rw [lookup_union_right h',lookup_eq_none.mpr h,lookup_eq_none.mpr h'] } end @[simp] theorem mem_lookup_union {a} {b : β a} {s₁ s₂ : finmap β} : b ∈ lookup a (s₁ ∪ s₂) ↔ b ∈ lookup a s₁ ∨ a ∉ s₁ ∧ b ∈ lookup a s₂ := induction_on₂ s₁ s₂ $ λ s₁ s₂, mem_lookup_union theorem mem_lookup_union_middle {a} {b : β a} {s₁ s₂ s₃ : finmap β} : b ∈ lookup a (s₁ ∪ s₃) → a ∉ s₂ → b ∈ lookup a (s₁ ∪ s₂ ∪ s₃) := induction_on₃ s₁ s₂ s₃ $ λ s₁ s₂ s₃, mem_lookup_union_middle theorem insert_union {a} {b : β a} {s₁ s₂ : finmap β} : insert a b (s₁ ∪ s₂) = insert a b s₁ ∪ s₂ := induction_on₂ s₁ s₂ $ λ a₁ a₂, by simp [insert_union] theorem union_assoc {s₁ s₂ s₃ : finmap β} : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := induction_on₃ s₁ s₂ s₃ $ λ s₁ s₂ s₃, by simp only [alist.to_finmap_eq,union_to_finmap,alist.union_assoc] @[simp] theorem empty_union {s₁ : finmap β} : ∅ ∪ s₁ = s₁ := induction_on s₁ $ λ s₁, by rw ← empty_to_finmap; simp [- empty_to_finmap, alist.to_finmap_eq,union_to_finmap,alist.union_assoc] @[simp] theorem union_empty {s₁ : finmap β} : s₁ ∪ ∅ = s₁ := induction_on s₁ $ λ s₁, by rw ← empty_to_finmap; simp [- empty_to_finmap, alist.to_finmap_eq,union_to_finmap,alist.union_assoc] theorem ext_lookup {s₁ s₂ : finmap β} : (∀ x, s₁.lookup x = s₂.lookup x) → s₁ = s₂ := induction_on₂ s₁ s₂ $ λ s₁ s₂ h, by simp only [alist.lookup, lookup_to_finmap] at h; rw [alist.to_finmap_eq]; apply lookup_ext s₁.nodupkeys s₂.nodupkeys; intros x y; rw h theorem erase_union_singleton (a : α) (b : β a) (s : finmap β) (h : s.lookup a = some b) : s.erase a ∪ singleton a b = s := ext_lookup (by { intro, by_cases h' : x = a, { subst a, rw [lookup_union_right not_mem_erase_self,lookup_singleton_eq,h], }, { have : x ∉ singleton a b, { rw mem_singleton, exact h' }, rw [lookup_union_left_of_not_in this,lookup_erase_ne h'] } } ) /- disjoint -/ def disjoint (s₁ s₂ : finmap β) := ∀ x ∈ s₁, ¬ x ∈ s₂ instance : decidable_rel (@disjoint α β _) := by intros x y; dsimp [disjoint]; apply_instance lemma disjoint_empty (x : finmap β) : disjoint ∅ x . @[symm] lemma disjoint.symm (x y : finmap β) (h : disjoint x y) : disjoint y x := λ p hy hx, h p hx hy lemma disjoint.symm_iff (x y : finmap β) : disjoint x y ↔ disjoint y x := ⟨ disjoint.symm x y, disjoint.symm y x ⟩ lemma disjoint_union_left (x y z : finmap β) : disjoint (x ∪ y) z ↔ disjoint x z ∧ disjoint y z := by simp [disjoint,finmap.mem_union,or_imp_distrib,forall_and_distrib] lemma disjoint_union_right (x y z : finmap β) : disjoint x (y ∪ z) ↔ disjoint x y ∧ disjoint x z := by rw [disjoint.symm_iff,disjoint_union_left,disjoint.symm_iff _ x,disjoint.symm_iff _ x] theorem union_comm_of_disjoint {s₁ s₂ : finmap β} : disjoint s₁ s₂ → s₁ ∪ s₂ = s₂ ∪ s₁ := induction_on₂ s₁ s₂ $ λ s₁ s₂, by { intros h, simp only [alist.to_finmap_eq,union_to_finmap,alist.union_comm_of_disjoint h] } theorem union_cancel {s₁ s₂ s₃ : finmap β} (h : disjoint s₁ s₃) (h' : disjoint s₂ s₃) : s₁ ∪ s₃ = s₂ ∪ s₃ ↔ s₁ = s₂ := ⟨λ h'', begin apply ext_lookup, intro x, have : (s₁ ∪ s₃).lookup x = (s₂ ∪ s₃).lookup x, from h'' ▸ rfl, by_cases hs₁ : x ∈ s₁, { rw [lookup_union_left hs₁,lookup_union_left_of_not_in (h _ hs₁)] at this, exact this }, { by_cases hs₂ : x ∈ s₂, { rw [lookup_union_left_of_not_in (h' _ hs₂),lookup_union_left hs₂] at this; exact this }, { rw [lookup_eq_none.mpr hs₁,lookup_eq_none.mpr hs₂] } } end, λ h, h ▸ rfl⟩ end finmap
1a84aed9598ddb23dab584d550d1bf81cb545bfa
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/coeIssue3.lean
0a9c5c6b4c4f19d54bbd5ba6e612c65d75a92117
[ "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
504
lean
structure Var : Type := (name : String) instance Var.nameCoe : Coe String Var := ⟨Var.mk⟩ structure A : Type := (u : Unit) structure B : Type := (u : Unit) def a : A := A.mk () def b : B := B.mk () def Foo.chalk : A → List Var → Unit := fun _ _ => () def Bar.chalk : B → Unit := fun _ => () instance listCoe {α β} [Coe α β] : Coe (List α) (List β) := ⟨fun as => as.map fun (a : α) => ↑a⟩ open Foo open Bar #check Foo.chalk a ["foo"] -- works #check chalk a ["foo"] -- works
86ce879c58ed92083482587944ad8465a49eafd1
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/topology/uniform_space/separation.lean
ebaa30918477e7306192c1f090cd28fe79bd7a7a
[ "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
22,525
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Patrick Massot -/ import topology.uniform_space.basic import tactic.apply_fun /-! # Hausdorff properties of uniform spaces. Separation quotient. This file studies uniform spaces whose underlying topological spaces are separated (also known as Hausdorff or T₂). This turns out to be equivalent to asking that the intersection of all entourages is the diagonal only. This condition actually implies the stronger separation property that the space is regular (T₃), hence those conditions are equivalent for topologies coming from a uniform structure. More generally, the intersection `𝓢 X` of all entourages of `X`, which has type `set (X × X)` is an equivalence relation on `X`. Points which are equivalent under the relation are basically undistinguishable from the point of view of the uniform structure. For instance any uniformly continuous function will send equivalent points to the same value. The quotient `separation_quotient X` of `X` by `𝓢 X` has a natural uniform structure which is separated, and satisfies a universal property: every uniformly continuous function from `X` to a separated uniform space uniquely factors through `separation_quotient X`. As usual, this allows to turn `separation_quotient` into a functor (but we don't use the category theory library in this file). These notions admit relative versions, one can ask that `s : set X` is separated, this is equivalent to asking that the uniform structure induced on `s` is separated. ## Main definitions * `separation_relation X : set (X × X)`: the separation relation * `separated_space X`: a predicate class asserting that `X` is separated * `is_separated s`: a predicate asserting that `s : set X` is separated * `separation_quotient X`: the maximal separated quotient of `X`. * `separation_quotient.lift f`: factors a map `f : X → Y` through the separation quotient of `X`. * `separation_quotient.map f`: turns a map `f : X → Y` into a map between the separation quotients of `X` and `Y`. ## Main results * `separated_iff_t2`: the equivalence between being separated and being Hausdorff for uniform spaces. * `separation_quotient.uniform_continuous_lift`: factoring a uniformly continuous map through the separation quotient gives a uniformly continuous map. * `separation_quotient.uniform_continuous_map`: maps induced between separation quotients are uniformly continuous. ## Notations Localized in `uniformity`, we have the notation `𝓢 X` for the separation relation on a uniform space `X`, ## Implementation notes The separation setoid `separation_setoid` is not declared as a global instance. It is made a local instance while building the theory of `separation_quotient`. The factored map `separation_quotient.lift f` is defined without imposing any condition on `f`, but returns junk if `f` is not uniformly continuous (constant junk hence it is always uniformly continuous). -/ open filter topological_space set classical function uniform_space open_locale classical topological_space uniformity filter noncomputable theory set_option eqn_compiler.zeta true universes u v w variables {α : Type u} {β : Type v} {γ : Type w} variables [uniform_space α] [uniform_space β] [uniform_space γ] /-! ### Separated uniform spaces -/ /-- The separation relation is the intersection of all entourages. Two points which are related by the separation relation are "indistinguishable" according to the uniform structure. -/ protected def separation_rel (α : Type u) [u : uniform_space α] := ⋂₀ (𝓤 α).sets localized "notation `𝓢` := separation_rel" in uniformity lemma separated_equiv : equivalence (λx y, (x, y) ∈ 𝓢 α) := ⟨assume x, assume s, refl_mem_uniformity, assume x y, assume h (s : set (α×α)) hs, have preimage prod.swap s ∈ 𝓤 α, from symm_le_uniformity hs, h _ this, assume x y z (hxy : (x, y) ∈ 𝓢 α) (hyz : (y, z) ∈ 𝓢 α) s (hs : s ∈ 𝓤 α), let ⟨t, ht, (h_ts : comp_rel t t ⊆ s)⟩ := comp_mem_uniformity_sets hs in h_ts $ show (x, z) ∈ comp_rel t t, from ⟨y, hxy t ht, hyz t ht⟩⟩ /-- A uniform space is separated if its separation relation is trivial (each point is related only to itself). -/ class separated_space (α : Type u) [uniform_space α] : Prop := (out : 𝓢 α = id_rel) theorem separated_space_iff {α : Type u} [uniform_space α] : separated_space α ↔ 𝓢 α = id_rel := ⟨λ h, h.1, λ h, ⟨h⟩⟩ theorem separated_def {α : Type u} [uniform_space α] : separated_space α ↔ ∀ x y, (∀ r ∈ 𝓤 α, (x, y) ∈ r) → x = y := by simp [separated_space_iff, id_rel_subset.2 separated_equiv.1, subset.antisymm_iff]; simp [subset_def, separation_rel] theorem separated_def' {α : Type u} [uniform_space α] : separated_space α ↔ ∀ x y, x ≠ y → ∃ r ∈ 𝓤 α, (x, y) ∉ r := separated_def.trans $ forall_congr $ λ x, forall_congr $ λ y, by rw ← not_imp_not; simp [not_forall] lemma eq_of_uniformity {α : Type*} [uniform_space α] [separated_space α] {x y : α} (h : ∀ {V}, V ∈ 𝓤 α → (x, y) ∈ V) : x = y := separated_def.mp ‹separated_space α› x y (λ _, h) lemma eq_of_uniformity_basis {α : Type*} [uniform_space α] [separated_space α] {ι : Type*} {p : ι → Prop} {s : ι → set (α × α)} (hs : (𝓤 α).has_basis p s) {x y : α} (h : ∀ {i}, p i → (x, y) ∈ s i) : x = y := eq_of_uniformity (λ V V_in, let ⟨i, hi, H⟩ := hs.mem_iff.mp V_in in H (h hi)) lemma eq_of_forall_symmetric {α : Type*} [uniform_space α] [separated_space α] {x y : α} (h : ∀ {V}, V ∈ 𝓤 α → symmetric_rel V → (x, y) ∈ V) : x = y := eq_of_uniformity_basis has_basis_symmetric (by simpa [and_imp] using λ _, h) lemma id_rel_sub_separation_relation (α : Type*) [uniform_space α] : id_rel ⊆ 𝓢 α := begin unfold separation_rel, rw id_rel_subset, intros x, suffices : ∀ t ∈ 𝓤 α, (x, x) ∈ t, by simpa only [refl_mem_uniformity], exact λ t, refl_mem_uniformity, end lemma separation_rel_comap {f : α → β} (h : ‹uniform_space α› = uniform_space.comap f ‹uniform_space β›) : 𝓢 α = (prod.map f f) ⁻¹' 𝓢 β := begin dsimp [separation_rel], rw [uniformity_comap h, (filter.comap_has_basis (prod.map f f) (𝓤 β)).sInter_sets, ← preimage_bInter, sInter_eq_bInter], refl, end protected lemma filter.has_basis.separation_rel {ι : Type*} {p : ι → Prop} {s : ι → set (α × α)} (h : has_basis (𝓤 α) p s) : 𝓢 α = ⋂ i ∈ set_of p, s i := by { unfold separation_rel, rw h.sInter_sets } lemma separation_rel_eq_inter_closure : 𝓢 α = ⋂₀ (closure '' (𝓤 α).sets) := by simpa [uniformity_has_basis_closure.separation_rel] lemma is_closed_separation_rel : is_closed (𝓢 α) := begin rw separation_rel_eq_inter_closure, apply is_closed_sInter, rintros _ ⟨t, t_in, rfl⟩, exact is_closed_closure, end lemma separated_iff_t2 : separated_space α ↔ t2_space α := begin classical, split ; intro h, { rw [t2_iff_is_closed_diagonal, ← show 𝓢 α = diagonal α, from h.1], exact is_closed_separation_rel }, { rw separated_def', intros x y hxy, have : 𝓝 x ⊓ 𝓝 y = ⊥, { rw t2_iff_nhds at h, by_contra H, exact hxy (h ⟨H⟩) }, rcases inf_eq_bot_iff.mp this with ⟨U, U_in, V, V_in, H⟩, rcases uniform_space.mem_nhds_iff.mp U_in with ⟨S, S_in, S_sub⟩, use [S, S_in], change y ∉ ball x S, intro y_in, have : y ∈ U ∩ V := ⟨S_sub y_in, mem_of_mem_nhds V_in⟩, rwa H at this }, end @[priority 100] -- see Note [lower instance priority] instance separated_regular [separated_space α] : regular_space α := { t0 := by { haveI := separated_iff_t2.mp ‹_›, exact t1_space.t0_space.t0 }, regular := λs a hs ha, have sᶜ ∈ 𝓝 a, from is_open.mem_nhds hs.is_open_compl ha, have {p : α × α | p.1 = a → p.2 ∈ sᶜ} ∈ 𝓤 α, from mem_nhds_uniformity_iff_right.mp this, let ⟨d, hd, h⟩ := comp_mem_uniformity_sets this in let e := {y:α| (a, y) ∈ d} in have hae : a ∈ closure e, from subset_closure $ refl_mem_uniformity hd, have set.prod (closure e) (closure e) ⊆ comp_rel d (comp_rel (set.prod e e) d), begin rw [←closure_prod_eq, closure_eq_inter_uniformity], change (⨅d' ∈ 𝓤 α, _) ≤ comp_rel d (comp_rel _ d), exact (infi_le_of_le d $ infi_le_of_le hd $ le_refl _) end, have e_subset : closure e ⊆ sᶜ, from assume a' ha', let ⟨x, (hx : (a, x) ∈ d), y, ⟨hx₁, hx₂⟩, (hy : (y, _) ∈ d)⟩ := @this ⟨a, a'⟩ ⟨hae, ha'⟩ in have (a, a') ∈ comp_rel d d, from ⟨y, hx₂, hy⟩, h this rfl, have closure e ∈ 𝓝 a, from (𝓝 a).sets_of_superset (mem_nhds_left a hd) subset_closure, have 𝓝 a ⊓ 𝓟 (closure e)ᶜ = ⊥, from (@inf_eq_bot_iff_le_compl _ _ _ (𝓟 (closure e)ᶜ) (𝓟 (closure e)) (by simp [principal_univ, union_comm]) (by simp)).mpr (by simp [this]), ⟨(closure e)ᶜ, is_closed_closure.is_open_compl, assume x h₁ h₂, @e_subset x h₂ h₁, this⟩, ..@t2_space.t1_space _ _ (separated_iff_t2.mp ‹_›) } lemma is_closed_of_spaced_out [separated_space α] {V₀ : set (α × α)} (V₀_in : V₀ ∈ 𝓤 α) {s : set α} (hs : ∀ {x y}, x ∈ s → y ∈ s → (x, y) ∈ V₀ → x = y) : is_closed s := begin rcases comp_symm_mem_uniformity_sets V₀_in with ⟨V₁, V₁_in, V₁_symm, h_comp⟩, apply is_closed_of_closure_subset, intros x hx, rw mem_closure_iff_ball at hx, rcases hx V₁_in with ⟨y, hy, hy'⟩, suffices : x = y, by rwa this, apply eq_of_forall_symmetric, intros V V_in V_symm, rcases hx (inter_mem_sets V₁_in V_in) with ⟨z, hz, hz'⟩, suffices : z = y, { rw ← this, exact ball_inter_right x _ _ hz }, exact hs hz' hy' (h_comp $ mem_comp_of_mem_ball V₁_symm (ball_inter_left x _ _ hz) hy) end /-! ### Separated sets -/ /-- A set `s` in a uniform space `α` is separated if the separation relation `𝓢 α` induces the trivial relation on `s`. -/ def is_separated (s : set α) : Prop := ∀ x y ∈ s, (x, y) ∈ 𝓢 α → x = y lemma is_separated_def (s : set α) : is_separated s ↔ ∀ x y ∈ s, (x, y) ∈ 𝓢 α → x = y := iff.rfl lemma is_separated_def' (s : set α) : is_separated s ↔ (s.prod s) ∩ 𝓢 α ⊆ id_rel := begin rw is_separated_def, split, { rintros h ⟨x, y⟩ ⟨⟨x_in, y_in⟩, H⟩, simp [h x y x_in y_in H] }, { intros h x y x_in y_in xy_in, rw ← mem_id_rel, exact h ⟨mk_mem_prod x_in y_in, xy_in⟩ } end lemma univ_separated_iff : is_separated (univ : set α) ↔ separated_space α := begin simp only [is_separated, mem_univ, true_implies_iff, separated_space_iff], split, { intro h, exact subset.antisymm (λ ⟨x, y⟩ xy_in, h x y xy_in) (id_rel_sub_separation_relation α), }, { intros h x y xy_in, rwa h at xy_in }, end lemma is_separated_of_separated_space [separated_space α] (s : set α) : is_separated s := begin rw [is_separated, separated_space.out], tauto, end lemma is_separated_iff_induced {s : set α} : is_separated s ↔ separated_space s := begin rw separated_space_iff, change _ ↔ 𝓢 {x // x ∈ s} = _, rw [separation_rel_comap rfl, is_separated_def'], split; intro h, { ext ⟨⟨x, x_in⟩, ⟨y, y_in⟩⟩, suffices : (x, y) ∈ 𝓢 α ↔ x = y, by simpa only [mem_id_rel], refine ⟨λ H, h ⟨mk_mem_prod x_in y_in, H⟩, _⟩, rintro rfl, exact id_rel_sub_separation_relation α rfl }, { rintros ⟨x, y⟩ ⟨⟨x_in, y_in⟩, hS⟩, have A : (⟨⟨x, x_in⟩, ⟨y, y_in⟩⟩ : ↥s × ↥s) ∈ prod.map (coe : s → α) (coe : s → α) ⁻¹' 𝓢 α, from hS, simpa using h.subset A } end lemma eq_of_uniformity_inf_nhds_of_is_separated {s : set α} (hs : is_separated s) : ∀ {x y : α}, x ∈ s → y ∈ s → cluster_pt (x, y) (𝓤 α) → x = y := begin intros x y x_in y_in H, have : ∀ V ∈ 𝓤 α, (x, y) ∈ closure V, { intros V V_in, rw mem_closure_iff_cluster_pt, have : 𝓤 α ≤ 𝓟 V, by rwa le_principal_iff, exact H.mono this }, apply hs x y x_in y_in, simpa [separation_rel_eq_inter_closure], end lemma eq_of_uniformity_inf_nhds [separated_space α] : ∀ {x y : α}, cluster_pt (x, y) (𝓤 α) → x = y := begin have : is_separated (univ : set α), { rw univ_separated_iff, assumption }, introv, simpa using eq_of_uniformity_inf_nhds_of_is_separated this, end /-! ### Separation quotient -/ namespace uniform_space /-- The separation relation of a uniform space seen as a setoid. -/ def separation_setoid (α : Type u) [uniform_space α] : setoid α := ⟨λx y, (x, y) ∈ 𝓢 α, separated_equiv⟩ local attribute [instance] separation_setoid instance separation_setoid.uniform_space {α : Type u} [u : uniform_space α] : uniform_space (quotient (separation_setoid α)) := { to_topological_space := u.to_topological_space.coinduced (λx, ⟦x⟧), uniformity := map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) u.uniformity, refl := le_trans (by simp [quotient.exists_rep]) (filter.map_mono refl_le_uniformity), symm := tendsto_map' $ by simp [prod.swap, (∘)]; exact tendsto_map.comp tendsto_swap_uniformity, comp := calc (map (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) u.uniformity).lift' (λs, comp_rel s s) = u.uniformity.lift' ((λs, comp_rel s s) ∘ image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧))) : map_lift'_eq2 $ monotone_comp_rel monotone_id monotone_id ... ≤ u.uniformity.lift' (image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ∘ (λs:set (α×α), comp_rel s (comp_rel s s))) : lift'_mono' $ assume s hs ⟨a, b⟩ ⟨c, ⟨⟨a₁, a₂⟩, ha, a_eq⟩, ⟨⟨b₁, b₂⟩, hb, b_eq⟩⟩, begin simp at a_eq, simp at b_eq, have h : ⟦a₂⟧ = ⟦b₁⟧, { rw [a_eq.right, b_eq.left] }, have h : (a₂, b₁) ∈ 𝓢 α := quotient.exact h, simp [function.comp, set.image, comp_rel, and.comm, and.left_comm, and.assoc], exact ⟨a₁, a_eq.left, b₂, b_eq.right, a₂, ha, b₁, h s hs, hb⟩ end ... = map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) (u.uniformity.lift' (λs:set (α×α), comp_rel s (comp_rel s s))) : by rw [map_lift'_eq]; exact monotone_comp_rel monotone_id (monotone_comp_rel monotone_id monotone_id) ... ≤ map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) u.uniformity : map_mono comp_le_uniformity3, is_open_uniformity := assume s, have ∀a, ⟦a⟧ ∈ s → ({p:α×α | p.1 = a → ⟦p.2⟧ ∈ s} ∈ 𝓤 α ↔ {p:α×α | p.1 ≈ a → ⟦p.2⟧ ∈ s} ∈ 𝓤 α), from assume a ha, ⟨assume h, let ⟨t, ht, hts⟩ := comp_mem_uniformity_sets h in have hts : ∀{a₁ a₂}, (a, a₁) ∈ t → (a₁, a₂) ∈ t → ⟦a₂⟧ ∈ s, from assume a₁ a₂ ha₁ ha₂, @hts (a, a₂) ⟨a₁, ha₁, ha₂⟩ rfl, have ht' : ∀{a₁ a₂}, a₁ ≈ a₂ → (a₁, a₂) ∈ t, from assume a₁ a₂ h, sInter_subset_of_mem ht h, u.uniformity.sets_of_superset ht $ assume ⟨a₁, a₂⟩ h₁ h₂, hts (ht' $ setoid.symm h₂) h₁, assume h, u.uniformity.sets_of_superset h $ by simp {contextual := tt}⟩, begin simp [topological_space.coinduced, u.is_open_uniformity, uniformity, forall_quotient_iff], exact ⟨λh a ha, (this a ha).mp $ h a ha, λh a ha, (this a ha).mpr $ h a ha⟩ end } lemma uniformity_quotient : 𝓤 (quotient (separation_setoid α)) = (𝓤 α).map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) := rfl lemma uniform_continuous_quotient_mk : uniform_continuous (quotient.mk : α → quotient (separation_setoid α)) := le_refl _ lemma uniform_continuous_quotient {f : quotient (separation_setoid α) → β} (hf : uniform_continuous (λx, f ⟦x⟧)) : uniform_continuous f := hf lemma uniform_continuous_quotient_lift {f : α → β} {h : ∀a b, (a, b) ∈ 𝓢 α → f a = f b} (hf : uniform_continuous f) : uniform_continuous (λa, quotient.lift f h a) := uniform_continuous_quotient hf lemma uniform_continuous_quotient_lift₂ {f : α → β → γ} {h : ∀a c b d, (a, b) ∈ 𝓢 α → (c, d) ∈ 𝓢 β → f a c = f b d} (hf : uniform_continuous (λp:α×β, f p.1 p.2)) : uniform_continuous (λp:_×_, quotient.lift₂ f h p.1 p.2) := begin rw [uniform_continuous, uniformity_prod_eq_prod, uniformity_quotient, uniformity_quotient, filter.prod_map_map_eq, filter.tendsto_map'_iff, filter.tendsto_map'_iff], rwa [uniform_continuous, uniformity_prod_eq_prod, filter.tendsto_map'_iff] at hf end lemma comap_quotient_le_uniformity : (𝓤 $ quotient $ separation_setoid α).comap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ≤ (𝓤 α) := assume t' ht', let ⟨t, ht, tt_t'⟩ := comp_mem_uniformity_sets ht' in let ⟨s, hs, ss_t⟩ := comp_mem_uniformity_sets ht in ⟨(λp:α×α, (⟦p.1⟧, ⟦p.2⟧)) '' s, (𝓤 α).sets_of_superset hs $ assume x hx, ⟨x, hx, rfl⟩, assume ⟨a₁, a₂⟩ ⟨⟨b₁, b₂⟩, hb, ab_eq⟩, have ⟦b₁⟧ = ⟦a₁⟧ ∧ ⟦b₂⟧ = ⟦a₂⟧, from prod.mk.inj ab_eq, have b₁ ≈ a₁ ∧ b₂ ≈ a₂, from and.imp quotient.exact quotient.exact this, have ab₁ : (a₁, b₁) ∈ t, from (setoid.symm this.left) t ht, have ba₂ : (b₂, a₂) ∈ s, from this.right s hs, tt_t' ⟨b₁, show ((a₁, a₂).1, b₁) ∈ t, from ab₁, ss_t ⟨b₂, show ((b₁, a₂).1, b₂) ∈ s, from hb, ba₂⟩⟩⟩ lemma comap_quotient_eq_uniformity : (𝓤 $ quotient $ separation_setoid α).comap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) = 𝓤 α := le_antisymm comap_quotient_le_uniformity le_comap_map instance separated_separation : separated_space (quotient (separation_setoid α)) := ⟨set.ext $ assume ⟨a, b⟩, quotient.induction_on₂ a b $ assume a b, ⟨assume h, have a ≈ b, from assume s hs, have s ∈ (𝓤 $ quotient $ separation_setoid α).comap (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)), from comap_quotient_le_uniformity hs, let ⟨t, ht, hts⟩ := this in hts begin dsimp [preimage], exact h t ht end, show ⟦a⟧ = ⟦b⟧, from quotient.sound this, assume heq : ⟦a⟧ = ⟦b⟧, assume h hs, heq ▸ refl_mem_uniformity hs⟩⟩ lemma separated_of_uniform_continuous {f : α → β} {x y : α} (H : uniform_continuous f) (h : x ≈ y) : f x ≈ f y := assume _ h', h _ (H h') lemma eq_of_separated_of_uniform_continuous [separated_space β] {f : α → β} {x y : α} (H : uniform_continuous f) (h : x ≈ y) : f x = f y := separated_def.1 (by apply_instance) _ _ $ separated_of_uniform_continuous H h /-- The maximal separated quotient of a uniform space `α`. -/ def separation_quotient (α : Type*) [uniform_space α] := quotient (separation_setoid α) namespace separation_quotient instance : uniform_space (separation_quotient α) := by dunfold separation_quotient ; apply_instance instance : separated_space (separation_quotient α) := by dunfold separation_quotient ; apply_instance instance [inhabited α] : inhabited (separation_quotient α) := by unfold separation_quotient; apply_instance /-- Factoring functions to a separated space through the separation quotient. -/ def lift [separated_space β] (f : α → β) : (separation_quotient α → β) := if h : uniform_continuous f then quotient.lift f (λ x y, eq_of_separated_of_uniform_continuous h) else λ x, f (nonempty.some ⟨x.out⟩) lemma lift_mk [separated_space β] {f : α → β} (h : uniform_continuous f) (a : α) : lift f ⟦a⟧ = f a := by rw [lift, dif_pos h]; refl lemma uniform_continuous_lift [separated_space β] (f : α → β) : uniform_continuous (lift f) := begin by_cases hf : uniform_continuous f, { rw [lift, dif_pos hf], exact uniform_continuous_quotient_lift hf }, { rw [lift, dif_neg hf], exact uniform_continuous_of_const (assume a b, rfl) } end /-- The separation quotient functor acting on functions. -/ def map (f : α → β) : separation_quotient α → separation_quotient β := lift (quotient.mk ∘ f) lemma map_mk {f : α → β} (h : uniform_continuous f) (a : α) : map f ⟦a⟧ = ⟦f a⟧ := by rw [map, lift_mk (uniform_continuous_quotient_mk.comp h)] lemma uniform_continuous_map (f : α → β) : uniform_continuous (map f) := uniform_continuous_lift (quotient.mk ∘ f) lemma map_unique {f : α → β} (hf : uniform_continuous f) {g : separation_quotient α → separation_quotient β} (comm : quotient.mk ∘ f = g ∘ quotient.mk) : map f = g := by ext ⟨a⟩; calc map f ⟦a⟧ = ⟦f a⟧ : map_mk hf a ... = g ⟦a⟧ : congr_fun comm a lemma map_id : map (@id α) = id := map_unique uniform_continuous_id rfl lemma map_comp {f : α → β} {g : β → γ} (hf : uniform_continuous f) (hg : uniform_continuous g) : map g ∘ map f = map (g ∘ f) := (map_unique (hg.comp hf) $ by simp only [(∘), map_mk, hf, hg]).symm end separation_quotient lemma separation_prod {a₁ a₂ : α} {b₁ b₂ : β} : (a₁, b₁) ≈ (a₂, b₂) ↔ a₁ ≈ a₂ ∧ b₁ ≈ b₂ := begin split, { assume h, exact ⟨separated_of_uniform_continuous uniform_continuous_fst h, separated_of_uniform_continuous uniform_continuous_snd h⟩ }, { rintros ⟨eqv_α, eqv_β⟩ r r_in, rw uniformity_prod at r_in, rcases r_in with ⟨t_α, ⟨r_α, r_α_in, h_α⟩, t_β, ⟨r_β, r_β_in, h_β⟩, H⟩, let p_α := λ(p : (α × β) × (α × β)), (p.1.1, p.2.1), let p_β := λ(p : (α × β) × (α × β)), (p.1.2, p.2.2), have key_α : p_α ((a₁, b₁), (a₂, b₂)) ∈ r_α, { simp [p_α, eqv_α r_α r_α_in] }, have key_β : p_β ((a₁, b₁), (a₂, b₂)) ∈ r_β, { simp [p_β, eqv_β r_β r_β_in] }, exact H ⟨h_α key_α, h_β key_β⟩ }, end instance separated.prod [separated_space α] [separated_space β] : separated_space (α × β) := separated_def.2 $ assume x y H, prod.ext (eq_of_separated_of_uniform_continuous uniform_continuous_fst H) (eq_of_separated_of_uniform_continuous uniform_continuous_snd H) end uniform_space
2e61f47c9554c7d205d5490200e119c12e1a3219
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/linear_algebra/affine_space/affine_equiv.lean
8e6ab93d2c543c0508af8c78f7f79ba9cb32fe1d
[ "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
16,096
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import linear_algebra.affine_space.affine_map import algebra.invertible /-! # Affine equivalences In this file we define `affine_equiv k P₁ P₂` (notation: `P₁ ≃ᵃ[k] P₂`) to be the type of affine equivalences between `P₁` and `P₂, i.e., equivalences such that both forward and inverse maps are affine maps. We define the following equivalences: * `affine_equiv.refl k P`: the identity map as an `affine_equiv`; * `e.symm`: the inverse map of an `affine_equiv` as an `affine_equiv`; * `e.trans e'`: composition of two `affine_equiv`s; note that the order follows `mathlib`'s `category_theory` convention (apply `e`, then `e'`), not the convention used in function composition and compositions of bundled morphisms. ## Tags affine space, affine equivalence -/ open function set open_locale affine /-- An affine equivalence is an equivalence between affine spaces such that both forward and inverse maps are affine. We define it using an `equiv` for the map and a `linear_equiv` for the linear part in order to allow affine equivalences with good definitional equalities. -/ @[nolint has_inhabited_instance] structure affine_equiv (k P₁ P₂ : Type*) {V₁ V₂ : Type*} [ring k] [add_comm_group V₁] [module k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [module k V₂] [add_torsor V₂ P₂] extends P₁ ≃ P₂ := (linear : V₁ ≃ₗ[k] V₂) (map_vadd' : ∀ (p : P₁) (v : V₁), to_equiv (v +ᵥ p) = linear v +ᵥ to_equiv p) notation P₁ ` ≃ᵃ[`:25 k:25 `] `:0 P₂:0 := affine_equiv k P₁ P₂ variables {k V₁ V₂ V₃ V₄ P₁ P₂ P₃ P₄ : Type*} [ring k] [add_comm_group V₁] [module k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [module k V₂] [add_torsor V₂ P₂] [add_comm_group V₃] [module k V₃] [add_torsor V₃ P₃] [add_comm_group V₄] [module k V₄] [add_torsor V₄ P₄] namespace affine_equiv include V₁ V₂ instance : has_coe_to_fun (P₁ ≃ᵃ[k] P₂) := ⟨_, λ e, e.to_fun⟩ instance : has_coe (P₁ ≃ᵃ[k] P₂) (P₁ ≃ P₂) := ⟨affine_equiv.to_equiv⟩ variables (k P₁) omit V₂ /-- Identity map as an `affine_equiv`. -/ @[refl] def refl : P₁ ≃ᵃ[k] P₁ := { to_equiv := equiv.refl P₁, linear := linear_equiv.refl k V₁, map_vadd' := λ _ _, rfl } @[simp] lemma coe_refl : ⇑(refl k P₁) = id := rfl lemma refl_apply (x : P₁) : refl k P₁ x = x := rfl @[simp] lemma to_equiv_refl : (refl k P₁).to_equiv = equiv.refl P₁ := rfl @[simp] lemma linear_refl : (refl k P₁).linear = linear_equiv.refl k V₁ := rfl variables {k P₁} include V₂ @[simp] lemma map_vadd (e : P₁ ≃ᵃ[k] P₂) (p : P₁) (v : V₁) : e (v +ᵥ p) = e.linear v +ᵥ e p := e.map_vadd' p v @[simp] lemma coe_to_equiv (e : P₁ ≃ᵃ[k] P₂) : ⇑e.to_equiv = e := rfl /-- Reinterpret an `affine_equiv` as an `affine_map`. -/ def to_affine_map (e : P₁ ≃ᵃ[k] P₂) : P₁ →ᵃ[k] P₂ := { to_fun := e, .. e } instance : has_coe (P₁ ≃ᵃ[k] P₂) (P₁ →ᵃ[k] P₂) := ⟨to_affine_map⟩ @[simp] lemma coe_to_affine_map (e : P₁ ≃ᵃ[k] P₂) : (e.to_affine_map : P₁ → P₂) = (e : P₁ → P₂) := rfl @[simp] lemma to_affine_map_mk (f : P₁ ≃ P₂) (f' : V₁ ≃ₗ[k] V₂) (h) : to_affine_map (mk f f' h) = ⟨f, f', h⟩ := rfl @[norm_cast, simp] lemma coe_coe (e : P₁ ≃ᵃ[k] P₂) : ((e : P₁ →ᵃ[k] P₂) : P₁ → P₂) = e := rfl @[simp] lemma linear_to_affine_map (e : P₁ ≃ᵃ[k] P₂) : e.to_affine_map.linear = e.linear := rfl lemma to_affine_map_injective : injective (to_affine_map : (P₁ ≃ᵃ[k] P₂) → (P₁ →ᵃ[k] P₂)) := begin rintros ⟨e, el, h⟩ ⟨e', el', h'⟩ H, simp only [to_affine_map_mk, equiv.coe_inj, linear_equiv.to_linear_map_inj] at H, congr, exacts [H.1, H.2] end @[simp] lemma to_affine_map_inj {e e' : P₁ ≃ᵃ[k] P₂} : e.to_affine_map = e'.to_affine_map ↔ e = e' := to_affine_map_injective.eq_iff @[ext] lemma ext {e e' : P₁ ≃ᵃ[k] P₂} (h : ∀ x, e x = e' x) : e = e' := to_affine_map_injective $ affine_map.ext h lemma coe_fn_injective : injective (λ (e : P₁ ≃ᵃ[k] P₂) (x : P₁), e x) := λ e e' H, ext $ congr_fun H @[simp, norm_cast] lemma coe_fn_inj {e e' : P₁ ≃ᵃ[k] P₂} : ⇑e = e' ↔ e = e' := coe_fn_injective.eq_iff lemma to_equiv_injective : injective (to_equiv : (P₁ ≃ᵃ[k] P₂) → (P₁ ≃ P₂)) := λ e e' H, ext $ equiv.ext_iff.1 H @[simp] lemma to_equiv_inj {e e' : P₁ ≃ᵃ[k] P₂} : e.to_equiv = e'.to_equiv ↔ e = e' := to_equiv_injective.eq_iff @[simp] lemma coe_mk (e : P₁ ≃ P₂) (e' : V₁ ≃ₗ[k] V₂) (h) : ((⟨e, e', h⟩ : P₁ ≃ᵃ[k] P₂) : P₁ → P₂) = e := rfl /-- Construct an affine equivalence by verifying the relation between the map and its linear part at one base point. Namely, this function takes a map `e : P₁ → P₂`, a linear equivalence `e' : V₁ ≃ₗ[k] V₂`, and a point `p` such that for any other point `p'` we have `e p' = e' (p' -ᵥ p) +ᵥ e p`. -/ def mk' (e : P₁ → P₂) (e' : V₁ ≃ₗ[k] V₂) (p : P₁) (h : ∀ p' : P₁, e p' = e' (p' -ᵥ p) +ᵥ e p) : P₁ ≃ᵃ[k] P₂ := { to_fun := e, inv_fun := λ q' : P₂, e'.symm (q' -ᵥ e p) +ᵥ p, left_inv := λ p', by simp [h p'], right_inv := λ q', by simp [h (e'.symm (q' -ᵥ e p) +ᵥ p)], linear := e', map_vadd' := λ p' v, by { simp [h p', h (v +ᵥ p'), vadd_vsub_assoc, vadd_vadd] } } @[simp] lemma coe_mk' (e : P₁ ≃ P₂) (e' : V₁ ≃ₗ[k] V₂) (p h) : ⇑(mk' e e' p h) = e := rfl @[simp] lemma linear_mk' (e : P₁ ≃ P₂) (e' : V₁ ≃ₗ[k] V₂) (p h) : (mk' e e' p h).linear = e' := rfl /-- Inverse of an affine equivalence as an affine equivalence. -/ @[symm] def symm (e : P₁ ≃ᵃ[k] P₂) : P₂ ≃ᵃ[k] P₁ := { to_equiv := e.to_equiv.symm, linear := e.linear.symm, map_vadd' := λ v p, e.to_equiv.symm.apply_eq_iff_eq_symm_apply.2 $ by simpa using (e.to_equiv.apply_symm_apply v).symm } @[simp] lemma symm_to_equiv (e : P₁ ≃ᵃ[k] P₂) : e.to_equiv.symm = e.symm.to_equiv := rfl @[simp] lemma symm_linear (e : P₁ ≃ᵃ[k] P₂) : e.linear.symm = e.symm.linear := rfl protected lemma bijective (e : P₁ ≃ᵃ[k] P₂) : bijective e := e.to_equiv.bijective protected lemma surjective (e : P₁ ≃ᵃ[k] P₂) : surjective e := e.to_equiv.surjective protected lemma injective (e : P₁ ≃ᵃ[k] P₂) : injective e := e.to_equiv.injective @[simp] lemma range_eq (e : P₁ ≃ᵃ[k] P₂) : range e = univ := e.surjective.range_eq @[simp] lemma apply_symm_apply (e : P₁ ≃ᵃ[k] P₂) (p : P₂) : e (e.symm p) = p := e.to_equiv.apply_symm_apply p @[simp] lemma symm_apply_apply (e : P₁ ≃ᵃ[k] P₂) (p : P₁) : e.symm (e p) = p := e.to_equiv.symm_apply_apply p lemma apply_eq_iff_eq_symm_apply (e : P₁ ≃ᵃ[k] P₂) {p₁ p₂} : e p₁ = p₂ ↔ p₁ = e.symm p₂ := e.to_equiv.apply_eq_iff_eq_symm_apply @[simp] lemma apply_eq_iff_eq (e : P₁ ≃ᵃ[k] P₂) {p₁ p₂ : P₁} : e p₁ = e p₂ ↔ p₁ = p₂ := e.to_equiv.apply_eq_iff_eq omit V₂ @[simp] lemma symm_refl : (refl k P₁).symm = refl k P₁ := rfl include V₂ V₃ /-- Composition of two `affine_equiv`alences, applied left to right. -/ @[trans] def trans (e : P₁ ≃ᵃ[k] P₂) (e' : P₂ ≃ᵃ[k] P₃) : P₁ ≃ᵃ[k] P₃ := { to_equiv := e.to_equiv.trans e'.to_equiv, linear := e.linear.trans e'.linear, map_vadd' := λ p v, by simp only [linear_equiv.trans_apply, coe_to_equiv, (∘), equiv.coe_trans, map_vadd] } @[simp] lemma coe_trans (e : P₁ ≃ᵃ[k] P₂) (e' : P₂ ≃ᵃ[k] P₃) : ⇑(e.trans e') = e' ∘ e := rfl lemma trans_apply (e : P₁ ≃ᵃ[k] P₂) (e' : P₂ ≃ᵃ[k] P₃) (p : P₁) : e.trans e' p = e' (e p) := rfl include V₄ lemma trans_assoc (e₁ : P₁ ≃ᵃ[k] P₂) (e₂ : P₂ ≃ᵃ[k] P₃) (e₃ : P₃ ≃ᵃ[k] P₄) : (e₁.trans e₂).trans e₃ = e₁.trans (e₂.trans e₃) := ext $ λ _, rfl omit V₃ V₄ @[simp] lemma trans_refl (e : P₁ ≃ᵃ[k] P₂) : e.trans (refl k P₂) = e := ext $ λ _, rfl @[simp] lemma refl_trans (e : P₁ ≃ᵃ[k] P₂) : (refl k P₁).trans e = e := ext $ λ _, rfl @[simp] lemma trans_symm (e : P₁ ≃ᵃ[k] P₂) : e.trans e.symm = refl k P₁ := ext e.symm_apply_apply @[simp] lemma symm_trans (e : P₁ ≃ᵃ[k] P₂) : e.symm.trans e = refl k P₂ := ext e.apply_symm_apply @[simp] lemma apply_line_map (e : P₁ ≃ᵃ[k] P₂) (a b : P₁) (c : k) : e (affine_map.line_map a b c) = affine_map.line_map (e a) (e b) c := e.to_affine_map.apply_line_map a b c omit V₂ instance : group (P₁ ≃ᵃ[k] P₁) := { one := refl k P₁, mul := λ e e', e'.trans e, inv := symm, mul_assoc := λ e₁ e₂ e₃, trans_assoc _ _ _, one_mul := trans_refl, mul_one := refl_trans, mul_left_inv := trans_symm } lemma one_def : (1 : P₁ ≃ᵃ[k] P₁) = refl k P₁ := rfl @[simp] lemma coe_one : ⇑(1 : P₁ ≃ᵃ[k] P₁) = id := rfl lemma mul_def (e e' : P₁ ≃ᵃ[k] P₁) : e * e' = e'.trans e := rfl @[simp] lemma coe_mul (e e' : P₁ ≃ᵃ[k] P₁) : ⇑(e * e') = e ∘ e' := rfl lemma inv_def (e : P₁ ≃ᵃ[k] P₁) : e⁻¹ = e.symm := rfl variable (k) /-- The map `v ↦ v +ᵥ b` as an affine equivalence between a module `V` and an affine space `P` with tangent space `V`. -/ def vadd_const (b : P₁) : V₁ ≃ᵃ[k] P₁ := { to_equiv := equiv.vadd_const b, linear := linear_equiv.refl _ _, map_vadd' := λ p v, add_vadd _ _ _ } @[simp] lemma linear_vadd_const (b : P₁) : (vadd_const k b).linear = linear_equiv.refl k V₁ := rfl @[simp] lemma vadd_const_apply (b : P₁) (v : V₁) : vadd_const k b v = v +ᵥ b := rfl @[simp] lemma vadd_const_symm_apply (b p : P₁) : (vadd_const k b).symm p = p -ᵥ b := rfl /-- `p' ↦ p -ᵥ p'` as an equivalence. -/ def const_vsub (p : P₁) : P₁ ≃ᵃ[k] V₁ := { to_equiv := equiv.const_vsub p, linear := linear_equiv.neg k, map_vadd' := λ p' v, by simp [vsub_vadd_eq_vsub_sub, neg_add_eq_sub] } @[simp] lemma coe_const_vsub (p : P₁) : ⇑(const_vsub k p) = (-ᵥ) p := rfl @[simp] lemma coe_const_vsub_symm (p : P₁) : ⇑(const_vsub k p).symm = λ v, -v +ᵥ p := rfl variable (P₁) /-- The map `p ↦ v +ᵥ p` as an affine automorphism of an affine space. -/ def const_vadd (v : V₁) : P₁ ≃ᵃ[k] P₁ := { to_equiv := equiv.const_vadd P₁ v, linear := linear_equiv.refl _ _, map_vadd' := λ p w, vadd_comm _ _ _ } @[simp] lemma linear_const_vadd (v : V₁) : (const_vadd k P₁ v).linear = linear_equiv.refl _ _ := rfl @[simp] lemma const_vadd_apply (v : V₁) (p : P₁) : const_vadd k P₁ v p = v +ᵥ p := rfl @[simp] lemma const_vadd_symm_apply (v : V₁) (p : P₁) : (const_vadd k P₁ v).symm p = -v +ᵥ p := rfl section homothety omit V₁ variables {R V P : Type*} [comm_ring R] [add_comm_group V] [module R V] [affine_space V P] include V /-- Fixing a point in affine space, homothety about this point gives a group homomorphism from (the centre of) the units of the scalars into the group of affine equivalences. -/ def homothety_units_mul_hom (p : P) : units R →* P ≃ᵃ[R] P := { to_fun := λ t, { to_fun := affine_map.homothety p (t : R), inv_fun := affine_map.homothety p (↑t⁻¹ : R), left_inv := λ p, by simp [← affine_map.comp_apply, ← affine_map.homothety_mul], right_inv := λ p, by simp [← affine_map.comp_apply, ← affine_map.homothety_mul], linear := { inv_fun := linear_map.lsmul R V (↑t⁻¹ : R), left_inv := λ v, by simp [smul_smul], right_inv := λ v, by simp [smul_smul], .. linear_map.lsmul R V t, }, map_vadd' := λ p v, by simp only [vadd_vsub_assoc, smul_add, add_vadd, affine_map.coe_line_map, affine_map.homothety_eq_line_map, equiv.coe_fn_mk, linear_equiv.coe_mk, linear_map.lsmul_apply, linear_map.to_fun_eq_coe], }, map_one' := by { ext, simp, }, map_mul' := λ t₁ t₂, by { ext, simp [← affine_map.comp_apply, ← affine_map.homothety_mul], }, } @[simp] lemma coe_homothety_units_mul_hom_apply (p : P) (t : units R) : (homothety_units_mul_hom p t : P → P) = affine_map.homothety p (t : R) := rfl @[simp] lemma coe_homothety_units_mul_hom_apply_symm (p : P) (t : units R) : ((homothety_units_mul_hom p t).symm : P → P) = affine_map.homothety p (↑t⁻¹ : R) := rfl @[simp] lemma coe_homothety_units_mul_hom_eq_homothety_hom_coe (p : P) : (coe : (P ≃ᵃ[R] P) → P →ᵃ[R] P) ∘ homothety_units_mul_hom p = (affine_map.homothety_hom p) ∘ (coe : units R → R) := by { ext, simp, } end homothety variable {P₁} open function /-- Point reflection in `x` as a permutation. -/ def point_reflection (x : P₁) : P₁ ≃ᵃ[k] P₁ := (const_vsub k x).trans (vadd_const k x) lemma point_reflection_apply (x y : P₁) : point_reflection k x y = x -ᵥ y +ᵥ x := rfl @[simp] lemma point_reflection_symm (x : P₁) : (point_reflection k x).symm = point_reflection k x := to_equiv_injective $ equiv.point_reflection_symm x @[simp] lemma to_equiv_point_reflection (x : P₁) : (point_reflection k x).to_equiv = equiv.point_reflection x := rfl @[simp] lemma point_reflection_self (x : P₁) : point_reflection k x x = x := vsub_vadd _ _ lemma point_reflection_involutive (x : P₁) : involutive (point_reflection k x : P₁ → P₁) := equiv.point_reflection_involutive x /-- `x` is the only fixed point of `point_reflection x`. This lemma requires `x + x = y + y ↔ x = y`. There is no typeclass to use here, so we add it as an explicit argument. -/ lemma point_reflection_fixed_iff_of_injective_bit0 {x y : P₁} (h : injective (bit0 : V₁ → V₁)) : point_reflection k x y = y ↔ y = x := equiv.point_reflection_fixed_iff_of_injective_bit0 h lemma injective_point_reflection_left_of_injective_bit0 (h : injective (bit0 : V₁ → V₁)) (y : P₁) : injective (λ x : P₁, point_reflection k x y) := equiv.injective_point_reflection_left_of_injective_bit0 h y lemma injective_point_reflection_left_of_module [invertible (2:k)]: ∀ y, injective (λ x : P₁, point_reflection k x y) := injective_point_reflection_left_of_injective_bit0 k $ λ x y h, by rwa [bit0, bit0, ← two_smul k x, ← two_smul k y, (is_unit_of_invertible (2:k)).smul_left_cancel] at h lemma point_reflection_fixed_iff_of_module [invertible (2:k)] {x y : P₁} : point_reflection k x y = y ↔ y = x := ((injective_point_reflection_left_of_module k y).eq_iff' (point_reflection_self k y)).trans eq_comm end affine_equiv namespace linear_equiv /-- Interpret a linear equivalence between modules as an affine equivalence. -/ def to_affine_equiv (e : V₁ ≃ₗ[k] V₂) : V₁ ≃ᵃ[k] V₂ := { to_equiv := e.to_equiv, linear := e, map_vadd' := λ p v, e.map_add v p } @[simp] lemma coe_to_affine_equiv (e : V₁ ≃ₗ[k] V₂) : ⇑e.to_affine_equiv = e := rfl end linear_equiv namespace affine_map open affine_equiv include V₁ lemma line_map_vadd (v v' : V₁) (p : P₁) (c : k) : line_map v v' c +ᵥ p = line_map (v +ᵥ p) (v' +ᵥ p) c := (vadd_const k p).apply_line_map v v' c lemma line_map_vsub (p₁ p₂ p₃ : P₁) (c : k) : line_map p₁ p₂ c -ᵥ p₃ = line_map (p₁ -ᵥ p₃) (p₂ -ᵥ p₃) c := (vadd_const k p₃).symm.apply_line_map p₁ p₂ c lemma vsub_line_map (p₁ p₂ p₃ : P₁) (c : k) : p₁ -ᵥ line_map p₂ p₃ c = line_map (p₁ -ᵥ p₂) (p₁ -ᵥ p₃) c := (const_vsub k p₁).apply_line_map p₂ p₃ c lemma vadd_line_map (v : V₁) (p₁ p₂ : P₁) (c : k) : v +ᵥ line_map p₁ p₂ c = line_map (v +ᵥ p₁) (v +ᵥ p₂) c := (const_vadd k P₁ v).apply_line_map p₁ p₂ c variables {R' : Type*} [comm_ring R'] [module R' V₁] lemma homothety_neg_one_apply (c p : P₁) : homothety c (-1:R') p = point_reflection R' c p := by simp [homothety_apply, point_reflection_apply] end affine_map
8f566702d726f6325b93fe522c09ef000188cbb4
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/src/Lean/Parser/Extra.lean
d0dd8f88c0c46a13e83433d43147eeaaa60696eb
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,012
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, Sebastian Ullrich -/ import Lean.Parser.Basic -- necessary for auto-generation import Lean.PrettyPrinter.Parenthesizer import Lean.PrettyPrinter.Formatter namespace Lean namespace Parser -- synthesize pretty printers for parsers declared prior to `Lean.PrettyPrinter` -- (because `Parser.Extension` depends on them) attribute [runBuiltinParserAttributeHooks] leadingNode termParser commandParser antiquotNestedExpr antiquotExpr mkAntiquot nodeWithAntiquot ident numLit charLit strLit nameLit @[runBuiltinParserAttributeHooks, inline] def group (p : Parser) : Parser := node nullKind p @[runBuiltinParserAttributeHooks, inline] def many1Indent (p : Parser) : Parser := withPosition $ many1 (checkColGe "irrelevant" >> p) @[runBuiltinParserAttributeHooks, inline] def manyIndent (p : Parser) : Parser := withPosition $ many (checkColGe "irrelevant" >> p) @[runBuiltinParserAttributeHooks] abbrev notSymbol (s : String) : Parser := notFollowedBy (symbol s) s /-- No-op parser that advises the pretty printer to emit a non-breaking space. -/ @[inline] def ppHardSpace : Parser := skip /-- No-op parser that advises the pretty printer to emit a space/soft line break. -/ @[inline] def ppSpace : Parser := skip /-- No-op parser that advises the pretty printer to emit a hard line break. -/ @[inline] def ppLine : Parser := skip /-- No-op parser combinator that advises the pretty printer to group and indent the given syntax. By default, only syntax categories are grouped. -/ @[inline] def ppGroup : Parser → Parser := id /-- No-op parser combinator that advises the pretty printer to indent the given syntax without grouping it. -/ @[inline] def ppIndent : Parser → Parser := id /-- No-op parser combinator that advises the pretty printer to dedent the given syntax. Dedenting can in particular be used to counteract automatic indentation. -/ @[inline] def ppDedent : Parser → Parser := id end Parser namespace PrettyPrinter namespace Formatter @[combinatorFormatter Lean.Parser.ppHardSpace] def ppHardSpace.formatter : Formatter := push " " @[combinatorFormatter Lean.Parser.ppSpace] def ppSpace.formatter : Formatter := pushLine @[combinatorFormatter Lean.Parser.ppLine] def ppLine.formatter : Formatter := push "\n" @[combinatorFormatter Lean.Parser.ppGroup] def ppGroup.formatter (p : Formatter) : Formatter := group $ indent p @[combinatorFormatter Lean.Parser.ppIndent] def ppIndent.formatter (p : Formatter) : Formatter := indent p @[combinatorFormatter Lean.Parser.ppDedent] def ppDedent.formatter (p : Formatter) : Formatter := do let opts ← getOptions indent p (some (0 - Format.getIndent opts)) end Formatter end PrettyPrinter namespace Parser -- now synthesize parenthesizers attribute [runBuiltinParserAttributeHooks] ppHardSpace ppSpace ppLine ppGroup ppIndent ppDedent end Parser end Lean
ab0be323355a24e0d8c3657740ac60a896dbd9bf
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/algebra/lie/nilpotent.lean
7f9584eef7148725fac91a982c2473c7cd76882f
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
7,756
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.solvable import linear_algebra.eigenspace /-! # Nilpotent Lie algebras Like groups, Lie algebras admit a natural concept of nilpotency. More generally, any Lie module carries a natural concept of nilpotency. We define these here via the lower central series. ## Main definitions * `lie_module.lower_central_series` * `lie_module.is_nilpotent` ## Tags lie algebra, lower central series, nilpotent -/ universes u v w w₁ w₂ namespace lie_module variables (R : Type u) (L : Type v) (M : Type w) variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M] variables [lie_ring_module L M] [lie_module R L M] /-- The lower central series of Lie submodules of a Lie module. -/ def lower_central_series (k : ℕ) : lie_submodule R L M := (λ I, ⁅(⊤ : lie_ideal R L), I⁆)^[k] ⊤ @[simp] lemma lower_central_series_zero : lower_central_series R L M 0 = ⊤ := rfl @[simp] lemma lower_central_series_succ (k : ℕ) : lower_central_series R L M (k + 1) = ⁅(⊤ : lie_ideal R L), lower_central_series R L M k⁆ := function.iterate_succ_apply' (λ I, ⁅(⊤ : lie_ideal R L), I⁆) k ⊤ lemma trivial_iff_lower_central_eq_bot : is_trivial L M ↔ lower_central_series R L M 1 = ⊥ := begin split; intros h, { erw [eq_bot_iff, lie_submodule.lie_span_le], rintros m ⟨x, n, hn⟩, rw [← hn, h.trivial], simp,}, { rw lie_submodule.eq_bot_iff at h, apply is_trivial.mk, intros x m, apply h, apply lie_submodule.subset_lie_span, use [x, m], refl, }, end lemma iterate_to_endomorphism_mem_lower_central_series (x : L) (m : M) (k : ℕ) : (to_endomorphism R L M x)^[k] m ∈ lower_central_series R L M k := begin induction k with k ih, { simp only [function.iterate_zero], }, { simp only [lower_central_series_succ, function.comp_app, function.iterate_succ', to_endomorphism_apply_apply], exact lie_submodule.lie_mem_lie _ _ (lie_submodule.mem_top x) ih, }, end open lie_algebra lemma derived_series_le_lower_central_series (k : ℕ) : derived_series R L k ≤ lower_central_series R L L k := begin induction k with k h, { rw [derived_series_def, derived_series_of_ideal_zero, lower_central_series_zero], exact le_refl _, }, { have h' : derived_series R L k ≤ ⊤, { by simp only [le_top], }, rw [derived_series_def, derived_series_of_ideal_succ, lower_central_series_succ], exact lie_submodule.mono_lie _ _ _ _ h' h, }, end /-- A Lie module is nilpotent if its lower central series reaches 0 (in a finite number of steps). -/ class is_nilpotent : Prop := (nilpotent : ∃ k, lower_central_series R L M k = ⊥) @[priority 100] instance trivial_is_nilpotent [is_trivial L M] : is_nilpotent R L M := ⟨by { use 1, change ⁅⊤, ⊤⁆ = ⊥, simp, }⟩ lemma nilpotent_endo_of_nilpotent_module [hM : is_nilpotent R L M] : ∃ (k : ℕ), ∀ (x : L), (to_endomorphism R L M x)^k = 0 := begin unfreezingI { obtain ⟨k, hM⟩ := hM, }, use k, intros x, ext m, rw [linear_map.pow_apply, linear_map.zero_apply, ← @lie_submodule.mem_bot R L M, ← hM], exact iterate_to_endomorphism_mem_lower_central_series R L M x m k, end /-- For a nilpotent Lie module, the weight space of the 0 weight is the whole module. This result will be used downstream to show that weight spaces are Lie submodules, at which time it will be possible to state it in the language of weight spaces. -/ lemma infi_max_gen_zero_eigenspace_eq_top_of_nilpotent [is_nilpotent R L M] : (⨅ (x : L), (to_endomorphism R L M x).maximal_generalized_eigenspace 0) = ⊤ := begin ext m, simp only [module.End.mem_maximal_generalized_eigenspace, submodule.mem_top, sub_zero, iff_true, zero_smul, submodule.mem_infi], intros x, obtain ⟨k, hk⟩ := nilpotent_endo_of_nilpotent_module R L M, use k, rw hk, exact linear_map.zero_apply m, end end lie_module @[priority 100] instance lie_algebra.is_solvable_of_is_nilpotent (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] [hL : lie_module.is_nilpotent R L L] : lie_algebra.is_solvable R L := begin obtain ⟨k, h⟩ : ∃ k, lie_module.lower_central_series R L L k = ⊥ := hL.nilpotent, use k, rw ← le_bot_iff at h ⊢, exact le_trans (lie_module.derived_series_le_lower_central_series R L k) h, end section nilpotent_algebras variables (R : Type u) (L : Type v) (L' : Type w) variables [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L'] /-- We say a Lie algebra is nilpotent when it is nilpotent as a Lie module over itself via the adjoint representation. -/ abbreviation lie_algebra.is_nilpotent (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] : Prop := lie_module.is_nilpotent R L L open lie_algebra lemma lie_algebra.nilpotent_ad_of_nilpotent_algebra [is_nilpotent R L] : ∃ (k : ℕ), ∀ (x : L), (ad R L x)^k = 0 := lie_module.nilpotent_endo_of_nilpotent_module R L L /-- See also `lie_algebra.zero_root_space_eq_top_of_nilpotent`. -/ lemma lie_algebra.infi_max_gen_zero_eigenspace_eq_top_of_nilpotent [is_nilpotent R L] : (⨅ (x : L), (ad R L x).maximal_generalized_eigenspace 0) = ⊤ := lie_module.infi_max_gen_zero_eigenspace_eq_top_of_nilpotent R L L -- TODO Generalise the below to Lie modules if / when we define morphisms, equivs of Lie modules -- covering a Lie algebra morphism of (possibly different) Lie algebras. variables {R L L'} open lie_module (lower_central_series) lemma lie_ideal.lower_central_series_map_le (k : ℕ) {f : L →ₗ⁅R⁆ L'} : lie_ideal.map f (lower_central_series R L L k) ≤ lower_central_series R L' L' k := begin induction k with k ih, { simp only [lie_module.lower_central_series_zero, le_top], }, { simp only [lie_module.lower_central_series_succ], exact le_trans (lie_ideal.map_bracket_le f) (lie_submodule.mono_lie _ _ _ _ le_top ih), }, end lemma lie_ideal.lower_central_series_map_eq (k : ℕ) {f : L →ₗ⁅R⁆ L'} (h : function.surjective f) : lie_ideal.map f (lower_central_series R L L k) = lower_central_series R L' L' k := begin have h' : (⊤ : lie_ideal R L).map f = ⊤, { rw ←f.ideal_range_eq_map, exact f.ideal_range_eq_top_of_surjective h, }, induction k with k ih, { simp only [lie_module.lower_central_series_zero], exact h', }, { simp only [lie_module.lower_central_series_succ, lie_ideal.map_bracket_eq f h, ih, h'], }, end lemma function.injective.lie_algebra_is_nilpotent [h₁ : is_nilpotent R L'] {f : L →ₗ⁅R⁆ L'} (h₂ : function.injective f) : is_nilpotent R L := { nilpotent := begin tactic.unfreeze_local_instances, obtain ⟨k, hk⟩ := h₁, use k, apply lie_ideal.bot_of_map_eq_bot h₂, rw [eq_bot_iff, ← hk], apply lie_ideal.lower_central_series_map_le, end, } lemma function.surjective.lie_algebra_is_nilpotent [h₁ : is_nilpotent R L] {f : L →ₗ⁅R⁆ L'} (h₂ : function.surjective f) : is_nilpotent R L' := { nilpotent := begin tactic.unfreeze_local_instances, obtain ⟨k, hk⟩ := h₁, use k, rw [← lie_ideal.lower_central_series_map_eq k h₂, hk], simp only [lie_ideal.map_eq_bot_iff, bot_le], end, } lemma lie_equiv.nilpotent_iff_equiv_nilpotent (e : L ≃ₗ⁅R⁆ L') : is_nilpotent R L ↔ is_nilpotent R L' := begin split; introsI h, { exact e.symm.injective.lie_algebra_is_nilpotent, }, { exact e.injective.lie_algebra_is_nilpotent, }, end instance [h : lie_algebra.is_nilpotent R L] : lie_algebra.is_nilpotent R (⊤ : lie_subalgebra R L) := lie_subalgebra.top_equiv_self.nilpotent_iff_equiv_nilpotent.mpr h end nilpotent_algebras
f1540b1788712d532eb488fb76c685ef1de11ae3
4e0d7c3132ce31edc5829849735dd25db406b144
/lean/love05_inductive_predicates_demo.lean
02fe7318ad5626779741f5f4fe2aa9dbcff02c07
[]
no_license
gonzalgu/logical_verification_2020
a0013a6c22ea254e9f4d245f2948f0f4d44df4bb
724d0457dff2c3ff10f9ab2170388f4c5e958b75
refs/heads/master
1,660,886,374,533
1,589,859,641,000
1,589,859,641,000
256,069,971
0
0
null
1,586,997,430,000
1,586,997,429,000
null
UTF-8
Lean
false
false
15,680
lean
import .love03_forward_proofs_demo import .love04_functional_programming_demo /-! # LoVe Demo 5: Inductive Predicates __Inductive predicates__, or inductively defined propositions, are a convenient way to specify functions of type `⋯ → Prop`. They are reminiscent of formal systems and of the Horn clauses of Prolog, the logic programming language par excellence. A possible view of Lean: Lean = typed functional programming + logic programming + more logic -/ set_option pp.beta true namespace LoVe /-! ## Introductory Examples ### Even Numbers Mathematicians often define sets as the smallest that meets some criteria. For example: The set `E` of even natural numbers is defined as the smallest set closed under the following rules: (1) `0 ∈ E` and (2) for every `k ∈ ℕ`, if `k ∈ E`, then `k + 2 ∈ E`. In Lean, we can define the corresponding "is even" predicate as follows: -/ inductive even : ℕ → Prop | zero : even 0 | add_two : ∀k : ℕ, even k → even (k + 2) /-! This should look familiar. We have used the same syntax, except with `Type` instead of `Prop`, for inductive types. The above command introduces a new unary predicate `even` as well as two constructors, `even.zero` and `even.add_two`, which can be used to build proof terms. Thanks to the "no junk" guarantee of inductive definitions, `even.zero` and `even.add_two` are the only two ways to construct proofs of `even`. By the Curry–Howard correspondence, `even` can be seen as a data type, the values being the proof terms. -/ lemma even_4 : even 4 := have even_0 : even 0 := even.zero, have even_2 : even 2 := even.add_two _ even_0, show even 4, from even.add_two _ even_2 /-! Why cannot we simply define `even` recursively? Indeed, why not? -/ def even₂ : ℕ → bool | 0 := tt | 1 := ff | (k + 2) := even₂ k /-! There are advantages and disadvantages to both styles. The recursive version requires us to specify a false case (1), and it requires us to worry about termination. On the other hand, because it is computational, it works well with `refl`, `simp`, `#reduce`, and `#eval`. The inductive version is often considered more abstract and elegant. Each rule is stated independently of the others. Yet another way to define `even` is as a nonrecursive definition: -/ def even₃ (k : ℕ) : bool := k % 2 = 0 /-! Mathematicians would probably find this the most satisfactory definition. But the inductive version is a convenient, intuitive example that is typical of many realistic inductive definitions. ### Tennis Games Transition systems consists of transition rules, which together specify a binary predicate connecting a "before" and an "after" state. As a simple specimen of a transition system, we consider the possible transitions, in a game of tennis, starting from 0–0. -/ inductive score : Type | vs : ℕ → ℕ → score | adv_srv : score | adv_rcv : score | game_srv : score | game_rcv : score infixr ` – ` : 10 := score.vs inductive step : score → score → Prop | srv_0_15 : ∀n, step (0–n) (15–n) | srv_15_30 : ∀n, step (15–n) (30–n) | srv_30_40 : ∀n, step (30–n) (40–n) | srv_40_game : ∀n, n < 40 → step (40–n) score.game_srv | srv_40_adv : step (40–40) score.adv_srv | rcv_0_15 : ∀n, step (n–0) (n–15) | rcv_15_30 : ∀n, step (n–15) (n–30) | rcv_30_40 : ∀n, step (n–30) (n–40) | rcv_40_game : ∀n, n < 40 → step (n–40) score.game_rcv | rcv_40_adv : step (40–40) score.adv_rcv infixr ` ⇒ ` := step /-! We can ask—and formally answer—questions such as: Is this transition system confluent? Does it always terminate? Can the score 65–15 be reached from 0–0? ### Reflexive Transitive Closure Our last introductory example is the reflexive transitive closure of a relation `r`, modeled as a binary predicate `star r`. -/ inductive star {α : Type} (r : α → α → Prop) : α → α → Prop | base (a b : α) : r a b → star a b | refl (a : α) : star a a | trans (a b c : α) : star a b → star b c → star a c /-! The first rule embeds `r` into `star r`. The second rule achieves the reflexive closure. The third rule achieves the transitive closure. The definition is truly elegant. If you doubt this, try implementing `star` as a recursive function: -/ def star₂ {α : Type} (r : α → α → Prop) : α → α → Prop := sorry /-! ### A Nonexample Not all inductive definitions admit a least solution. -/ -- fails inductive illegal : Prop | intro : ¬ illegal → illegal /-! ## Logical Symbols The truth values `false` and `true`, the connectives `∧` and `∨`, the `∃`-quantifier, and the equality predicate `=` are all defined as inductive propositions or predicates. In contrast, `∀` (= `Π`) and `→` are built into the logic. Syntactic sugar: `∃x : α, p` := `Exists (λx : α, p)` `x = y` := `eq x y` -/ namespace logical_symbols inductive and (a b : Prop) : Prop | intro : a → b → and inductive or (a b : Prop) : Prop | intro_left : a → or | intro_right : b → or inductive iff (a b : Prop) : Prop | intro : (a → b) → (b → a) → iff inductive Exists {α : Type} (p : α → Prop) : Prop | intro : ∀a : α, p a → Exists inductive true : Prop | intro : true inductive false : Prop inductive eq {α : Type} : α → α → Prop | refl : ∀a : α, eq a a end logical_symbols #print and #print or #print iff #print Exists #print true #print false #print eq /-! ## Rule Induction Just as we can perform induction on a term, we can perform induction on a proof term. This is called __rule induction__, because the induction is on the introduction rules (i.e., the constructors of the proof term). Thanks to the Curry–Howard correspondence, this works as expected. -/ lemma mod_two_eq_zero_of_even (n : ℕ) (h : even n) : n % 2 = 0 := begin induction h, case even.zero { refl }, case even.add_two : k hk ih { simp [ih] } end lemma star_star_iff_star {α : Type} (r : α → α → Prop) (a b : α) : star (star r) a b ↔ star r a b := begin apply iff.intro, { intro h, induction h, case star.base : a b hab { exact hab }, case star.refl : a { apply star.refl }, case star.trans : a b c hab hbc ihab ihbc { apply star.trans a b, { exact ihab }, { exact ihbc } } }, { intro h, apply star.base, exact h } end @[simp] lemma star_star_eq_star {α : Type} (r : α → α → Prop) : star (star r) = star r := begin apply funext, intro a, apply funext, intro b, apply propext, apply star_star_iff_star end #check @funext #check @propext /-! ## Rule Induction Pitfalls Inductive predicates often have arguments that evolve through the induction. Some care is necessary. -/ lemma p_of_even (p : ℕ → Prop) (n : ℕ) : even n → p n := begin intro h, induction h, case even.zero { sorry }, -- looks reasonable case even.add_two { sorry } -- looks reasonable end lemma not_even_2_mul_add_1_sorry (n : ℕ) : ¬ even (2 * n + 1) := begin intro h, induction h, case even.zero { sorry }, -- unprovable case even.add_two : k hk ih { exact ih } end lemma not_even_2_mul_add_1_sorry₂ (n : ℕ) : ¬ even (2 * n + 1) := begin generalize hx : 2 * n + 1 = x, intro h, induction h, case even.zero { cases hx }, case even.add_two : k hk ih { apply ih, rewrite hx, sorry } -- unprovable end lemma not_even_2_mul_add_1 (n : ℕ) : ¬ even (2 * n + 1) := begin generalize hx : 2 * n + 1 = x, intro h, induction h generalizing n, case even.zero { cases hx }, case even.add_two : k hk ih { apply ih (n - 1), cases n, case nat.zero { linarith }, case nat.succ : m { simp [nat.succ_eq_add_one] at *, linarith } } end /-! `linarith` proves goals involving linear arithmetic equalities or inequalities. "Linear" means it works only with `+` and `-`, not `*` and `/` (but multiplication by a constant is supported). -/ lemma linarith_example (i : ℤ) (hi : i > 5) : 2 * i + 3 > 11 := by linarith /-! ## Elimination Given an inductive predicate `p`, its introduction rules typically have the form `∀…, ⋯ → p …` and can be used to prove goals of the form `⊢ p …`. Elimination works the other way around: It extracts information from a lemma or hypothesis of the form `p …`. Elimination takes various forms: pattern matching, the `cases` and `induction` tactics, and custom elimination rules (e.g., `and.elim_left`). * `cases` works roughly like `induction` but without induction hypothesis. * `match` is available as well, but it corresponds to dependently typed pattern matching (cf. `vector` in lecture 4). Now we can finally analyze how `cases h`, where `h : l = r`, and how `cases classical.em h` work. -/ #print eq lemma cases_eq_example {α : Type} (l r : α) (h : l = r) (p : α → α → Prop) : p l r := begin cases h, sorry end #check classical.em #print or lemma cases_classical_em_example {α : Type} (a : α) (p q : α → Prop) : q a := begin have h : p a ∨ ¬ p a := classical.em (p a), cases h, case or.inl { sorry }, case or.inr { sorry } end /-! Often it is convenient to rewrite concrete terms of the form `p (c …)`, where `c` is typically a constructor. We can state and prove an __inversion rule__ to support such eliminative reasoning. Typical inversion rule: `∀x y, p (c x y) → (∃…, ⋯ ∧ ⋯) ∨ ⋯ ∨ (∃…, ⋯ ∧ ⋯)` It can be useful to combine introduction and elimination into a single lemma, which can be used for rewriting both the hypotheses and conclusions of goals: `∀x y, p (c x y) ↔ (∃…, ⋯ ∧ ⋯) ∨ ⋯ ∨ (∃…, ⋯ ∧ ⋯)` -/ lemma even_iff (n : ℕ) : even n ↔ n = 0 ∨ (∃m : ℕ, n = m + 2 ∧ even m) := begin apply iff.intro, { intro hn, cases hn, case even.zero { simp }, case even.add_two : k hk { apply or.intro_right, apply exists.intro k, simp [hk] } }, { intro hor, cases hor, case or.inl : heq { simp [heq, even.zero] }, case or.inr : hex { cases hex with k hand, cases hand with heq hk, simp [heq, even.add_two _ hk] } } end lemma even_iff₂ (n : ℕ) : even n ↔ n = 0 ∨ (∃m : ℕ, n = m + 2 ∧ even m) := iff.intro (assume hn : even n, match n, hn with | _, even.zero := show 0 = 0 ∨ _, from by simp | _, even.add_two k hk := show _ ∨ (∃m, k + 2 = m + 2 ∧ even m), from or.intro_right _ (exists.intro k (by simp [*])) end) (assume hor : n = 0 ∨ (∃m, n = m + 2 ∧ even m), match hor with | or.intro_left _ heq := show even n, from by simp [heq, even.zero] | or.intro_right _ hex := match hex with | Exists.intro m hand := match hand with | and.intro heq hm := show even n, from by simp [heq, even.add_two _ hm] end end end) lemma even_iff₃ (n : ℕ) : even n ↔ n = 0 ∨ (∃m : ℕ, n = m + 2 ∧ even m) := iff.intro (assume hen : even n, match n, hen with | _, even.zero := show 0 = 0 ∨ _, from begin left, refl, end | _, even.add_two k hek := show _ ∨ (∃ (m : ℕ), k + 2 = m + 2 ∧ even m), from begin right, existsi k, split, refl, assumption, end end) (assume hor : (n = 0 ∨ ∃ (m : ℕ), n = m + 2 ∧ even m), show even n, from begin cases hor, { simp [hor, even.zero] }, cases n, { simp [even.zero] }, cases hor with m hand, cases hand with heq hem, rw heq, apply even.add_two, assumption, end ) /-! ## Further Examples ### Sorted Lists -/ inductive sorted : list ℕ → Prop | nil : sorted [] | single {x : ℕ} : sorted [x] | two_or_more {x y : ℕ} {zs : list ℕ} (hle : x ≤ y) (hsorted : sorted (y :: zs)) : sorted (x :: y :: zs) lemma sorted_nil : sorted [] := sorted.nil lemma sorted_2 : sorted [2] := sorted.single lemma sorted_3_5 : sorted [3, 5] := begin apply sorted.two_or_more, { exact dec_trivial }, { exact sorted.single } end lemma sorted_3_5₂ : sorted [3, 5] := sorted.two_or_more dec_trivial sorted.single lemma sorted_7_9_9_11 : sorted [7, 9, 9, 11] := sorted.two_or_more dec_trivial (sorted.two_or_more dec_trivial (sorted.two_or_more dec_trivial sorted.single)) lemma not_sorted_17_13 : ¬ sorted [17, 13] := assume h : sorted [17, 13], have 17 ≤ 13 := match h with | sorted.two_or_more hle _ := hle end, have ¬ 17 ≤ 13 := dec_trivial, show false, from by cc /-! ### Palindromes -/ inductive palindrome {α : Type} : list α → Prop | nil : palindrome [] | single (x : α) : palindrome [x] | sandwich (x : α) (xs : list α) (hxs : palindrome xs) : palindrome ([x] ++ xs ++ [x]) -- fails def palindrome₂ {α : Type} : list α → Prop | [] := true | [_] := true | ([x] ++ xs ++ [x]) := palindrome₂ xs | _ := false lemma palindrome_aa {α : Type} (a : α) : palindrome [a, a] := palindrome.sandwich a _ palindrome.nil lemma palindrome_aba {α : Type} (a b : α) : palindrome [a, b, a] := palindrome.sandwich a _ (palindrome.single b) lemma reverse_palindrome {α : Type} (xs : list α) (hxs : palindrome xs) : palindrome (reverse xs) := begin induction hxs, case palindrome.nil { exact palindrome.nil }, case palindrome.single : x { exact palindrome.single x }, case palindrome.sandwich : x xs hxs ih { simp [reverse, reverse_append], exact palindrome.sandwich _ _ ih } end /-! ### Full Binary Trees -/ #check btree inductive is_full {α : Type} : btree α → Prop | empty : is_full btree.empty | node (a : α) (l r : btree α) (hl : is_full l) (hr : is_full r) (hiff : l = btree.empty ↔ r = btree.empty) : is_full (btree.node a l r) lemma is_full_singleton {α : Type} (a : α) : is_full (btree.node a btree.empty btree.empty) := begin apply is_full.node, { exact is_full.empty }, { exact is_full.empty }, { refl } end lemma is_full_mirror {α : Type} (t : btree α) (ht : is_full t) : is_full (mirror t) := begin induction ht, case is_full.empty { exact is_full.empty }, case is_full.node : a l r hl hr hiff ih_l ih_r { rewrite mirror, apply is_full.node, { exact ih_r }, { exact ih_l }, { simp [mirror_eq_empty_iff, *] } } end lemma is_full_mirror₂ {α : Type} : ∀t : btree α, is_full t → is_full (mirror t) | btree.empty := begin intro ht, exact ht end | (btree.node a l r) := begin intro ht, cases ht with _ _ _ hl hr hiff, rewrite mirror, apply is_full.node, { exact is_full_mirror₂ _ hr }, { apply is_full_mirror₂ _ hl }, { simp [mirror_eq_empty_iff, *] } end /-! ### First-Order Terms -/ inductive term (α β : Type) : Type | var {} : β → term | fn : α → list term → term inductive well_formed {α β : Type} (arity : α → ℕ) : term α β → Prop | var (x : β) : well_formed (term.var x) | fn (f : α) (ts : list (term α β)) (hargs : ∀t ∈ ts, well_formed t) (hlen : list.length ts = arity f) : well_formed (term.fn f ts) inductive variable_free {α β : Type} : term α β → Prop | fn (f : α) (ts : list (term α β)) (hargs : ∀t ∈ ts, variable_free t) : variable_free (term.fn f ts) end LoVe
b82bb86339a02a4a4cbd4923f399ae3f1ff555e3
b32d3853770e6eaf06817a1b8c52064baaed0ef1
/src/super/resolve.lean
336b7b4eaffd28d08546829e894aa03eb6ded7de
[]
no_license
gebner/super2
4d58b7477b6f7d945d5d866502982466db33ab0b
9bc5256c31750021ab97d6b59b7387773e54b384
refs/heads/master
1,635,021,682,021
1,634,886,326,000
1,634,886,326,000
225,600,688
4
2
null
1,598,209,306,000
1,575,371,550,000
Lean
UTF-8
Lean
false
false
5,085
lean
import super.clause universes u v w noncomputable def or.elim' {a b : Prop} {c : Sort u} : a ∨ b → (a → c) → (b → c) → c := λ ab ac bc, match classical.prop_decidable a with | decidable.is_true h := ac h | decidable.is_false h := bc (ab.elim (λ ha, (h ha).elim) id) end def psum.elim {α : Sort u} {β : Sort v} {γ : Sort w} (p : psum α β) (hl : α → γ) (hr : β → γ) : γ := by refine p.cases_on _ _; assumption namespace super namespace clause open tactic meta def mk_or (a b : clause) (elim : expr → expr → tactic expr) : tactic clause := do ae ← a.ty.to_expr, be ← b.ty.to_expr, ae_ip ← is_prop ae, be_ip ← is_prop be, if ae_ip ∧ be_ip then do prf ← elim `(@or.inl %%ae %%be %%a.prf) `(@or.inr %%ae %%be %%b.prf), pure ⟨clause_type.disj tt a.ty b.ty, prf⟩ else do prfa ← mk_mapp ``psum.inl [ae, be, a.prf], prfb ← mk_mapp ``psum.inr [ae, be, b.prf], prf ← elim prfa prfb, pure ⟨clause_type.disj ff a.ty b.ty, prf⟩ meta def or_congr (c : clause) (fa fb : clause → tactic clause) : tactic clause := match c with | ⟨clause_type.disj io a b, prf⟩ := do ae ← a.to_expr, ha ← mk_local_def ae.hyp_name_hint ae, be ← b.to_expr, hb ← mk_local_def be.hyp_name_hint be, ⟨a', prfa'⟩ ← fa ⟨a, ha⟩, ⟨b', prfb'⟩ ← fb ⟨b, hb⟩, psumab ← mk_mapp ``psum [ae,be], match io, a', b' with | tt, clause_type.ff, _ := do let hb' := `(@or.elim %%ae %%be _ %%prf %%(expr.mk_lambda ha `(@false.elim.{0} %%be %%prfa')) id), pure ⟨b', (expr.mk_lambda hb prfb').app' hb'⟩ | tt, _, clause_type.ff := do let ha' := `(@or.elim %%ae %%be _ %%prf id %%(expr.mk_lambda hb `(@false.elim.{0} %%ae %%prfb'))), pure ⟨a', (expr.mk_lambda ha prfa').app' ha'⟩ | tt, _, _ := do ae' ← a'.to_expr, be' ← b'.to_expr, mk_or ⟨a',prfa'⟩ ⟨b',prfb'⟩ $ λ prfa'' prfb'', do motive ← infer_type prfa'', motive_ip ← is_prop motive, mk_mapp (if motive_ip then ``or.elim else ``or.elim') [ ae, be, motive, prf, expr.mk_lambda ha prfa'', expr.mk_lambda hb prfb''] | bool.ff, clause_type.ff, _ := do prfa' ← mk_mapp ``false.elim [be, prfa'], hb' ← mk_mapp ``psum.elim [ae, be, be, prf, expr.mk_lambda ha prfa', expr.mk_lambda hb hb ], pure ⟨b', (expr.mk_lambda hb prfb').app' hb'⟩ | ff, _, clause_type.ff := do tprf ← infer_type prf, prfb' ← mk_mapp ``false.elim [ae, prfb'], ha' ← mk_mapp ``psum.elim [ae, be, ae, prf, expr.mk_lambda ha ha, expr.mk_lambda hb prfb' ], pure ⟨a', (expr.mk_lambda ha prfa').app' ha'⟩ | ff, _, _ := do ae' ← a'.to_expr, be' ← b'.to_expr, mk_or ⟨a',prfa'⟩ ⟨b',prfb'⟩ $ λ prfa'' prfb'', do motive ← infer_type prfa'', mk_mapp ``psum.elim [ae, be, motive, prf, expr.mk_lambda ha prfa'', expr.mk_lambda hb prfb''] end | _ := fail "or_congr" end meta def propg_pos : clause → ℕ → expr → tactic clause | ⟨clause_type.ff, _⟩ _ _ := fail "propg_pos ff" | ⟨clause_type.atom _, _⟩ _ _ := fail "propg_pos atom" | ⟨clause_type.imp a b, prf⟩ 0 h := pure ⟨b, prf.app' h⟩ | ⟨clause_type.imp a b, prf⟩ (i+1) h := do l ← mk_local_def a.hyp_name_hint a, ⟨b', prf'⟩ ← propg_pos ⟨b, prf.app' l⟩ i h, pure ⟨clause_type.imp a b', expr.mk_lambda l prf'⟩ | c@⟨clause_type.disj _ a b, prf⟩ i h := do let an := a.num_literals, if i < an then or_congr c (λ ca, propg_pos ca i h) pure else or_congr c pure (λ cb, propg_pos cb (i - an) h) meta def propg_neg : clause → ℕ → clause → ℕ → tactic clause | ⟨clause_type.ff, _⟩ _ _ _ := fail "propg_neg ff" | ⟨clause_type.atom _, _⟩ (i+1) _ _ := fail "propg_neg atom (i+1)" | ⟨clause_type.atom _, prf⟩ 0 h j := propg_pos h j prf | ⟨clause_type.imp _ _, _⟩ 0 _ _ := undefined_core "propg_neg imp 0" | ⟨clause_type.imp a b, prf⟩ (i+1) h j := do ha ← mk_local_def a.hyp_name_hint a, ⟨b', prf'⟩ ← propg_neg ⟨b, prf.app' ha⟩ i h j, pure ⟨clause_type.imp a b', expr.mk_lambda ha prf'⟩ | c@⟨clause_type.disj _ a b, prf⟩ i h j := do let an := a.literals.length, if i < an then or_congr c (λ ca, propg_neg ca i h j) pure else or_congr c pure (λ cb, propg_neg cb (i - an) h j) meta def resolve (a : clause) (ai : ℕ) (b : clause) (bi : ℕ) : tactic clause := on_exception (trace_call_stack >> trace (a, b)) $ clause.check_result_if_debug $ do some (literal.pos al) ← pure (a.literals.nth ai) | fail "unknown literal", some (literal.neg bl) ← pure (b.literals.nth bi) | fail "unknown literal", is_def_eq al bl, propg_neg a ai b bi meta def mgu_resolve (a : clause) (ai : ℕ) (b : clause) (bi : ℕ) : tactic clause := clause.check_result_if_debug $ do some (literal.pos al) ← pure (a.literals.nth ai) | fail "unknown literal", some (literal.neg bl) ← pure (b.literals.nth bi) | fail "unknown literal", unify al bl, propg_neg a ai b bi end clause end super
77ac5b6fa7d8c2818a27de47e3eb840f448af8e1
43390109ab88557e6090f3245c47479c123ee500
/src/finite_dimensional_vector_spaces/ring_n_is_module.lean
e3a727a0145cc98509fd57e052d0cca4a60867ae
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,556
lean
import algebra.module linear_algebra.basic analysis.real data.vector data.list.basic universes u namespace vector variables (n : ℕ) (R : Type u) instance to_module [h : ring R] : module R (vector R n) := { add := map₂ h.add, add_assoc := by { intros a b c, cases a with a la, cases b with b lb, cases c with c lc, simp [map₂], induction n with _ ih generalizing a b c; cases a; cases b; cases c; simp [list.map₂], contradiction, simp [nat.add_one] at la lb lc, split, apply add_assoc, exact ih _ _ _ la lb lc }, add_comm := by { intros a b, cases a with a la, cases b with b lb, simp [has_add.add, map₂], induction n with _ ih generalizing a b; cases a; cases b; simp [list.map₂], contradiction, simp [nat.add_one] at la lb, split, apply add_comm, exact ih _ _ la lb }, zero := repeat h.zero _, zero_add := by { intro a, cases a with a la, simp [repeat, map₂], induction n with _ ih generalizing a; cases a; simp [list.repeat, list.map₂], contradiction, simp [nat.add_one] at la, split, apply zero_add, exact ih _ la }, add_zero := by { intro a, cases a with a la, simp [has_add.add, repeat, map₂], induction n with _ ih generalizing a; cases a; simp [list.repeat, list.map₂], contradiction, simp [nat.add_one] at la, split, apply add_zero, exact ih _ la }, smul := map ∘ h.mul, smul_add := by { intros _ a b, cases a with a la, cases b with b lb, simp [add_group.add, map, map₂], induction n with _ ih generalizing a b; cases a; cases b; simp [list.map, list.map₂], contradiction, simp [nat.add_one] at la lb, split, apply left_distrib, exact ih _ _ la lb }, add_smul := by { intros _ _ a, cases a with a la, simp [has_add.add, add_semigroup.add, add_monoid.add, add_group.add, map, map₂], induction n with _ ih generalizing a; cases a; simp [list.map, list.map₂], contradiction, simp [nat.add_one] at la, split, apply right_distrib, exact ih _ la }, mul_smul := by { intros _ _ a, cases a with a la, simp [map], induction n with _ ih generalizing a; cases a; simp [list.map], contradiction, simp [nat.add_one] at la, split, apply mul_assoc, exact ih _ la }, one_smul := by { intro a, cases a with a la, simp [map], induction n with _ ih generalizing a; cases a; simp [list.map], contradiction, simp [nat.add_one] at la, split, apply one_mul, exact ih _ la }, neg := map h.neg, add_left_neg := by { intro a, cases a with a la, simp [repeat, map, map₂], induction n with _ ih generalizing a; cases a; simp [list.repeat, list.map, list.map₂], repeat { contradiction }, simp [nat.add_one] at la, split, apply add_left_neg, exact ih _ la } } instance to_vector_space [h : field R] : vector_space R (vector R n) := vector_space.mk _ _ instance [h : ring R] : has_add (vector R n) := by apply_instance end vector
52a6dd459d3c5787a68e3c09cec069f720956609
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/measure_theory/category/Meas.lean
189935cd135d174e66831672aeba72ac7817a9c6
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,324
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import topology.category.Top.basic import measure_theory.measure.giry_monad import category_theory.monad.algebra /-! # The category of measurable spaces Measurable spaces and measurable functions form a (concrete) category `Meas`. ## Main definitions * `Measure : Meas ⥤ Meas`: the functor which sends a measurable space `X` to the space of measures on `X`; it is a monad (the "Giry monad"). * `Borel : Top ⥤ Meas`: sends a topological space `X` to `X` equipped with the `σ`-algebra of Borel sets (the `σ`-algebra generated by the open subsets of `X`). ## Tags measurable space, giry monad, borel -/ noncomputable theory open category_theory measure_theory open_locale ennreal universes u v /-- The category of measurable spaces and measurable functions. -/ @[derive has_coe_to_sort] def Meas : Type (u+1) := bundled measurable_space namespace Meas instance (X : Meas) : measurable_space X := X.str /-- Construct a bundled `Meas` from the underlying type and the typeclass. -/ def of (α : Type u) [measurable_space α] : Meas := ⟨α⟩ @[simp] lemma coe_of (X : Type u) [measurable_space X] : (of X : Type u) = X := rfl instance unbundled_hom : unbundled_hom @measurable := ⟨@measurable_id, @measurable.comp⟩ attribute [derive [large_category, concrete_category]] Meas instance : inhabited Meas := ⟨Meas.of empty⟩ /-- `Measure X` is the measurable space of measures over the measurable space `X`. It is the weakest measurable space, s.t. λμ, μ s is measurable for all measurable sets `s` in `X`. An important purpose is to assign a monadic structure on it, the Giry monad. In the Giry monad, the pure values are the Dirac measure, and the bind operation maps to the integral: `(μ >>= ν) s = ∫ x. (ν x) s dμ`. In probability theory, the `Meas`-morphisms `X → Prob X` are (sub-)Markov kernels (here `Prob` is the restriction of `Measure` to (sub-)probability space.) -/ def Measure : Meas ⥤ Meas := { obj := λX, ⟨@measure_theory.measure X.1 X.2⟩, map := λX Y f, ⟨measure.map (f : X → Y), measure.measurable_map f f.2⟩, map_id' := assume ⟨α, I⟩, subtype.eq $ funext $ assume μ, @measure.map_id α I μ, map_comp':= assume X Y Z ⟨f, hf⟩ ⟨g, hg⟩, subtype.eq $ funext $ assume μ, (measure.map_map hg hf).symm } /-- The Giry monad, i.e. the monadic structure associated with `Measure`. -/ def Giry : category_theory.monad Meas := { to_functor := Measure, η' := { app := λX, ⟨@measure.dirac X.1 X.2, measure.measurable_dirac⟩, naturality' := assume X Y ⟨f, hf⟩, subtype.eq $ funext $ assume a, (measure.map_dirac hf a).symm }, μ' := { app := λX, ⟨@measure.join X.1 X.2, measure.measurable_join⟩, naturality' := assume X Y ⟨f, hf⟩, subtype.eq $ funext $ assume μ, measure.join_map_map hf μ }, assoc' := assume α, subtype.eq $ funext $ assume μ, @measure.join_map_join _ _ _, left_unit' := assume α, subtype.eq $ funext $ assume μ, @measure.join_dirac _ _ _, right_unit' := assume α, subtype.eq $ funext $ assume μ, @measure.join_map_dirac _ _ _ } /-- An example for an algebra on `Measure`: the nonnegative Lebesgue integral is a hom, behaving nicely under the monad operations. -/ def Integral : Giry.algebra := { A := Meas.of ℝ≥0∞ , a := ⟨λm:measure ℝ≥0∞, ∫⁻ x, x ∂m, measure.measurable_lintegral measurable_id ⟩, unit' := subtype.eq $ funext $ assume r:ℝ≥0∞, lintegral_dirac' _ measurable_id, assoc' := subtype.eq $ funext $ assume μ : measure (measure ℝ≥0∞), show ∫⁻ x, x ∂ μ.join = ∫⁻ x, x ∂ (measure.map (λm:measure ℝ≥0∞, ∫⁻ x, x ∂m) μ), by rw [measure.lintegral_join, lintegral_map]; apply_rules [measurable_id, measure.measurable_lintegral] } end Meas instance Top.has_forget_to_Meas : has_forget₂ Top.{u} Meas.{u} := bundled_hom.mk_has_forget₂ borel (λ X Y f, ⟨f.1, f.2.borel_measurable⟩) (by intros; refl) /-- The Borel functor, the canonical embedding of topological spaces into measurable spaces. -/ @[reducible] def Borel : Top.{u} ⥤ Meas.{u} := forget₂ Top.{u} Meas.{u}
9cb3c46107d2ae43f1b61208faf30ac94daed29a
9dc8cecdf3c4634764a18254e94d43da07142918
/src/field_theory/finite/polynomial.lean
156caacf61b7b6f276e47bd139aef461be3593b9
[ "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
8,070
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 linear_algebra.finite_dimensional import linear_algebra.basic import ring_theory.mv_polynomial.basic import data.mv_polynomial.expand import field_theory.finite.basic /-! ## Polynomials over finite fields -/ namespace mv_polynomial variables {σ : Type*} /-- A polynomial over the integers is divisible by `n : ℕ` if and only if it is zero over `zmod n`. -/ lemma C_dvd_iff_zmod (n : ℕ) (φ : mv_polynomial σ ℤ) : C (n:ℤ) ∣ φ ↔ map (int.cast_ring_hom (zmod n)) φ = 0 := C_dvd_iff_map_hom_eq_zero _ _ (char_p.int_cast_eq_zero_iff (zmod n) n) _ section frobenius variables {p : ℕ} [fact p.prime] lemma frobenius_zmod (f : mv_polynomial σ (zmod p)) : frobenius _ p f = expand p f := begin apply induction_on f, { intro a, rw [expand_C, frobenius_def, ← C_pow, zmod.pow_card], }, { simp only [alg_hom.map_add, ring_hom.map_add], intros _ _ hf hg, rw [hf, hg] }, { simp only [expand_X, ring_hom.map_mul, alg_hom.map_mul], intros _ _ hf, rw [hf, frobenius_def], }, end lemma expand_zmod (f : mv_polynomial σ (zmod p)) : expand p f = f ^ p := (frobenius_zmod _).symm end frobenius end mv_polynomial namespace mv_polynomial noncomputable theory open_locale big_operators classical open set linear_map submodule variables {K : Type*} {σ : Type*} section indicator variables [fintype K] [fintype σ] /-- Over a field, this is the indicator function as an `mv_polynomial`. -/ def indicator [comm_ring K] (a : σ → K) : mv_polynomial σ K := ∏ n, (1 - (X n - C (a n)) ^ (fintype.card K - 1)) section comm_ring variables [comm_ring K] lemma eval_indicator_apply_eq_one (a : σ → K) : eval a (indicator a) = 1 := begin nontriviality, have : 0 < fintype.card K - 1 := tsub_pos_of_lt fintype.one_lt_card, simp only [indicator, map_prod, map_sub, map_one, map_pow, eval_X, eval_C, sub_self, zero_pow this, sub_zero, finset.prod_const_one] end lemma degrees_indicator (c : σ → K) : degrees (indicator c) ≤ ∑ s : σ, (fintype.card K - 1) • {s} := begin rw [indicator], refine le_trans (degrees_prod _ _) (finset.sum_le_sum $ assume s hs, _), refine le_trans (degrees_sub _ _) _, rw [degrees_one, ← bot_eq_zero, bot_sup_eq], refine le_trans (degrees_pow _ _) (nsmul_le_nsmul_of_le_right _ _), refine le_trans (degrees_sub _ _) _, rw [degrees_C, ← bot_eq_zero, sup_bot_eq], exact degrees_X' _ end lemma indicator_mem_restrict_degree (c : σ → K) : indicator c ∈ restrict_degree σ K (fintype.card K - 1) := begin rw [mem_restrict_degree_iff_sup, indicator], assume n, refine le_trans (multiset.count_le_of_le _ $ degrees_indicator _) (le_of_eq _), simp_rw [ ← multiset.coe_count_add_monoid_hom, (multiset.count_add_monoid_hom n).map_sum, add_monoid_hom.map_nsmul, multiset.coe_count_add_monoid_hom, nsmul_eq_mul, nat.cast_id], transitivity, refine finset.sum_eq_single n _ _, { assume b hb ne, rw [multiset.count_singleton, if_neg ne.symm, mul_zero] }, { assume h, exact (h $ finset.mem_univ _).elim }, { rw [multiset.count_singleton_self, mul_one] } end end comm_ring variables [field K] lemma eval_indicator_apply_eq_zero (a b : σ → K) (h : a ≠ b) : eval a (indicator b) = 0 := begin obtain ⟨i, hi⟩ : ∃ i, a i ≠ b i := by rwa [(≠), function.funext_iff, not_forall] at h, simp only [indicator, map_prod, map_sub, map_one, map_pow, eval_X, eval_C, sub_self, finset.prod_eq_zero_iff], refine ⟨i, finset.mem_univ _, _⟩, rw [finite_field.pow_card_sub_one_eq_one, sub_self], rwa [(≠), sub_eq_zero], end end indicator section variables (K σ) /-- `mv_polynomial.eval` as a `K`-linear map. -/ @[simps] def evalₗ [comm_semiring K] : mv_polynomial σ K →ₗ[K] (σ → K) → K := { to_fun := λ p e, eval e p, map_add' := λ p q, by { ext x, rw ring_hom.map_add, refl, }, map_smul' := λ a p, by { ext e, rw [smul_eq_C_mul, ring_hom.map_mul, eval_C], refl } } end variables [field K] [fintype K] [finite σ] lemma map_restrict_dom_evalₗ : (restrict_degree σ K (fintype.card K - 1)).map (evalₗ K σ) = ⊤ := begin casesI nonempty_fintype σ, refine top_unique (set_like.le_def.2 $ assume e _, mem_map.2 _), refine ⟨∑ n : σ → K, e n • indicator n, _, _⟩, { exact sum_mem (assume c _, smul_mem _ _ (indicator_mem_restrict_degree _)) }, { ext n, simp only [linear_map.map_sum, @finset.sum_apply (σ → K) (λ_, K) _ _ _ _ _, pi.smul_apply, linear_map.map_smul], simp only [evalₗ_apply], transitivity, refine finset.sum_eq_single n (λ b _ h, _) _, { rw [eval_indicator_apply_eq_zero _ _ h.symm, smul_zero] }, { exact λ h, (h $ finset.mem_univ n).elim }, { rw [eval_indicator_apply_eq_one, smul_eq_mul, mul_one] } } end end mv_polynomial namespace mv_polynomial open_locale classical cardinal open linear_map submodule universe u variables (σ : Type u) (K : Type u) [fintype K] /-- The submodule of multivariate polynomials whose degree of each variable is strictly less than the cardinality of K. -/ @[derive [add_comm_group, module K, inhabited]] def R [comm_ring K] : Type u := restrict_degree σ K (fintype.card K - 1) /-- Evaluation in the `mv_polynomial.R` subtype. -/ def evalᵢ [comm_ring K] : R σ K →ₗ[K] (σ → K) → K := ((evalₗ K σ).comp (restrict_degree σ K (fintype.card K - 1)).subtype) section comm_ring variables [comm_ring K] noncomputable instance decidable_restrict_degree (m : ℕ) : decidable_pred (∈ {n : σ →₀ ℕ | ∀i, n i ≤ m }) := by simp only [set.mem_set_of_eq]; apply_instance end comm_ring variables [field K] lemma dim_R [fintype σ] : module.rank K (R σ K) = fintype.card (σ → K) := calc module.rank K (R σ K) = module.rank K (↥{s : σ →₀ ℕ | ∀ (n : σ), s n ≤ fintype.card K - 1} →₀ K) : linear_equiv.dim_eq (finsupp.supported_equiv_finsupp {s : σ →₀ ℕ | ∀n:σ, s n ≤ fintype.card K - 1 }) ... = #{s : σ →₀ ℕ | ∀ (n : σ), s n ≤ fintype.card K - 1} : by rw [finsupp.dim_eq, dim_self, mul_one] ... = #{s : σ → ℕ | ∀ (n : σ), s n < fintype.card K } : begin refine quotient.sound ⟨equiv.subtype_equiv finsupp.equiv_fun_on_fintype $ assume f, _⟩, refine forall_congr (assume n, le_tsub_iff_right _), exact fintype.card_pos_iff.2 ⟨0⟩ end ... = #(σ → {n // n < fintype.card K}) : (@equiv.subtype_pi_equiv_pi σ (λ_, ℕ) (λs n, n < fintype.card K)).cardinal_eq ... = #(σ → fin (fintype.card K)) : (equiv.arrow_congr (equiv.refl σ) fin.equiv_subtype.symm).cardinal_eq ... = #(σ → K) : (equiv.arrow_congr (equiv.refl σ) (fintype.equiv_fin K).symm).cardinal_eq ... = fintype.card (σ → K) : cardinal.mk_fintype _ instance [finite σ] : finite_dimensional K (R σ K) := by { casesI nonempty_fintype σ, exact is_noetherian.iff_fg.1 (is_noetherian.iff_dim_lt_aleph_0.mpr $ by simpa only [dim_R] using cardinal.nat_lt_aleph_0 (fintype.card (σ → K))) } lemma finrank_R [fintype σ] : finite_dimensional.finrank K (R σ K) = fintype.card (σ → K) := finite_dimensional.finrank_eq_of_dim_eq (dim_R σ K) lemma range_evalᵢ [finite σ] : (evalᵢ σ K).range = ⊤ := begin rw [evalᵢ, linear_map.range_comp, range_subtype], exact map_restrict_dom_evalₗ end lemma ker_evalₗ [finite σ] : (evalᵢ σ K).ker = ⊥ := begin casesI nonempty_fintype σ, refine (ker_eq_bot_iff_range_eq_top_of_finrank_eq_finrank _).mpr (range_evalᵢ _ _), rw [finite_dimensional.finrank_fintype_fun_eq_card, finrank_R] end lemma eq_zero_of_eval_eq_zero [finite σ] (p : mv_polynomial σ K) (h : ∀v:σ → K, eval v p = 0) (hp : p ∈ restrict_degree σ K (fintype.card K - 1)) : p = 0 := let p' : R σ K := ⟨p, hp⟩ in have p' ∈ (evalᵢ σ K).ker := funext h, show p'.1 = (0 : R σ K).1, from congr_arg _ $ by rwa [ker_evalₗ, mem_bot] at this end mv_polynomial
db1af7700ecc33f9c58fb99243fb5cf1a7ec57bf
3de1f42c556c29dec35f78b82950d93ee1fe0e39
/library/init/meta/tactic.lean
b56cf654b43f73e8c082bcd62497c7b6f15743f4
[ "Apache-2.0" ]
permissive
anamariasosam/lean
a410ca781afc1117a56686436f48c40f6f5e9306
4887d8a30621941c883f208e151e61ab268c006d
refs/heads/master
1,693,033,022,523
1,636,381,977,000
1,636,381,977,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
76,479
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.function init.data.option.basic init.util import init.control.combinators init.control.monad init.control.alternative init.control.monad_fail import init.data.nat.div init.meta.exceptional init.meta.format init.meta.environment import init.meta.pexpr init.data.repr init.data.string.basic init.meta.interaction_monad import init.classical open native meta constant tactic_state : Type universes u v namespace tactic_state meta constant env : tactic_state → environment /-- Format the given tactic state. If `target_lhs_only` is true and the target is of the form `lhs ~ rhs`, where `~` is a simplification relation, then only the `lhs` is displayed. Remark: the parameter `target_lhs_only` is a temporary hack used to implement the `conv` monad. It will be removed in the future. -/ meta constant to_format (s : tactic_state) (target_lhs_only : bool := ff) : format /-- Format expression with respect to the main goal in the tactic state. If the tactic state does not contain any goals, then format expression using an empty local context. -/ meta constant format_expr : tactic_state → expr → format meta constant get_options : tactic_state → options meta constant set_options : tactic_state → options → tactic_state end tactic_state meta instance : has_to_format tactic_state := ⟨tactic_state.to_format⟩ meta instance : has_to_string tactic_state := ⟨λ s, (to_fmt s).to_string s.get_options⟩ /-- `tactic` is the monad for building tactics. You use this to: - View and modify the local goals and hypotheses in the prover's state. - Invoke type checking and elaboration of terms. - View and modify the environment. - Build new tactics out of existing ones such as `simp` and `rewrite`. -/ @[reducible] meta def tactic := interaction_monad tactic_state @[reducible] meta def tactic_result := interaction_monad.result tactic_state namespace tactic export interaction_monad (result result.success result.exception result.cases_on result_to_string mk_exception silent_fail orelse' bracket) /-- Cause the tactic to fail with no error message. -/ meta def failed {α : Type} : tactic α := interaction_monad.failed meta def fail {α : Type u} {β : Type v} [has_to_format β] (msg : β) : tactic α := interaction_monad.fail msg end tactic namespace tactic_result export interaction_monad.result end tactic_result open tactic open tactic_result infixl ` >>=[tactic] `:2 := interaction_monad_bind infixl ` >>[tactic] `:2 := interaction_monad_seq meta instance : alternative tactic := { failure := @interaction_monad.failed _, orelse := @interaction_monad_orelse _, ..interaction_monad.monad } meta def {u₁ u₂} tactic.up {α : Type u₂} (t : tactic α) : tactic (ulift.{u₁} α) := λ s, match t s with | success a s' := success (ulift.up a) s' | exception t ref s := exception t ref s end meta def {u₁ u₂} tactic.down {α : Type u₂} (t : tactic (ulift.{u₁} α)) : tactic α := λ s, match t s with | success (ulift.up a) s' := success a s' | exception t ref s := exception t ref s end namespace interactive /-- Typeclass for custom interaction monads, which provides the information required to convert an interactive-mode construction to a `tactic` which can actually be executed. Given a `[monad m]`, `execute_with` explains how to turn a `begin ... end` block, or a `by ...` statement into a `tactic α` which can actually be executed. The `inhabited` first argument facilitates the passing of an optional configuration parameter `config`, using the syntax: ``` begin [custom_monad] with config, ... end ``` -/ meta class executor (m : Type → Type u) [monad m] := (config_type : Type) [inhabited : inhabited config_type] (execute_with : config_type → m unit → tactic unit) attribute [inline] executor.execute_with @[inline] meta def executor.execute_explicit (m : Type → Type u) [monad m] [e : executor m] : m unit → tactic unit := executor.execute_with e.inhabited.default @[inline] meta def executor.execute_with_explicit (m : Type → Type u) [monad m] [executor m] : executor.config_type m → m unit → tactic unit := executor.execute_with /-- Default `executor` instance for `tactic`s themselves -/ meta instance executor_tactic : executor tactic := { config_type := unit, inhabited := ⟨()⟩, execute_with := λ _, id } end interactive namespace tactic open interaction_monad.result variables {α : Type u} /-- Does nothing. -/ meta def skip : tactic unit := success () /-- `try_core t` acts like `t`, but succeeds even if `t` fails. It returns the result of `t` if `t` succeeded and `none` otherwise. -/ meta def try_core (t : tactic α) : tactic (option α) := λ s, match t s with | (exception _ _ _) := success none s | (success a s') := success (some a) s' end /-- `try t` acts like `t`, but succeeds even if `t` fails. -/ meta def try (t : tactic α) : tactic unit := λ s, match t s with | (exception _ _ _) := success () s | (success _ s') := success () s' end meta def try_lst : list (tactic unit) → tactic unit | [] := failed | (tac :: tacs) := λ s, match tac s with | success _ s' := try (try_lst tacs) s' | exception e p s' := match try_lst tacs s' with | exception _ _ _ := exception e p s' | r := r end end /-- `fail_if_success t` acts like `t`, but succeeds if `t` fails and fails if `t` succeeds. Changes made by `t` to the `tactic_state` are preserved only if `t` succeeds. -/ meta def fail_if_success {α : Type u} (t : tactic α) : tactic unit := λ s, match (t s) with | (success a s) := mk_exception "fail_if_success combinator failed, given tactic succeeded" none s | (exception _ _ _) := success () s end /-- `success_if_fail t` acts like `t`, but succeeds if `t` fails and fails if `t` succeeds. Changes made by `t` to the `tactic_state` are preserved only if `t` succeeds. -/ meta def success_if_fail {α : Type u} (t : tactic α) : tactic unit := λ s, match t s with | (success a s) := mk_exception "success_if_fail combinator failed, given tactic succeeded" none s | (exception _ _ _) := success () s end open nat /-- `iterate_at_most n t` iterates `t` `n` times or until `t` fails, returning the result of each successful iteration. -/ meta def iterate_at_most : nat → tactic α → tactic (list α) | 0 t := pure [] | (n + 1) t := do (some a) ← try_core t | pure [], as ← iterate_at_most n t, pure $ a :: as /-- `iterate_at_most' n t` repeats `t` `n` times or until `t` fails. -/ meta def iterate_at_most' : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := do (some _) ← try_core t | skip, iterate_at_most' n t /-- `iterate_exactly n t` iterates `t` `n` times, returning the result of each iteration. If any iteration fails, the whole tactic fails. -/ meta def iterate_exactly : nat → tactic α → tactic (list α) | 0 t := pure [] | (n + 1) t := do a ← t, as ← iterate_exactly n t, pure $ a ::as /-- `iterate_exactly' n t` executes `t` `n` times. If any iteration fails, the whole tactic fails. -/ meta def iterate_exactly' : nat → tactic unit → tactic unit | 0 t := skip | (n + 1) t := t *> iterate_exactly' n t /-- `iterate t` repeats `t` 100.000 times or until `t` fails, returning the result of each iteration. -/ meta def iterate : tactic α → tactic (list α) := iterate_at_most 100000 /-- `iterate' t` repeats `t` 100.000 times or until `t` fails. -/ meta def iterate' : tactic unit → tactic unit := iterate_at_most' 100000 meta def returnopt (e : option α) : tactic α := λ s, match e with | (some a) := success a s | none := mk_exception "failed" none s end meta instance opt_to_tac : has_coe (option α) (tactic α) := ⟨returnopt⟩ /-- Decorate t's exceptions with msg. -/ meta def decorate_ex (msg : format) (t : tactic α) : tactic α := λ s, result.cases_on (t s) success (λ opt_thunk, match opt_thunk with | some e := exception (some (λ u, msg ++ format.nest 2 (format.line ++ e u))) | none := exception none end) /-- Set the tactic_state. -/ @[inline] meta def write (s' : tactic_state) : tactic unit := λ s, success () s' /-- Get the tactic_state. -/ @[inline] meta def read : tactic tactic_state := λ s, success s s /-- `capture t` acts like `t`, but succeeds with a result containing either the returned value or the exception. Changes made by `t` to the `tactic_state` are preserved in both cases. The result can be used to inspect the error message, or passed to `unwrap` to rethrow the failure later. -/ meta def capture (t : tactic α) : tactic (tactic_result α) := λ s, match t s with | (success r s') := success (success r s') s' | (exception f p s') := success (exception f p s') s' end /-- `unwrap r` unwraps a result previously obtained using `capture`. If the previous result was a success, this produces its wrapped value. If the previous result was an exception, this "rethrows" the exception as if it came from where it originated. `do r ← capture t, unwrap r` is identical to `t`, but allows for intermediate tactics to be inserted. -/ meta def unwrap {α : Type*} (t : tactic_result α) : tactic α := match t with | (success r s') := return r | e := λ s, e end /-- `resume r` continues execution from a result previously obtained using `capture`. This is like `unwrap`, but the `tactic_state` is rolled back to point of capture even upon success. -/ meta def resume {α : Type*} (t : tactic_result α) : tactic α := λ s, t meta def get_options : tactic options := do s ← read, return s.get_options meta def set_options (o : options) : tactic unit := do s ← read, write (s.set_options o) meta def save_options {α : Type} (t : tactic α) : tactic α := do o ← get_options, a ← t, set_options o, return a meta def returnex {α : Type} (e : exceptional α) : tactic α := λ s, match e with | exceptional.success a := success a s | exceptional.exception f := match get_options s with | success opt _ := exception (some (λ u, f opt)) none s | exception _ _ _ := exception (some (λ u, f options.mk)) none s end end meta instance ex_to_tac {α : Type} : has_coe (exceptional α) (tactic α) := ⟨returnex⟩ end tactic meta def tactic_format_expr (e : expr) : tactic format := do s ← tactic.read, return (tactic_state.format_expr s e) meta class has_to_tactic_format (α : Type u) := (to_tactic_format : α → tactic format) meta instance : has_to_tactic_format expr := ⟨tactic_format_expr⟩ meta def tactic.pp {α : Type u} [has_to_tactic_format α] : α → tactic format := has_to_tactic_format.to_tactic_format open tactic format meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (list α) := ⟨λ l, to_fmt <$> l.mmap pp⟩ meta instance (α : Type u) (β : Type v) [has_to_tactic_format α] [has_to_tactic_format β] : has_to_tactic_format (α × β) := ⟨λ ⟨a, b⟩, to_fmt <$> (prod.mk <$> pp a <*> pp b)⟩ meta def option_to_tactic_format {α : Type u} [has_to_tactic_format α] : option α → tactic format | (some a) := do fa ← pp a, return (to_fmt "(some " ++ fa ++ ")") | none := return "none" meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (option α) := ⟨option_to_tactic_format⟩ meta instance {α} (a : α) : has_to_tactic_format (reflected a) := ⟨λ h, pp h.to_expr⟩ @[priority 10] meta instance has_to_format_to_has_to_tactic_format (α : Type) [has_to_format α] : has_to_tactic_format α := ⟨(λ x, return x) ∘ to_fmt⟩ namespace tactic open tactic_state meta def get_env : tactic environment := do s ← read, return $ env s meta def get_decl (n : name) : tactic declaration := do s ← read, (env s).get n meta constant get_trace_msg_pos : tactic pos meta def trace {α : Type u} [has_to_tactic_format α] (a : α) : tactic unit := do fmt ← pp a, return $ _root_.trace_fmt fmt (λ u, ()) meta def trace_call_stack : tactic unit := assume state, _root_.trace_call_stack (success () state) meta def timetac {α : Type u} (desc : string) (t : thunk (tactic α)) : tactic α := λ s, timeit desc (t () s) meta def trace_state : tactic unit := do s ← read, trace $ to_fmt s /-- A parameter representing how aggressively definitions should be unfolded when trying to decide if two terms match, unify or are definitionally equal. By default, theorem declarations are never unfolded. - `all` will unfold everything, including macros and theorems. Except projection macros. - `semireducible` will unfold everything except theorems and definitions tagged as irreducible. - `instances` will unfold all class instance definitions and definitions tagged with reducible. - `reducible` will only unfold definitions tagged with the `reducible` attribute. - `none` will never unfold anything. [NOTE] You are not allowed to tag a definition with more than one of `reducible`, `irreducible`, `semireducible` attributes. [NOTE] there is a config flag `m_unfold_lemmas`that will make it unfold theorems. -/ inductive transparency | all | semireducible | instances | reducible | none export transparency (reducible semireducible) /-- (eval_expr α e) evaluates 'e' IF 'e' has type 'α'. -/ meta constant eval_expr (α : Type u) [reflected α] : expr → tactic α /-- Return the partial term/proof constructed so far. Note that the resultant expression may contain variables that are not declarate in the current main goal. -/ meta constant result : tactic expr /-- Display the partial term/proof constructed so far. This tactic is *not* equivalent to `do { r ← result, s ← read, return (format_expr s r) }` because this one will format the result with respect to the current goal, and trace_result will do it with respect to the initial goal. -/ meta constant format_result : tactic format /-- Return target type of the main goal. Fail if tactic_state does not have any goal left. -/ meta constant target : tactic expr meta constant intro_core : name → tactic expr meta constant intron : nat → tactic unit /-- Clear the given local constant. The tactic fails if the given expression is not a local constant. -/ meta constant clear : expr → tactic unit /-- `revert_lst : list expr → tactic nat` is the reverse of `intron`. It takes a local constant `c` and puts it back as bound by a `pi` or `elet` of the main target. If there are other local constants that depend on `c`, these are also reverted. Because of this, the `nat` that is returned is the actual number of reverted local constants. Example: with `x : ℕ, h : P(x) ⊢ T(x)`, `revert_lst [x]` returns `2` and produces the state ` ⊢ Π x, P(x) → T(x)`. -/ meta constant revert_lst : list expr → tactic nat /-- Return `e` in weak head normal form with respect to the given transparency setting. If `unfold_ginductive` is `tt`, then nested and/or mutually recursive inductive datatype constructors and types are unfolded. Recall that nested and mutually recursive inductive datatype declarations are compiled into primitive datatypes accepted by the Kernel. -/ meta constant whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic expr /-- (head) eta expand the given expression. `f : α → β` head-eta-expands to `λ a, f a`. If `f` isn't a function then it just returns `f`. -/ meta constant head_eta_expand : expr → tactic expr /-- (head) beta reduction. `(λ x, B) c` reduces to `B[x/c]`. -/ meta constant head_beta : expr → tactic expr /-- (head) zeta reduction. Reduction of let bindings at the head of the expression. `let x : a := b in c` reduces to `c[x/b]`. -/ meta constant head_zeta : expr → tactic expr /-- Zeta reduction. Reduction of let bindings. `let x : a := b in c` reduces to `c[x/b]`. -/ meta constant zeta : expr → tactic expr /-- (head) eta reduction. `(λ x, f x)` reduces to `f`. -/ meta constant head_eta : expr → tactic expr /-- Succeeds if `t` and `s` can be unified using the given transparency setting. -/ meta constant unify (t s : expr) (md := semireducible) (approx := ff) : tactic unit /-- Similar to `unify`, but it treats metavariables as constants. -/ meta constant is_def_eq (t s : expr) (md := semireducible) (approx := ff) : tactic unit /-- Infer the type of the given expression. Remark: transparency does not affect type inference -/ meta constant infer_type : expr → tactic expr /-- Get the `local_const` expr for the given `name`. -/ meta constant get_local : name → tactic expr /-- Resolve a name using the current local context, environment, aliases, etc. -/ meta constant resolve_name : name → tactic pexpr /-- Return the hypothesis in the main goal. Fail if tactic_state does not have any goal left. -/ meta constant local_context : tactic (list expr) /-- Get a fresh name that is guaranteed to not be in use in the local context. If `n` is provided and `n` is not in use, then `n` is returned. Otherwise a number `i` is appended to give `"n_i"`. -/ meta constant get_unused_name (n : name := `_x) (i : option nat := none) : tactic name /-- Helper tactic for creating simple applications where some arguments are inferred using type inference. Example, given ``` rel.{l_1 l_2} : Pi (α : Type.{l_1}) (β : α -> Type.{l_2}), (Pi x : α, β x) -> (Pi x : α, β x) -> , Prop nat : Type real : Type vec.{l} : Pi (α : Type l) (n : nat), Type.{l1} f g : Pi (n : nat), vec real n ``` then ``` mk_app_core semireducible "rel" [f, g] ``` returns the application ``` rel.{1 2} nat (fun n : nat, vec real n) f g ``` The unification constraints due to type inference are solved using the transparency `md`. -/ meta constant mk_app (fn : name) (args : list expr) (md := semireducible) : tactic expr /-- Similar to `mk_app`, but allows to specify which arguments are explicit/implicit. Example, given `(a b : nat)` then ``` mk_mapp "ite" [some (a > b), none, none, some a, some b] ``` returns the application ``` @ite.{1} nat (a > b) (nat.decidable_gt a b) a b ``` -/ meta constant mk_mapp (fn : name) (args : list (option expr)) (md := semireducible) : tactic expr /-- (mk_congr_arg h₁ h₂) is a more efficient version of (mk_app `congr_arg [h₁, h₂]) -/ meta constant mk_congr_arg : expr → expr → tactic expr /-- (mk_congr_fun h₁ h₂) is a more efficient version of (mk_app `congr_fun [h₁, h₂]) -/ meta constant mk_congr_fun : expr → expr → tactic expr /-- (mk_congr h₁ h₂) is a more efficient version of (mk_app `congr [h₁, h₂]) -/ meta constant mk_congr : expr → expr → tactic expr /-- (mk_eq_refl h) is a more efficient version of (mk_app `eq.refl [h]) -/ meta constant mk_eq_refl : expr → tactic expr /-- (mk_eq_symm h) is a more efficient version of (mk_app `eq.symm [h]) -/ meta constant mk_eq_symm : expr → tactic expr /-- (mk_eq_trans h₁ h₂) is a more efficient version of (mk_app `eq.trans [h₁, h₂]) -/ meta constant mk_eq_trans : expr → expr → tactic expr /-- (mk_eq_mp h₁ h₂) is a more efficient version of (mk_app `eq.mp [h₁, h₂]) -/ meta constant mk_eq_mp : expr → expr → tactic expr /-- (mk_eq_mpr h₁ h₂) is a more efficient version of (mk_app `eq.mpr [h₁, h₂]) -/ meta constant mk_eq_mpr : expr → expr → tactic expr /-- Given a local constant t, if t has type (lhs = rhs) apply substitution. Otherwise, try to find a local constant that has type of the form (t = t') or (t' = t). The tactic fails if the given expression is not a local constant. -/ meta constant subst_core : expr → tactic unit /-- Close the current goal using `e`. Fail if the type of `e` is not definitionally equal to the target type. -/ meta constant exact (e : expr) (md := semireducible) : tactic unit /-- Elaborate the given quoted expression with respect to the current main goal. Note that this means that any implicit arguments for the given `pexpr` will be applied with fresh metavariables. If `allow_mvars` is tt, then metavariables are tolerated and become new goals if `subgoals` is tt. -/ meta constant to_expr (q : pexpr) (allow_mvars := tt) (subgoals := tt) : tactic expr /-- Return true if the given expression is a type class. -/ meta constant is_class : expr → tactic bool /-- Try to create an instance of the given type class. -/ meta constant mk_instance : expr → tactic expr /-- Change the target of the main goal. The input expression must be definitionally equal to the current target. If `check` is `ff`, then the tactic does not check whether `e` is definitionally equal to the current target. If it is not, then the error will only be detected by the kernel type checker. -/ meta constant change (e : expr) (check : bool := tt): tactic unit /-- `assert_core H T`, adds a new goal for T, and change target to `T -> target`. -/ meta constant assert_core : name → expr → tactic unit /-- `assertv_core H T P`, change target to (T -> target) if P has type T. -/ meta constant assertv_core : name → expr → expr → tactic unit /-- `define_core H T`, adds a new goal for T, and change target to `let H : T := ?M in target` in the current goal. -/ meta constant define_core : name → expr → tactic unit /-- `definev_core H T P`, change target to `let H : T := P in target` if P has type T. -/ meta constant definev_core : name → expr → expr → tactic unit /-- Rotate goals to the left. That is, `rotate_left 1` takes the main goal and puts it to the back of the subgoal list. -/ meta constant rotate_left : nat → tactic unit /-- Gets a list of metavariables, one for each goal. -/ meta constant get_goals : tactic (list expr) /-- Replace the current list of goals with the given one. Each expr in the list should be a metavariable. Any assigned metavariables will be ignored.-/ meta constant set_goals : list expr → tactic unit /-- How to order the new goals made from an `apply` tactic. Supposing we were applying `e : ∀ (a:α) (p : P(a)), Q` - `non_dep_first` would produce goals `⊢ P(?m)`, `⊢ α`. It puts the P goal at the front because none of the arguments after `p` in `e` depend on `p`. It doesn't matter what the result `Q` depends on. - `non_dep_only` would produce goal `⊢ P(?m)`. - `all` would produce goals `⊢ α`, `⊢ P(?m)`. -/ inductive new_goals | non_dep_first | non_dep_only | all /-- Configuration options for the `apply` tactic. - `md` sets how aggressively definitions are unfolded. - `new_goals` is the strategy for ordering new goals. - `instances` if `tt`, then `apply` tries to synthesize unresolved `[...]` arguments using type class resolution. - `auto_param` if `tt`, then `apply` tries to synthesize unresolved `(h : p . tac_id)` arguments using tactic `tac_id`. - `opt_param` if `tt`, then `apply` tries to synthesize unresolved `(a : t := v)` arguments by setting them to `v`. - `unify` if `tt`, then `apply` is free to assign existing metavariables in the goal when solving unification constraints. For example, in the goal `|- ?x < succ 0`, the tactic `apply succ_lt_succ` succeeds with the default configuration, but `apply_with succ_lt_succ {unify := ff}` doesn't since it would require Lean to assign `?x` to `succ ?y` where `?y` is a fresh metavariable. -/ structure apply_cfg := (md := semireducible) (approx := tt) (new_goals := new_goals.non_dep_first) (instances := tt) (auto_param := tt) (opt_param := tt) (unify := tt) /-- Apply the expression `e` to the main goal, the unification is performed using the transparency mode in `cfg`. Supposing `e : Π (a₁:α₁) ... (aₙ:αₙ), P(a₁,...,aₙ)` and the target is `Q`, `apply` will attempt to unify `Q` with `P(?a₁,...?aₙ)`. All of the metavariables that are not assigned are added as new metavariables. If `cfg.approx` is `tt`, then fallback to first-order unification, and approximate context during unification. `cfg.new_goals` specifies which unassigned metavariables become new goals, and their order. If `cfg.instances` is `tt`, then use type class resolution to instantiate unassigned meta-variables. The fields `cfg.auto_param` and `cfg.opt_param` are ignored by this tactic (See `tactic.apply`). It returns a list of all introduced meta variables and the parameter name associated with them, even the assigned ones. -/ meta constant apply_core (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) /- Create a fresh meta universe variable. -/ meta constant mk_meta_univ : tactic level /- Create a fresh meta-variable with the given type. The scope of the new meta-variable is the local context of the main goal. -/ meta constant mk_meta_var : expr → tactic expr /-- Return the value assigned to the given universe meta-variable. Fail if argument is not an universe meta-variable or if it is not assigned. -/ meta constant get_univ_assignment : level → tactic level /-- Return the value assigned to the given meta-variable. Fail if argument is not a meta-variable or if it is not assigned. -/ meta constant get_assignment : expr → tactic expr /-- Return true if the given meta-variable is assigned. Fail if argument is not a meta-variable. -/ meta constant is_assigned : expr → tactic bool /-- Make a name that is guaranteed to be unique. Eg `_fresh.1001.4667`. These will be different for each run of the tactic. -/ meta constant mk_fresh_name : tactic name /-- Induction on `h` using recursor `rec`, names for the new hypotheses are retrieved from `ns`. If `ns` does not have sufficient names, then use the internal binder names in the recursor. It returns for each new goal the name of the constructor (if `rec_name` is a builtin recursor), a list of new hypotheses, and a list of substitutions for hypotheses depending on `h`. The substitutions map internal names to their replacement terms. If the replacement is again a hypothesis the user name stays the same. The internal names are only valid in the original goal, not in the type context of the new goal. Remark: if `rec_name` is not a builtin recursor, we use parameter names of `rec_name` instead of constructor names. If `rec` is none, then the type of `h` is inferred, if it is of the form `C ...`, tactic uses `C.rec` -/ meta constant induction (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic (list (name × list expr × list (name × expr))) /-- Apply `cases_on` recursor, names for the new hypotheses are retrieved from `ns`. `h` must be a local constant. It returns for each new goal the name of the constructor, a list of new hypotheses, and a list of substitutions for hypotheses depending on `h`. The number of new goals may be smaller than the number of constructors. Some goals may be discarded when the indices to not match. See `induction` for information on the list of substitutions. The `cases` tactic is implemented using this one, and it relaxes the restriction of `h`. Note: There is one "new hypothesis" for every constructor argument. These are usually local constants, but due to dependent pattern matching, they can also be arbitrary terms. -/ meta constant cases_core (h : expr) (ns : list name := []) (md := semireducible) : tactic (list (name × list expr × list (name × expr))) /-- Similar to cases tactic, but does not revert/intro/clear hypotheses. -/ meta constant destruct (e : expr) (md := semireducible) : tactic unit /-- Generalizes the target with respect to `e`. -/ meta constant generalize (e : expr) (n : name := `_x) (md := semireducible) : tactic unit /-- instantiate assigned metavariables in the given expression -/ meta constant instantiate_mvars : expr → tactic expr /-- Add the given declaration to the environment -/ meta constant add_decl : declaration → tactic unit /-- Changes the environment to the `new_env`. The new environment does not need to be a descendant of the old one. Use with care. -/ meta constant set_env_core : environment → tactic unit /-- Changes the environment to the `new_env`. `new_env` needs to be a descendant from the current environment. -/ meta constant set_env : environment → tactic unit /-- `doc_string env d k` returns the doc string for `d` (if available) -/ meta constant doc_string : name → tactic string /-- Set the docstring for the given declaration. -/ meta constant add_doc_string : name → string → tactic unit /-- Create an auxiliary definition with name `c` where `type` and `value` may contain local constants and meta-variables. This function collects all dependencies (universe parameters, universe metavariables, local constants (aka hypotheses) and metavariables). It updates the environment in the tactic_state, and returns an expression of the form (c.{l_1 ... l_n} a_1 ... a_m) where l_i's and a_j's are the collected dependencies. -/ meta constant add_aux_decl (c : name) (type : expr) (val : expr) (is_lemma : bool) : tactic expr /-- Returns a list of all top-level (`/-! ... -/`) docstrings in the active module and imported ones. The returned object is a list of modules, indexed by `(some filename)` for imported modules and `none` for the active one, where each module in the list is paired with a list of `(position_in_file, docstring)` pairs. -/ meta constant olean_doc_strings : tactic (list (option string × (list (pos × string)))) /-- Returns a list of docstrings in the active module. An entry in the list can be either: - a top-level (`/-! ... -/`) docstring, represented as `(none, docstring)` - a declaration-specific (`/-- ... -/`) docstring, represented as `(some decl_name, docstring)` -/ meta def module_doc_strings : tactic (list (option name × string)) := do /- Obtain a list of top-level docs in current module. -/ mod_docs ← olean_doc_strings, let mod_docs: list (list (option name × string)) := mod_docs.filter_map (λ d, if d.1.is_none then some (d.2.map (λ pos_doc, ⟨none, pos_doc.2⟩)) else none), let mod_docs := mod_docs.join, /- Obtain list of declarations in current module. -/ e ← get_env, let decls := environment.fold e ([]: list name) (λ d acc, let n := d.to_name in if (environment.decl_olean e n).is_none then n::acc else acc), /- Map declarations to those which have docstrings. -/ decls ← decls.mfoldl (λa n, (doc_string n >>= λ doc, pure $ (some n, doc) :: a) <|> pure a) [], pure (mod_docs ++ decls) /-- Set attribute `attr_name` for constant `c_name` with the given priority. If the priority is none, then use default -/ meta constant set_basic_attribute (attr_name : name) (c_name : name) (persistent := ff) (prio : option nat := none) : tactic unit /-- `unset_attribute attr_name c_name` -/ meta constant unset_attribute : name → name → tactic unit /-- `has_attribute attr_name c_name` succeeds if the declaration `decl_name` has the attribute `attr_name`. The result is the priority and whether or not the attribute is persistent. -/ meta constant has_attribute : name → name → tactic (bool × nat) /-- `copy_attribute attr_name c_name p d_name` copy attribute `attr_name` from `src` to `tgt` if it is defined for `src`; make it persistent if `p` is `tt`; if `p` is `none`, the copied attribute is made persistent iff it is persistent on `src` -/ meta def copy_attribute (attr_name : name) (src : name) (tgt : name) (p : option bool := none) : tactic unit := try $ do (p', prio) ← has_attribute attr_name src, let p := p.get_or_else p', set_basic_attribute attr_name tgt p (some prio) /-- Name of the declaration currently being elaborated. -/ meta constant decl_name : tactic name /-- `save_type_info e ref` save (typeof e) at position associated with ref -/ meta constant save_type_info {elab : bool} : expr → expr elab → tactic unit meta constant save_info_thunk : pos → (unit → format) → tactic unit /-- Return list of currently open namespaces -/ meta constant open_namespaces : tactic (list name) /-- Return tt iff `t` "occurs" in `e`. The occurrence checking is performed using keyed matching with the given transparency setting. We say `t` occurs in `e` by keyed matching iff there is a subterm `s` s.t. `t` and `s` have the same head, and `is_def_eq t s md` The main idea is to minimize the number of `is_def_eq` checks performed. -/ meta constant kdepends_on (e t : expr) (md := reducible) : tactic bool /-- Abstracts all occurrences of the term `t` in `e` using keyed matching. If `unify` is `ff`, then matching is used instead of unification. That is, metavariables occurring in `e` are not assigned. -/ meta constant kabstract (e t : expr) (md := reducible) (unify := tt) : tactic expr /-- Blocks the execution of the current thread for at least `msecs` milliseconds. This tactic is used mainly for debugging purposes. -/ meta constant sleep (msecs : nat) : tactic unit /-- Type check `e` with respect to the current goal. Fails if `e` is not type correct. -/ meta constant type_check (e : expr) (md := semireducible) : tactic unit open list nat /-- A `tag` is a list of `names`. These are attached to goals to help tactics track them.-/ def tag : Type := list name /-- Enable/disable goal tagging. -/ meta constant enable_tags (b : bool) : tactic unit /-- Return tt iff goal tagging is enabled. -/ meta constant tags_enabled : tactic bool /-- Tag goal `g` with tag `t`. It does nothing if goal tagging is disabled. Remark: `set_goal g []` removes the tag -/ meta constant set_tag (g : expr) (t : tag) : tactic unit /-- Return tag associated with `g`. Return `[]` if there is no tag. -/ meta constant get_tag (g : expr) : tactic tag /-- By default, Lean only considers local instances in the header of declarations. This has two main benefits. 1- Results produced by the type class resolution procedure can be easily cached. 2- The set of local instances does not have to be recomputed. This approach has the following disadvantages: 1- Frozen local instances cannot be reverted. 2- Local instances defined inside of a declaration are not considered during type class resolution. This tactic resets the set of local instances. After executing this tactic, the set of local instances will be recomputed and the cache will be frequently reset. Note that, the cache is still used when executing a single tactic that may generate many type class resolution problems (e.g., `simp`). -/ meta constant unfreeze_local_instances : tactic unit /-- Freeze the current set of local instances. -/ meta constant freeze_local_instances : tactic unit /- Return the list of frozen local instances. Return `none` if local instances were not frozen. -/ meta constant frozen_local_instances : tactic (option (list expr)) /-- Run the provided tactic, associating it to the given AST node. -/ meta constant with_ast {α : Type u} (ast : ℕ) (t : tactic α) : tactic α meta def induction' (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic unit := induction h ns rec md >> return () /-- Remark: set_goals will erase any solved goal -/ meta def cleanup : tactic unit := get_goals >>= set_goals /-- Auxiliary definition used to implement begin ... end blocks -/ meta def step {α : Type u} (t : tactic α) : tactic unit := t >>[tactic] cleanup meta def istep {α : Type u} (line0 col0 line col ast : ℕ) (t : tactic α) : tactic unit := λ s, (@scope_trace _ line col (λ _, with_ast ast (step t) s)).clamp_pos line0 line col meta def is_prop (e : expr) : tactic bool := do t ← infer_type e, return (t = `(Prop)) /-- Return true iff n is the name of declaration that is a proposition. -/ meta def is_prop_decl (n : name) : tactic bool := do env ← get_env, d ← env.get n, t ← return $ d.type, is_prop t meta def is_proof (e : expr) : tactic bool := infer_type e >>= is_prop meta def whnf_no_delta (e : expr) : tactic expr := whnf e transparency.none /-- Return `e` in weak head normal form with respect to the given transparency setting, or `e` head is a generalized constructor or inductive datatype. -/ meta def whnf_ginductive (e : expr) (md := semireducible) : tactic expr := whnf e md ff meta def whnf_target : tactic unit := target >>= whnf >>= change /-- Change the target of the main goal. The input expression must be definitionally equal to the current target. The tactic does not check whether `e` is definitionally equal to the current target. The error will only be detected by the kernel type checker. -/ meta def unsafe_change (e : expr) : tactic unit := change e ff /-- Pi or elet introduction. Given the tactic state `⊢ Π x : α, Y`, ``intro `hello`` will produce the state `hello : α ⊢ Y[x/hello]`. Returns the new local constant. Similarly for `elet` expressions. If the target is not a Pi or elet it will try to put it in WHNF. -/ meta def intro (n : name) : tactic expr := do t ← target, if expr.is_pi t ∨ expr.is_let t then intro_core n else whnf_target >> intro_core n /-- A variant of `intro` which makes sure that the introduced hypothesis's name is unique in the context. If there is no hypothesis named `n` in the context yet, `intro_fresh n` is the same as `intro n`. If there is already a hypothesis named `n`, the new hypothesis is named `n_1` (or `n_2` if `n_1` already exists, etc.). If `offset` is given, the new names are `n_offset`, `n_offset+1` etc. If `n` is `_`, `intro_fresh n` is the same as `intro1`. The `offset` is ignored in this case. -/ meta def intro_fresh (n : name) (offset : option nat := none) : tactic expr := if n = `_ then intro `_ else do n ← get_unused_name n offset, intro n /-- Like `intro` except the name is derived from the bound name in the Π. -/ meta def intro1 : tactic expr := intro `_ /-- Repeatedly apply `intro1` and return the list of new local constants in order of introduction. -/ meta def intros : tactic (list expr) := do t ← target, match t with | expr.pi _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs) | expr.elet _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs) | _ := return [] end /-- Same as `intros`, except with the given names for the new hypotheses. Use the name ```_``` to instead use the binder's name.-/ meta def intro_lst (ns : list name) : tactic (list expr) := ns.mmap intro /-- A variant of `intro_lst` which makes sure that the introduced hypotheses' names are unique in the context. See `intro_fresh`. -/ meta def intro_lst_fresh (ns : list name) : tactic (list expr) := ns.mmap intro_fresh /-- Introduces new hypotheses with forward dependencies. -/ meta def intros_dep : tactic (list expr) := do t ← target, let proc (b : expr) := if b.has_var_idx 0 then do h ← intro1, hs ← intros_dep, return (h::hs) else -- body doesn't depend on new hypothesis return [], match t with | expr.pi _ _ _ b := proc b | expr.elet _ _ _ b := proc b | _ := return [] end meta def introv : list name → tactic (list expr) | [] := intros_dep | (n::ns) := do hs ← intros_dep, h ← intro n, hs' ← introv ns, return (hs ++ h :: hs') /-- `intron' n` introduces `n` hypotheses and returns the resulting local constants. Fails if there are not at least `n` arguments to introduce. If you do not need the return value, use `intron`. -/ meta def intron' (n : ℕ) : tactic (list expr) := iterate_exactly n intro1 /-- Like `intron'` but the introduced hypotheses' names are derived from `base`, i.e. `base`, `base_1` etc. The new names are unique in the context. If `offset` is given, the new names will be `base_offset`, `base_offset+1` etc. -/ meta def intron_base (n : ℕ) (base : name) (offset : option nat := none) : tactic (list expr) := iterate_exactly n (intro_fresh base offset) /-- `intron_with i ns base offset` introduces `i` hypotheses using the names from `ns`. If `ns` contains less than `i` names, the remaining hypotheses' names are derived from `base` and `offset` (as with `intron_base`). If `base` is `_`, the names are derived from the Π binder names. Returns the introduced local constants and the remaining names from `ns` (if `ns` contains more than `i` names). -/ meta def intron_with : ℕ → list name → opt_param name `_ → opt_param (option ℕ) none → tactic (list expr × list name) | 0 ns _ _ := pure ([], ns) | (i + 1) [] base offset := do hs ← intron_base (i + 1) base offset, pure (hs, []) | (i + 1) (n :: ns) base offset := do h ← intro n, ⟨hs, rest⟩ ← intron_with i ns base offset, pure (h :: hs, rest) /-- Returns n fully qualified if it refers to a constant, or else fails. -/ meta def resolve_constant (n : name) : tactic name := do e ← resolve_name n, match e with | expr.const n _ := pure n | _ := do e ← to_expr e tt ff, expr.const n _ ← pure $ e.get_app_fn, pure n end meta def to_expr_strict (q : pexpr) : tactic expr := to_expr q /-- Example: with `x : ℕ, h : P(x) ⊢ T(x)`, `revert x` returns `2` and produces the state ` ⊢ Π x, P(x) → T(x)`. -/ meta def revert (l : expr) : tactic nat := revert_lst [l] /- Revert "all" hypotheses. Actually, the tactic only reverts hypotheses occurring after the last frozen local instance. Recall that frozen local instances cannot be reverted. We can use `unfreeze_local_instances` to workaround this limitation. -/ meta def revert_all : tactic nat := do lctx ← local_context, lis ← frozen_local_instances, match lis with | none := revert_lst lctx | some [] := revert_lst lctx /- `hi` is the last local instance. We shoul truncate `lctx` at `hi`. -/ | some (hi::his) := revert_lst $ lctx.foldl (λ r h, if h.local_uniq_name = hi.local_uniq_name then [] else h :: r) [] end meta def clear_lst : list name → tactic unit | [] := skip | (n::ns) := do H ← get_local n, clear H, clear_lst ns meta def match_not (e : expr) : tactic expr := match (expr.is_not e) with | (some a) := return a | none := fail "expression is not a negation" end meta def match_and (e : expr) : tactic (expr × expr) := match (expr.is_and e) with | (some (α, β)) := return (α, β) | none := fail "expression is not a conjunction" end meta def match_or (e : expr) : tactic (expr × expr) := match (expr.is_or e) with | (some (α, β)) := return (α, β) | none := fail "expression is not a disjunction" end meta def match_iff (e : expr) : tactic (expr × expr) := match (expr.is_iff e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not an iff" end meta def match_eq (e : expr) : tactic (expr × expr) := match (expr.is_eq e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not an equality" end meta def match_ne (e : expr) : tactic (expr × expr) := match (expr.is_ne e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not a disequality" end meta def match_heq (e : expr) : tactic (expr × expr × expr × expr) := do match (expr.is_heq e) with | (some (α, lhs, β, rhs)) := return (α, lhs, β, rhs) | none := fail "expression is not a heterogeneous equality" end meta def match_refl_app (e : expr) : tactic (name × expr × expr) := do env ← get_env, match (environment.is_refl_app env e) with | (some (R, lhs, rhs)) := return (R, lhs, rhs) | none := fail "expression is not an application of a reflexive relation" end meta def match_app_of (e : expr) (n : name) : tactic (list expr) := guard (expr.is_app_of e n) >> return e.get_app_args meta def get_local_type (n : name) : tactic expr := get_local n >>= infer_type meta def trace_result : tactic unit := format_result >>= trace meta def rexact (e : expr) : tactic unit := exact e reducible meta def any_hyp_aux {α : Type} (f : expr → tactic α) : list expr → tactic α | [] := failed | (h :: hs) := f h <|> any_hyp_aux hs meta def any_hyp {α : Type} (f : expr → tactic α) : tactic α := local_context >>= any_hyp_aux f /-- `find_same_type t es` tries to find in es an expression with type definitionally equal to t -/ meta def find_same_type : expr → list expr → tactic expr | e [] := failed | e (H :: Hs) := do t ← infer_type H, (unify e t >> return H) <|> find_same_type e Hs meta def find_assumption (e : expr) : tactic expr := do ctx ← local_context, find_same_type e ctx meta def assumption : tactic unit := do { ctx ← local_context, t ← target, H ← find_same_type t ctx, exact H } <|> fail "assumption tactic failed" meta def save_info (p : pos) : tactic unit := do s ← read, tactic.save_info_thunk p (λ _, tactic_state.to_format s) notation `‹` p `›` := (by assumption : p) /-- Swap first two goals, do nothing if tactic state does not have at least two goals. -/ meta def swap : tactic unit := do gs ← get_goals, match gs with | (g₁ :: g₂ :: rs) := set_goals (g₂ :: g₁ :: rs) | e := skip end /-- `assert h t`, adds a new goal for t, and the hypothesis `h : t` in the current goal. -/ meta def assert (h : name) (t : expr) : tactic expr := do assert_core h t, swap, e ← intro h, swap, return e /-- `assertv h t v`, adds the hypothesis `h : t` in the current goal if v has type t. -/ meta def assertv (h : name) (t : expr) (v : expr) : tactic expr := assertv_core h t v >> intro h /-- `define h t`, adds a new goal for t, and the hypothesis `h : t := ?M` in the current goal. -/ meta def define (h : name) (t : expr) : tactic expr := do define_core h t, swap, e ← intro h, swap, return e /-- `definev h t v`, adds the hypothesis (h : t := v) in the current goal if v has type t. -/ meta def definev (h : name) (t : expr) (v : expr) : tactic expr := definev_core h t v >> intro h /-- Add `h : t := pr` to the current goal -/ meta def pose (h : name) (t : option expr := none) (pr : expr) : tactic expr := let dv := λt, definev h t pr in option.cases_on t (infer_type pr >>= dv) dv /-- Add `h : t` to the current goal, given a proof `pr : t` -/ meta def note (h : name) (t : option expr := none) (pr : expr) : tactic expr := let dv := λt, assertv h t pr in option.cases_on t (infer_type pr >>= dv) dv /-- Return the number of goals that need to be solved -/ meta def num_goals : tactic nat := do gs ← get_goals, return (length gs) /-- Rotate the goals to the right by `n`. That is, take the goal at the back and push it to the front `n` times. [NOTE] We have to provide the instance argument `[has_mod nat]` because mod for nat was not defined yet -/ meta def rotate_right (n : nat) [has_mod nat] : tactic unit := do ng ← num_goals, if ng = 0 then skip else rotate_left (ng - n % ng) /-- Rotate the goals to the left by `n`. That is, put the main goal to the back `n` times. -/ meta def rotate : nat → tactic unit := rotate_left private meta def repeat_aux (t : tactic unit) : list expr → list expr → tactic unit | [] r := set_goals r.reverse | (g::gs) r := do ok ← try_core (set_goals [g] >> t), match ok with | none := repeat_aux gs (g::r) | _ := do gs' ← get_goals, repeat_aux (gs' ++ gs) r end /-- This tactic is applied to each goal. If the application succeeds, the tactic is applied recursively to all the generated subgoals until it eventually fails. The recursion stops in a subgoal when the tactic has failed to make progress. The tactic `repeat` never fails. -/ meta def repeat (t : tactic unit) : tactic unit := do gs ← get_goals, repeat_aux t gs [] /-- `first [t_1, ..., t_n]` applies the first tactic that doesn't fail. The tactic fails if all t_i's fail. -/ meta def first {α : Type u} : list (tactic α) → tactic α | [] := fail "first tactic failed, no more alternatives" | (t::ts) := t <|> first ts /-- Applies the given tactic to the main goal and fails if it is not solved. -/ meta def solve1 {α} (tac : tactic α) : tactic α := do gs ← get_goals, match gs with | [] := fail "solve1 tactic failed, there isn't any goal left to focus" | (g::rs) := do set_goals [g], a ← tac, gs' ← get_goals, match gs' with | [] := set_goals rs >> pure a | gs := fail "solve1 tactic failed, focused goal has not been solved" end end /-- `solve [t_1, ... t_n]` applies the first tactic that solves the main goal. -/ meta def solve {α} (ts : list (tactic α)) : tactic α := first $ map solve1 ts private meta def focus_aux {α} : list (tactic α) → list expr → list expr → tactic (list α) | [] [] rs := set_goals rs *> pure [] | (t::ts) [] rs := fail "focus tactic failed, insufficient number of goals" | tts (g::gs) rs := mcond (is_assigned g) (focus_aux tts gs rs) $ do set_goals [g], t::ts ← pure tts | fail "focus tactic failed, insufficient number of tactics", a ← t, rs' ← get_goals, as ← focus_aux ts gs (rs ++ rs'), pure $ a :: as /-- `focus [t_1, ..., t_n]` applies t_i to the i-th goal. Fails if the number of goals is not n. Returns the results of t_i (one per goal). -/ meta def focus {α} (ts : list (tactic α)) : tactic (list α) := do gs ← get_goals, focus_aux ts gs [] private meta def focus'_aux : list (tactic unit) → list expr → list expr → tactic unit | [] [] rs := set_goals rs | (t::ts) [] rs := fail "focus' tactic failed, insufficient number of goals" | tts (g::gs) rs := mcond (is_assigned g) (focus'_aux tts gs rs) $ do set_goals [g], t::ts ← pure tts | fail "focus' tactic failed, insufficient number of tactics", t, rs' ← get_goals, focus'_aux ts gs (rs ++ rs') /-- `focus' [t_1, ..., t_n]` applies t_i to the i-th goal. Fails if the number of goals is not n. -/ meta def focus' (ts : list (tactic unit)) : tactic unit := do gs ← get_goals, focus'_aux ts gs [] meta def focus1 {α} (tac : tactic α) : tactic α := do g::gs ← get_goals, match gs with | [] := tac | _ := do set_goals [g], a ← tac, gs' ← get_goals, set_goals (gs' ++ gs), return a end private meta def all_goals_core {α} (tac : tactic α) : list expr → list expr → tactic (list α) | [] ac := set_goals ac *> pure [] | (g :: gs) ac := mcond (is_assigned g) (all_goals_core gs ac) $ do set_goals [g], a ← tac, new_gs ← get_goals, as ← all_goals_core gs (ac ++ new_gs), pure $ a :: as /-- Apply the given tactic to all goals. Return one result per goal. -/ meta def all_goals {α} (tac : tactic α) : tactic (list α) := do gs ← get_goals, all_goals_core tac gs [] private meta def all_goals'_core (tac : tactic unit) : list expr → list expr → tactic unit | [] ac := set_goals ac | (g :: gs) ac := mcond (is_assigned g) (all_goals'_core gs ac) $ do set_goals [g], tac, new_gs ← get_goals, all_goals'_core gs (ac ++ new_gs) /-- Apply the given tactic to all goals. -/ meta def all_goals' (tac : tactic unit) : tactic unit := do gs ← get_goals, all_goals'_core tac gs [] private meta def any_goals_core {α} (tac : tactic α) : list expr → list expr → bool → tactic (list (option α)) | [] ac progress := guard progress *> set_goals ac *> pure [] | (g :: gs) ac progress := mcond (is_assigned g) (any_goals_core gs ac progress) $ do set_goals [g], res ← try_core tac, new_gs ← get_goals, ress ← any_goals_core gs (ac ++ new_gs) (res.is_some || progress), pure $ res :: ress /-- Apply `tac` to any goal where it succeeds. The tactic succeeds if `tac` succeeds for at least one goal. The returned list contains the result of `tac` for each goal: `some a` if tac succeeded, or `none` if it did not. -/ meta def any_goals {α} (tac : tactic α) : tactic (list (option α)) := do gs ← get_goals, any_goals_core tac gs [] ff private meta def any_goals'_core (tac : tactic unit) : list expr → list expr → bool → tactic unit | [] ac progress := guard progress >> set_goals ac | (g :: gs) ac progress := mcond (is_assigned g) (any_goals'_core gs ac progress) $ do set_goals [g], succeeded ← try_core tac, new_gs ← get_goals, any_goals'_core gs (ac ++ new_gs) (succeeded.is_some || progress) /-- Apply the given tactic to any goal where it succeeds. The tactic succeeds only if tac succeeds for at least one goal. -/ meta def any_goals' (tac : tactic unit) : tactic unit := do gs ← get_goals, any_goals'_core tac gs [] ff /-- LCF-style AND_THEN tactic. It applies `tac1` to the main goal, then applies `tac2` to each goal produced by `tac1`. -/ meta def seq {α β} (tac1 : tactic α) (tac2 : α → tactic β) : tactic (list β) := do g::gs ← get_goals, set_goals [g], a ← tac1, bs ← all_goals $ tac2 a, gs' ← get_goals, set_goals (gs' ++ gs), pure bs /-- LCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/ meta def seq' (tac1 : tactic unit) (tac2 : tactic unit) : tactic unit := do g::gs ← get_goals, set_goals [g], tac1, all_goals' tac2, gs' ← get_goals, set_goals (gs' ++ gs) /-- Applies `tac1` to the main goal, then applies each of the tactics in `tacs2` to one of the produced subgoals (like `focus'`). -/ meta def seq_focus {α β} (tac1 : tactic α) (tacs2 : α → list (tactic β)) : tactic (list β) := do g::gs ← get_goals, set_goals [g], a ← tac1, bs ← focus $ tacs2 a, gs' ← get_goals, set_goals (gs' ++ gs), pure bs /-- Applies `tac1` to the main goal, then applies each of the tactics in `tacs2` to one of the produced subgoals (like `focus`). -/ meta def seq_focus' (tac1 : tactic unit) (tacs2 : list (tactic unit)) : tactic unit := do g::gs ← get_goals, set_goals [g], tac1, focus tacs2, gs' ← get_goals, set_goals (gs' ++ gs) meta instance andthen_seq : has_andthen (tactic unit) (tactic unit) (tactic unit) := ⟨seq'⟩ meta instance andthen_seq_focus : has_andthen (tactic unit) (list (tactic unit)) (tactic unit) := ⟨seq_focus'⟩ meta constant is_trace_enabled_for : name → bool /-- Execute tac only if option trace.n is set to true. -/ meta def when_tracing (n : name) (tac : tactic unit) : tactic unit := when (is_trace_enabled_for n = tt) tac /-- Fail if there are no remaining goals. -/ meta def fail_if_no_goals : tactic unit := do n ← num_goals, when (n = 0) (fail "tactic failed, there are no goals to be solved") /-- Fail if there are unsolved goals. -/ meta def done : tactic unit := do n ← num_goals, when (n ≠ 0) (fail "done tactic failed, there are unsolved goals") meta def apply_opt_param : tactic unit := do `(opt_param %%t %%v) ← target, exact v meta def apply_auto_param : tactic unit := do `(auto_param %%type %%tac_name_expr) ← target, change type, tac_name ← eval_expr name tac_name_expr, tac ← eval_expr (tactic unit) (expr.const tac_name []), tac meta def has_opt_auto_param (ms : list expr) : tactic bool := ms.mfoldl (λ r m, do type ← infer_type m, return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2) ff meta def try_apply_opt_auto_param (cfg : apply_cfg) (ms : list expr) : tactic unit := when (cfg.auto_param || cfg.opt_param) $ mwhen (has_opt_auto_param ms) $ do gs ← get_goals, ms.mmap' (λ m, mwhen (bnot <$> is_assigned m) $ set_goals [m] >> when cfg.opt_param (try apply_opt_param) >> when cfg.auto_param (try apply_auto_param)), set_goals gs meta def has_opt_auto_param_for_apply (ms : list (name × expr)) : tactic bool := ms.mfoldl (λ r m, do type ← infer_type m.2, return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2) ff meta def try_apply_opt_auto_param_for_apply (cfg : apply_cfg) (ms : list (name × expr)) : tactic unit := mwhen (has_opt_auto_param_for_apply ms) $ do gs ← get_goals, ms.mmap' (λ m, mwhen (bnot <$> (is_assigned m.2)) $ set_goals [m.2] >> when cfg.opt_param (try apply_opt_param) >> when cfg.auto_param (try apply_auto_param)), set_goals gs meta def apply (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) := do r ← apply_core e cfg, try_apply_opt_auto_param_for_apply cfg r, return r /-- Same as `apply` but __all__ arguments that weren't inferred are added to goal list. -/ meta def fapply (e : expr) : tactic (list (name × expr)) := apply e {new_goals := new_goals.all} /-- Same as `apply` but only goals that don't depend on other goals are added to goal list. -/ meta def eapply (e : expr) : tactic (list (name × expr)) := apply e {new_goals := new_goals.non_dep_only} /-- Try to solve the main goal using type class resolution. -/ meta def apply_instance : tactic unit := do tgt ← target >>= instantiate_mvars, b ← is_class tgt, if b then mk_instance tgt >>= exact else fail "apply_instance tactic fail, target is not a type class" /-- Create a list of universe meta-variables of the given size. -/ meta def mk_num_meta_univs : nat → tactic (list level) | 0 := return [] | (succ n) := do l ← mk_meta_univ, ls ← mk_num_meta_univs n, return (l::ls) /-- Return `expr.const c [l_1, ..., l_n]` where l_i's are fresh universe meta-variables. -/ meta def mk_const (c : name) : tactic expr := do env ← get_env, decl ← env.get c, let num := decl.univ_params.length, ls ← mk_num_meta_univs num, return (expr.const c ls) /-- Apply the constant `c` -/ meta def applyc (c : name) (cfg : apply_cfg := {}) : tactic unit := do c ← mk_const c, apply c cfg, skip meta def eapplyc (c : name) : tactic unit := do c ← mk_const c, eapply c, skip meta def save_const_type_info (n : name) {elab : bool} (ref : expr elab) : tactic unit := try (do c ← mk_const n, save_type_info c ref) /-- Create a fresh universe `?u`, a metavariable `?T : Type.{?u}`, and return metavariable `?M : ?T`. This action can be used to create a meta-variable when we don't know its type at creation time -/ meta def mk_mvar : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), mk_meta_var t /-- Makes a sorry macro with a meta-variable as its type. -/ meta def mk_sorry : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), return $ expr.mk_sorry t /-- Closes the main goal using sorry. -/ meta def admit : tactic unit := target >>= exact ∘ expr.mk_sorry meta def mk_local' (pp_name : name) (bi : binder_info) (type : expr) : tactic expr := do uniq_name ← mk_fresh_name, return $ expr.local_const uniq_name pp_name bi type meta def mk_local_def (pp_name : name) (type : expr) : tactic expr := mk_local' pp_name binder_info.default type meta def mk_local_pis : expr → tactic (list expr × expr) | (expr.pi n bi d b) := do p ← mk_local' n bi d, (ps, r) ← mk_local_pis (expr.instantiate_var b p), return ((p :: ps), r) | e := return ([], e) private meta def get_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, new_b ← whnf (expr.instantiate_var b l), r ← get_pi_arity_aux new_b, return (r + 1) | e := return 0 /-- Compute the arity of the given (Pi-)type -/ meta def get_pi_arity (type : expr) : tactic nat := whnf type >>= get_pi_arity_aux /-- Compute the arity of the given function -/ meta def get_arity (fn : expr) : tactic nat := infer_type fn >>= get_pi_arity meta def triv : tactic unit := mk_const `trivial >>= exact notation `dec_trivial` := of_as_true (by tactic.triv) meta def by_contradiction (H : name) : tactic expr := do tgt ← target, tgt_wh ← whnf tgt reducible, -- to ensure that `not` in `ne` is found (match_not tgt_wh $> ()) <|> (mk_mapp `decidable.by_contradiction [some tgt, none] >>= eapply >> skip) <|> (mk_mapp `classical.by_contradiction [some tgt] >>= eapply >> skip) <|> fail "tactic by_contradiction failed, target is not a proposition", intro H private meta def generalizes_aux (md : transparency) : list expr → tactic unit | [] := skip | (e::es) := generalize e `x md >> generalizes_aux es meta def generalizes (es : list expr) (md := semireducible) : tactic unit := generalizes_aux md es private meta def kdependencies_core (e : expr) (md : transparency) : list expr → list expr → tactic (list expr) | [] r := return r | (h::hs) r := do type ← infer_type h, d ← kdepends_on type e md, if d then kdependencies_core hs (h::r) else kdependencies_core hs r /-- Return all hypotheses that depends on `e` The dependency test is performed using `kdepends_on` with the given transparency setting. -/ meta def kdependencies (e : expr) (md := reducible) : tactic (list expr) := do ctx ← local_context, kdependencies_core e md ctx [] /-- Revert all hypotheses that depend on `e` -/ meta def revert_kdependencies (e : expr) (md := reducible) : tactic nat := kdependencies e md >>= revert_lst meta def revert_kdeps (e : expr) (md := reducible) := revert_kdependencies e md /-- Postprocess the output of `cases_core`: - The third component of each tuple in the input list (the list of substitutions) is dropped since we don't use it anywhere. - The second component (the list of new hypotheses) is filtered: any expression that is not a local constant is dropped. We only use the new hypotheses for the renaming functionality of `case`, so we want to keep only those "new hypotheses" that are, in fact, local constants. -/ private meta def cases_postprocess (hs : list (name × list expr × list (name × expr))) : list (name × list expr) := hs.map $ λ ⟨n, hs, _⟩, (n, hs.filter (λ h, h.is_local_constant)) /-- Similar to `cases_core`, but `e` doesn't need to be a hypothesis. Remark, it reverts dependencies using `revert_kdeps`. Two different transparency modes are used `md` and `dmd`. The mode `md` is used with `cases_core` and `dmd` with `generalize` and `revert_kdeps`. It returns the constructor names associated with each new goal and the newly introduced hypotheses. Note that while `cases_core` may return "new hypotheses" that are not local constants, this tactic only returns local constants. -/ meta def cases (e : expr) (ids : list name := []) (md := semireducible) (dmd := semireducible) : tactic (list (name × list expr)) := if e.is_local_constant then do r ← cases_core e ids md, return $ cases_postprocess r else do n ← revert_kdependencies e dmd, x ← get_unused_name, (tactic.generalize e x dmd) <|> (do t ← infer_type e, tactic.assertv x t e, get_local x >>= tactic.revert, return ()), h ← tactic.intro1, focus1 $ do r ← cases_core h ids md, hs' ← all_goals (intron' n), return $ cases_postprocess $ r.map₂ (λ ⟨n, hs, x⟩ hs', (n, hs ++ hs', x)) hs' /-- The same as `exact` except you can add proof holes. -/ meta def refine (e : pexpr) : tactic unit := do tgt : expr ← target, to_expr ``(%%e : %%tgt) tt >>= exact /-- `by_cases p h` splits the main goal into two cases, assuming `h : p` in the first branch, and `h : ¬ p` in the second branch. The expression `p` needs to be a proposition. The produced proof term is `dite p ?m_1 ?m_2`. -/ meta def by_cases (e : expr) (h : name) : tactic unit := do dec_e ← mk_app ``decidable [e] <|> fail "by_cases tactic failed, type is not a proposition", inst ← mk_instance dec_e <|> pure `(classical.prop_decidable %%e), tgt ← target, expr.sort tgt_u ← infer_type tgt >>= whnf, g1 ← mk_meta_var (e.imp tgt), g2 ← mk_meta_var (`(¬ %%e).imp tgt), focus1 $ do exact $ expr.const ``dite [tgt_u] tgt e inst g1 g2, set_goals [g1, g2], all_goals' $ intro h >> skip meta def funext_core : list name → bool → tactic unit | [] tt := return () | ids only_ids := try $ do some (lhs, rhs) ← expr.is_eq <$> (target >>= whnf), applyc `funext, id ← if ids.empty ∨ ids.head = `_ then do (expr.lam n _ _ _) ← whnf lhs | pure `_, return n else return ids.head, intro id, funext_core ids.tail only_ids meta def funext : tactic unit := funext_core [] ff meta def funext_lst (ids : list name) : tactic unit := funext_core ids tt private meta def get_undeclared_const (env : environment) (base : name) : ℕ → name | i := let n := base <.> ("_aux_" ++ repr i) in if ¬env.contains n then n else get_undeclared_const (i+1) meta def new_aux_decl_name : tactic name := do env ← get_env, n ← decl_name, return $ get_undeclared_const env n 1 private meta def mk_aux_decl_name : option name → tactic name | none := new_aux_decl_name | (some suffix) := do p ← decl_name, return $ p ++ suffix meta def abstract (tac : tactic unit) (suffix : option name := none) (zeta_reduce := tt) : tactic unit := do fail_if_no_goals, gs ← get_goals, type ← if zeta_reduce then target >>= zeta else target, is_lemma ← is_prop type, m ← mk_meta_var type, set_goals [m], tac, n ← num_goals, when (n ≠ 0) (fail "abstract tactic failed, there are unsolved goals"), set_goals gs, val ← instantiate_mvars m, val ← if zeta_reduce then zeta val else return val, c ← mk_aux_decl_name suffix, e ← add_aux_decl c type val is_lemma, exact e /-- `solve_aux type tac` synthesize an element of 'type' using tactic 'tac' -/ meta def solve_aux {α : Type} (type : expr) (tac : tactic α) : tactic (α × expr) := do m ← mk_meta_var type, gs ← get_goals, set_goals [m], a ← tac, set_goals gs, return (a, m) /-- Return tt iff 'd' is a declaration in one of the current open namespaces -/ meta def in_open_namespaces (d : name) : tactic bool := do ns ← open_namespaces, env ← get_env, return $ ns.any (λ n, n.is_prefix_of d) && env.contains d /-- Execute tac for 'max' "heartbeats". The heartbeat is approx. the maximum number of memory allocations (in thousands) performed by 'tac'. This is a deterministic way of interrupting long running tactics. -/ meta def try_for {α} (max : nat) (tac : tactic α) : tactic α := λ s, match _root_.try_for max (tac s) with | some r := r | none := mk_exception "try_for tactic failed, timeout" none s end /-- Execute `tac` for `max` milliseconds. Useful due to variance in the number of heartbeats taken by various tactics. -/ meta def try_for_time {α} (max : nat) (tac : tactic α) : tactic α := λ s, match _root_.try_for_time max (tac s) with | some r := r | none := mk_exception "try_for_time tactic failed, timeout" none s end meta def updateex_env (f : environment → exceptional environment) : tactic unit := do env ← get_env, env ← returnex $ f env, set_env env /- Add a new inductive datatype to the environment name, universe parameters, number of parameters, type, constructors (name and type), is_meta -/ meta def add_inductive (n : name) (ls : list name) (p : nat) (ty : expr) (is : list (name × expr)) (is_meta : bool := ff) : tactic unit := updateex_env $ λe, e.add_inductive n ls p ty is is_meta meta def add_meta_definition (n : name) (lvls : list name) (type value : expr) : tactic unit := add_decl (declaration.defn n lvls type value reducibility_hints.abbrev ff) /-- add declaration `d` as a protected declaration -/ meta def add_protected_decl (d : declaration) : tactic unit := updateex_env $ λ e, e.add_protected d /-- check if `n` is the name of a protected declaration -/ meta def is_protected_decl (n : name) : tactic bool := do env ← get_env, return $ env.is_protected n /-- `add_defn_equations` adds a definition specified by a list of equations. The arguments: * `lp`: list of universe parameters * `params`: list of parameters (binders before the colon); * `fn`: a local constant giving the name and type of the declaration (with `params` in the local context); * `eqns`: a list of equations, each of which is a list of patterns (constructors applied to new local constants) and the branch expression; * `is_meta`: is the definition meta? `add_defn_equations` can be used as: do my_add ← mk_local_def `my_add `(ℕ → ℕ), a ← mk_local_def `a ℕ, b ← mk_local_def `b ℕ, add_defn_equations [a] my_add [ ([``(nat.zero)], a), ([``(nat.succ %%b)], my_add b) ]) ff -- non-meta to create the following definition: def my_add (a : ℕ) : ℕ → ℕ | nat.zero := a | (nat.succ b) := my_add b -/ meta def add_defn_equations (lp : list name) (params : list expr) (fn : expr) (eqns : list (list pexpr × expr)) (is_meta : bool) : tactic unit := do opt ← get_options, updateex_env $ λ e, e.add_defn_eqns opt lp params fn eqns is_meta /-- Get the revertible part of the local context. These are the hypotheses that appear after the last frozen local instance in the local context. We call them revertible because `revert` can revert them, unlike those hypotheses which occur before a frozen instance. -/ meta def revertible_local_context : tactic (list expr) := do ctx ← local_context, frozen ← frozen_local_instances, pure $ match frozen with | none := ctx | some [] := ctx | some (h :: _) := ctx.after (eq h) end /-- Rename local hypotheses according to the given `name_map`. The `name_map` contains as keys those hypotheses that should be renamed; the associated values are the new names. This tactic can only rename hypotheses which occur after the last frozen local instance. If you need to rename earlier hypotheses, try `unfreeze_local_instances`. If `strict` is true, we fail if `name_map` refers to hypotheses that do not appear in the local context or that appear before a frozen local instance. Conversely, if `strict` is false, some entries of `name_map` may be silently ignored. If `use_unique_names` is true, the keys of `name_map` should be the unique names of hypotheses to be renamed. Otherwise, the keys should be display names. Note that we allow shadowing, so renamed hypotheses may have the same name as other hypotheses in the context. If `use_unique_names` is false and there are multiple hypotheses with the same display name in the context, they are all renamed. -/ meta def rename_many (renames : name_map name) (strict := tt) (use_unique_names := ff) : tactic unit := do let hyp_name : expr → name := if use_unique_names then expr.local_uniq_name else expr.local_pp_name, ctx ← revertible_local_context, -- The part of the context after (but including) the first hypthesis that -- must be renamed. let ctx_suffix := ctx.drop_while (λ h, (renames.find $ hyp_name h).is_none), when strict $ do { let ctx_names := rb_map.set_of_list (ctx_suffix.map hyp_name), let invalid_renames := (renames.to_list.map prod.fst).filter (λ h, ¬ ctx_names.contains h), when ¬ invalid_renames.empty $ fail $ format.join [ "Cannot rename these hypotheses:\n" , format.join $ (invalid_renames.map to_fmt).intersperse ", " , format.line , "This is because these hypotheses either do not occur in the\n" , "context or they occur before a frozen local instance.\n" , "In the latter case, try `tactic.unfreeze_local_instances`." ] }, -- The new names for all hypotheses in ctx_suffix. let new_names := ctx_suffix.map $ λ h, (renames.find $ hyp_name h).get_or_else h.local_pp_name, revert_lst ctx_suffix, intro_lst new_names, pure () /-- Rename a local hypothesis. This is a special case of `rename_many`; see there for caveats. -/ meta def rename (curr : name) (new : name) : tactic unit := rename_many (rb_map.of_list [⟨curr, new⟩]) /-- Rename a local hypothesis. Unlike `rename` and `rename_many`, this tactic does not preserve the order of hypotheses. Its implementation is simpler (and therefore probably faster) than that of `rename`. -/ meta def rename_unstable (curr : name) (new : name) : tactic unit := do h ← get_local curr, n ← revert h, intro new, intron (n - 1) /-- "Replace" hypothesis `h : type` with `h : new_type` where `eq_pr` is a proof that (type = new_type). The tactic actually creates a new hypothesis with the same user facing name, and (tries to) clear `h`. The `clear` step fails if `h` has forward dependencies. In this case, the old `h` will remain in the local context. The tactic returns the new hypothesis. -/ meta def replace_hyp (h : expr) (new_type : expr) (eq_pr : expr) : tactic expr := do h_type ← infer_type h, new_h ← assert h.local_pp_name new_type, mk_eq_mp eq_pr h >>= exact, try $ clear h, return new_h meta def main_goal : tactic expr := do g::gs ← get_goals, return g /- Goal tagging support -/ meta def with_enable_tags {α : Type} (t : tactic α) (b := tt) : tactic α := do old ← tags_enabled, enable_tags b, r ← t, enable_tags old, return r meta def get_main_tag : tactic tag := main_goal >>= get_tag meta def set_main_tag (t : tag) : tactic unit := do g ← main_goal, set_tag g t meta def subst (h : expr) : tactic unit := (do guard h.is_local_constant, some (α, lhs, β, rhs) ← expr.is_heq <$> infer_type h, is_def_eq α β, new_h_type ← mk_app `eq [lhs, rhs], new_h_pr ← mk_app `eq_of_heq [h], new_h ← assertv h.local_pp_name new_h_type new_h_pr, try (clear h), subst_core new_h) <|> subst_core h end tactic notation [parsing_only] `command`:max := tactic unit open tactic namespace list meta def for_each {α} : list α → (α → tactic unit) → tactic unit | [] fn := skip | (e::es) fn := do fn e, for_each es fn meta def any_of {α β} : list α → (α → tactic β) → tactic β | [] fn := failed | (e::es) fn := do opt_b ← try_core (fn e), match opt_b with | some b := return b | none := any_of es fn end end list /- Install monad laws tactic and use it to prove some instances. -/ /-- Try to prove with `iff.refl`.-/ meta def order_laws_tac := whnf_target >> intros >> to_expr ``(iff.refl _) >>= exact meta def monad_from_pure_bind {m : Type u → Type v} (pure : Π {α : Type u}, α → m α) (bind : Π {α β : Type u}, m α → (α → m β) → m β) : monad m := {pure := @pure, bind := @bind} meta instance : monad task := {map := @task.map, bind := @task.bind, pure := @task.pure} namespace tactic meta def mk_id_proof (prop : expr) (pr : expr) : expr := expr.app (expr.app (expr.const ``id [level.zero]) prop) pr meta def mk_id_eq (lhs : expr) (rhs : expr) (pr : expr) : tactic expr := do prop ← mk_app `eq [lhs, rhs], return $ mk_id_proof prop pr meta def replace_target (new_target : expr) (pr : expr) : tactic unit := do t ← target, assert `htarget new_target, swap, ht ← get_local `htarget, locked_pr ← mk_id_eq t new_target pr, mk_eq_mpr locked_pr ht >>= exact meta def eval_pexpr (α) [reflected α] (e : pexpr) : tactic α := to_expr ``(%%e : %%(reflect α)) ff ff >>= eval_expr α meta def run_simple {α} : tactic_state → tactic α → option α | ts t := match t ts with | (interaction_monad.result.success a ts') := some a | (interaction_monad.result.exception _ _ _) := none end end tactic
93e4c4382ab9bb15f3deca3f0fcf1543de1a4c58
367134ba5a65885e863bdc4507601606690974c1
/src/set_theory/lists.lean
d36334e8112e10722e3d8e8e2d1c413fef8ed43f
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
11,852
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro A computable model of hereditarily finite sets with atoms (ZFA without infinity). This is useful for calculations in naive set theory. -/ import data.list.basic import data.sigma variables {α : Type*} @[derive decidable_eq] inductive {u} lists' (α : Type u) : bool → Type u | atom : α → lists' ff | nil : lists' tt | cons' {b} : lists' b → lists' tt → lists' tt def lists (α : Type*) := Σ b, lists' α b namespace lists' instance [inhabited α] : ∀ b, inhabited (lists' α b) | tt := ⟨nil⟩ | ff := ⟨atom (default _)⟩ def cons : lists α → lists' α tt → lists' α tt | ⟨b, a⟩ l := cons' a l @[simp] def to_list : ∀ {b}, lists' α b → list (lists α) | _ (atom a) := [] | _ nil := [] | _ (cons' a l) := ⟨_, a⟩ :: l.to_list @[simp] theorem to_list_cons (a : lists α) (l) : to_list (cons a l) = a :: l.to_list := by cases a; simp [cons] @[simp] def of_list : list (lists α) → lists' α tt | [] := nil | (a :: l) := cons a (of_list l) @[simp] theorem to_of_list (l : list (lists α)) : to_list (of_list l) = l := by induction l; simp * @[simp] theorem of_to_list : ∀ (l : lists' α tt), of_list (to_list l) = l := suffices ∀ b (h : tt = b) (l : lists' α b), let l' : lists' α tt := by rw h; exact l in of_list (to_list l') = l', from this _ rfl, λ b h l, begin induction l, {cases h}, {exact rfl}, case lists'.cons' : b a l IH₁ IH₂ { intro, change l' with cons' a l, simpa [cons] using IH₂ rfl } end end lists' mutual inductive lists.equiv, lists'.subset with lists.equiv : lists α → lists α → Prop | refl (l) : lists.equiv l l | antisymm {l₁ l₂ : lists' α tt} : lists'.subset l₁ l₂ → lists'.subset l₂ l₁ → lists.equiv ⟨_, l₁⟩ ⟨_, l₂⟩ with lists'.subset : lists' α tt → lists' α tt → Prop | nil {l} : lists'.subset lists'.nil l | cons {a a' l l'} : lists.equiv a a' → a' ∈ lists'.to_list l' → lists'.subset l l' → lists'.subset (lists'.cons a l) l' local infix ~ := lists.equiv namespace lists' instance : has_subset (lists' α tt) := ⟨lists'.subset⟩ instance {b} : has_mem (lists α) (lists' α b) := ⟨λ a l, ∃ a' ∈ l.to_list, a ~ a'⟩ theorem mem_def {b a} {l : lists' α b} : a ∈ l ↔ ∃ a' ∈ l.to_list, a ~ a' := iff.rfl @[simp] theorem mem_cons {a y l} : a ∈ @cons α y l ↔ a ~ y ∨ a ∈ l := by simp [mem_def, or_and_distrib_right, exists_or_distrib] theorem cons_subset {a} {l₁ l₂ : lists' α tt} : lists'.cons a l₁ ⊆ l₂ ↔ a ∈ l₂ ∧ l₁ ⊆ l₂ := begin refine ⟨λ h, _, λ ⟨⟨a', m, e⟩, s⟩, subset.cons e m s⟩, generalize_hyp h' : lists'.cons a l₁ = l₁' at h, cases h with l a' a'' l l' e m s, {cases a, cases h'}, cases a, cases a', cases h', exact ⟨⟨_, m, e⟩, s⟩ end theorem of_list_subset {l₁ l₂ : list (lists α)} (h : l₁ ⊆ l₂) : lists'.of_list l₁ ⊆ lists'.of_list l₂ := begin induction l₁, {exact subset.nil}, refine subset.cons (lists.equiv.refl _) _ (l₁_ih (list.subset_of_cons_subset h)), simp at h, simp [h] end @[refl] theorem subset.refl {l : lists' α tt} : l ⊆ l := by rw ← lists'.of_to_list l; exact of_list_subset (list.subset.refl _) theorem subset_nil {l : lists' α tt} : l ⊆ lists'.nil → l = lists'.nil := begin rw ← of_to_list l, induction to_list l; intro h, {refl}, rcases cons_subset.1 h with ⟨⟨_, ⟨⟩, _⟩, _⟩ end theorem mem_of_subset' {a} {l₁ l₂ : lists' α tt} (s : l₁ ⊆ l₂) (h : a ∈ l₁.to_list) : a ∈ l₂ := begin induction s with _ a a' l l' e m s IH, {cases h}, simp at h, rcases h with rfl|h, exacts [⟨_, m, e⟩, IH h] end theorem subset_def {l₁ l₂ : lists' α tt} : l₁ ⊆ l₂ ↔ ∀ a ∈ l₁.to_list, a ∈ l₂ := ⟨λ H a, mem_of_subset' H, λ H, begin rw ← of_to_list l₁, revert H, induction to_list l₁; intro, { exact subset.nil }, { simp at H, exact cons_subset.2 ⟨H.1, ih H.2⟩ } end⟩ end lists' namespace lists @[pattern] def atom (a : α) : lists α := ⟨_, lists'.atom a⟩ @[pattern] def of' (l : lists' α tt) : lists α := ⟨_, l⟩ @[simp] def to_list : lists α → list (lists α) | ⟨b, l⟩ := l.to_list def is_list (l : lists α) : Prop := l.1 def of_list (l : list (lists α)) : lists α := of' (lists'.of_list l) theorem is_list_to_list (l : list (lists α)) : is_list (of_list l) := eq.refl _ theorem to_of_list (l : list (lists α)) : to_list (of_list l) = l := by simp [of_list, of'] theorem of_to_list : ∀ {l : lists α}, is_list l → of_list (to_list l) = l | ⟨tt, l⟩ _ := by simp [of_list, of'] instance : inhabited (lists α) := ⟨of' lists'.nil⟩ instance [decidable_eq α] : decidable_eq (lists α) := by unfold lists; apply_instance instance [has_sizeof α] : has_sizeof (lists α) := by unfold lists; apply_instance def induction_mut (C : lists α → Sort*) (D : lists' α tt → Sort*) (C0 : ∀ a, C (atom a)) (C1 : ∀ l, D l → C (of' l)) (D0 : D lists'.nil) (D1 : ∀ a l, C a → D l → D (lists'.cons a l)) : pprod (∀ l, C l) (∀ l, D l) := begin suffices : ∀ {b} (l : lists' α b), pprod (C ⟨_, l⟩) (match b, l with | tt, l := D l | ff, l := punit end), { exact ⟨λ ⟨b, l⟩, (this _).1, λ l, (this l).2⟩ }, intros, induction l with a b a l IH₁ IH₂, { exact ⟨C0 _, ⟨⟩⟩ }, { exact ⟨C1 _ D0, D0⟩ }, { suffices, {exact ⟨C1 _ this, this⟩}, exact D1 ⟨_, _⟩ _ IH₁.1 IH₂.2 } end def mem (a : lists α) : lists α → Prop | ⟨ff, l⟩ := false | ⟨tt, l⟩ := a ∈ l instance : has_mem (lists α) (lists α) := ⟨mem⟩ theorem is_list_of_mem {a : lists α} : ∀ {l : lists α}, a ∈ l → is_list l | ⟨_, lists'.nil⟩ _ := rfl | ⟨_, lists'.cons' _ _⟩ _ := rfl theorem equiv.antisymm_iff {l₁ l₂ : lists' α tt} : of' l₁ ~ of' l₂ ↔ l₁ ⊆ l₂ ∧ l₂ ⊆ l₁ := begin refine ⟨λ h, _, λ ⟨h₁, h₂⟩, equiv.antisymm h₁ h₂⟩, cases h with _ _ _ h₁ h₂, { simp [lists'.subset.refl] }, { exact ⟨h₁, h₂⟩ } end attribute [refl] equiv.refl theorem equiv_atom {a} {l : lists α} : atom a ~ l ↔ atom a = l := ⟨λ h, by cases h; refl, λ h, h ▸ equiv.refl _⟩ theorem equiv.symm {l₁ l₂ : lists α} (h : l₁ ~ l₂) : l₂ ~ l₁ := by cases h with _ _ _ h₁ h₂; [refl, exact equiv.antisymm h₂ h₁] theorem equiv.trans : ∀ {l₁ l₂ l₃ : lists α}, l₁ ~ l₂ → l₂ ~ l₃ → l₁ ~ l₃ := begin let trans := λ (l₁ : lists α), ∀ ⦃l₂ l₃⦄, l₁ ~ l₂ → l₂ ~ l₃ → l₁ ~ l₃, suffices : pprod (∀ l₁, trans l₁) (∀ (l : lists' α tt) (l' ∈ l.to_list), trans l'), {exact this.1}, apply induction_mut, { intros a l₂ l₃ h₁ h₂, rwa ← equiv_atom.1 h₁ at h₂ }, { intros l₁ IH l₂ l₃ h₁ h₂, cases h₁ with _ _ l₂, {exact h₂}, cases h₂ with _ _ l₃, {exact h₁}, cases equiv.antisymm_iff.1 h₁ with hl₁ hr₁, cases equiv.antisymm_iff.1 h₂ with hl₂ hr₂, apply equiv.antisymm_iff.2; split; apply lists'.subset_def.2, { intros a₁ m₁, rcases lists'.mem_of_subset' hl₁ m₁ with ⟨a₂, m₂, e₁₂⟩, rcases lists'.mem_of_subset' hl₂ m₂ with ⟨a₃, m₃, e₂₃⟩, exact ⟨a₃, m₃, IH _ m₁ e₁₂ e₂₃⟩ }, { intros a₃ m₃, rcases lists'.mem_of_subset' hr₂ m₃ with ⟨a₂, m₂, e₃₂⟩, rcases lists'.mem_of_subset' hr₁ m₂ with ⟨a₁, m₁, e₂₁⟩, exact ⟨a₁, m₁, (IH _ m₁ e₂₁.symm e₃₂.symm).symm⟩ } }, { rintro _ ⟨⟩ }, { intros a l IH₁ IH₂, simpa [IH₁] using IH₂ } end instance : setoid (lists α) := ⟨(~), equiv.refl, @equiv.symm _, @equiv.trans _⟩ section decidable @[simp] def equiv.decidable_meas : (psum (Σ' (l₁ : lists α), lists α) $ psum (Σ' (l₁ : lists' α tt), lists' α tt) Σ' (a : lists α), lists' α tt) → ℕ | (psum.inl ⟨l₁, l₂⟩) := sizeof l₁ + sizeof l₂ | (psum.inr $ psum.inl ⟨l₁, l₂⟩) := sizeof l₁ + sizeof l₂ | (psum.inr $ psum.inr ⟨l₁, l₂⟩) := sizeof l₁ + sizeof l₂ open well_founded_tactics theorem sizeof_pos {b} (l : lists' α b) : 0 < sizeof l := by cases l; unfold_sizeof; trivial_nat_lt theorem lt_sizeof_cons' {b} (a : lists' α b) (l) : sizeof (⟨b, a⟩ : lists α) < sizeof (lists'.cons' a l) := by {unfold_sizeof, apply sizeof_pos} @[instance] mutual def equiv.decidable, subset.decidable, mem.decidable [decidable_eq α] with equiv.decidable : ∀ l₁ l₂ : lists α, decidable (l₁ ~ l₂) | ⟨ff, l₁⟩ ⟨ff, l₂⟩ := decidable_of_iff' (l₁ = l₂) $ by cases l₁; refine equiv_atom.trans (by simp [atom]) | ⟨ff, l₁⟩ ⟨tt, l₂⟩ := is_false $ by rintro ⟨⟩ | ⟨tt, l₁⟩ ⟨ff, l₂⟩ := is_false $ by rintro ⟨⟩ | ⟨tt, l₁⟩ ⟨tt, l₂⟩ := begin haveI := have sizeof l₁ + sizeof l₂ < sizeof (⟨tt, l₁⟩ : lists α) + sizeof (⟨tt, l₂⟩ : lists α), by default_dec_tac, subset.decidable l₁ l₂, haveI := have sizeof l₂ + sizeof l₁ < sizeof (⟨tt, l₁⟩ : lists α) + sizeof (⟨tt, l₂⟩ : lists α), by default_dec_tac, subset.decidable l₂ l₁, exact decidable_of_iff' _ equiv.antisymm_iff, end with subset.decidable : ∀ l₁ l₂ : lists' α tt, decidable (l₁ ⊆ l₂) | lists'.nil l₂ := is_true subset.nil | (@lists'.cons' _ b a l₁) l₂ := begin haveI := have sizeof (⟨b, a⟩ : lists α) + sizeof l₂ < sizeof (lists'.cons' a l₁) + sizeof l₂, from add_lt_add_right (lt_sizeof_cons' _ _) _, mem.decidable ⟨b, a⟩ l₂, haveI := have sizeof l₁ + sizeof l₂ < sizeof (lists'.cons' a l₁) + sizeof l₂, by default_dec_tac, subset.decidable l₁ l₂, exact decidable_of_iff' _ (@lists'.cons_subset _ ⟨_, _⟩ _ _) end with mem.decidable : ∀ (a : lists α) (l : lists' α tt), decidable (a ∈ l) | a lists'.nil := is_false $ by rintro ⟨_, ⟨⟩, _⟩ | a (lists'.cons' b l₂) := begin haveI := have sizeof a + sizeof (⟨_, b⟩ : lists α) < sizeof a + sizeof (lists'.cons' b l₂), from add_lt_add_left (lt_sizeof_cons' _ _) _, equiv.decidable a ⟨_, b⟩, haveI := have sizeof a + sizeof l₂ < sizeof a + sizeof (lists'.cons' b l₂), by default_dec_tac, mem.decidable a l₂, refine decidable_of_iff' (a ~ ⟨_, b⟩ ∨ a ∈ l₂) _, rw ← lists'.mem_cons, refl end using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf equiv.decidable_meas⟩], dec_tac := `[assumption] } end decidable end lists namespace lists' theorem mem_equiv_left {l : lists' α tt} : ∀ {a a'}, a ~ a' → (a ∈ l ↔ a' ∈ l) := suffices ∀ {a a'}, a ~ a' → a ∈ l → a' ∈ l, from λ a a' e, ⟨this e, this e.symm⟩, λ a₁ a₂ e₁ ⟨a₃, m₃, e₂⟩, ⟨_, m₃, e₁.symm.trans e₂⟩ theorem mem_of_subset {a} {l₁ l₂ : lists' α tt} (s : l₁ ⊆ l₂) : a ∈ l₁ → a ∈ l₂ | ⟨a', m, e⟩ := (mem_equiv_left e).2 (mem_of_subset' s m) theorem subset.trans {l₁ l₂ l₃ : lists' α tt} (h₁ : l₁ ⊆ l₂) (h₂ : l₂ ⊆ l₃) : l₁ ⊆ l₃ := subset_def.2 $ λ a₁ m₁, mem_of_subset h₂ $ mem_of_subset' h₁ m₁ end lists' def finsets (α : Type*) := quotient (@lists.setoid α) namespace finsets instance : has_emptyc (finsets α) := ⟨⟦lists.of' lists'.nil⟧⟩ instance : inhabited (finsets α) := ⟨∅⟩ instance [decidable_eq α] : decidable_eq (finsets α) := by unfold finsets; apply_instance end finsets
906c17c6a53de609ff07700b7585d377a2a8aa58
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/order/filter/bases.lean
705e18f6a6d0faf7d04e22462d262a3507eb8d00
[ "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
38,221
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import order.filter.basic import data.set.countable import data.pprod /-! # Filter bases A filter basis `B : filter_basis α` on a type `α` is a nonempty collection of sets of `α` such that the intersection of two elements of this collection contains some element of the collection. Compared to filters, filter bases do not require that any set containing an element of `B` belongs to `B`. A filter basis `B` can be used to construct `B.filter : filter α` such that a set belongs to `B.filter` if and only if it contains an element of `B`. Given an indexing type `ι`, a predicate `p : ι → Prop`, and a map `s : ι → set α`, the proposition `h : filter.is_basis p s` makes sure the range of `s` bounded by `p` (ie. `s '' set_of p`) defines a filter basis `h.filter_basis`. If one already has a filter `l` on `α`, `filter.has_basis l p s` (where `p : ι → Prop` and `s : ι → set α` as above) means that a set belongs to `l` if and only if it contains some `s i` with `p i`. It implies `h : filter.is_basis p s`, and `l = h.filter_basis.filter`. The point of this definition is that checking statements involving elements of `l` often reduces to checking them on the basis elements. We define a function `has_basis.index (h : filter.has_basis l p s) (t) (ht : t ∈ l)` that returns some index `i` such that `p i` and `s i ⊆ t`. This function can be useful to avoid manual destruction of `h.mem_iff.mpr ht` using `cases` or `let`. This file also introduces more restricted classes of bases, involving monotonicity or countability. In particular, for `l : filter α`, `l.is_countably_generated` means there is a countable set of sets which generates `s`. This is reformulated in term of bases, and consequences are derived. ## Main statements * `has_basis.mem_iff`, `has_basis.mem_of_superset`, `has_basis.mem_of_mem` : restate `t ∈ f` in terms of a basis; * `basis_sets` : all sets of a filter form a basis; * `has_basis.inf`, `has_basis.inf_principal`, `has_basis.prod`, `has_basis.prod_self`, `has_basis.map`, `has_basis.comap` : combinators to construct filters of `l ⊓ l'`, `l ⊓ 𝓟 t`, `l ×ᶠ l'`, `l ×ᶠ l`, `l.map f`, `l.comap f` respectively; * `has_basis.le_iff`, `has_basis.ge_iff`, has_basis.le_basis_iff` : restate `l ≤ l'` in terms of bases. * `has_basis.tendsto_right_iff`, `has_basis.tendsto_left_iff`, `has_basis.tendsto_iff` : restate `tendsto f l l'` in terms of bases. * `is_countably_generated_iff_exists_antitone_basis` : proves a filter is countably generated if and only if it admits a basis parametrized by a decreasing sequence of sets indexed by `ℕ`. * `tendsto_iff_seq_tendsto ` : an abstract version of "sequentially continuous implies continuous". ## Implementation notes As with `Union`/`bUnion`/`sUnion`, there are three different approaches to filter bases: * `has_basis l s`, `s : set (set α)`; * `has_basis l s`, `s : ι → set α`; * `has_basis l p s`, `p : ι → Prop`, `s : ι → set α`. We use the latter one because, e.g., `𝓝 x` in an `emetric_space` or in a `metric_space` has a basis of this form. The other two can be emulated using `s = id` or `p = λ _, true`. With this approach sometimes one needs to `simp` the statement provided by the `has_basis` machinery, e.g., `simp only [exists_prop, true_and]` or `simp only [forall_const]` can help with the case `p = λ _, true`. -/ open set filter open_locale filter classical section sort variables {α β γ : Type*} {ι ι' : Sort*} /-- A filter basis `B` on a type `α` is a nonempty collection of sets of `α` such that the intersection of two elements of this collection contains some element of the collection. -/ structure filter_basis (α : Type*) := (sets : set (set α)) (nonempty : sets.nonempty) (inter_sets {x y} : x ∈ sets → y ∈ sets → ∃ z ∈ sets, z ⊆ x ∩ y) instance filter_basis.nonempty_sets (B : filter_basis α) : nonempty B.sets := B.nonempty.to_subtype /-- If `B` is a filter basis on `α`, and `U` a subset of `α` then we can write `U ∈ B` as on paper. -/ @[reducible] instance {α : Type*}: has_mem (set α) (filter_basis α) := ⟨λ U B, U ∈ B.sets⟩ -- For illustration purposes, the filter basis defining (at_top : filter ℕ) instance : inhabited (filter_basis ℕ) := ⟨{ sets := range Ici, nonempty := ⟨Ici 0, mem_range_self 0⟩, inter_sets := begin rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, refine ⟨Ici (max n m), mem_range_self _, _⟩, rintros p p_in, split ; rw mem_Ici at *, exact le_of_max_le_left p_in, exact le_of_max_le_right p_in, end }⟩ /-- `is_basis p s` means the image of `s` bounded by `p` is a filter basis. -/ protected structure filter.is_basis (p : ι → Prop) (s : ι → set α) : Prop := (nonempty : ∃ i, p i) (inter : ∀ {i j}, p i → p j → ∃ k, p k ∧ s k ⊆ s i ∩ s j) namespace filter namespace is_basis /-- Constructs a filter basis from an indexed family of sets satisfying `is_basis`. -/ protected def filter_basis {p : ι → Prop} {s : ι → set α} (h : is_basis p s) : filter_basis α := { sets := {t | ∃ i, p i ∧ s i = t}, nonempty := let ⟨i, hi⟩ := h.nonempty in ⟨s i, ⟨i, hi, rfl⟩⟩, inter_sets := by { rintros _ _ ⟨i, hi, rfl⟩ ⟨j, hj, rfl⟩, rcases h.inter hi hj with ⟨k, hk, hk'⟩, exact ⟨_, ⟨k, hk, rfl⟩, hk'⟩ } } variables {p : ι → Prop} {s : ι → set α} (h : is_basis p s) lemma mem_filter_basis_iff {U : set α} : U ∈ h.filter_basis ↔ ∃ i, p i ∧ s i = U := iff.rfl end is_basis end filter namespace filter_basis /-- The filter associated to a filter basis. -/ protected def filter (B : filter_basis α) : filter α := { sets := {s | ∃ t ∈ B, t ⊆ s}, univ_sets := let ⟨s, s_in⟩ := B.nonempty in ⟨s, s_in, s.subset_univ⟩, sets_of_superset := λ x y ⟨s, s_in, h⟩ hxy, ⟨s, s_in, set.subset.trans h hxy⟩, inter_sets := λ x y ⟨s, s_in, hs⟩ ⟨t, t_in, ht⟩, let ⟨u, u_in, u_sub⟩ := B.inter_sets s_in t_in in ⟨u, u_in, set.subset.trans u_sub $ set.inter_subset_inter hs ht⟩ } lemma mem_filter_iff (B : filter_basis α) {U : set α} : U ∈ B.filter ↔ ∃ s ∈ B, s ⊆ U := iff.rfl lemma mem_filter_of_mem (B : filter_basis α) {U : set α} : U ∈ B → U ∈ B.filter:= λ U_in, ⟨U, U_in, subset.refl _⟩ lemma eq_infi_principal (B : filter_basis α) : B.filter = ⨅ s : B.sets, 𝓟 s := begin have : directed (≥) (λ (s : B.sets), 𝓟 (s : set α)), { rintros ⟨U, U_in⟩ ⟨V, V_in⟩, rcases B.inter_sets U_in V_in with ⟨W, W_in, W_sub⟩, use [W, W_in], finish }, ext U, simp [mem_filter_iff, mem_infi_of_directed this] end protected lemma generate (B : filter_basis α) : generate B.sets = B.filter := begin apply le_antisymm, { intros U U_in, rcases B.mem_filter_iff.mp U_in with ⟨V, V_in, h⟩, exact generate_sets.superset (generate_sets.basic V_in) h }, { rw sets_iff_generate, apply mem_filter_of_mem } end end filter_basis namespace filter namespace is_basis variables {p : ι → Prop} {s : ι → set α} /-- Constructs a filter from an indexed family of sets satisfying `is_basis`. -/ protected def filter (h : is_basis p s) : filter α := h.filter_basis.filter protected lemma mem_filter_iff (h : is_basis p s) {U : set α} : U ∈ h.filter ↔ ∃ i, p i ∧ s i ⊆ U := begin erw [h.filter_basis.mem_filter_iff], simp only [mem_filter_basis_iff h, exists_prop], split, { rintros ⟨_, ⟨i, pi, rfl⟩, h⟩, tauto }, { tauto } end lemma filter_eq_generate (h : is_basis p s) : h.filter = generate {U | ∃ i, p i ∧ s i = U} := by erw h.filter_basis.generate ; refl end is_basis /-- We say that a filter `l` has a basis `s : ι → set α` bounded by `p : ι → Prop`, if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`. -/ protected structure has_basis (l : filter α) (p : ι → Prop) (s : ι → set α) : Prop := (mem_iff' : ∀ (t : set α), t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t) section same_type variables {l l' : filter α} {p : ι → Prop} {s : ι → set α} {t : set α} {i : ι} {p' : ι' → Prop} {s' : ι' → set α} {i' : ι'} lemma has_basis_generate (s : set (set α)) : (generate s).has_basis (λ t, finite t ∧ t ⊆ s) (λ t, ⋂₀ t) := ⟨begin intro U, rw mem_generate_iff, apply exists_congr, tauto end⟩ /-- The smallest filter basis containing a given collection of sets. -/ def filter_basis.of_sets (s : set (set α)) : filter_basis α := { sets := sInter '' { t | finite t ∧ t ⊆ s}, nonempty := ⟨univ, ∅, ⟨⟨finite_empty, empty_subset s⟩, sInter_empty⟩⟩, inter_sets := begin rintros _ _ ⟨a, ⟨fina, suba⟩, rfl⟩ ⟨b, ⟨finb, subb⟩, rfl⟩, exact ⟨⋂₀ (a ∪ b), mem_image_of_mem _ ⟨fina.union finb, union_subset suba subb⟩, by rw sInter_union⟩, end } /-- Definition of `has_basis` unfolded with implicit set argument. -/ lemma has_basis.mem_iff (hl : l.has_basis p s) : t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t := hl.mem_iff' t lemma has_basis.eq_of_same_basis (hl : l.has_basis p s) (hl' : l'.has_basis p s) : l = l' := begin ext t, rw [hl.mem_iff, hl'.mem_iff] end lemma has_basis_iff : l.has_basis p s ↔ ∀ t, t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t := ⟨λ ⟨h⟩, h, λ h, ⟨h⟩⟩ lemma has_basis.ex_mem (h : l.has_basis p s) : ∃ i, p i := let ⟨i, pi, h⟩ := h.mem_iff.mp univ_mem in ⟨i, pi⟩ protected lemma has_basis.nonempty (h : l.has_basis p s) : nonempty ι := nonempty_of_exists h.ex_mem protected lemma is_basis.has_basis (h : is_basis p s) : has_basis h.filter p s := ⟨λ t, by simp only [h.mem_filter_iff, exists_prop]⟩ lemma has_basis.mem_of_superset (hl : l.has_basis p s) (hi : p i) (ht : s i ⊆ t) : t ∈ l := (hl.mem_iff).2 ⟨i, hi, ht⟩ lemma has_basis.mem_of_mem (hl : l.has_basis p s) (hi : p i) : s i ∈ l := hl.mem_of_superset hi $ subset.refl _ /-- Index of a basis set such that `s i ⊆ t` as an element of `subtype p`. -/ noncomputable def has_basis.index (h : l.has_basis p s) (t : set α) (ht : t ∈ l) : {i : ι // p i} := ⟨(h.mem_iff.1 ht).some, (h.mem_iff.1 ht).some_spec.fst⟩ lemma has_basis.property_index (h : l.has_basis p s) (ht : t ∈ l) : p (h.index t ht) := (h.index t ht).2 lemma has_basis.set_index_mem (h : l.has_basis p s) (ht : t ∈ l) : s (h.index t ht) ∈ l := h.mem_of_mem $ h.property_index _ lemma has_basis.set_index_subset (h : l.has_basis p s) (ht : t ∈ l) : s (h.index t ht) ⊆ t := (h.mem_iff.1 ht).some_spec.snd lemma has_basis.is_basis (h : l.has_basis p s) : is_basis p s := { nonempty := let ⟨i, hi, H⟩ := h.mem_iff.mp univ_mem in ⟨i, hi⟩, inter := λ i j hi hj, by simpa [h.mem_iff] using l.inter_sets (h.mem_of_mem hi) (h.mem_of_mem hj) } lemma has_basis.filter_eq (h : l.has_basis p s) : h.is_basis.filter = l := by { ext U, simp [h.mem_iff, is_basis.mem_filter_iff] } lemma has_basis.eq_generate (h : l.has_basis p s) : l = generate { U | ∃ i, p i ∧ s i = U } := by rw [← h.is_basis.filter_eq_generate, h.filter_eq] lemma generate_eq_generate_inter (s : set (set α)) : generate s = generate (sInter '' { t | finite t ∧ t ⊆ s}) := by erw [(filter_basis.of_sets s).generate, ← (has_basis_generate s).filter_eq] ; refl lemma of_sets_filter_eq_generate (s : set (set α)) : (filter_basis.of_sets s).filter = generate s := by rw [← (filter_basis.of_sets s).generate, generate_eq_generate_inter s] ; refl protected lemma _root_.filter_basis.has_basis {α : Type*} (B : filter_basis α) : has_basis (B.filter) (λ s : set α, s ∈ B) id := ⟨λ t, B.mem_filter_iff⟩ lemma has_basis.to_has_basis' (hl : l.has_basis p s) (h : ∀ i, p i → ∃ i', p' i' ∧ s' i' ⊆ s i) (h' : ∀ i', p' i' → s' i' ∈ l) : l.has_basis p' s' := begin refine ⟨λ t, ⟨λ ht, _, λ ⟨i', hi', ht⟩, mem_of_superset (h' i' hi') ht⟩⟩, rcases hl.mem_iff.1 ht with ⟨i, hi, ht⟩, rcases h i hi with ⟨i', hi', hs's⟩, exact ⟨i', hi', subset.trans hs's ht⟩ end lemma has_basis.to_has_basis (hl : l.has_basis p s) (h : ∀ i, p i → ∃ i', p' i' ∧ s' i' ⊆ s i) (h' : ∀ i', p' i' → ∃ i, p i ∧ s i ⊆ s' i') : l.has_basis p' s' := hl.to_has_basis' h $ λ i' hi', let ⟨i, hi, hss'⟩ := h' i' hi' in hl.mem_iff.2 ⟨i, hi, hss'⟩ lemma has_basis.to_subset (hl : l.has_basis p s) {t : ι → set α} (h : ∀ i, p i → t i ⊆ s i) (ht : ∀ i, p i → t i ∈ l) : l.has_basis p t := hl.to_has_basis' (λ i hi, ⟨i, hi, h i hi⟩) ht lemma has_basis.eventually_iff (hl : l.has_basis p s) {q : α → Prop} : (∀ᶠ x in l, q x) ↔ ∃ i, p i ∧ ∀ ⦃x⦄, x ∈ s i → q x := by simpa using hl.mem_iff lemma has_basis.frequently_iff (hl : l.has_basis p s) {q : α → Prop} : (∃ᶠ x in l, q x) ↔ ∀ i, p i → ∃ x ∈ s i, q x := by simp [filter.frequently, hl.eventually_iff] lemma has_basis.exists_iff (hl : l.has_basis p s) {P : set α → Prop} (mono : ∀ ⦃s t⦄, s ⊆ t → P t → P s) : (∃ s ∈ l, P s) ↔ ∃ (i) (hi : p i), P (s i) := ⟨λ ⟨s, hs, hP⟩, let ⟨i, hi, his⟩ := hl.mem_iff.1 hs in ⟨i, hi, mono his hP⟩, λ ⟨i, hi, hP⟩, ⟨s i, hl.mem_of_mem hi, hP⟩⟩ lemma has_basis.forall_iff (hl : l.has_basis p s) {P : set α → Prop} (mono : ∀ ⦃s t⦄, s ⊆ t → P s → P t) : (∀ s ∈ l, P s) ↔ ∀ i, p i → P (s i) := ⟨λ H i hi, H (s i) $ hl.mem_of_mem hi, λ H s hs, let ⟨i, hi, his⟩ := hl.mem_iff.1 hs in mono his (H i hi)⟩ lemma has_basis.ne_bot_iff (hl : l.has_basis p s) : ne_bot l ↔ (∀ {i}, p i → (s i).nonempty) := forall_mem_nonempty_iff_ne_bot.symm.trans $ hl.forall_iff $ λ _ _, nonempty.mono lemma has_basis.eq_bot_iff (hl : l.has_basis p s) : l = ⊥ ↔ ∃ i, p i ∧ s i = ∅ := not_iff_not.1 $ ne_bot_iff.symm.trans $ hl.ne_bot_iff.trans $ by simp only [not_exists, not_and, ← ne_empty_iff_nonempty] lemma basis_sets (l : filter α) : l.has_basis (λ s : set α, s ∈ l) id := ⟨λ t, exists_mem_subset_iff.symm⟩ lemma has_basis_self {l : filter α} {P : set α → Prop} : has_basis l (λ s, s ∈ l ∧ P s) id ↔ ∀ t ∈ l, ∃ r ∈ l, P r ∧ r ⊆ t := begin simp only [has_basis_iff, exists_prop, id, and_assoc], exact forall_congr (λ s, ⟨λ h, h.1, λ h, ⟨h, λ ⟨t, hl, hP, hts⟩, mem_of_superset hl hts⟩⟩) end /-- If `{s i | p i}` is a basis of a filter `l` and each `s i` includes `s j` such that `p j ∧ q j`, then `{s j | p j ∧ q j}` is a basis of `l`. -/ lemma has_basis.restrict (h : l.has_basis p s) {q : ι → Prop} (hq : ∀ i, p i → ∃ j, p j ∧ q j ∧ s j ⊆ s i) : l.has_basis (λ i, p i ∧ q i) s := begin refine ⟨λ t, ⟨λ ht, _, λ ⟨i, hpi, hti⟩, h.mem_iff.2 ⟨i, hpi.1, hti⟩⟩⟩, rcases h.mem_iff.1 ht with ⟨i, hpi, hti⟩, rcases hq i hpi with ⟨j, hpj, hqj, hji⟩, exact ⟨j, ⟨hpj, hqj⟩, subset.trans hji hti⟩ end /-- If `{s i | p i}` is a basis of a filter `l` and `V ∈ l`, then `{s i | p i ∧ s i ⊆ V}` is a basis of `l`. -/ lemma has_basis.restrict_subset (h : l.has_basis p s) {V : set α} (hV : V ∈ l) : l.has_basis (λ i, p i ∧ s i ⊆ V) s := h.restrict $ λ i hi, (h.mem_iff.1 (inter_mem hV (h.mem_of_mem hi))).imp $ λ j hj, ⟨hj.fst, subset_inter_iff.1 hj.snd⟩ lemma has_basis.has_basis_self_subset {p : set α → Prop} (h : l.has_basis (λ s, s ∈ l ∧ p s) id) {V : set α} (hV : V ∈ l) : l.has_basis (λ s, s ∈ l ∧ p s ∧ s ⊆ V) id := by simpa only [and_assoc] using h.restrict_subset hV theorem has_basis.ge_iff (hl' : l'.has_basis p' s') : l ≤ l' ↔ ∀ i', p' i' → s' i' ∈ l := ⟨λ h i' hi', h $ hl'.mem_of_mem hi', λ h s hs, let ⟨i', hi', hs⟩ := hl'.mem_iff.1 hs in mem_of_superset (h _ hi') hs⟩ theorem has_basis.le_iff (hl : l.has_basis p s) : l ≤ l' ↔ ∀ t ∈ l', ∃ i (hi : p i), s i ⊆ t := by simp only [le_def, hl.mem_iff] theorem has_basis.le_basis_iff (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : l ≤ l' ↔ ∀ i', p' i' → ∃ i (hi : p i), s i ⊆ s' i' := by simp only [hl'.ge_iff, hl.mem_iff] lemma has_basis.ext (hl : l.has_basis p s) (hl' : l'.has_basis p' s') (h : ∀ i, p i → ∃ i', p' i' ∧ s' i' ⊆ s i) (h' : ∀ i', p' i' → ∃ i, p i ∧ s i ⊆ s' i') : l = l' := begin apply le_antisymm, { rw hl.le_basis_iff hl', simpa using h' }, { rw hl'.le_basis_iff hl, simpa using h }, end lemma has_basis.inf' (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : (l ⊓ l').has_basis (λ i : pprod ι ι', p i.1 ∧ p' i.2) (λ i, s i.1 ∩ s' i.2) := ⟨begin intro t, split, { simp only [mem_inf_iff, exists_prop, hl.mem_iff, hl'.mem_iff], rintros ⟨t, ⟨i, hi, ht⟩, t', ⟨i', hi', ht'⟩, rfl⟩, use [⟨i, i'⟩, ⟨hi, hi'⟩, inter_subset_inter ht ht'] }, { rintros ⟨⟨i, i'⟩, ⟨hi, hi'⟩, H⟩, exact mem_inf_of_inter (hl.mem_of_mem hi) (hl'.mem_of_mem hi') H } end⟩ lemma has_basis.inf {ι ι' : Type*} {p : ι → Prop} {s : ι → set α} {p' : ι' → Prop} {s' : ι' → set α} (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : (l ⊓ l').has_basis (λ i : ι × ι', p i.1 ∧ p' i.2) (λ i, s i.1 ∩ s' i.2) := (hl.inf' hl').to_has_basis (λ i hi, ⟨⟨i.1, i.2⟩, hi, subset.rfl⟩) (λ i hi, ⟨⟨i.1, i.2⟩, hi, subset.rfl⟩) lemma has_basis_principal (t : set α) : (𝓟 t).has_basis (λ i : unit, true) (λ i, t) := ⟨λ U, by simp⟩ lemma has_basis_pure (x : α) : (pure x : filter α).has_basis (λ i : unit, true) (λ i, {x}) := by simp only [← principal_singleton, has_basis_principal] lemma has_basis.sup' (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : (l ⊔ l').has_basis (λ i : pprod ι ι', p i.1 ∧ p' i.2) (λ i, s i.1 ∪ s' i.2) := ⟨begin intros t, simp only [mem_sup, hl.mem_iff, hl'.mem_iff, pprod.exists, union_subset_iff, exists_prop, and_assoc, exists_and_distrib_left], simp only [← and_assoc, exists_and_distrib_right, and_comm] end⟩ lemma has_basis.sup {ι ι' : Type*} {p : ι → Prop} {s : ι → set α} {p' : ι' → Prop} {s' : ι' → set α} (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : (l ⊔ l').has_basis (λ i : ι × ι', p i.1 ∧ p' i.2) (λ i, s i.1 ∪ s' i.2) := (hl.sup' hl').to_has_basis (λ i hi, ⟨⟨i.1, i.2⟩, hi, subset.rfl⟩) (λ i hi, ⟨⟨i.1, i.2⟩, hi, subset.rfl⟩) lemma has_basis_supr {ι : Sort*} {ι' : ι → Type*} {l : ι → filter α} {p : Π i, ι' i → Prop} {s : Π i, ι' i → set α} (hl : ∀ i, (l i).has_basis (p i) (s i)) : (⨆ i, l i).has_basis (λ f : Π i, ι' i, ∀ i, p i (f i)) (λ f : Π i, ι' i, ⋃ i, s i (f i)) := has_basis_iff.mpr $ λ t, by simp only [has_basis_iff, (hl _).mem_iff, classical.skolem, forall_and_distrib, Union_subset_iff, mem_supr] lemma has_basis.sup_principal (hl : l.has_basis p s) (t : set α) : (l ⊔ 𝓟 t).has_basis p (λ i, s i ∪ t) := ⟨λ u, by simp only [(hl.sup' (has_basis_principal t)).mem_iff, pprod.exists, exists_prop, and_true, unique.exists_iff]⟩ lemma has_basis.sup_pure (hl : l.has_basis p s) (x : α) : (l ⊔ pure x).has_basis p (λ i, s i ∪ {x}) := by simp only [← principal_singleton, hl.sup_principal] lemma has_basis.inf_principal (hl : l.has_basis p s) (s' : set α) : (l ⊓ 𝓟 s').has_basis p (λ i, s i ∩ s') := ⟨λ t, by simp only [mem_inf_principal, hl.mem_iff, subset_def, mem_set_of_eq, mem_inter_iff, and_imp]⟩ lemma has_basis.inf_basis_ne_bot_iff (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : ne_bot (l ⊓ l') ↔ ∀ ⦃i⦄ (hi : p i) ⦃i'⦄ (hi' : p' i'), (s i ∩ s' i').nonempty := (hl.inf' hl').ne_bot_iff.trans $ by simp [@forall_swap _ ι'] lemma has_basis.inf_ne_bot_iff (hl : l.has_basis p s) : ne_bot (l ⊓ l') ↔ ∀ ⦃i⦄ (hi : p i) ⦃s'⦄ (hs' : s' ∈ l'), (s i ∩ s').nonempty := hl.inf_basis_ne_bot_iff l'.basis_sets lemma has_basis.inf_principal_ne_bot_iff (hl : l.has_basis p s) {t : set α} : ne_bot (l ⊓ 𝓟 t) ↔ ∀ ⦃i⦄ (hi : p i), (s i ∩ t).nonempty := (hl.inf_principal t).ne_bot_iff lemma inf_ne_bot_iff : ne_bot (l ⊓ l') ↔ ∀ ⦃s : set α⦄ (hs : s ∈ l) ⦃s'⦄ (hs' : s' ∈ l'), (s ∩ s').nonempty := l.basis_sets.inf_ne_bot_iff lemma inf_principal_ne_bot_iff {s : set α} : ne_bot (l ⊓ 𝓟 s) ↔ ∀ U ∈ l, (U ∩ s).nonempty := l.basis_sets.inf_principal_ne_bot_iff lemma inf_eq_bot_iff {f g : filter α} : f ⊓ g = ⊥ ↔ ∃ (U ∈ f) (V ∈ g), U ∩ V = ∅ := not_iff_not.1 $ ne_bot_iff.symm.trans $ inf_ne_bot_iff.trans $ by simp [← ne_empty_iff_nonempty] protected lemma disjoint_iff {f g : filter α} : disjoint f g ↔ ∃ (U ∈ f) (V ∈ g), U ∩ V = ∅ := disjoint_iff.trans inf_eq_bot_iff lemma mem_iff_inf_principal_compl {f : filter α} {s : set α} : s ∈ f ↔ f ⊓ 𝓟 sᶜ = ⊥ := begin refine not_iff_not.1 ((inf_principal_ne_bot_iff.trans _).symm.trans ne_bot_iff), exact ⟨λ h hs, by simpa [empty_not_nonempty] using h s hs, λ hs t ht, inter_compl_nonempty_iff.2 $ λ hts, hs $ mem_of_superset ht hts⟩, end lemma not_mem_iff_inf_principal_compl {f : filter α} {s : set α} : s ∉ f ↔ ne_bot (f ⊓ 𝓟 sᶜ) := (not_congr mem_iff_inf_principal_compl).trans ne_bot_iff.symm lemma mem_iff_disjoint_principal_compl {f : filter α} {s : set α} : s ∈ f ↔ disjoint f (𝓟 sᶜ) := mem_iff_inf_principal_compl.trans disjoint_iff.symm lemma le_iff_forall_disjoint_principal_compl {f g : filter α} : f ≤ g ↔ ∀ V ∈ g, disjoint f (𝓟 Vᶜ) := forall_congr $ λ _, forall_congr $ λ _, mem_iff_disjoint_principal_compl lemma le_iff_forall_inf_principal_compl {f g : filter α} : f ≤ g ↔ ∀ V ∈ g, f ⊓ 𝓟 Vᶜ = ⊥ := forall_congr $ λ _, forall_congr $ λ _, mem_iff_inf_principal_compl lemma inf_ne_bot_iff_frequently_left {f g : filter α} : ne_bot (f ⊓ g) ↔ ∀ {p : α → Prop}, (∀ᶠ x in f, p x) → ∃ᶠ x in g, p x := by simpa only [inf_ne_bot_iff, frequently_iff, exists_prop, and_comm] lemma inf_ne_bot_iff_frequently_right {f g : filter α} : ne_bot (f ⊓ g) ↔ ∀ {p : α → Prop}, (∀ᶠ x in g, p x) → ∃ᶠ x in f, p x := by { rw inf_comm, exact inf_ne_bot_iff_frequently_left } lemma has_basis.eq_binfi (h : l.has_basis p s) : l = ⨅ i (_ : p i), 𝓟 (s i) := eq_binfi_of_mem_iff_exists_mem $ λ t, by simp only [h.mem_iff, mem_principal] lemma has_basis.eq_infi (h : l.has_basis (λ _, true) s) : l = ⨅ i, 𝓟 (s i) := by simpa only [infi_true] using h.eq_binfi lemma has_basis_infi_principal {s : ι → set α} (h : directed (≥) s) [nonempty ι] : (⨅ i, 𝓟 (s i)).has_basis (λ _, true) s := ⟨begin refine λ t, (mem_infi_of_directed (h.mono_comp _ _) t).trans $ by simp only [exists_prop, true_and, mem_principal], exact λ _ _, principal_mono.2 end⟩ /-- If `s : ι → set α` is an indexed family of sets, then finite intersections of `s i` form a basis of `⨅ i, 𝓟 (s i)`. -/ lemma has_basis_infi_principal_finite {ι : Type*} (s : ι → set α) : (⨅ i, 𝓟 (s i)).has_basis (λ t : set ι, finite t) (λ t, ⋂ i ∈ t, s i) := begin refine ⟨λ U, (mem_infi_finite _).trans _⟩, simp only [infi_principal_finset, mem_Union, mem_principal, exists_prop, exists_finite_iff_finset, finset.set_bInter_coe] end lemma has_basis_binfi_principal {s : β → set α} {S : set β} (h : directed_on (s ⁻¹'o (≥)) S) (ne : S.nonempty) : (⨅ i ∈ S, 𝓟 (s i)).has_basis (λ i, i ∈ S) s := ⟨begin refine λ t, (mem_binfi_of_directed _ ne).trans $ by simp only [mem_principal], rw [directed_on_iff_directed, ← directed_comp, (∘)] at h ⊢, apply h.mono_comp _ _, exact λ _ _, principal_mono.2 end⟩ lemma has_basis_binfi_principal' {ι : Type*} {p : ι → Prop} {s : ι → set α} (h : ∀ i, p i → ∀ j, p j → ∃ k (h : p k), s k ⊆ s i ∧ s k ⊆ s j) (ne : ∃ i, p i) : (⨅ i (h : p i), 𝓟 (s i)).has_basis p s := filter.has_basis_binfi_principal h ne lemma has_basis.map (f : α → β) (hl : l.has_basis p s) : (l.map f).has_basis p (λ i, f '' (s i)) := ⟨λ t, by simp only [mem_map, image_subset_iff, hl.mem_iff, preimage]⟩ lemma has_basis.comap (f : β → α) (hl : l.has_basis p s) : (l.comap f).has_basis p (λ i, f ⁻¹' (s i)) := ⟨begin intro t, simp only [mem_comap, exists_prop, hl.mem_iff], split, { rintros ⟨t', ⟨i, hi, ht'⟩, H⟩, exact ⟨i, hi, subset.trans (preimage_mono ht') H⟩ }, { rintros ⟨i, hi, H⟩, exact ⟨s i, ⟨i, hi, subset.refl _⟩, H⟩ } end⟩ lemma comap_has_basis (f : α → β) (l : filter β) : has_basis (comap f l) (λ s : set β, s ∈ l) (λ s, f ⁻¹' s) := ⟨λ t, mem_comap⟩ lemma has_basis.prod_self (hl : l.has_basis p s) : (l ×ᶠ l).has_basis p (λ i, (s i).prod (s i)) := ⟨begin intro t, apply mem_prod_iff.trans, split, { rintros ⟨t₁, ht₁, t₂, ht₂, H⟩, rcases hl.mem_iff.1 (inter_mem ht₁ ht₂) with ⟨i, hi, ht⟩, exact ⟨i, hi, λ p ⟨hp₁, hp₂⟩, H ⟨(ht hp₁).1, (ht hp₂).2⟩⟩ }, { rintros ⟨i, hi, H⟩, exact ⟨s i, hl.mem_of_mem hi, s i, hl.mem_of_mem hi, H⟩ } end⟩ lemma mem_prod_self_iff {s} : s ∈ l ×ᶠ l ↔ ∃ t ∈ l, set.prod t t ⊆ s := l.basis_sets.prod_self.mem_iff lemma has_basis.sInter_sets (h : has_basis l p s) : ⋂₀ l.sets = ⋂ i (hi : p i), s i := begin ext x, suffices : (∀ t ∈ l, x ∈ t) ↔ ∀ i, p i → x ∈ s i, by simpa only [mem_Inter, mem_set_of_eq, mem_sInter], simp_rw h.mem_iff, split, { intros h i hi, exact h (s i) ⟨i, hi, subset.refl _⟩ }, { rintros h _ ⟨i, hi, sub⟩, exact sub (h i hi) }, end variables {ι'' : Type*} [preorder ι''] (l) (p'' : ι'' → Prop) (s'' : ι'' → set α) /-- `is_antitone_basis p s` means the image of `s` bounded by `p` is a filter basis such that `s` is decreasing and `p` is increasing, ie `i ≤ j → p i → p j`. -/ structure is_antitone_basis extends is_basis p'' s'' : Prop := (decreasing : ∀ {i j}, p'' i → p'' j → i ≤ j → s'' j ⊆ s'' i) (mono : monotone p'') /-- We say that a filter `l` has an antitone basis `s : ι → set α` bounded by `p : ι → Prop`, if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`, and `s` is decreasing and `p` is increasing, ie `i ≤ j → p i → p j`. -/ structure has_antitone_basis (l : filter α) (p : ι'' → Prop) (s : ι'' → set α) extends has_basis l p s : Prop := (decreasing : ∀ {i j}, p i → p j → i ≤ j → s j ⊆ s i) (mono : monotone p) end same_type section two_types variables {la : filter α} {pa : ι → Prop} {sa : ι → set α} {lb : filter β} {pb : ι' → Prop} {sb : ι' → set β} {f : α → β} lemma has_basis.tendsto_left_iff (hla : la.has_basis pa sa) : tendsto f la lb ↔ ∀ t ∈ lb, ∃ i (hi : pa i), maps_to f (sa i) t := by { simp only [tendsto, (hla.map f).le_iff, image_subset_iff], refl } lemma has_basis.tendsto_right_iff (hlb : lb.has_basis pb sb) : tendsto f la lb ↔ ∀ i (hi : pb i), ∀ᶠ x in la, f x ∈ sb i := by simpa only [tendsto, hlb.ge_iff, mem_map, filter.eventually] lemma has_basis.tendsto_iff (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) : tendsto f la lb ↔ ∀ ib (hib : pb ib), ∃ ia (hia : pa ia), ∀ x ∈ sa ia, f x ∈ sb ib := by simp [hlb.tendsto_right_iff, hla.eventually_iff] lemma tendsto.basis_left (H : tendsto f la lb) (hla : la.has_basis pa sa) : ∀ t ∈ lb, ∃ i (hi : pa i), maps_to f (sa i) t := hla.tendsto_left_iff.1 H lemma tendsto.basis_right (H : tendsto f la lb) (hlb : lb.has_basis pb sb) : ∀ i (hi : pb i), ∀ᶠ x in la, f x ∈ sb i := hlb.tendsto_right_iff.1 H lemma tendsto.basis_both (H : tendsto f la lb) (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) : ∀ ib (hib : pb ib), ∃ ia (hia : pa ia), ∀ x ∈ sa ia, f x ∈ sb ib := (hla.tendsto_iff hlb).1 H lemma has_basis.prod'' (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) : (la ×ᶠ lb).has_basis (λ i : pprod ι ι', pa i.1 ∧ pb i.2) (λ i, (sa i.1).prod (sb i.2)) := (hla.comap prod.fst).inf' (hlb.comap prod.snd) lemma has_basis.prod {ι ι' : Type*} {pa : ι → Prop} {sa : ι → set α} {pb : ι' → Prop} {sb : ι' → set β} (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) : (la ×ᶠ lb).has_basis (λ i : ι × ι', pa i.1 ∧ pb i.2) (λ i, (sa i.1).prod (sb i.2)) := (hla.comap prod.fst).inf (hlb.comap prod.snd) lemma has_basis.prod' {la : filter α} {lb : filter β} {ι : Type*} {p : ι → Prop} {sa : ι → set α} {sb : ι → set β} (hla : la.has_basis p sa) (hlb : lb.has_basis p sb) (h_dir : ∀ {i j}, p i → p j → ∃ k, p k ∧ sa k ⊆ sa i ∧ sb k ⊆ sb j) : (la ×ᶠ lb).has_basis p (λ i, (sa i).prod (sb i)) := begin simp only [has_basis_iff, (hla.prod hlb).mem_iff], refine λ t, ⟨_, _⟩, { rintros ⟨⟨i, j⟩, ⟨hi, hj⟩, hsub : (sa i).prod (sb j) ⊆ t⟩, rcases h_dir hi hj with ⟨k, hk, ki, kj⟩, exact ⟨k, hk, (set.prod_mono ki kj).trans hsub⟩ }, { rintro ⟨i, hi, h⟩, exact ⟨⟨i, i⟩, ⟨hi, hi⟩, h⟩ }, end end two_types end filter end sort namespace filter variables {α β γ ι ι' : Type*} /-- `is_countably_generated f` means `f = generate s` for some countable `s`. -/ class is_countably_generated (f : filter α) : Prop := (out [] : ∃ s : set (set α), countable s ∧ f = generate s) /-- `is_countable_basis p s` means the image of `s` bounded by `p` is a countable filter basis. -/ structure is_countable_basis (p : ι → Prop) (s : ι → set α) extends is_basis p s : Prop := (countable : countable $ set_of p) /-- We say that a filter `l` has a countable basis `s : ι → set α` bounded by `p : ι → Prop`, if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`, and the set defined by `p` is countable. -/ structure has_countable_basis (l : filter α) (p : ι → Prop) (s : ι → set α) extends has_basis l p s : Prop := (countable : countable $ set_of p) /-- A countable filter basis `B` on a type `α` is a nonempty countable collection of sets of `α` such that the intersection of two elements of this collection contains some element of the collection. -/ structure countable_filter_basis (α : Type*) extends filter_basis α := (countable : countable sets) -- For illustration purposes, the countable filter basis defining (at_top : filter ℕ) instance nat.inhabited_countable_filter_basis : inhabited (countable_filter_basis ℕ) := ⟨{ countable := countable_range (λ n, Ici n), ..(default $ filter_basis ℕ),}⟩ lemma has_countable_basis.is_countably_generated {f : filter α} {p : ι → Prop} {s : ι → set α} (h : f.has_countable_basis p s) : f.is_countably_generated := ⟨⟨{t | ∃ i, p i ∧ s i = t}, h.countable.image s, h.to_has_basis.eq_generate⟩⟩ lemma antitone_seq_of_seq (s : ℕ → set α) : ∃ t : ℕ → set α, (∀ i j, i ≤ j → t j ⊆ t i) ∧ (⨅ i, 𝓟 $ s i) = ⨅ i, 𝓟 (t i) := begin use λ n, ⋂ m ≤ n, s m, split, { exact λ i j hij, bInter_mono' (Iic_subset_Iic.2 hij) (λ n hn, subset.refl _) }, apply le_antisymm; rw le_infi_iff; intro i, { rw le_principal_iff, refine (bInter_mem (finite_le_nat _)).2 (λ j hji, _), rw ← le_principal_iff, apply infi_le_of_le j _, apply le_refl _ }, { apply infi_le_of_le i _, rw principal_mono, intro a, simp, intro h, apply h, refl }, end lemma countable_binfi_eq_infi_seq [complete_lattice α] {B : set ι} (Bcbl : countable B) (Bne : B.nonempty) (f : ι → α) : ∃ (x : ℕ → ι), (⨅ t ∈ B, f t) = ⨅ i, f (x i) := begin rw countable_iff_exists_surjective_to_subtype Bne at Bcbl, rcases Bcbl with ⟨g, gsurj⟩, rw infi_subtype', use (λ n, g n), apply le_antisymm; rw le_infi_iff, { intro i, apply infi_le_of_le (g i) _, apply le_refl _ }, { intros a, rcases gsurj a with ⟨i, rfl⟩, apply infi_le } end lemma countable_binfi_eq_infi_seq' [complete_lattice α] {B : set ι} (Bcbl : countable B) (f : ι → α) {i₀ : ι} (h : f i₀ = ⊤) : ∃ (x : ℕ → ι), (⨅ t ∈ B, f t) = ⨅ i, f (x i) := begin cases B.eq_empty_or_nonempty with hB Bnonempty, { rw [hB, infi_emptyset], use λ n, i₀, simp [h] }, { exact countable_binfi_eq_infi_seq Bcbl Bnonempty f } end lemma countable_binfi_principal_eq_seq_infi {B : set (set α)} (Bcbl : countable B) : ∃ (x : ℕ → set α), (⨅ t ∈ B, 𝓟 t) = ⨅ i, 𝓟 (x i) := countable_binfi_eq_infi_seq' Bcbl 𝓟 principal_univ section is_countably_generated /-- If `f` is countably generated and `f.has_basis p s`, then `f` admits a decreasing basis enumerated by natural numbers such that all sets have the form `s i`. More precisely, there is a sequence `i n` such that `p (i n)` for all `n` and `s (i n)` is a decreasing sequence of sets which forms a basis of `f`-/ lemma has_basis.exists_antitone_subbasis {f : filter α} [h : f.is_countably_generated] {p : ι → Prop} {s : ι → set α} (hs : f.has_basis p s) : ∃ x : ℕ → ι, (∀ i, p (x i)) ∧ f.has_antitone_basis (λ _, true) (λ i, s (x i)) := begin obtain ⟨x', hx'⟩ : ∃ x : ℕ → set α, f = ⨅ i, 𝓟 (x i), { unfreezingI { rcases h with ⟨s, hsc, rfl⟩ }, rw generate_eq_binfi, exact countable_binfi_principal_eq_seq_infi hsc }, have : ∀ i, x' i ∈ f := λ i, hx'.symm ▸ (infi_le (λ i, 𝓟 (x' i)) i) (mem_principal_self _), let x : ℕ → {i : ι // p i} := λ n, nat.rec_on n (hs.index _ $ this 0) (λ n xn, (hs.index _ $ inter_mem (this $ n + 1) (hs.mem_of_mem xn.coe_prop))), have x_mono : antitone (λ i, s (x i)), { refine antitone_nat_of_succ_le (λ i, _), exact (hs.set_index_subset _).trans (inter_subset_right _ _) }, have x_subset : ∀ i, s (x i) ⊆ x' i, { rintro (_|i), exacts [hs.set_index_subset _, subset.trans (hs.set_index_subset _) (inter_subset_left _ _)] }, refine ⟨λ i, x i, λ i, (x i).2, _⟩, have : (⨅ i, 𝓟 (s (x i))).has_antitone_basis (λ _, true) (λ i, s (x i)) := ⟨has_basis_infi_principal (directed_of_sup x_mono), λ i j _ _ hij, x_mono hij, monotone_const⟩, convert this, exact le_antisymm (le_infi $ λ i, le_principal_iff.2 $ by cases i; apply hs.set_index_mem) (hx'.symm ▸ le_infi (λ i, le_principal_iff.2 $ this.to_has_basis.mem_iff.2 ⟨i, trivial, x_subset i⟩)) end /-- A countably generated filter admits a basis formed by an antitone sequence of sets. -/ lemma exists_antitone_basis (f : filter α) [f.is_countably_generated] : ∃ x : ℕ → set α, f.has_antitone_basis (λ _, true) x := let ⟨x, hxf, hx⟩ := f.basis_sets.exists_antitone_subbasis in ⟨x, hx⟩ lemma exists_antitone_eq_infi_principal (f : filter α) [f.is_countably_generated] : ∃ x : ℕ → set α, antitone x ∧ f = ⨅ n, 𝓟 (x n) := let ⟨x, hxf⟩ := f.exists_antitone_basis in ⟨x, λ i j, hxf.decreasing trivial trivial, hxf.to_has_basis.eq_infi⟩ lemma exists_antitone_seq (f : filter α) [f.is_countably_generated] : ∃ x : ℕ → set α, antitone x ∧ ∀ {s}, (s ∈ f ↔ ∃ i, x i ⊆ s) := let ⟨x, hx⟩ := f.exists_antitone_basis in ⟨x, λ i j, hx.decreasing trivial trivial, λ s, by simp [hx.to_has_basis.mem_iff]⟩ instance inf.is_countably_generated (f g : filter α) [is_countably_generated f] [is_countably_generated g] : is_countably_generated (f ⊓ g) := begin rcases f.exists_antitone_basis with ⟨s, hs⟩, rcases g.exists_antitone_basis with ⟨t, ht⟩, exact has_countable_basis.is_countably_generated ⟨hs.to_has_basis.inf ht.to_has_basis, set.countable_encodable _⟩ end instance comap.is_countably_generated (l : filter β) [l.is_countably_generated] (f : α → β) : (comap f l).is_countably_generated := let ⟨x, hxl⟩ := l.exists_antitone_basis in has_countable_basis.is_countably_generated ⟨hxl.to_has_basis.comap _, countable_encodable _⟩ instance sup.is_countably_generated (f g : filter α) [is_countably_generated f] [is_countably_generated g] : is_countably_generated (f ⊔ g) := begin rcases f.exists_antitone_basis with ⟨s, hs⟩, rcases g.exists_antitone_basis with ⟨t, ht⟩, exact has_countable_basis.is_countably_generated ⟨hs.to_has_basis.sup ht.to_has_basis, set.countable_encodable _⟩ end end is_countably_generated @[instance] lemma is_countably_generated_seq [encodable β] (x : β → set α) : is_countably_generated (⨅ i, 𝓟 $ x i) := begin use [range x, countable_range x], rw [generate_eq_binfi, infi_range] end lemma is_countably_generated_of_seq {f : filter α} (h : ∃ x : ℕ → set α, f = ⨅ i, 𝓟 $ x i) : f.is_countably_generated := let ⟨x, h⟩ := h in by rw h ; apply is_countably_generated_seq lemma is_countably_generated_binfi_principal {B : set $ set α} (h : countable B) : is_countably_generated (⨅ (s ∈ B), 𝓟 s) := is_countably_generated_of_seq (countable_binfi_principal_eq_seq_infi h) lemma is_countably_generated_iff_exists_antitone_basis {f : filter α} : is_countably_generated f ↔ ∃ x : ℕ → set α, f.has_antitone_basis (λ _, true) x := begin split, { introI h, exact f.exists_antitone_basis }, { rintros ⟨x, h⟩, rw h.to_has_basis.eq_infi, exact is_countably_generated_seq x }, end @[instance] lemma is_countably_generated_principal (s : set α) : is_countably_generated (𝓟 s) := is_countably_generated_of_seq ⟨λ _, s, infi_const.symm⟩ @[instance] lemma is_countably_generated_bot : is_countably_generated (⊥ : filter α) := @principal_empty α ▸ is_countably_generated_principal _ @[instance] lemma is_countably_generated_top : is_countably_generated (⊤ : filter α) := @principal_univ α ▸ is_countably_generated_principal _ end filter
d24cd078908f3d94a55dfad653375f445b1a68fe
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/add_torsor.lean
6b72f08f2be914bcdb163908be43584228379806
[ "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
14,674
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers, Yury Kudryashov -/ import data.set.pointwise.smul /-! # Torsors of additive group actions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines torsors of additive group actions. ## Notations The group elements are referred to as acting on points. This file defines the notation `+ᵥ` for adding a group element to a point and `-ᵥ` for subtracting two points to produce a group element. ## Implementation notes Affine spaces are the motivating example of torsors of additive group actions. It may be appropriate to refactor in terms of the general definition of group actions, via `to_additive`, when there is a use for multiplicative torsors (currently mathlib only develops the theory of group actions for multiplicative group actions). ## Notations * `v +ᵥ p` is a notation for `has_vadd.vadd`, the left action of an additive monoid; * `p₁ -ᵥ p₂` is a notation for `has_vsub.vsub`, difference between two points in an additive torsor as an element of the corresponding additive group; ## References * https://en.wikipedia.org/wiki/Principal_homogeneous_space * https://en.wikipedia.org/wiki/Affine_space -/ /-- An `add_torsor G P` gives a structure to the nonempty type `P`, acted on by an `add_group G` with a transitive and free action given by the `+ᵥ` operation and a corresponding subtraction given by the `-ᵥ` operation. In the case of a vector space, it is an affine space. -/ class add_torsor (G : out_param Type*) (P : Type*) [out_param $ add_group G] extends add_action G P, has_vsub G P := [nonempty : nonempty P] (vsub_vadd' : ∀ (p1 p2 : P), (p1 -ᵥ p2 : G) +ᵥ p2 = p1) (vadd_vsub' : ∀ (g : G) (p : P), g +ᵥ p -ᵥ p = g) attribute [instance, priority 100, nolint dangerous_instance] add_torsor.nonempty attribute [nolint dangerous_instance] add_torsor.to_has_vsub /-- An `add_group G` is a torsor for itself. -/ @[nolint instance_priority] instance add_group_is_add_torsor (G : Type*) [add_group G] : add_torsor G G := { vsub := has_sub.sub, vsub_vadd' := sub_add_cancel, vadd_vsub' := add_sub_cancel } /-- Simplify subtraction for a torsor for an `add_group G` over itself. -/ @[simp] lemma vsub_eq_sub {G : Type*} [add_group G] (g1 g2 : G) : g1 -ᵥ g2 = g1 - g2 := rfl section general variables {G : Type*} {P : Type*} [add_group G] [T : add_torsor G P] include T /-- Adding the result of subtracting from another point produces that point. -/ @[simp] lemma vsub_vadd (p1 p2 : P) : p1 -ᵥ p2 +ᵥ p2 = p1 := add_torsor.vsub_vadd' p1 p2 /-- Adding a group element then subtracting the original point produces that group element. -/ @[simp] lemma vadd_vsub (g : G) (p : P) : g +ᵥ p -ᵥ p = g := add_torsor.vadd_vsub' g p /-- If the same point added to two group elements produces equal results, those group elements are equal. -/ lemma vadd_right_cancel {g1 g2 : G} (p : P) (h : g1 +ᵥ p = g2 +ᵥ p) : g1 = g2 := by rw [←vadd_vsub g1, h, vadd_vsub] @[simp] lemma vadd_right_cancel_iff {g1 g2 : G} (p : P) : g1 +ᵥ p = g2 +ᵥ p ↔ g1 = g2 := ⟨vadd_right_cancel p, λ h, h ▸ rfl⟩ /-- Adding a group element to the point `p` is an injective function. -/ lemma vadd_right_injective (p : P) : function.injective ((+ᵥ p) : G → P) := λ g1 g2, vadd_right_cancel p /-- Adding a group element to a point, then subtracting another point, produces the same result as subtracting the points then adding the group element. -/ lemma vadd_vsub_assoc (g : G) (p1 p2 : P) : g +ᵥ p1 -ᵥ p2 = g + (p1 -ᵥ p2) := begin apply vadd_right_cancel p2, rw [vsub_vadd, add_vadd, vsub_vadd] end /-- Subtracting a point from itself produces 0. -/ @[simp] lemma vsub_self (p : P) : p -ᵥ p = (0 : G) := by rw [←zero_add (p -ᵥ p), ←vadd_vsub_assoc, vadd_vsub] /-- If subtracting two points produces 0, they are equal. -/ lemma eq_of_vsub_eq_zero {p1 p2 : P} (h : p1 -ᵥ p2 = (0 : G)) : p1 = p2 := by rw [←vsub_vadd p1 p2, h, zero_vadd] /-- Subtracting two points produces 0 if and only if they are equal. -/ @[simp] lemma vsub_eq_zero_iff_eq {p1 p2 : P} : p1 -ᵥ p2 = (0 : G) ↔ p1 = p2 := iff.intro eq_of_vsub_eq_zero (λ h, h ▸ vsub_self _) lemma vsub_ne_zero {p q : P} : p -ᵥ q ≠ (0 : G) ↔ p ≠ q := not_congr vsub_eq_zero_iff_eq /-- Cancellation adding the results of two subtractions. -/ @[simp] lemma vsub_add_vsub_cancel (p1 p2 p3 : P) : p1 -ᵥ p2 + (p2 -ᵥ p3) = (p1 -ᵥ p3) := begin apply vadd_right_cancel p3, rw [add_vadd, vsub_vadd, vsub_vadd, vsub_vadd] end /-- Subtracting two points in the reverse order produces the negation of subtracting them. -/ @[simp] lemma neg_vsub_eq_vsub_rev (p1 p2 : P) : -(p1 -ᵥ p2) = (p2 -ᵥ p1) := begin refine neg_eq_of_add_eq_zero_right (vadd_right_cancel p1 _), rw [vsub_add_vsub_cancel, vsub_self], end lemma vadd_vsub_eq_sub_vsub (g : G) (p q : P) : g +ᵥ p -ᵥ q = g - (q -ᵥ p) := by rw [vadd_vsub_assoc, sub_eq_add_neg, neg_vsub_eq_vsub_rev] /-- Subtracting the result of adding a group element produces the same result as subtracting the points and subtracting that group element. -/ lemma vsub_vadd_eq_vsub_sub (p1 p2 : P) (g : G) : p1 -ᵥ (g +ᵥ p2) = (p1 -ᵥ p2) - g := by rw [←add_right_inj (p2 -ᵥ p1 : G), vsub_add_vsub_cancel, ←neg_vsub_eq_vsub_rev, vadd_vsub, ←add_sub_assoc, ←neg_vsub_eq_vsub_rev, neg_add_self, zero_sub] /-- Cancellation subtracting the results of two subtractions. -/ @[simp] lemma vsub_sub_vsub_cancel_right (p1 p2 p3 : P) : (p1 -ᵥ p3) - (p2 -ᵥ p3) = (p1 -ᵥ p2) := by rw [←vsub_vadd_eq_vsub_sub, vsub_vadd] /-- Convert between an equality with adding a group element to a point and an equality of a subtraction of two points with a group element. -/ lemma eq_vadd_iff_vsub_eq (p1 : P) (g : G) (p2 : P) : p1 = g +ᵥ p2 ↔ p1 -ᵥ p2 = g := ⟨λ h, h.symm ▸ vadd_vsub _ _, λ h, h ▸ (vsub_vadd _ _).symm⟩ lemma vadd_eq_vadd_iff_neg_add_eq_vsub {v₁ v₂ : G} {p₁ p₂ : P} : v₁ +ᵥ p₁ = v₂ +ᵥ p₂ ↔ - v₁ + v₂ = p₁ -ᵥ p₂ := by rw [eq_vadd_iff_vsub_eq, vadd_vsub_assoc, ← add_right_inj (-v₁), neg_add_cancel_left, eq_comm] namespace set open_locale pointwise @[simp] lemma singleton_vsub_self (p : P) : ({p} : set P) -ᵥ {p} = {(0:G)} := by rw [set.singleton_vsub_singleton, vsub_self] end set @[simp] lemma vadd_vsub_vadd_cancel_right (v₁ v₂ : G) (p : P) : (v₁ +ᵥ p) -ᵥ (v₂ +ᵥ p) = v₁ - v₂ := by rw [vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, vsub_self, add_zero] /-- If the same point subtracted from two points produces equal results, those points are equal. -/ lemma vsub_left_cancel {p1 p2 p : P} (h : p1 -ᵥ p = p2 -ᵥ p) : p1 = p2 := by rwa [←sub_eq_zero, vsub_sub_vsub_cancel_right, vsub_eq_zero_iff_eq] at h /-- The same point subtracted from two points produces equal results if and only if those points are equal. -/ @[simp] lemma vsub_left_cancel_iff {p1 p2 p : P} : (p1 -ᵥ p) = p2 -ᵥ p ↔ p1 = p2 := ⟨vsub_left_cancel, λ h, h ▸ rfl⟩ /-- Subtracting the point `p` is an injective function. -/ lemma vsub_left_injective (p : P) : function.injective ((-ᵥ p) : P → G) := λ p2 p3, vsub_left_cancel /-- If subtracting two points from the same point produces equal results, those points are equal. -/ lemma vsub_right_cancel {p1 p2 p : P} (h : p -ᵥ p1 = p -ᵥ p2) : p1 = p2 := begin refine vadd_left_cancel (p -ᵥ p2) _, rw [vsub_vadd, ← h, vsub_vadd] end /-- Subtracting two points from the same point produces equal results if and only if those points are equal. -/ @[simp] lemma vsub_right_cancel_iff {p1 p2 p : P} : p -ᵥ p1 = p -ᵥ p2 ↔ p1 = p2 := ⟨vsub_right_cancel, λ h, h ▸ rfl⟩ /-- Subtracting a point from the point `p` is an injective function. -/ lemma vsub_right_injective (p : P) : function.injective ((-ᵥ) p : P → G) := λ p2 p3, vsub_right_cancel end general section comm variables {G : Type*} {P : Type*} [add_comm_group G] [add_torsor G P] include G /-- Cancellation subtracting the results of two subtractions. -/ @[simp] lemma vsub_sub_vsub_cancel_left (p1 p2 p3 : P) : (p3 -ᵥ p2) - (p3 -ᵥ p1) = (p1 -ᵥ p2) := by rw [sub_eq_add_neg, neg_vsub_eq_vsub_rev, add_comm, vsub_add_vsub_cancel] @[simp] lemma vadd_vsub_vadd_cancel_left (v : G) (p1 p2 : P) : (v +ᵥ p1) -ᵥ (v +ᵥ p2) = p1 -ᵥ p2 := by rw [vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_sub_cancel'] lemma vsub_vadd_comm (p1 p2 p3 : P) : (p1 -ᵥ p2 : G) +ᵥ p3 = p3 -ᵥ p2 +ᵥ p1 := begin rw [←@vsub_eq_zero_iff_eq G, vadd_vsub_assoc, vsub_vadd_eq_vsub_sub], simp end lemma vadd_eq_vadd_iff_sub_eq_vsub {v₁ v₂ : G} {p₁ p₂ : P} : v₁ +ᵥ p₁ = v₂ +ᵥ p₂ ↔ v₂ - v₁ = p₁ -ᵥ p₂ := by rw [vadd_eq_vadd_iff_neg_add_eq_vsub, neg_add_eq_sub] lemma vsub_sub_vsub_comm (p₁ p₂ p₃ p₄ : P) : (p₁ -ᵥ p₂) - (p₃ -ᵥ p₄) = (p₁ -ᵥ p₃) - (p₂ -ᵥ p₄) := by rw [← vsub_vadd_eq_vsub_sub, vsub_vadd_comm, vsub_vadd_eq_vsub_sub] end comm namespace prod variables {G : Type*} {P : Type*} {G' : Type*} {P' : Type*} [add_group G] [add_group G'] [add_torsor G P] [add_torsor G' P'] instance : add_torsor (G × G') (P × P') := { vadd := λ v p, (v.1 +ᵥ p.1, v.2 +ᵥ p.2), zero_vadd := λ p, by simp, add_vadd := by simp [add_vadd], vsub := λ p₁ p₂, (p₁.1 -ᵥ p₂.1, p₁.2 -ᵥ p₂.2), nonempty := prod.nonempty, vsub_vadd' := λ p₁ p₂, show (p₁.1 -ᵥ p₂.1 +ᵥ p₂.1, _) = p₁, by simp, vadd_vsub' := λ v p, show (v.1 +ᵥ p.1 -ᵥ p.1, v.2 +ᵥ p.2 -ᵥ p.2) =v, by simp } @[simp] lemma fst_vadd (v : G × G') (p : P × P') : (v +ᵥ p).1 = v.1 +ᵥ p.1 := rfl @[simp] lemma snd_vadd (v : G × G') (p : P × P') : (v +ᵥ p).2 = v.2 +ᵥ p.2 := rfl @[simp] lemma mk_vadd_mk (v : G) (v' : G') (p : P) (p' : P') : (v, v') +ᵥ (p, p') = (v +ᵥ p, v' +ᵥ p') := rfl @[simp] lemma fst_vsub (p₁ p₂ : P × P') : (p₁ -ᵥ p₂ : G × G').1 = p₁.1 -ᵥ p₂.1 := rfl @[simp] lemma snd_vsub (p₁ p₂ : P × P') : (p₁ -ᵥ p₂ : G × G').2 = p₁.2 -ᵥ p₂.2 := rfl @[simp] lemma mk_vsub_mk (p₁ p₂ : P) (p₁' p₂' : P') : ((p₁, p₁') -ᵥ (p₂, p₂') : G × G') = (p₁ -ᵥ p₂, p₁' -ᵥ p₂') := rfl end prod namespace pi universes u v w variables {I : Type u} {fg : I → Type v} [∀ i, add_group (fg i)] {fp : I → Type w} open add_action add_torsor /-- A product of `add_torsor`s is an `add_torsor`. -/ instance [T : ∀ i, add_torsor (fg i) (fp i)] : add_torsor (Π i, fg i) (Π i, fp i) := { vadd := λ g p, λ i, g i +ᵥ p i, zero_vadd := λ p, funext $ λ i, zero_vadd (fg i) (p i), add_vadd := λ g₁ g₂ p, funext $ λ i, add_vadd (g₁ i) (g₂ i) (p i), vsub := λ p₁ p₂, λ i, p₁ i -ᵥ p₂ i, nonempty := ⟨λ i, classical.choice (T i).nonempty⟩, vsub_vadd' := λ p₁ p₂, funext $ λ i, vsub_vadd (p₁ i) (p₂ i), vadd_vsub' := λ g p, funext $ λ i, vadd_vsub (g i) (p i) } end pi namespace equiv variables {G : Type*} {P : Type*} [add_group G] [add_torsor G P] include G /-- `v ↦ v +ᵥ p` as an equivalence. -/ def vadd_const (p : P) : G ≃ P := { to_fun := λ v, v +ᵥ p, inv_fun := λ p', p' -ᵥ p, left_inv := λ v, vadd_vsub _ _, right_inv := λ p', vsub_vadd _ _ } @[simp] lemma coe_vadd_const (p : P) : ⇑(vadd_const p) = λ v, v+ᵥ p := rfl @[simp] lemma coe_vadd_const_symm (p : P) : ⇑(vadd_const p).symm = λ p', p' -ᵥ p := rfl /-- `p' ↦ p -ᵥ p'` as an equivalence. -/ def const_vsub (p : P) : P ≃ G := { to_fun := (-ᵥ) p, inv_fun := λ v, -v +ᵥ p, left_inv := λ p', by simp, right_inv := λ v, by simp [vsub_vadd_eq_vsub_sub] } @[simp] lemma coe_const_vsub (p : P) : ⇑(const_vsub p) = (-ᵥ) p := rfl @[simp] lemma coe_const_vsub_symm (p : P) : ⇑(const_vsub p).symm = λ v, -v +ᵥ p := rfl variables (P) /-- The permutation given by `p ↦ v +ᵥ p`. -/ def const_vadd (v : G) : equiv.perm P := { to_fun := (+ᵥ) v, inv_fun := (+ᵥ) (-v), left_inv := λ p, by simp [vadd_vadd], right_inv := λ p, by simp [vadd_vadd] } @[simp] lemma coe_const_vadd (v : G) : ⇑(const_vadd P v) = (+ᵥ) v := rfl variable (G) @[simp] lemma const_vadd_zero : const_vadd P (0:G) = 1 := ext $ zero_vadd G variable {G} @[simp] lemma const_vadd_add (v₁ v₂ : G) : const_vadd P (v₁ + v₂) = const_vadd P v₁ * const_vadd P v₂ := ext $ add_vadd v₁ v₂ /-- `equiv.const_vadd` as a homomorphism from `multiplicative G` to `equiv.perm P` -/ def const_vadd_hom : multiplicative G →* equiv.perm P := { to_fun := λ v, const_vadd P v.to_add, map_one' := const_vadd_zero G P, map_mul' := const_vadd_add P } variable {P} open _root_.function /-- Point reflection in `x` as a permutation. -/ def point_reflection (x : P) : perm P := (const_vsub x).trans (vadd_const x) lemma point_reflection_apply (x y : P) : point_reflection x y = x -ᵥ y +ᵥ x := rfl @[simp] lemma point_reflection_symm (x : P) : (point_reflection x).symm = point_reflection x := ext $ by simp [point_reflection] @[simp] lemma point_reflection_self (x : P) : point_reflection x x = x := vsub_vadd _ _ lemma point_reflection_involutive (x : P) : involutive (point_reflection x : P → P) := λ y, (equiv.apply_eq_iff_eq_symm_apply _).2 $ by rw point_reflection_symm /-- `x` is the only fixed point of `point_reflection x`. This lemma requires `x + x = y + y ↔ x = y`. There is no typeclass to use here, so we add it as an explicit argument. -/ lemma point_reflection_fixed_iff_of_injective_bit0 {x y : P} (h : injective (bit0 : G → G)) : point_reflection x y = y ↔ y = x := by rw [point_reflection_apply, eq_comm, eq_vadd_iff_vsub_eq, ← neg_vsub_eq_vsub_rev, neg_eq_iff_add_eq_zero, ← bit0, ← bit0_zero, h.eq_iff, vsub_eq_zero_iff_eq, eq_comm] omit G lemma injective_point_reflection_left_of_injective_bit0 {G P : Type*} [add_comm_group G] [add_torsor G P] (h : injective (bit0 : G → G)) (y : P) : injective (λ x : P, point_reflection x y) := λ x₁ x₂ (hy : point_reflection x₁ y = point_reflection x₂ y), by rwa [point_reflection_apply, point_reflection_apply, vadd_eq_vadd_iff_sub_eq_vsub, vsub_sub_vsub_cancel_right, ← neg_vsub_eq_vsub_rev, neg_eq_iff_add_eq_zero, ← bit0, ← bit0_zero, h.eq_iff, vsub_eq_zero_iff_eq] at hy end equiv lemma add_torsor.subsingleton_iff (G P : Type*) [add_group G] [add_torsor G P] : subsingleton G ↔ subsingleton P := begin inhabit P, exact (equiv.vadd_const default).subsingleton_congr, end
3350e75e1d5aa6d72cc5f8b8a12d6ae22a1a7eaa
c777c32c8e484e195053731103c5e52af26a25d1
/src/category_theory/monoidal/braided.lean
79d3d2935f8c27ca8a933f8ab55d04c5f6290a9a
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
34,893
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_lemmas import category_theory.monoidal.natural_transformation import category_theory.monoidal.discrete /-! # Braided and symmetric monoidal categories The basic definitions of braided monoidal categories, and symmetric monoidal categories, as well as braided functors. ## Implementation note We make `braided_monoidal_category` another typeclass, but then have `symmetric_monoidal_category` extend this. The rationale is that we are not carrying any additional data, just requiring a property. ## Future work * Construct the Drinfeld center of a monoidal category as a braided monoidal category. * Say something about pseudo-natural transformations. -/ open category_theory universes v v₁ v₂ v₃ u u₁ u₂ u₃ namespace category_theory /-- A braided monoidal category is a monoidal category equipped with a braiding isomorphism `β_ X Y : X ⊗ Y ≅ Y ⊗ X` which is natural in both arguments, and also satisfies the two hexagon identities. -/ class braided_category (C : Type u) [category.{v} C] [monoidal_category.{v} C] := -- braiding natural iso: (braiding : Π X Y : C, X ⊗ Y ≅ Y ⊗ X) (braiding_naturality' : ∀ {X X' Y Y' : C} (f : X ⟶ Y) (g : X' ⟶ Y'), (f ⊗ g) ≫ (braiding Y Y').hom = (braiding X X').hom ≫ (g ⊗ f) . obviously) -- hexagon identities: (hexagon_forward' : Π X Y Z : C, (α_ X Y Z).hom ≫ (braiding X (Y ⊗ Z)).hom ≫ (α_ Y Z X).hom = ((braiding X Y).hom ⊗ (𝟙 Z)) ≫ (α_ Y X Z).hom ≫ ((𝟙 Y) ⊗ (braiding X Z).hom) . obviously) (hexagon_reverse' : Π X Y Z : C, (α_ X Y Z).inv ≫ (braiding (X ⊗ Y) Z).hom ≫ (α_ Z X Y).inv = ((𝟙 X) ⊗ (braiding Y Z).hom) ≫ (α_ X Z Y).inv ≫ ((braiding X Z).hom ⊗ (𝟙 Y)) . obviously) restate_axiom braided_category.braiding_naturality' attribute [simp,reassoc] braided_category.braiding_naturality restate_axiom braided_category.hexagon_forward' restate_axiom braided_category.hexagon_reverse' attribute [reassoc] braided_category.hexagon_forward braided_category.hexagon_reverse open category open monoidal_category open braided_category notation `β_` := braiding /-- Verifying the axioms for a braiding by checking that the candidate braiding is sent to a braiding by a faithful monoidal functor. -/ def braided_category_of_faithful {C D : Type*} [category C] [category D] [monoidal_category C] [monoidal_category D] (F : monoidal_functor C D) [faithful F.to_functor] [braided_category D] (β : Π X Y : C, X ⊗ Y ≅ Y ⊗ X) (w : ∀ X Y, F.μ _ _ ≫ F.map (β X Y).hom = (β_ _ _).hom ≫ F.μ _ _) : braided_category C := { braiding := β, braiding_naturality' := begin intros, apply F.to_functor.map_injective, refine (cancel_epi (F.μ _ _)).1 _, rw [functor.map_comp, ←lax_monoidal_functor.μ_natural_assoc, w, functor.map_comp, reassoc_of w, braiding_naturality_assoc, lax_monoidal_functor.μ_natural], end, hexagon_forward' := begin intros, apply F.to_functor.map_injective, refine (cancel_epi (F.μ _ _)).1 _, refine (cancel_epi (F.μ _ _ ⊗ 𝟙 _)).1 _, rw [functor.map_comp, functor.map_comp, functor.map_comp, functor.map_comp, ←lax_monoidal_functor.μ_natural_assoc, functor.map_id, ←comp_tensor_id_assoc, w, comp_tensor_id, category.assoc, lax_monoidal_functor.associativity_assoc, lax_monoidal_functor.associativity_assoc, ←lax_monoidal_functor.μ_natural, functor.map_id, ←id_tensor_comp_assoc, w, id_tensor_comp_assoc, reassoc_of w, braiding_naturality_assoc, lax_monoidal_functor.associativity, hexagon_forward_assoc], end, hexagon_reverse' := begin intros, apply F.to_functor.map_injective, refine (cancel_epi (F.μ _ _)).1 _, refine (cancel_epi (𝟙 _ ⊗ F.μ _ _)).1 _, rw [functor.map_comp, functor.map_comp, functor.map_comp, functor.map_comp, ←lax_monoidal_functor.μ_natural_assoc, functor.map_id, ←id_tensor_comp_assoc, w, id_tensor_comp_assoc, lax_monoidal_functor.associativity_inv_assoc, lax_monoidal_functor.associativity_inv_assoc, ←lax_monoidal_functor.μ_natural, functor.map_id, ←comp_tensor_id_assoc, w, comp_tensor_id_assoc, reassoc_of w, braiding_naturality_assoc, lax_monoidal_functor.associativity_inv, hexagon_reverse_assoc], end, } /-- Pull back a braiding along a fully faithful monoidal functor. -/ noncomputable def braided_category_of_fully_faithful {C D : Type*} [category C] [category D] [monoidal_category C] [monoidal_category D] (F : monoidal_functor C D) [full F.to_functor] [faithful F.to_functor] [braided_category D] : braided_category C := braided_category_of_faithful F (λ X Y, F.to_functor.preimage_iso ((as_iso (F.μ _ _)).symm ≪≫ β_ (F.obj X) (F.obj Y) ≪≫ (as_iso (F.μ _ _)))) (by tidy) section /-! We now establish how the braiding interacts with the unitors. I couldn't find a detailed proof in print, but this is discussed in: * Proposition 1 of André Joyal and Ross Street, "Braided monoidal categories", Macquarie Math Reports 860081 (1986). * Proposition 2.1 of André Joyal and Ross Street, "Braided tensor categories" , Adv. Math. 102 (1993), 20–78. * Exercise 8.1.6 of Etingof, Gelaki, Nikshych, Ostrik, "Tensor categories", vol 25, Mathematical Surveys and Monographs (2015), AMS. -/ variables (C : Type u₁) [category.{v₁} C] [monoidal_category C] [braided_category C] lemma braiding_left_unitor_aux₁ (X : C) : (α_ (𝟙_ C) (𝟙_ C) X).hom ≫ (𝟙 (𝟙_ C) ⊗ (β_ X (𝟙_ C)).inv) ≫ (α_ _ X _).inv ≫ ((λ_ X).hom ⊗ 𝟙 _) = ((λ_ _).hom ⊗ 𝟙 X) ≫ (β_ X (𝟙_ C)).inv := by { rw [←left_unitor_tensor, left_unitor_naturality], simp, } lemma braiding_left_unitor_aux₂ (X : C) : ((β_ X (𝟙_ C)).hom ⊗ (𝟙 (𝟙_ C))) ≫ ((λ_ X).hom ⊗ (𝟙 (𝟙_ C))) = (ρ_ X).hom ⊗ (𝟙 (𝟙_ C)) := calc ((β_ X (𝟙_ C)).hom ⊗ (𝟙 (𝟙_ C))) ≫ ((λ_ X).hom ⊗ (𝟙 (𝟙_ C))) = ((β_ X (𝟙_ C)).hom ⊗ (𝟙 (𝟙_ C))) ≫ (α_ _ _ _).hom ≫ (α_ _ _ _).inv ≫ ((λ_ X).hom ⊗ (𝟙 (𝟙_ C))) : by coherence ... = ((β_ X (𝟙_ C)).hom ⊗ (𝟙 (𝟙_ C))) ≫ (α_ _ _ _).hom ≫ (𝟙 _ ⊗ (β_ X _).hom) ≫ (𝟙 _ ⊗ (β_ X _).inv) ≫ (α_ _ _ _).inv ≫ ((λ_ X).hom ⊗ (𝟙 (𝟙_ C))) : by { slice_rhs 3 4 { rw [←id_tensor_comp, iso.hom_inv_id, tensor_id], }, rw [id_comp], } ... = (α_ _ _ _).hom ≫ (β_ _ _).hom ≫ (α_ _ _ _).hom ≫ (𝟙 _ ⊗ (β_ X _).inv) ≫ (α_ _ _ _).inv ≫ ((λ_ X).hom ⊗ (𝟙 (𝟙_ C))) : by { slice_lhs 1 3 { rw ←hexagon_forward }, simp only [assoc], } ... = (α_ _ _ _).hom ≫ (β_ _ _).hom ≫ ((λ_ _).hom ⊗ 𝟙 X) ≫ (β_ X _).inv : by rw braiding_left_unitor_aux₁ ... = (α_ _ _ _).hom ≫ (𝟙 _ ⊗ (λ_ _).hom) ≫ (β_ _ _).hom ≫ (β_ X _).inv : by { slice_lhs 2 3 { rw [←braiding_naturality] }, simp only [assoc], } ... = (α_ _ _ _).hom ≫ (𝟙 _ ⊗ (λ_ _).hom) : by rw [iso.hom_inv_id, comp_id] ... = (ρ_ X).hom ⊗ (𝟙 (𝟙_ C)) : by rw triangle @[simp] lemma braiding_left_unitor (X : C) : (β_ X (𝟙_ C)).hom ≫ (λ_ X).hom = (ρ_ X).hom := by rw [←tensor_right_iff, comp_tensor_id, braiding_left_unitor_aux₂] lemma braiding_right_unitor_aux₁ (X : C) : (α_ X (𝟙_ C) (𝟙_ C)).inv ≫ ((β_ (𝟙_ C) X).inv ⊗ 𝟙 (𝟙_ C)) ≫ (α_ _ X _).hom ≫ (𝟙 _ ⊗ (ρ_ X).hom) = (𝟙 X ⊗ (ρ_ _).hom) ≫ (β_ (𝟙_ C) X).inv := by { rw [←right_unitor_tensor, right_unitor_naturality], simp, } lemma braiding_right_unitor_aux₂ (X : C) : ((𝟙 (𝟙_ C)) ⊗ (β_ (𝟙_ C) X).hom) ≫ ((𝟙 (𝟙_ C)) ⊗ (ρ_ X).hom) = (𝟙 (𝟙_ C)) ⊗ (λ_ X).hom := calc ((𝟙 (𝟙_ C)) ⊗ (β_ (𝟙_ C) X).hom) ≫ ((𝟙 (𝟙_ C)) ⊗ (ρ_ X).hom) = ((𝟙 (𝟙_ C)) ⊗ (β_ (𝟙_ C) X).hom) ≫ (α_ _ _ _).inv ≫ (α_ _ _ _).hom ≫ ((𝟙 (𝟙_ C)) ⊗ (ρ_ X).hom) : by coherence ... = ((𝟙 (𝟙_ C)) ⊗ (β_ (𝟙_ C) X).hom) ≫ (α_ _ _ _).inv ≫ ((β_ _ X).hom ⊗ 𝟙 _) ≫ ((β_ _ X).inv ⊗ 𝟙 _) ≫ (α_ _ _ _).hom ≫ ((𝟙 (𝟙_ C)) ⊗ (ρ_ X).hom) : by { slice_rhs 3 4 { rw [←comp_tensor_id, iso.hom_inv_id, tensor_id], }, rw [id_comp], } ... = (α_ _ _ _).inv ≫ (β_ _ _).hom ≫ (α_ _ _ _).inv ≫ ((β_ _ X).inv ⊗ 𝟙 _) ≫ (α_ _ _ _).hom ≫ ((𝟙 (𝟙_ C)) ⊗ (ρ_ X).hom) : by { slice_lhs 1 3 { rw ←hexagon_reverse }, simp only [assoc], } ... = (α_ _ _ _).inv ≫ (β_ _ _).hom ≫ (𝟙 X ⊗ (ρ_ _).hom) ≫ (β_ _ X).inv : by rw braiding_right_unitor_aux₁ ... = (α_ _ _ _).inv ≫ ((ρ_ _).hom ⊗ 𝟙 _) ≫ (β_ _ X).hom ≫ (β_ _ _).inv : by { slice_lhs 2 3 { rw [←braiding_naturality] }, simp only [assoc], } ... = (α_ _ _ _).inv ≫ ((ρ_ _).hom ⊗ 𝟙 _) : by rw [iso.hom_inv_id, comp_id] ... = (𝟙 (𝟙_ C)) ⊗ (λ_ X).hom : by rw [triangle_assoc_comp_right] @[simp] lemma braiding_right_unitor (X : C) : (β_ (𝟙_ C) X).hom ≫ (ρ_ X).hom = (λ_ X).hom := by rw [←tensor_left_iff, id_tensor_comp, braiding_right_unitor_aux₂] @[simp] lemma left_unitor_inv_braiding (X : C) : (λ_ X).inv ≫ (β_ (𝟙_ C) X).hom = (ρ_ X).inv := begin apply (cancel_mono (ρ_ X).hom).1, simp only [assoc, braiding_right_unitor, iso.inv_hom_id], end @[simp] lemma right_unitor_inv_braiding (X : C) : (ρ_ X).inv ≫ (β_ X (𝟙_ C)).hom = (λ_ X).inv := begin apply (cancel_mono (λ_ X).hom).1, simp only [assoc, braiding_left_unitor, iso.inv_hom_id], end end /-- A symmetric monoidal category is a braided monoidal category for which the braiding is symmetric. See <https://stacks.math.columbia.edu/tag/0FFW>. -/ class symmetric_category (C : Type u) [category.{v} C] [monoidal_category.{v} C] extends braided_category.{v} C := -- braiding symmetric: (symmetry' : ∀ X Y : C, (β_ X Y).hom ≫ (β_ Y X).hom = 𝟙 (X ⊗ Y) . obviously) restate_axiom symmetric_category.symmetry' attribute [simp,reassoc] symmetric_category.symmetry initialize_simps_projections symmetric_category (to_braided_category_braiding → braiding, -to_braided_category) variables (C : Type u₁) [category.{v₁} C] [monoidal_category C] [braided_category C] variables (D : Type u₂) [category.{v₂} D] [monoidal_category D] [braided_category D] variables (E : Type u₃) [category.{v₃} E] [monoidal_category E] [braided_category E] /-- A lax braided functor between braided monoidal categories is a lax monoidal functor which preserves the braiding. -/ structure lax_braided_functor extends lax_monoidal_functor C D := (braided' : ∀ X Y : C, μ X Y ≫ map (β_ X Y).hom = (β_ (obj X) (obj Y)).hom ≫ μ Y X . obviously) restate_axiom lax_braided_functor.braided' namespace lax_braided_functor /-- The identity lax braided monoidal functor. -/ @[simps] def id : lax_braided_functor C C := { .. monoidal_functor.id C } instance : inhabited (lax_braided_functor C C) := ⟨id C⟩ variables {C D E} /-- The composition of lax braided monoidal functors. -/ @[simps] def comp (F : lax_braided_functor C D) (G : lax_braided_functor D E) : lax_braided_functor C E := { braided' := λ X Y, begin dsimp, slice_lhs 2 3 { rw [←category_theory.functor.map_comp, F.braided, category_theory.functor.map_comp], }, slice_lhs 1 2 { rw [G.braided], }, simp only [category.assoc], end, ..(lax_monoidal_functor.comp F.to_lax_monoidal_functor G.to_lax_monoidal_functor) } instance category_lax_braided_functor : category (lax_braided_functor C D) := induced_category.category lax_braided_functor.to_lax_monoidal_functor @[simp] lemma comp_to_nat_trans {F G H : lax_braided_functor C D} {α : F ⟶ G} {β : G ⟶ H} : (α ≫ β).to_nat_trans = @category_struct.comp (C ⥤ D) _ _ _ _ (α.to_nat_trans) (β.to_nat_trans) := rfl /-- Interpret a natural isomorphism of the underlyling lax monoidal functors as an isomorphism of the lax braided monoidal functors. -/ @[simps] def mk_iso {F G : lax_braided_functor C D} (i : F.to_lax_monoidal_functor ≅ G.to_lax_monoidal_functor) : F ≅ G := { ..i } end lax_braided_functor /-- A braided functor between braided monoidal categories is a monoidal functor which preserves the braiding. -/ structure braided_functor extends monoidal_functor C D := -- Note this is stated differently than for `lax_braided_functor`. -- We move the `μ X Y` to the right hand side, -- so that this makes a good `@[simp]` lemma. (braided' : ∀ X Y : C, map (β_ X Y).hom = inv (μ X Y) ≫ (β_ (obj X) (obj Y)).hom ≫ μ Y X . obviously) restate_axiom braided_functor.braided' attribute [simp] braided_functor.braided /-- A braided category with a braided functor to a symmetric category is itself symmetric. -/ def symmetric_category_of_faithful {C D : Type*} [category C] [category D] [monoidal_category C] [monoidal_category D] [braided_category C] [symmetric_category D] (F : braided_functor C D) [faithful F.to_functor] : symmetric_category C := { symmetry' := λ X Y, F.to_functor.map_injective (by simp), } namespace braided_functor /-- Turn a braided functor into a lax braided functor. -/ @[simps] def to_lax_braided_functor (F : braided_functor C D) : lax_braided_functor C D := { braided' := λ X Y, by { rw F.braided, simp, } .. F } /-- The identity braided monoidal functor. -/ @[simps] def id : braided_functor C C := { .. monoidal_functor.id C } instance : inhabited (braided_functor C C) := ⟨id C⟩ variables {C D E} /-- The composition of braided monoidal functors. -/ @[simps] def comp (F : braided_functor C D) (G : braided_functor D E) : braided_functor C E := { ..(monoidal_functor.comp F.to_monoidal_functor G.to_monoidal_functor) } instance category_braided_functor : category (braided_functor C D) := induced_category.category braided_functor.to_monoidal_functor @[simp] lemma comp_to_nat_trans {F G H : braided_functor C D} {α : F ⟶ G} {β : G ⟶ H} : (α ≫ β).to_nat_trans = @category_struct.comp (C ⥤ D) _ _ _ _ (α.to_nat_trans) (β.to_nat_trans) := rfl /-- Interpret a natural isomorphism of the underlyling monoidal functors as an isomorphism of the braided monoidal functors. -/ @[simps] def mk_iso {F G : braided_functor C D} (i : F.to_monoidal_functor ≅ G.to_monoidal_functor) : F ≅ G := { ..i } end braided_functor section comm_monoid variables (M : Type u) [comm_monoid M] instance : braided_category (discrete M) := { braiding := λ X Y, discrete.eq_to_iso (mul_comm X.as Y.as), } variables {M} {N : Type u} [comm_monoid N] /-- A multiplicative morphism between commutative monoids gives a braided functor between the corresponding discrete braided monoidal categories. -/ @[simps] def discrete.braided_functor (F : M →* N) : braided_functor (discrete M) (discrete N) := { ..discrete.monoidal_functor F } end comm_monoid section tensor /-- The strength of the tensor product functor from `C × C` to `C`. -/ def tensor_μ (X Y : C × C) : (tensor C).obj X ⊗ (tensor C).obj Y ⟶ (tensor C).obj (X ⊗ Y) := (α_ X.1 X.2 (Y.1 ⊗ Y.2)).hom ≫ (𝟙 X.1 ⊗ (α_ X.2 Y.1 Y.2).inv) ≫ (𝟙 X.1 ⊗ ((β_ X.2 Y.1).hom ⊗ 𝟙 Y.2)) ≫ (𝟙 X.1 ⊗ (α_ Y.1 X.2 Y.2).hom) ≫ (α_ X.1 Y.1 (X.2 ⊗ Y.2)).inv lemma tensor_μ_def₁ (X₁ X₂ Y₁ Y₂ : C) : tensor_μ C (X₁, X₂) (Y₁, Y₂) ≫ (α_ X₁ Y₁ (X₂ ⊗ Y₂)).hom ≫ (𝟙 X₁ ⊗ (α_ Y₁ X₂ Y₂).inv) = (α_ X₁ X₂ (Y₁ ⊗ Y₂)).hom ≫ (𝟙 X₁ ⊗ (α_ X₂ Y₁ Y₂).inv) ≫ (𝟙 X₁ ⊗ ((β_ X₂ Y₁).hom ⊗ 𝟙 Y₂)) := by { dsimp [tensor_μ], simp } lemma tensor_μ_def₂ (X₁ X₂ Y₁ Y₂ : C) : (𝟙 X₁ ⊗ (α_ X₂ Y₁ Y₂).hom) ≫ (α_ X₁ X₂ (Y₁ ⊗ Y₂)).inv ≫ tensor_μ C (X₁, X₂) (Y₁, Y₂) = (𝟙 X₁ ⊗ ((β_ X₂ Y₁).hom ⊗ 𝟙 Y₂)) ≫ (𝟙 X₁ ⊗ (α_ Y₁ X₂ Y₂).hom) ≫ (α_ X₁ Y₁ (X₂ ⊗ Y₂)).inv := by { dsimp [tensor_μ], simp } lemma tensor_μ_natural {X₁ X₂ Y₁ Y₂ U₁ U₂ V₁ V₂ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (g₁ : U₁ ⟶ V₁) (g₂ : U₂ ⟶ V₂) : ((f₁ ⊗ f₂) ⊗ (g₁ ⊗ g₂)) ≫ tensor_μ C (Y₁, Y₂) (V₁, V₂) = tensor_μ C (X₁, X₂) (U₁, U₂) ≫ ((f₁ ⊗ g₁) ⊗ (f₂ ⊗ g₂)) := begin dsimp [tensor_μ], slice_lhs 1 2 { rw [associator_naturality] }, slice_lhs 2 3 { rw [←tensor_comp, comp_id f₁, ←id_comp f₁, associator_inv_naturality, tensor_comp] }, slice_lhs 3 4 { rw [←tensor_comp, ←tensor_comp, comp_id f₁, ←id_comp f₁, comp_id g₂, ←id_comp g₂, braiding_naturality, tensor_comp, tensor_comp] }, slice_lhs 4 5 { rw [←tensor_comp, comp_id f₁, ←id_comp f₁, associator_naturality, tensor_comp] }, slice_lhs 5 6 { rw [associator_inv_naturality] }, simp only [assoc], end lemma tensor_left_unitality (X₁ X₂ : C) : (λ_ (X₁ ⊗ X₂)).hom = ((λ_ (𝟙_ C)).inv ⊗ 𝟙 (X₁ ⊗ X₂)) ≫ tensor_μ C (𝟙_ C, 𝟙_ C) (X₁, X₂) ≫ ((λ_ X₁).hom ⊗ (λ_ X₂).hom) := begin dsimp [tensor_μ], have : ((λ_ (𝟙_ C)).inv ⊗ 𝟙 (X₁ ⊗ X₂)) ≫ (α_ (𝟙_ C) (𝟙_ C) (X₁ ⊗ X₂)).hom ≫ (𝟙 (𝟙_ C) ⊗ (α_ (𝟙_ C) X₁ X₂).inv) = 𝟙 (𝟙_ C) ⊗ ((λ_ X₁).inv ⊗ 𝟙 X₂) := by pure_coherence, slice_rhs 1 3 { rw this }, clear this, slice_rhs 1 2 { rw [←tensor_comp, ←tensor_comp, comp_id, comp_id, left_unitor_inv_braiding] }, simp only [assoc], coherence, end lemma tensor_right_unitality (X₁ X₂ : C) : (ρ_ (X₁ ⊗ X₂)).hom = (𝟙 (X₁ ⊗ X₂) ⊗ (λ_ (𝟙_ C)).inv) ≫ tensor_μ C (X₁, X₂) (𝟙_ C, 𝟙_ C) ≫ ((ρ_ X₁).hom ⊗ (ρ_ X₂).hom) := begin dsimp [tensor_μ], have : (𝟙 (X₁ ⊗ X₂) ⊗ (λ_ (𝟙_ C)).inv) ≫ (α_ X₁ X₂ (𝟙_ C ⊗ 𝟙_ C)).hom ≫ (𝟙 X₁ ⊗ (α_ X₂ (𝟙_ C) (𝟙_ C)).inv) = (α_ X₁ X₂ (𝟙_ C)).hom ≫ (𝟙 X₁ ⊗ ((ρ_ X₂).inv ⊗ 𝟙 (𝟙_ C))) := by pure_coherence, slice_rhs 1 3 { rw this }, clear this, slice_rhs 2 3 { rw [←tensor_comp, ←tensor_comp, comp_id, comp_id, right_unitor_inv_braiding] }, simp only [assoc], coherence, end /- Diagram B6 from Proposition 1 of [Joyal and Street, *Braided monoidal categories*][Joyal_Street]. -/ lemma tensor_associativity_aux (W X Y Z : C) : ((β_ W X).hom ⊗ 𝟙 (Y ⊗ Z)) ≫ (α_ X W (Y ⊗ Z)).hom ≫ (𝟙 X ⊗ (α_ W Y Z).inv) ≫ (𝟙 X ⊗ (β_ (W ⊗ Y) Z).hom) ≫ (𝟙 X ⊗ (α_ Z W Y).inv) = (𝟙 (W ⊗ X) ⊗ (β_ Y Z).hom) ≫ (α_ (W ⊗ X) Z Y).inv ≫ ((α_ W X Z).hom ⊗ 𝟙 Y) ≫ ((β_ W (X ⊗ Z)).hom ⊗ 𝟙 Y) ≫ ((α_ X Z W).hom ⊗ 𝟙 Y) ≫ (α_ X (Z ⊗ W) Y).hom := begin slice_rhs 3 5 { rw [←tensor_comp, ←tensor_comp, hexagon_forward, tensor_comp, tensor_comp] }, slice_rhs 5 6 { rw [associator_naturality] }, slice_rhs 2 3 { rw [←associator_inv_naturality] }, slice_rhs 3 5 { rw [←pentagon_hom_inv] }, slice_rhs 1 2 { rw [tensor_id, id_tensor_comp_tensor_id, ←tensor_id_comp_id_tensor] }, slice_rhs 2 3 { rw [← tensor_id, associator_naturality] }, slice_rhs 3 5 { rw [←tensor_comp, ←tensor_comp, ←hexagon_reverse, tensor_comp, tensor_comp] }, end lemma tensor_associativity (X₁ X₂ Y₁ Y₂ Z₁ Z₂ : C) : (tensor_μ C (X₁, X₂) (Y₁, Y₂) ⊗ 𝟙 (Z₁ ⊗ Z₂)) ≫ tensor_μ C (X₁ ⊗ Y₁, X₂ ⊗ Y₂) (Z₁, Z₂) ≫ ((α_ X₁ Y₁ Z₁).hom ⊗ (α_ X₂ Y₂ Z₂).hom) = (α_ (X₁ ⊗ X₂) (Y₁ ⊗ Y₂) (Z₁ ⊗ Z₂)).hom ≫ (𝟙 (X₁ ⊗ X₂) ⊗ tensor_μ C (Y₁, Y₂) (Z₁, Z₂)) ≫ tensor_μ C (X₁, X₂) (Y₁ ⊗ Z₁, Y₂ ⊗ Z₂) := begin have : ((α_ X₁ Y₁ Z₁).hom ⊗ (α_ X₂ Y₂ Z₂).hom) = (α_ (X₁ ⊗ Y₁) Z₁ ((X₂ ⊗ Y₂) ⊗ Z₂)).hom ≫ (𝟙 (X₁ ⊗ Y₁) ⊗ (α_ Z₁ (X₂ ⊗ Y₂) Z₂).inv) ≫ (α_ X₁ Y₁ ((Z₁ ⊗ (X₂ ⊗ Y₂)) ⊗ Z₂)).hom ≫ (𝟙 X₁ ⊗ (α_ Y₁ (Z₁ ⊗ (X₂ ⊗ Y₂)) Z₂).inv) ≫ (α_ X₁ (Y₁ ⊗ (Z₁ ⊗ (X₂ ⊗ Y₂))) Z₂).inv ≫ ((𝟙 X₁ ⊗ (𝟙 Y₁ ⊗ (α_ Z₁ X₂ Y₂).inv)) ⊗ 𝟙 Z₂) ≫ ((𝟙 X₁ ⊗ (α_ Y₁ (Z₁ ⊗ X₂) Y₂).inv) ⊗ 𝟙 Z₂) ≫ ((𝟙 X₁ ⊗ ((α_ Y₁ Z₁ X₂).inv ⊗ 𝟙 Y₂)) ⊗ 𝟙 Z₂) ≫ (α_ X₁ (((Y₁ ⊗ Z₁) ⊗ X₂) ⊗ Y₂) Z₂).hom ≫ (𝟙 X₁ ⊗ (α_ ((Y₁ ⊗ Z₁) ⊗ X₂) Y₂ Z₂).hom) ≫ (𝟙 X₁ ⊗ (α_ (Y₁ ⊗ Z₁) X₂ (Y₂ ⊗ Z₂)).hom) ≫ (α_ X₁ (Y₁ ⊗ Z₁) (X₂ ⊗ (Y₂ ⊗ Z₂))).inv := by pure_coherence, rw this, clear this, slice_lhs 2 4 { rw [tensor_μ_def₁] }, slice_lhs 4 5 { rw [←tensor_id, associator_naturality] }, slice_lhs 5 6 { rw [←tensor_comp, associator_inv_naturality, tensor_comp] }, slice_lhs 6 7 { rw [associator_inv_naturality] }, have : (α_ (X₁ ⊗ Y₁) (X₂ ⊗ Y₂) (Z₁ ⊗ Z₂)).hom ≫ (𝟙 (X₁ ⊗ Y₁) ⊗ (α_ (X₂ ⊗ Y₂) Z₁ Z₂).inv) ≫ (α_ X₁ Y₁ (((X₂ ⊗ Y₂) ⊗ Z₁) ⊗ Z₂)).hom ≫ (𝟙 X₁ ⊗ (α_ Y₁ ((X₂ ⊗ Y₂) ⊗ Z₁) Z₂).inv) ≫ (α_ X₁ (Y₁ ⊗ ((X₂ ⊗ Y₂) ⊗ Z₁)) Z₂).inv = ((α_ X₁ Y₁ (X₂ ⊗ Y₂)).hom ⊗ 𝟙 (Z₁ ⊗ Z₂)) ≫ ((𝟙 X₁ ⊗ (α_ Y₁ X₂ Y₂).inv) ⊗ 𝟙 (Z₁ ⊗ Z₂)) ≫ (α_ (X₁ ⊗ ((Y₁ ⊗ X₂) ⊗ Y₂)) Z₁ Z₂).inv ≫ ((α_ X₁ ((Y₁ ⊗ X₂) ⊗ Y₂) Z₁).hom ⊗ 𝟙 Z₂) ≫ ((𝟙 X₁ ⊗ (α_ (Y₁ ⊗ X₂) Y₂ Z₁).hom) ⊗ 𝟙 Z₂) ≫ ((𝟙 X₁ ⊗ (α_ Y₁ X₂ (Y₂ ⊗ Z₁)).hom) ⊗ 𝟙 Z₂) ≫ ((𝟙 X₁ ⊗ (𝟙 Y₁ ⊗ (α_ X₂ Y₂ Z₁).inv)) ⊗ 𝟙 Z₂) := by pure_coherence, slice_lhs 2 6 { rw this }, clear this, slice_lhs 1 3 { rw [←tensor_comp, ←tensor_comp, tensor_μ_def₁, tensor_comp, tensor_comp] }, slice_lhs 3 4 { rw [←tensor_id, associator_inv_naturality] }, slice_lhs 4 5 { rw [←tensor_comp, associator_naturality, tensor_comp] }, slice_lhs 5 6 { rw [←tensor_comp, ←tensor_comp, associator_naturality, tensor_comp, tensor_comp] }, slice_lhs 6 10 { rw [←tensor_comp, ←tensor_comp, ←tensor_comp, ←tensor_comp, ←tensor_comp, ←tensor_comp, ←tensor_comp, ←tensor_comp, tensor_id, tensor_associativity_aux, ←tensor_id, ←id_comp (𝟙 X₁ ≫ 𝟙 X₁ ≫ 𝟙 X₁ ≫ 𝟙 X₁ ≫ 𝟙 X₁), ←id_comp (𝟙 Z₂ ≫ 𝟙 Z₂ ≫ 𝟙 Z₂ ≫ 𝟙 Z₂ ≫ 𝟙 Z₂), tensor_comp, tensor_comp, tensor_comp, tensor_comp, tensor_comp, tensor_comp, tensor_comp, tensor_comp, tensor_comp, tensor_comp] }, slice_lhs 11 12 { rw [←tensor_comp, ←tensor_comp, iso.hom_inv_id], simp }, simp only [assoc, id_comp], slice_lhs 10 11 { rw [←tensor_comp, ←tensor_comp, ←tensor_comp, iso.hom_inv_id], simp }, simp only [assoc, id_comp], slice_lhs 9 10 { rw [associator_naturality] }, slice_lhs 10 11 { rw [←tensor_comp, associator_naturality, tensor_comp] }, slice_lhs 11 13 { rw [tensor_id, ←tensor_μ_def₂] }, have : ((𝟙 X₁ ⊗ (α_ (X₂ ⊗ Y₁) Z₁ Y₂).inv) ⊗ 𝟙 Z₂) ≫ ((𝟙 X₁ ⊗ (α_ X₂ Y₁ Z₁).hom ⊗ 𝟙 Y₂) ⊗ 𝟙 Z₂) ≫ (α_ X₁ ((X₂ ⊗ Y₁ ⊗ Z₁) ⊗ Y₂) Z₂).hom ≫ (𝟙 X₁ ⊗ (α_ (X₂ ⊗ Y₁ ⊗ Z₁) Y₂ Z₂).hom) ≫ (𝟙 X₁ ⊗ (α_ X₂ (Y₁ ⊗ Z₁) (Y₂ ⊗ Z₂)).hom) ≫ (α_ X₁ X₂ ((Y₁ ⊗ Z₁) ⊗ Y₂ ⊗ Z₂)).inv = (α_ X₁ ((X₂ ⊗ Y₁) ⊗ (Z₁ ⊗ Y₂)) Z₂).hom ≫ (𝟙 X₁ ⊗ (α_ (X₂ ⊗ Y₁) (Z₁ ⊗ Y₂) Z₂).hom) ≫ (𝟙 X₁ ⊗ (α_ X₂ Y₁ ((Z₁ ⊗ Y₂) ⊗ Z₂)).hom) ≫ (α_ X₁ X₂ (Y₁ ⊗ ((Z₁ ⊗ Y₂) ⊗ Z₂))).inv ≫ (𝟙 (X₁ ⊗ X₂) ⊗ (𝟙 Y₁ ⊗ (α_ Z₁ Y₂ Z₂).hom)) ≫ (𝟙 (X₁ ⊗ X₂) ⊗ (α_ Y₁ Z₁ (Y₂ ⊗ Z₂)).inv) := by pure_coherence, slice_lhs 7 12 { rw this }, clear this, slice_lhs 6 7 { rw [associator_naturality] }, slice_lhs 7 8 { rw [←tensor_comp, associator_naturality, tensor_comp] }, slice_lhs 8 9 { rw [←tensor_comp, associator_naturality, tensor_comp] }, slice_lhs 9 10 { rw [associator_inv_naturality] }, slice_lhs 10 12 { rw [←tensor_comp, ←tensor_comp, ←tensor_μ_def₂, tensor_comp, tensor_comp] }, dsimp, coherence, end /-- The tensor product functor from `C × C` to `C` as a monoidal functor. -/ @[simps] def tensor_monoidal : monoidal_functor (C × C) C := { ε := (λ_ (𝟙_ C)).inv, μ := λ X Y, tensor_μ C X Y, μ_natural' := λ X Y X' Y' f g, tensor_μ_natural C f.1 f.2 g.1 g.2, associativity' := λ X Y Z, tensor_associativity C X.1 X.2 Y.1 Y.2 Z.1 Z.2, left_unitality' := λ ⟨X₁, X₂⟩, tensor_left_unitality C X₁ X₂, right_unitality' := λ ⟨X₁, X₂⟩, tensor_right_unitality C X₁ X₂, μ_is_iso := by { dsimp [tensor_μ], apply_instance }, .. tensor C } lemma left_unitor_monoidal (X₁ X₂ : C) : (λ_ X₁).hom ⊗ (λ_ X₂).hom = tensor_μ C (𝟙_ C, X₁) (𝟙_ C, X₂) ≫ ((λ_ (𝟙_ C)).hom ⊗ 𝟙 (X₁ ⊗ X₂)) ≫ (λ_ (X₁ ⊗ X₂)).hom := begin dsimp [tensor_μ], have : (λ_ X₁).hom ⊗ (λ_ X₂).hom = (α_ (𝟙_ C) X₁ (𝟙_ C ⊗ X₂)).hom ≫ (𝟙 (𝟙_ C) ⊗ (α_ X₁ (𝟙_ C) X₂).inv) ≫ (λ_ ((X₁ ⊗ (𝟙_ C)) ⊗ X₂)).hom ≫ ((ρ_ X₁).hom ⊗ (𝟙 X₂)) := by pure_coherence, rw this, clear this, rw ←braiding_left_unitor, slice_lhs 3 4 { rw [←id_comp (𝟙 X₂), tensor_comp] }, slice_lhs 3 4 { rw [←left_unitor_naturality] }, coherence, end lemma right_unitor_monoidal (X₁ X₂ : C) : (ρ_ X₁).hom ⊗ (ρ_ X₂).hom = tensor_μ C (X₁, 𝟙_ C) (X₂, 𝟙_ C) ≫ (𝟙 (X₁ ⊗ X₂) ⊗ (λ_ (𝟙_ C)).hom) ≫ (ρ_ (X₁ ⊗ X₂)).hom := begin dsimp [tensor_μ], have : (ρ_ X₁).hom ⊗ (ρ_ X₂).hom = (α_ X₁ (𝟙_ C) (X₂ ⊗ (𝟙_ C))).hom ≫ (𝟙 X₁ ⊗ (α_ (𝟙_ C) X₂ (𝟙_ C)).inv) ≫ (𝟙 X₁ ⊗ (ρ_ (𝟙_ C ⊗ X₂)).hom) ≫ (𝟙 X₁ ⊗ (λ_ X₂).hom) := by pure_coherence, rw this, clear this, rw ←braiding_right_unitor, slice_lhs 3 4 { rw [←id_comp (𝟙 X₁), tensor_comp, id_comp] }, slice_lhs 3 4 { rw [←tensor_comp, ←right_unitor_naturality, tensor_comp] }, coherence, end lemma associator_monoidal_aux (W X Y Z : C) : (𝟙 W ⊗ (β_ X (Y ⊗ Z)).hom) ≫ (𝟙 W ⊗ (α_ Y Z X).hom) ≫ (α_ W Y (Z ⊗ X)).inv ≫ ((β_ W Y).hom ⊗ 𝟙 (Z ⊗ X)) = (α_ W X (Y ⊗ Z)).inv ≫ (α_ (W ⊗ X) Y Z).inv ≫ ((β_ (W ⊗ X) Y).hom ⊗ 𝟙 Z) ≫ ((α_ Y W X).inv ⊗ 𝟙 Z) ≫ (α_ (Y ⊗ W) X Z).hom ≫ (𝟙 (Y ⊗ W) ⊗ (β_ X Z).hom) := begin slice_rhs 1 2 { rw ←pentagon_inv }, slice_rhs 3 5 { rw [←tensor_comp, ←tensor_comp, hexagon_reverse, tensor_comp, tensor_comp] }, slice_rhs 5 6 { rw associator_naturality }, slice_rhs 6 7 { rw [tensor_id, tensor_id_comp_id_tensor, ←id_tensor_comp_tensor_id] }, slice_rhs 2 3 { rw ←associator_inv_naturality }, slice_rhs 3 5 { rw pentagon_inv_inv_hom }, slice_rhs 4 5 { rw [←tensor_id, ←associator_inv_naturality] }, slice_rhs 2 4 { rw [←tensor_comp, ←tensor_comp, ←hexagon_forward, tensor_comp, tensor_comp] }, simp, end lemma associator_monoidal (X₁ X₂ X₃ Y₁ Y₂ Y₃ : C) : tensor_μ C (X₁ ⊗ X₂, X₃) (Y₁ ⊗ Y₂, Y₃) ≫ (tensor_μ C (X₁, X₂) (Y₁, Y₂) ⊗ 𝟙 (X₃ ⊗ Y₃)) ≫ (α_ (X₁ ⊗ Y₁) (X₂ ⊗ Y₂) (X₃ ⊗ Y₃)).hom = ((α_ X₁ X₂ X₃).hom ⊗ (α_ Y₁ Y₂ Y₃).hom) ≫ tensor_μ C (X₁, X₂ ⊗ X₃) (Y₁, Y₂ ⊗ Y₃) ≫ (𝟙 (X₁ ⊗ Y₁) ⊗ tensor_μ C (X₂, X₃) (Y₂, Y₃)) := begin have : (α_ (X₁ ⊗ Y₁) (X₂ ⊗ Y₂) (X₃ ⊗ Y₃)).hom = ((α_ X₁ Y₁ (X₂ ⊗ Y₂)).hom ⊗ 𝟙 (X₃ ⊗ Y₃)) ≫ ((𝟙 X₁ ⊗ (α_ Y₁ X₂ Y₂).inv) ⊗ 𝟙 (X₃ ⊗ Y₃)) ≫ (α_ (X₁ ⊗ ((Y₁ ⊗ X₂) ⊗ Y₂)) X₃ Y₃).inv ≫ ((α_ X₁ ((Y₁ ⊗ X₂) ⊗ Y₂) X₃).hom ⊗ 𝟙 Y₃) ≫ ((𝟙 X₁ ⊗ (α_ (Y₁ ⊗ X₂) Y₂ X₃).hom) ⊗ 𝟙 Y₃) ≫ (α_ X₁ ((Y₁ ⊗ X₂) ⊗ (Y₂ ⊗ X₃)) Y₃).hom ≫ (𝟙 X₁ ⊗ (α_ (Y₁ ⊗ X₂) (Y₂ ⊗ X₃) Y₃).hom) ≫ (𝟙 X₁ ⊗ (α_ Y₁ X₂ ((Y₂ ⊗ X₃) ⊗ Y₃)).hom) ≫ (α_ X₁ Y₁ (X₂ ⊗ ((Y₂ ⊗ X₃) ⊗ Y₃))).inv ≫ (𝟙 (X₁ ⊗ Y₁) ⊗ (𝟙 X₂ ⊗ (α_ Y₂ X₃ Y₃).hom)) ≫ (𝟙 (X₁ ⊗ Y₁) ⊗ (α_ X₂ Y₂ (X₃ ⊗ Y₃)).inv) := by pure_coherence, rw this, clear this, slice_lhs 2 4 { rw [←tensor_comp, ←tensor_comp, tensor_μ_def₁, tensor_comp, tensor_comp] }, slice_lhs 4 5 { rw [←tensor_id, associator_inv_naturality] }, slice_lhs 5 6 { rw [←tensor_comp, associator_naturality, tensor_comp] }, slice_lhs 6 7 { rw [←tensor_comp, ←tensor_comp, associator_naturality, tensor_comp, tensor_comp] }, have : ((α_ X₁ X₂ (Y₁ ⊗ Y₂)).hom ⊗ 𝟙 (X₃ ⊗ Y₃)) ≫ ((𝟙 X₁ ⊗ (α_ X₂ Y₁ Y₂).inv) ⊗ 𝟙 (X₃ ⊗ Y₃)) ≫ (α_ (X₁ ⊗ ((X₂ ⊗ Y₁) ⊗ Y₂)) X₃ Y₃).inv ≫ ((α_ X₁ ((X₂ ⊗ Y₁) ⊗ Y₂) X₃).hom ⊗ 𝟙 Y₃) ≫ ((𝟙 X₁ ⊗ (α_ (X₂ ⊗ Y₁) Y₂ X₃).hom) ⊗ 𝟙 Y₃) = (α_ (X₁ ⊗ X₂) (Y₁ ⊗ Y₂) (X₃ ⊗ Y₃)).hom ≫ (𝟙 (X₁ ⊗ X₂) ⊗ (α_ (Y₁ ⊗ Y₂) X₃ Y₃).inv) ≫ (α_ X₁ X₂ (((Y₁ ⊗ Y₂) ⊗ X₃) ⊗ Y₃)).hom ≫ (𝟙 X₁ ⊗ (α_ X₂ ((Y₁ ⊗ Y₂) ⊗ X₃) Y₃).inv) ≫ (α_ X₁ (X₂ ⊗ ((Y₁ ⊗ Y₂) ⊗ X₃)) Y₃).inv ≫ ((𝟙 X₁ ⊗ (𝟙 X₂ ⊗ (α_ Y₁ Y₂ X₃).hom)) ⊗ 𝟙 Y₃) ≫ ((𝟙 X₁ ⊗ (α_ X₂ Y₁ (Y₂ ⊗ X₃)).inv) ⊗ 𝟙 Y₃) := by pure_coherence, slice_lhs 2 6 { rw this }, clear this, slice_lhs 1 3 { rw tensor_μ_def₁ }, slice_lhs 3 4 { rw [←tensor_id, associator_naturality] }, slice_lhs 4 5 { rw [←tensor_comp, associator_inv_naturality, tensor_comp] }, slice_lhs 5 6 { rw associator_inv_naturality }, slice_lhs 6 9 { rw [←tensor_comp, ←tensor_comp, ←tensor_comp, ←tensor_comp, ←tensor_comp, ←tensor_comp, tensor_id, associator_monoidal_aux, ←id_comp (𝟙 X₁ ≫ 𝟙 X₁ ≫ 𝟙 X₁ ≫ 𝟙 X₁), ←id_comp (𝟙 X₁ ≫ 𝟙 X₁ ≫ 𝟙 X₁ ≫ 𝟙 X₁ ≫ 𝟙 X₁), ←id_comp (𝟙 Y₃ ≫ 𝟙 Y₃ ≫ 𝟙 Y₃ ≫ 𝟙 Y₃), ←id_comp (𝟙 Y₃ ≫ 𝟙 Y₃ ≫ 𝟙 Y₃ ≫ 𝟙 Y₃ ≫ 𝟙 Y₃), tensor_comp, tensor_comp, tensor_comp, tensor_comp, tensor_comp, tensor_comp, tensor_comp, tensor_comp, tensor_comp, tensor_comp] }, slice_lhs 11 12 { rw associator_naturality }, slice_lhs 12 13 { rw [←tensor_comp, associator_naturality, tensor_comp] }, slice_lhs 13 14 { rw [←tensor_comp, ←tensor_id, associator_naturality, tensor_comp] }, slice_lhs 14 15 { rw associator_inv_naturality }, slice_lhs 15 17 { rw [tensor_id, ←tensor_comp, ←tensor_comp, ←tensor_μ_def₂, tensor_comp, tensor_comp] }, have : ((𝟙 X₁ ⊗ ((α_ Y₁ X₂ X₃).inv ⊗ 𝟙 Y₂)) ⊗ 𝟙 Y₃) ≫ ((𝟙 X₁ ⊗ (α_ (Y₁ ⊗ X₂) X₃ Y₂).hom) ⊗ 𝟙 Y₃) ≫ (α_ X₁ ((Y₁ ⊗ X₂) ⊗ (X₃ ⊗ Y₂)) Y₃).hom ≫ (𝟙 X₁ ⊗ (α_ (Y₁ ⊗ X₂) (X₃ ⊗ Y₂) Y₃).hom) ≫ (𝟙 X₁ ⊗ (α_ Y₁ X₂ ((X₃ ⊗ Y₂) ⊗ Y₃)).hom) ≫ (α_ X₁ Y₁ (X₂ ⊗ ((X₃ ⊗ Y₂) ⊗ Y₃))).inv ≫ (𝟙 (X₁ ⊗ Y₁) ⊗ (𝟙 X₂ ⊗ (α_ X₃ Y₂ Y₃).hom)) ≫ (𝟙 (X₁ ⊗ Y₁) ⊗ (α_ X₂ X₃ (Y₂ ⊗ Y₃)).inv) = (α_ X₁ ((Y₁ ⊗ (X₂ ⊗ X₃)) ⊗ Y₂) Y₃).hom ≫ (𝟙 X₁ ⊗ (α_ (Y₁ ⊗ (X₂ ⊗ X₃)) Y₂ Y₃).hom) ≫ (𝟙 X₁ ⊗ (α_ Y₁ (X₂ ⊗ X₃) (Y₂ ⊗ Y₃)).hom) ≫ (α_ X₁ Y₁ ((X₂ ⊗ X₃) ⊗ (Y₂ ⊗ Y₃))).inv := by pure_coherence, slice_lhs 9 16 { rw this }, clear this, slice_lhs 8 9 { rw associator_naturality }, slice_lhs 9 10 { rw [←tensor_comp, associator_naturality, tensor_comp] }, slice_lhs 10 12 { rw [tensor_id, ←tensor_μ_def₂] }, dsimp, coherence, end end tensor end category_theory
4067fc26eed8c6f50d9dfb76677f32207b339b0b
3dc4623269159d02a444fe898d33e8c7e7e9461b
/.github/workflows/project_1_a_decrire/lean-scheme-submission/src/scheme.lean
f0c5e86714a6f822039e74022d9af703094b7c3f
[]
no_license
Or7ando/lean
cc003e6c41048eae7c34aa6bada51c9e9add9e66
d41169cf4e416a0d42092fb6bdc14131cee9dd15
refs/heads/master
1,650,600,589,722
1,587,262,906,000
1,587,262,906,000
255,387,160
0
0
null
null
null
null
UTF-8
Lean
false
false
738
lean
/- Definition of a scheme. https://stacks.math.columbia.edu/tag/01II -/ import topology.basic import sheaves.covering.covering import sheaves.presheaf_of_rings_maps import sheaves.locally_ringed_space import spectrum_of_a_ring.zariski_topology import spectrum_of_a_ring.structure_sheaf open topological_space universes u v open presheaf_of_rings -- A scheme is a locally ringed space covered by affine schemes. structure scheme (α : Type u) [topological_space α] := (carrier : locally_ringed_space α) (Haffinecov : ∃ (OC : covering.univ α), ∀ i, ∃ (R : Type v) [comm_ring R] (fpU : open_immersion_pullback (Spec R) carrier.O.F), fpU.range = OC.Uis i ∧ fpU.carrier ≅ structure_sheaf.presheaf R)
6ef2a43115de70593eb430a69f67319eb2209ca2
d1bbf1801b3dcb214451d48214589f511061da63
/src/topology/instances/ennreal.lean
d78937b8f813ff7de534f2b6f4c653a7e2a4b40e
[ "Apache-2.0" ]
permissive
cheraghchi/mathlib
5c366f8c4f8e66973b60c37881889da8390cab86
f29d1c3038422168fbbdb2526abf7c0ff13e86db
refs/heads/master
1,676,577,831,283
1,610,894,638,000
1,610,894,638,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
43,647
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 -/ import topology.instances.nnreal /-! # Extended non-negative reals -/ noncomputable theory open classical set filter metric open_locale classical topological_space ennreal nnreal big_operators filter variables {α : Type*} {β : Type*} {γ : Type*} namespace ennreal variables {a b c d : ennreal} {r p q : ℝ≥0} variables {x y z : ennreal} {ε ε₁ ε₂ : ennreal} {s : set ennreal} section topological_space open topological_space /-- Topology on `ennreal`. Note: this is different from the `emetric_space` topology. The `emetric_space` topology has `is_open {⊤}`, while this topology doesn't have singleton elements. -/ instance : topological_space ennreal := preorder.topology ennreal instance : order_topology ennreal := ⟨rfl⟩ instance : t2_space ennreal := by apply_instance -- short-circuit type class inference instance : second_countable_topology ennreal := ⟨⟨⋃q ≥ (0:ℚ), {{a : ennreal | a < nnreal.of_real q}, {a : ennreal | ↑(nnreal.of_real q) < a}}, (countable_encodable _).bUnion $ assume a ha, (countable_singleton _).insert _, le_antisymm (le_generate_from $ by simp [or_imp_distrib, is_open_lt', is_open_gt'] {contextual := tt}) (le_generate_from $ λ s h, begin rcases h with ⟨a, hs | hs⟩; [ rw show s = ⋃q∈{q:ℚ | 0 ≤ q ∧ a < nnreal.of_real q}, {b | ↑(nnreal.of_real q) < b}, from set.ext (assume b, by simp [hs, @ennreal.lt_iff_exists_rat_btwn a b, and_assoc]), rw show s = ⋃q∈{q:ℚ | 0 ≤ q ∧ ↑(nnreal.of_real q) < a}, {b | b < ↑(nnreal.of_real q)}, from set.ext (assume b, by simp [hs, @ennreal.lt_iff_exists_rat_btwn b a, and_comm, and_assoc])]; { apply is_open_Union, intro q, apply is_open_Union, intro hq, exact generate_open.basic _ (mem_bUnion hq.1 $ by simp) } end)⟩⟩ lemma embedding_coe : embedding (coe : ℝ≥0 → ennreal) := ⟨⟨begin refine le_antisymm _ _, { rw [@order_topology.topology_eq_generate_intervals ennreal _, ← coinduced_le_iff_le_induced], refine le_generate_from (assume s ha, _), rcases ha with ⟨a, rfl | rfl⟩, show is_open {b : ℝ≥0 | a < ↑b}, { cases a; simp [none_eq_top, some_eq_coe, is_open_lt'] }, show is_open {b : ℝ≥0 | ↑b < a}, { cases a; simp [none_eq_top, some_eq_coe, is_open_gt', is_open_const] } }, { rw [@order_topology.topology_eq_generate_intervals ℝ≥0 _], refine le_generate_from (assume s ha, _), rcases ha with ⟨a, rfl | rfl⟩, exact ⟨Ioi a, is_open_Ioi, by simp [Ioi]⟩, exact ⟨Iio a, is_open_Iio, by simp [Iio]⟩ } end⟩, assume a b, coe_eq_coe.1⟩ lemma is_open_ne_top : is_open {a : ennreal | a ≠ ⊤} := is_open_ne lemma is_open_Ico_zero : is_open (Ico 0 b) := by { rw ennreal.Ico_eq_Iio, exact is_open_Iio} lemma coe_range_mem_nhds : range (coe : ℝ≥0 → ennreal) ∈ 𝓝 (r : ennreal) := have {a : ennreal | a ≠ ⊤} = range (coe : ℝ≥0 → ennreal), from set.ext $ assume a, by cases a; simp [none_eq_top, some_eq_coe], this ▸ mem_nhds_sets is_open_ne_top coe_ne_top @[norm_cast] lemma tendsto_coe {f : filter α} {m : α → ℝ≥0} {a : ℝ≥0} : tendsto (λa, (m a : ennreal)) f (𝓝 ↑a) ↔ tendsto m f (𝓝 a) := embedding_coe.tendsto_nhds_iff.symm lemma continuous_coe : continuous (coe : ℝ≥0 → ennreal) := embedding_coe.continuous lemma continuous_coe_iff {α} [topological_space α] {f : α → ℝ≥0} : continuous (λa, (f a : ennreal)) ↔ continuous f := embedding_coe.continuous_iff.symm lemma nhds_coe {r : ℝ≥0} : 𝓝 (r : ennreal) = (𝓝 r).map coe := by rw [embedding_coe.induced, map_nhds_induced_eq coe_range_mem_nhds] lemma nhds_coe_coe {r p : ℝ≥0} : 𝓝 ((r : ennreal), (p : ennreal)) = (𝓝 (r, p)).map (λp:ℝ≥0×ℝ≥0, (p.1, p.2)) := begin rw [(embedding_coe.prod_mk embedding_coe).map_nhds_eq], rw [← prod_range_range_eq], exact prod_mem_nhds_sets coe_range_mem_nhds coe_range_mem_nhds end lemma continuous_of_real : continuous ennreal.of_real := (continuous_coe_iff.2 continuous_id).comp nnreal.continuous_of_real lemma tendsto_of_real {f : filter α} {m : α → ℝ} {a : ℝ} (h : tendsto m f (𝓝 a)) : tendsto (λa, ennreal.of_real (m a)) f (𝓝 (ennreal.of_real a)) := tendsto.comp (continuous.tendsto continuous_of_real _) h lemma tendsto_to_nnreal {a : ennreal} : a ≠ ⊤ → tendsto (ennreal.to_nnreal) (𝓝 a) (𝓝 a.to_nnreal) := begin cases a; simp [some_eq_coe, none_eq_top, nhds_coe, tendsto_map'_iff, (∘)], exact tendsto_id end lemma continuous_on_to_nnreal : continuous_on ennreal.to_nnreal {a | a ≠ ∞} := continuous_on_iff_continuous_restrict.2 $ continuous_iff_continuous_at.2 $ λ x, (tendsto_to_nnreal x.2).comp continuous_at_subtype_coe lemma tendsto_to_real {a : ennreal} : a ≠ ⊤ → tendsto (ennreal.to_real) (𝓝 a) (𝓝 a.to_real) := λ ha, tendsto.comp ((@nnreal.tendsto_coe _ (𝓝 a.to_nnreal) id (a.to_nnreal)).2 tendsto_id) (tendsto_to_nnreal ha) /-- The set of finite `ennreal` numbers is homeomorphic to `ℝ≥0`. -/ def ne_top_homeomorph_nnreal : {a | a ≠ ∞} ≃ₜ ℝ≥0 := { continuous_to_fun := continuous_on_iff_continuous_restrict.1 continuous_on_to_nnreal, continuous_inv_fun := continuous_subtype_mk _ continuous_coe, .. ne_top_equiv_nnreal } /-- The set of finite `ennreal` numbers is homeomorphic to `ℝ≥0`. -/ def lt_top_homeomorph_nnreal : {a | a < ∞} ≃ₜ ℝ≥0 := by refine (homeomorph.set_congr $ set.ext $ λ x, _).trans ne_top_homeomorph_nnreal; simp only [mem_set_of_eq, lt_top_iff_ne_top] lemma nhds_top : 𝓝 ∞ = ⨅ a ≠ ∞, 𝓟 (Ioi a) := nhds_top_order.trans $ by simp [lt_top_iff_ne_top, Ioi] lemma nhds_top' : 𝓝 ∞ = ⨅ r : ℝ≥0, 𝓟 (Ioi r) := nhds_top.trans $ infi_ne_top _ lemma tendsto_nhds_top_iff_nnreal {m : α → ennreal} {f : filter α} : tendsto m f (𝓝 ⊤) ↔ ∀ x : ℝ≥0, ∀ᶠ a in f, ↑x < m a := by simp only [nhds_top', tendsto_infi, tendsto_principal, mem_Ioi] lemma tendsto_nhds_top_iff_nat {m : α → ennreal} {f : filter α} : tendsto m f (𝓝 ⊤) ↔ ∀ n : ℕ, ∀ᶠ a in f, ↑n < m a := tendsto_nhds_top_iff_nnreal.trans ⟨λ h n, by simpa only [ennreal.coe_nat] using h n, λ h x, let ⟨n, hn⟩ := exists_nat_gt x in (h n).mono (λ y, lt_trans $ by rwa [← ennreal.coe_nat, coe_lt_coe])⟩ lemma tendsto_nhds_top {m : α → ennreal} {f : filter α} (h : ∀ n : ℕ, ∀ᶠ a in f, ↑n < m a) : tendsto m f (𝓝 ⊤) := tendsto_nhds_top_iff_nat.2 h lemma tendsto_nat_nhds_top : tendsto (λ n : ℕ, ↑n) at_top (𝓝 ∞) := tendsto_nhds_top $ λ n, mem_at_top_sets.2 ⟨n+1, λ m hm, ennreal.coe_nat_lt_coe_nat.2 $ nat.lt_of_succ_le hm⟩ @[simp, norm_cast] lemma tendsto_coe_nhds_top {f : α → ℝ≥0} {l : filter α} : tendsto (λ x, (f x : ennreal)) l (𝓝 ∞) ↔ tendsto f l at_top := by rw [tendsto_nhds_top_iff_nnreal, at_top_basis_Ioi.tendsto_right_iff]; [simp, apply_instance, apply_instance] lemma nhds_zero : 𝓝 (0 : ennreal) = ⨅a ≠ 0, 𝓟 (Iio a) := nhds_bot_order.trans $ by simp [bot_lt_iff_ne_bot, Iio] -- using Icc because -- • don't have 'Ioo (x - ε) (x + ε) ∈ 𝓝 x' unless x > 0 -- • (x - y ≤ ε ↔ x ≤ ε + y) is true, while (x - y < ε ↔ x < ε + y) is not lemma Icc_mem_nhds : x ≠ ⊤ → 0 < ε → Icc (x - ε) (x + ε) ∈ 𝓝 x := begin assume xt ε0, rw mem_nhds_sets_iff, by_cases x0 : x = 0, { use Iio (x + ε), have : Iio (x + ε) ⊆ Icc (x - ε) (x + ε), assume a, rw x0, simpa using le_of_lt, use this, exact ⟨is_open_Iio, mem_Iio_self_add xt ε0⟩ }, { use Ioo (x - ε) (x + ε), use Ioo_subset_Icc_self, exact ⟨is_open_Ioo, mem_Ioo_self_sub_add xt x0 ε0 ε0 ⟩ } end lemma nhds_of_ne_top : x ≠ ⊤ → 𝓝 x = ⨅ε > 0, 𝓟 (Icc (x - ε) (x + ε)) := begin assume xt, refine le_antisymm _ _, -- first direction simp only [le_infi_iff, le_principal_iff], assume ε ε0, exact Icc_mem_nhds xt ε0, -- second direction rw nhds_generate_from, refine le_infi (assume s, le_infi $ assume hs, _), simp only [mem_set_of_eq] at hs, rcases hs with ⟨xs, ⟨a, ha⟩⟩, cases ha, { rw ha at *, rcases exists_between xs with ⟨b, ⟨ab, bx⟩⟩, have xb_pos : x - b > 0 := zero_lt_sub_iff_lt.2 bx, have xxb : x - (x - b) = b := sub_sub_cancel (by rwa lt_top_iff_ne_top) (le_of_lt bx), refine infi_le_of_le (x - b) (infi_le_of_le xb_pos _), simp only [mem_principal_sets, le_principal_iff], assume y, rintros ⟨h₁, h₂⟩, rw xxb at h₁, calc a < b : ab ... ≤ y : h₁ }, { rw ha at *, rcases exists_between xs with ⟨b, ⟨xb, ba⟩⟩, have bx_pos : b - x > 0 := zero_lt_sub_iff_lt.2 xb, have xbx : x + (b - x) = b := add_sub_cancel_of_le (le_of_lt xb), refine infi_le_of_le (b - x) (infi_le_of_le bx_pos _), simp only [mem_principal_sets, le_principal_iff], assume y, rintros ⟨h₁, h₂⟩, rw xbx at h₂, calc y ≤ b : h₂ ... < a : ba }, end /-- Characterization of neighborhoods for `ennreal` numbers. See also `tendsto_order` for a version with strict inequalities. -/ protected theorem tendsto_nhds {f : filter α} {u : α → ennreal} {a : ennreal} (ha : a ≠ ⊤) : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, (u x) ∈ Icc (a - ε) (a + ε) := by simp only [nhds_of_ne_top ha, tendsto_infi, tendsto_principal, mem_Icc] protected lemma tendsto_at_top [nonempty β] [semilattice_sup β] {f : β → ennreal} {a : ennreal} (ha : a ≠ ⊤) : tendsto f at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, (f n) ∈ Icc (a - ε) (a + ε) := by simp only [ennreal.tendsto_nhds ha, mem_at_top_sets, mem_set_of_eq, filter.eventually] instance : has_continuous_add ennreal := begin refine ⟨continuous_iff_continuous_at.2 _⟩, rintro ⟨(_|a), b⟩, { exact tendsto_nhds_top_mono' continuous_at_fst (λ p, le_add_right le_rfl) }, rcases b with (_|b), { exact tendsto_nhds_top_mono' continuous_at_snd (λ p, le_add_left le_rfl) }, simp only [continuous_at, some_eq_coe, nhds_coe_coe, ← coe_add, tendsto_map'_iff, (∘), tendsto_coe, tendsto_add] end protected lemma tendsto_mul (ha : a ≠ 0 ∨ b ≠ ⊤) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λp:ennreal×ennreal, p.1 * p.2) (𝓝 (a, b)) (𝓝 (a * b)) := have ht : ∀b:ennreal, b ≠ 0 → tendsto (λp:ennreal×ennreal, p.1 * p.2) (𝓝 ((⊤:ennreal), b)) (𝓝 ⊤), begin refine assume b hb, tendsto_nhds_top_iff_nnreal.2 $ assume n, _, rcases lt_iff_exists_nnreal_btwn.1 (pos_iff_ne_zero.2 hb) with ⟨ε, hε, hεb⟩, replace hε : 0 < ε, from coe_pos.1 hε, filter_upwards [prod_mem_nhds_sets (lt_mem_nhds $ @coe_lt_top (n / ε)) (lt_mem_nhds hεb)], rintros ⟨a₁, a₂⟩ ⟨h₁, h₂⟩, dsimp at h₁ h₂ ⊢, rw [← div_mul_cancel n hε.ne', coe_mul], exact mul_lt_mul h₁ h₂ end, begin cases a, {simp [none_eq_top] at hb, simp [none_eq_top, ht b hb, top_mul, hb] }, cases b, { simp [none_eq_top] at ha, simp [*, nhds_swap (a : ennreal) ⊤, none_eq_top, some_eq_coe, top_mul, tendsto_map'_iff, (∘), mul_comm] }, simp [some_eq_coe, nhds_coe_coe, tendsto_map'_iff, (∘)], simp only [coe_mul.symm, tendsto_coe, tendsto_mul] end protected lemma tendsto.mul {f : filter α} {ma : α → ennreal} {mb : α → ennreal} {a b : ennreal} (hma : tendsto ma f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ ⊤) (hmb : tendsto mb f (𝓝 b)) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λa, ma a * mb a) f (𝓝 (a * b)) := show tendsto ((λp:ennreal×ennreal, p.1 * p.2) ∘ (λa, (ma a, mb a))) f (𝓝 (a * b)), from tendsto.comp (ennreal.tendsto_mul ha hb) (hma.prod_mk_nhds hmb) protected lemma tendsto.const_mul {f : filter α} {m : α → ennreal} {a b : ennreal} (hm : tendsto m f (𝓝 b)) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λb, a * m b) f (𝓝 (a * b)) := by_cases (assume : a = 0, by simp [this, tendsto_const_nhds]) (assume ha : a ≠ 0, ennreal.tendsto.mul tendsto_const_nhds (or.inl ha) hm hb) protected lemma tendsto.mul_const {f : filter α} {m : α → ennreal} {a b : ennreal} (hm : tendsto m f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ ⊤) : tendsto (λx, m x * b) f (𝓝 (a * b)) := by simpa only [mul_comm] using ennreal.tendsto.const_mul hm ha protected lemma continuous_at_const_mul {a b : ennreal} (h : a ≠ ⊤ ∨ b ≠ 0) : continuous_at ((*) a) b := tendsto.const_mul tendsto_id h.symm protected lemma continuous_at_mul_const {a b : ennreal} (h : a ≠ ⊤ ∨ b ≠ 0) : continuous_at (λ x, x * a) b := tendsto.mul_const tendsto_id h.symm protected lemma continuous_const_mul {a : ennreal} (ha : a ≠ ⊤) : continuous ((*) a) := continuous_iff_continuous_at.2 $ λ x, ennreal.continuous_at_const_mul (or.inl ha) protected lemma continuous_mul_const {a : ennreal} (ha : a ≠ ⊤) : continuous (λ x, x * a) := continuous_iff_continuous_at.2 $ λ x, ennreal.continuous_at_mul_const (or.inl ha) lemma le_of_forall_lt_one_mul_le {x y : ennreal} (h : ∀ a < 1, a * x ≤ y) : x ≤ y := begin have : tendsto (* x) (𝓝[Iio 1] 1) (𝓝 (1 * x)) := (ennreal.continuous_at_mul_const (or.inr one_ne_zero)).mono_left inf_le_left, rw one_mul at this, haveI : (𝓝[Iio 1] (1 : ennreal)).ne_bot := nhds_within_Iio_self_ne_bot' ennreal.zero_lt_one, exact le_of_tendsto this (eventually_nhds_within_iff.2 $ eventually_of_forall h) end lemma infi_mul_left {ι} [nonempty ι] {f : ι → ennreal} {a : ennreal} (h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) : (⨅ i, a * f i) = a * ⨅ i, f i := begin by_cases H : a = ⊤ ∧ (⨅ i, f i) = 0, { rcases h H.1 H.2 with ⟨i, hi⟩, rw [H.2, mul_zero, ← bot_eq_zero, infi_eq_bot], exact λ b hb, ⟨i, by rwa [hi, mul_zero, ← bot_eq_zero]⟩ }, { rw not_and_distrib at H, exact (map_infi_of_continuous_at_of_monotone' (ennreal.continuous_at_const_mul H) ennreal.mul_left_mono).symm } end lemma infi_mul_right {ι} [nonempty ι] {f : ι → ennreal} {a : ennreal} (h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) : (⨅ i, f i * a) = (⨅ i, f i) * a := by simpa only [mul_comm a] using infi_mul_left h protected lemma continuous_inv : continuous (has_inv.inv : ennreal → ennreal) := continuous_iff_continuous_at.2 $ λ a, tendsto_order.2 ⟨begin assume b hb, simp only [@ennreal.lt_inv_iff_lt_inv b], exact gt_mem_nhds (ennreal.lt_inv_iff_lt_inv.1 hb), end, begin assume b hb, simp only [gt_iff_lt, @ennreal.inv_lt_iff_inv_lt _ b], exact lt_mem_nhds (ennreal.inv_lt_iff_inv_lt.1 hb) end⟩ @[simp] protected lemma tendsto_inv_iff {f : filter α} {m : α → ennreal} {a : ennreal} : tendsto (λ x, (m x)⁻¹) f (𝓝 a⁻¹) ↔ tendsto m f (𝓝 a) := ⟨λ h, by simpa only [function.comp, ennreal.inv_inv] using (ennreal.continuous_inv.tendsto a⁻¹).comp h, (ennreal.continuous_inv.tendsto a).comp⟩ protected lemma tendsto.div {f : filter α} {ma : α → ennreal} {mb : α → ennreal} {a b : ennreal} (hma : tendsto ma f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ 0) (hmb : tendsto mb f (𝓝 b)) (hb : b ≠ ⊤ ∨ a ≠ ⊤) : tendsto (λa, ma a / mb a) f (𝓝 (a / b)) := by { apply tendsto.mul hma _ (ennreal.tendsto_inv_iff.2 hmb) _; simp [ha, hb] } protected lemma tendsto.const_div {f : filter α} {m : α → ennreal} {a b : ennreal} (hm : tendsto m f (𝓝 b)) (hb : b ≠ ⊤ ∨ a ≠ ⊤) : tendsto (λb, a / m b) f (𝓝 (a / b)) := by { apply tendsto.const_mul (ennreal.tendsto_inv_iff.2 hm), simp [hb] } protected lemma tendsto.div_const {f : filter α} {m : α → ennreal} {a b : ennreal} (hm : tendsto m f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ 0) : tendsto (λx, m x / b) f (𝓝 (a / b)) := by { apply tendsto.mul_const hm, simp [ha] } protected lemma tendsto_inv_nat_nhds_zero : tendsto (λ n : ℕ, (n : ennreal)⁻¹) at_top (𝓝 0) := ennreal.inv_top ▸ ennreal.tendsto_inv_iff.2 tendsto_nat_nhds_top lemma bsupr_add {ι} {s : set ι} (hs : s.nonempty) {f : ι → ennreal} : (⨆ i ∈ s, f i) + a = ⨆ i ∈ s, f i + a := begin simp only [← Sup_image], symmetry, rw [image_comp (+ a)], refine is_lub.Sup_eq (is_lub_of_is_lub_of_tendsto _ (is_lub_Sup _) (hs.image _) _), exacts [λ x _ y _ hxy, add_le_add hxy le_rfl, tendsto.add (tendsto_id' inf_le_left) tendsto_const_nhds] end lemma Sup_add {s : set ennreal} (hs : s.nonempty) : Sup s + a = ⨆b∈s, b + a := by rw [Sup_eq_supr, bsupr_add hs] lemma supr_add {ι : Sort*} {s : ι → ennreal} [h : nonempty ι] : supr s + a = ⨆b, s b + a := let ⟨x⟩ := h in calc supr s + a = Sup (range s) + a : by rw Sup_range ... = (⨆b∈range s, b + a) : Sup_add ⟨s x, x, rfl⟩ ... = _ : supr_range lemma add_supr {ι : Sort*} {s : ι → ennreal} [h : nonempty ι] : a + supr s = ⨆b, a + s b := by rw [add_comm, supr_add]; simp [add_comm] lemma supr_add_supr {ι : Sort*} {f g : ι → ennreal} (h : ∀i j, ∃k, f i + g j ≤ f k + g k) : supr f + supr g = (⨆ a, f a + g a) := begin by_cases hι : nonempty ι, { letI := hι, refine le_antisymm _ (supr_le $ λ a, add_le_add (le_supr _ _) (le_supr _ _)), simpa [add_supr, supr_add] using λ i j:ι, show f i + g j ≤ ⨆ a, f a + g a, from let ⟨k, hk⟩ := h i j in le_supr_of_le k hk }, { have : ∀f:ι → ennreal, (⨆i, f i) = 0 := λ f, bot_unique (supr_le $ assume i, (hι ⟨i⟩).elim), rw [this, this, this, zero_add] } end lemma supr_add_supr_of_monotone {ι : Sort*} [semilattice_sup ι] {f g : ι → ennreal} (hf : monotone f) (hg : monotone g) : supr f + supr g = (⨆ a, f a + g a) := supr_add_supr $ assume i j, ⟨i ⊔ j, add_le_add (hf $ le_sup_left) (hg $ le_sup_right)⟩ lemma finset_sum_supr_nat {α} {ι} [semilattice_sup ι] {s : finset α} {f : α → ι → ennreal} (hf : ∀a, monotone (f a)) : ∑ a in s, supr (f a) = (⨆ n, ∑ a in s, f a n) := begin refine finset.induction_on s _ _, { simp, exact (bot_unique $ supr_le $ assume i, le_refl ⊥).symm }, { assume a s has ih, simp only [finset.sum_insert has], rw [ih, supr_add_supr_of_monotone (hf a)], assume i j h, exact (finset.sum_le_sum $ assume a ha, hf a h) } end lemma mul_Sup {s : set ennreal} {a : ennreal} : a * Sup s = ⨆i∈s, a * i := begin by_cases hs : ∀x∈s, x = (0:ennreal), { have h₁ : Sup s = 0 := (bot_unique $ Sup_le $ assume a ha, (hs a ha).symm ▸ le_refl 0), have h₂ : (⨆i ∈ s, a * i) = 0 := (bot_unique $ supr_le $ assume a, supr_le $ assume ha, by simp [hs a ha]), rw [h₁, h₂, mul_zero] }, { simp only [not_forall] at hs, rcases hs with ⟨x, hx, hx0⟩, have s₁ : Sup s ≠ 0 := pos_iff_ne_zero.1 (lt_of_lt_of_le (pos_iff_ne_zero.2 hx0) (le_Sup hx)), have : Sup ((λb, a * b) '' s) = a * Sup s := is_lub.Sup_eq (is_lub_of_is_lub_of_tendsto (assume x _ y _ h, canonically_ordered_semiring.mul_le_mul (le_refl _) h) (is_lub_Sup _) ⟨x, hx⟩ (ennreal.tendsto.const_mul (tendsto_id' inf_le_left) (or.inl s₁))), rw [this.symm, Sup_image] } end lemma mul_supr {ι : Sort*} {f : ι → ennreal} {a : ennreal} : a * supr f = ⨆i, a * f i := by rw [← Sup_range, mul_Sup, supr_range] lemma supr_mul {ι : Sort*} {f : ι → ennreal} {a : ennreal} : supr f * a = ⨆i, f i * a := by rw [mul_comm, mul_supr]; congr; funext; rw [mul_comm] protected lemma tendsto_coe_sub : ∀{b:ennreal}, tendsto (λb:ennreal, ↑r - b) (𝓝 b) (𝓝 (↑r - b)) := begin refine (forall_ennreal.2 $ and.intro (assume a, _) _), { simp [@nhds_coe a, tendsto_map'_iff, (∘), tendsto_coe, coe_sub.symm], exact tendsto_const_nhds.sub tendsto_id }, simp, exact (tendsto.congr' (mem_sets_of_superset (lt_mem_nhds $ @coe_lt_top r) $ by simp [le_of_lt] {contextual := tt})) tendsto_const_nhds end lemma sub_supr {ι : Sort*} [hι : nonempty ι] {b : ι → ennreal} (hr : a < ⊤) : a - (⨆i, b i) = (⨅i, a - b i) := let ⟨i⟩ := hι in let ⟨r, eq, _⟩ := lt_iff_exists_coe.mp hr in have Inf ((λb, ↑r - b) '' range b) = ↑r - (⨆i, b i), from is_glb.Inf_eq $ is_glb_of_is_lub_of_tendsto (assume x _ y _, sub_le_sub (le_refl _)) is_lub_supr ⟨_, i, rfl⟩ (tendsto.comp ennreal.tendsto_coe_sub (tendsto_id' inf_le_left)), by rw [eq, ←this]; simp [Inf_image, infi_range, -mem_range]; exact le_refl _ lemma supr_eq_zero {ι : Sort*} {f : ι → ennreal} : (⨆ i, f i) = 0 ↔ ∀ i, f i = 0 := by simp_rw [← nonpos_iff_eq_zero, supr_le_iff] end topological_space section tsum variables {f g : α → ennreal} @[norm_cast] protected lemma has_sum_coe {f : α → ℝ≥0} {r : ℝ≥0} : has_sum (λa, (f a : ennreal)) ↑r ↔ has_sum f r := have (λs:finset α, ∑ a in s, ↑(f a)) = (coe : ℝ≥0 → ennreal) ∘ (λs:finset α, ∑ a in s, f a), from funext $ assume s, ennreal.coe_finset_sum.symm, by unfold has_sum; rw [this, tendsto_coe] protected lemma tsum_coe_eq {f : α → ℝ≥0} (h : has_sum f r) : ∑'a, (f a : ennreal) = r := (ennreal.has_sum_coe.2 h).tsum_eq protected lemma coe_tsum {f : α → ℝ≥0} : summable f → ↑(tsum f) = ∑'a, (f a : ennreal) | ⟨r, hr⟩ := by rw [hr.tsum_eq, ennreal.tsum_coe_eq hr] protected lemma has_sum : has_sum f (⨆s:finset α, ∑ a in s, f a) := tendsto_at_top_supr $ λ s t, finset.sum_le_sum_of_subset @[simp] protected lemma summable : summable f := ⟨_, ennreal.has_sum⟩ lemma tsum_coe_ne_top_iff_summable {f : β → ℝ≥0} : ∑' b, (f b:ennreal) ≠ ∞ ↔ summable f := begin refine ⟨λ h, _, λ h, ennreal.coe_tsum h ▸ ennreal.coe_ne_top⟩, lift (∑' b, (f b:ennreal)) to ℝ≥0 using h with a ha, refine ⟨a, ennreal.has_sum_coe.1 _⟩, rw ha, exact ennreal.summable.has_sum end protected lemma tsum_eq_supr_sum : ∑'a, f a = (⨆s:finset α, ∑ a in s, f a) := ennreal.has_sum.tsum_eq protected lemma tsum_eq_supr_sum' {ι : Type*} (s : ι → finset α) (hs : ∀ t, ∃ i, t ⊆ s i) : ∑' a, f a = ⨆ i, ∑ a in s i, f a := begin rw [ennreal.tsum_eq_supr_sum], symmetry, change (⨆i:ι, (λ t : finset α, ∑ a in t, f a) (s i)) = ⨆s:finset α, ∑ a in s, f a, exact (finset.sum_mono_set f).supr_comp_eq hs end protected lemma tsum_sigma {β : α → Type*} (f : Πa, β a → ennreal) : ∑'p:Σa, β a, f p.1 p.2 = ∑'a b, f a b := tsum_sigma' (assume b, ennreal.summable) ennreal.summable protected lemma tsum_sigma' {β : α → Type*} (f : (Σ a, β a) → ennreal) : ∑'p:(Σa, β a), f p = ∑'a b, f ⟨a, b⟩ := tsum_sigma' (assume b, ennreal.summable) ennreal.summable protected lemma tsum_prod {f : α → β → ennreal} : ∑'p:α×β, f p.1 p.2 = ∑'a, ∑'b, f a b := tsum_prod' ennreal.summable $ λ _, ennreal.summable protected lemma tsum_comm {f : α → β → ennreal} : ∑'a, ∑'b, f a b = ∑'b, ∑'a, f a b := tsum_comm' ennreal.summable (λ _, ennreal.summable) (λ _, ennreal.summable) protected lemma tsum_add : ∑'a, (f a + g a) = (∑'a, f a) + (∑'a, g a) := tsum_add ennreal.summable ennreal.summable protected lemma tsum_le_tsum (h : ∀a, f a ≤ g a) : ∑'a, f a ≤ ∑'a, g a := tsum_le_tsum h ennreal.summable ennreal.summable protected lemma sum_le_tsum {f : α → ennreal} (s : finset α) : ∑ x in s, f x ≤ ∑' x, f x := sum_le_tsum s (λ x hx, zero_le _) ennreal.summable protected lemma tsum_eq_supr_nat' {f : ℕ → ennreal} {N : ℕ → ℕ} (hN : tendsto N at_top at_top) : ∑'i:ℕ, f i = (⨆i:ℕ, ∑ a in finset.range (N i), f a) := ennreal.tsum_eq_supr_sum' _ $ λ t, let ⟨n, hn⟩ := t.exists_nat_subset_range, ⟨k, _, hk⟩ := exists_le_of_tendsto_at_top hN 0 n in ⟨k, finset.subset.trans hn (finset.range_mono hk)⟩ protected lemma tsum_eq_supr_nat {f : ℕ → ennreal} : ∑'i:ℕ, f i = (⨆i:ℕ, ∑ a in finset.range i, f a) := ennreal.tsum_eq_supr_sum' _ finset.exists_nat_subset_range protected lemma le_tsum (a : α) : f a ≤ ∑'a, f a := le_tsum' ennreal.summable a protected lemma tsum_eq_top_of_eq_top : (∃ a, f a = ∞) → ∑' a, f a = ∞ | ⟨a, ha⟩ := top_unique $ ha ▸ ennreal.le_tsum a protected lemma ne_top_of_tsum_ne_top (h : ∑' a, f a ≠ ∞) (a : α) : f a ≠ ∞ := λ ha, h $ ennreal.tsum_eq_top_of_eq_top ⟨a, ha⟩ protected lemma tsum_mul_left : ∑'i, a * f i = a * ∑'i, f i := if h : ∀i, f i = 0 then by simp [h] else let ⟨i, (hi : f i ≠ 0)⟩ := not_forall.mp h in have sum_ne_0 : ∑'i, f i ≠ 0, from ne_of_gt $ calc 0 < f i : lt_of_le_of_ne (zero_le _) hi.symm ... ≤ ∑'i, f i : ennreal.le_tsum _, have tendsto (λs:finset α, ∑ j in s, a * f j) at_top (𝓝 (a * ∑'i, f i)), by rw [← show (*) a ∘ (λs:finset α, ∑ j in s, f j) = λs, ∑ j in s, a * f j, from funext $ λ s, finset.mul_sum]; exact ennreal.tendsto.const_mul ennreal.summable.has_sum (or.inl sum_ne_0), has_sum.tsum_eq this protected lemma tsum_mul_right : (∑'i, f i * a) = (∑'i, f i) * a := by simp [mul_comm, ennreal.tsum_mul_left] @[simp] lemma tsum_supr_eq {α : Type*} (a : α) {f : α → ennreal} : ∑'b:α, (⨆ (h : a = b), f b) = f a := le_antisymm (by rw [ennreal.tsum_eq_supr_sum]; exact supr_le (assume s, calc (∑ b in s, ⨆ (h : a = b), f b) ≤ ∑ b in {a}, ⨆ (h : a = b), f b : finset.sum_le_sum_of_ne_zero $ assume b _ hb, suffices a = b, by simpa using this.symm, classical.by_contradiction $ assume h, by simpa [h] using hb ... = f a : by simp)) (calc f a ≤ (⨆ (h : a = a), f a) : le_supr (λh:a=a, f a) rfl ... ≤ (∑'b:α, ⨆ (h : a = b), f b) : ennreal.le_tsum _) lemma has_sum_iff_tendsto_nat {f : ℕ → ennreal} (r : ennreal) : has_sum f r ↔ tendsto (λn:ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) := begin refine ⟨has_sum.tendsto_sum_nat, assume h, _⟩, rw [← supr_eq_of_tendsto _ h, ← ennreal.tsum_eq_supr_nat], { exact ennreal.summable.has_sum }, { exact assume s t hst, finset.sum_le_sum_of_subset (finset.range_subset.2 hst) } end lemma to_nnreal_apply_of_tsum_ne_top {α : Type*} {f : α → ennreal} (hf : ∑' i, f i ≠ ∞) (x : α) : (((ennreal.to_nnreal ∘ f) x : ℝ≥0) : ennreal) = f x := coe_to_nnreal $ ennreal.ne_top_of_tsum_ne_top hf _ lemma summable_to_nnreal_of_tsum_ne_top {α : Type*} {f : α → ennreal} (hf : ∑' i, f i ≠ ∞) : summable (ennreal.to_nnreal ∘ f) := by simpa only [←tsum_coe_ne_top_iff_summable, to_nnreal_apply_of_tsum_ne_top hf] using hf protected lemma tsum_apply {ι α : Type*} {f : ι → α → ennreal} {x : α} : (∑' i, f i) x = ∑' i, f i x := tsum_apply $ pi.summable.mpr $ λ _, ennreal.summable lemma tsum_sub {f : ℕ → ennreal} {g : ℕ → ennreal} (h₁ : ∑' i, g i < ∞) (h₂ : g ≤ f) : ∑' i, (f i - g i) = (∑' i, f i) - (∑' i, g i) := begin have h₃: ∑' i, (f i - g i) = ∑' i, (f i - g i + g i) - ∑' i, g i, { rw [ennreal.tsum_add, add_sub_self h₁]}, have h₄:(λ i, (f i - g i) + (g i)) = f, { ext n, rw ennreal.sub_add_cancel_of_le (h₂ n)}, rw h₄ at h₃, apply h₃, end end tsum end ennreal namespace nnreal open_locale nnreal /-- Comparison test of convergence of `ℝ≥0`-valued series. -/ lemma exists_le_has_sum_of_le {f g : β → ℝ≥0} {r : ℝ≥0} (hgf : ∀b, g b ≤ f b) (hfr : has_sum f r) : ∃p≤r, has_sum g p := have ∑'b, (g b : ennreal) ≤ r, begin refine has_sum_le (assume b, _) ennreal.summable.has_sum (ennreal.has_sum_coe.2 hfr), exact ennreal.coe_le_coe.2 (hgf _) end, let ⟨p, eq, hpr⟩ := ennreal.le_coe_iff.1 this in ⟨p, hpr, ennreal.has_sum_coe.1 $ eq ▸ ennreal.summable.has_sum⟩ /-- Comparison test of convergence of `ℝ≥0`-valued series. -/ lemma summable_of_le {f g : β → ℝ≥0} (hgf : ∀b, g b ≤ f b) : summable f → summable g | ⟨r, hfr⟩ := let ⟨p, _, hp⟩ := exists_le_has_sum_of_le hgf hfr in hp.summable /-- A series of non-negative real numbers converges to `r` in the sense of `has_sum` if and only if the sequence of partial sum converges to `r`. -/ lemma has_sum_iff_tendsto_nat {f : ℕ → ℝ≥0} {r : ℝ≥0} : has_sum f r ↔ tendsto (λn:ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) := begin rw [← ennreal.has_sum_coe, ennreal.has_sum_iff_tendsto_nat], simp only [ennreal.coe_finset_sum.symm], exact ennreal.tendsto_coe end lemma not_summable_iff_tendsto_nat_at_top {f : ℕ → ℝ≥0} : ¬ summable f ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top := begin split, { intros h, refine ((tendsto_of_monotone _).resolve_right h).comp _, exacts [finset.sum_mono_set _, tendsto_finset_range] }, { rintros hnat ⟨r, hr⟩, exact not_tendsto_nhds_of_tendsto_at_top hnat _ (has_sum_iff_tendsto_nat.1 hr) } end lemma summable_iff_not_tendsto_nat_at_top {f : ℕ → ℝ≥0} : summable f ↔ ¬ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top := by rw [← not_iff_not, not_not, not_summable_iff_tendsto_nat_at_top] lemma summable_of_sum_range_le {f : ℕ → ℝ≥0} {c : ℝ≥0} (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : summable f := begin apply summable_iff_not_tendsto_nat_at_top.2 (λ H, _), rcases exists_lt_of_tendsto_at_top H 0 c with ⟨n, -, hn⟩, exact lt_irrefl _ (hn.trans_le (h n)), end lemma tsum_le_of_sum_range_le {f : ℕ → ℝ≥0} {c : ℝ≥0} (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : ∑' n, f n ≤ c := le_of_tendsto' (has_sum_iff_tendsto_nat.1 (summable_of_sum_range_le h).has_sum) h lemma tsum_comp_le_tsum_of_inj {β : Type*} {f : α → ℝ≥0} (hf : summable f) {i : β → α} (hi : function.injective i) : ∑' x, f (i x) ≤ ∑' x, f x := tsum_le_tsum_of_inj i hi (λ c hc, zero_le _) (λ b, le_refl _) (summable_comp_injective hf hi) hf lemma summable_sigma {β : Π x : α, Type*} {f : (Σ x, β x) → ℝ≥0} : summable f ↔ (∀ x, summable (λ y, f ⟨x, y⟩)) ∧ summable (λ x, ∑' y, f ⟨x, y⟩) := begin split, { simp only [← nnreal.summable_coe, nnreal.coe_tsum], exact λ h, ⟨h.sigma_factor, h.sigma⟩ }, { rintro ⟨h₁, h₂⟩, simpa only [← ennreal.tsum_coe_ne_top_iff_summable, ennreal.tsum_sigma', ennreal.coe_tsum, h₁] using h₂ } end open finset /-- For `f : ℕ → ℝ≥0`, then `∑' k, f (k + i)` tends to zero. This does not require a summability assumption on `f`, as otherwise all sums are zero. -/ lemma tendsto_sum_nat_add (f : ℕ → ℝ≥0) : tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) := begin rw ← tendsto_coe, convert tendsto_sum_nat_add (λ i, (f i : ℝ)), norm_cast, end end nnreal namespace ennreal lemma tendsto_sum_nat_add (f : ℕ → ennreal) (hf : ∑' i, f i ≠ ∞) : tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) := begin have : ∀ i, ∑' k, (((ennreal.to_nnreal ∘ f) (k + i) : ℝ≥0) : ennreal) = (∑' k, (ennreal.to_nnreal ∘ f) (k + i) : ℝ≥0) := λ i, (ennreal.coe_tsum (nnreal.summable_nat_add _ (summable_to_nnreal_of_tsum_ne_top hf) _)).symm, simp only [λ x, (to_nnreal_apply_of_tsum_ne_top hf x).symm, ←ennreal.coe_zero, this, ennreal.tendsto_coe] { single_pass := tt }, exact nnreal.tendsto_sum_nat_add _ end end ennreal lemma tsum_comp_le_tsum_of_inj {β : Type*} {f : α → ℝ} (hf : summable f) (hn : ∀ a, 0 ≤ f a) {i : β → α} (hi : function.injective i) : tsum (f ∘ i) ≤ tsum f := begin let g : α → ℝ≥0 := λ a, ⟨f a, hn a⟩, have hg : summable g, by rwa ← nnreal.summable_coe, convert nnreal.coe_le_coe.2 (nnreal.tsum_comp_le_tsum_of_inj hg hi); { rw nnreal.coe_tsum, congr } end /-- Comparison test of convergence of series of non-negative real numbers. -/ lemma summable_of_nonneg_of_le {f g : β → ℝ} (hg : ∀b, 0 ≤ g b) (hgf : ∀b, g b ≤ f b) (hf : summable f) : summable g := let f' (b : β) : ℝ≥0 := ⟨f b, le_trans (hg b) (hgf b)⟩ in let g' (b : β) : ℝ≥0 := ⟨g b, hg b⟩ in have summable f', from nnreal.summable_coe.1 hf, have summable g', from nnreal.summable_of_le (assume b, (@nnreal.coe_le_coe (g' b) (f' b)).2 $ hgf b) this, show summable (λb, g' b : β → ℝ), from nnreal.summable_coe.2 this /-- A series of non-negative real numbers converges to `r` in the sense of `has_sum` if and only if the sequence of partial sum converges to `r`. -/ lemma has_sum_iff_tendsto_nat_of_nonneg {f : ℕ → ℝ} (hf : ∀i, 0 ≤ f i) (r : ℝ) : has_sum f r ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) := begin lift f to ℕ → ℝ≥0 using hf, simp only [has_sum, ← nnreal.coe_sum, nnreal.tendsto_coe'], exact exists_congr (λ hr, nnreal.has_sum_iff_tendsto_nat) end lemma not_summable_iff_tendsto_nat_at_top_of_nonneg {f : ℕ → ℝ} (hf : ∀ n, 0 ≤ f n) : ¬ summable f ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top := begin lift f to ℕ → ℝ≥0 using hf, exact_mod_cast nnreal.not_summable_iff_tendsto_nat_at_top end lemma summable_iff_not_tendsto_nat_at_top_of_nonneg {f : ℕ → ℝ} (hf : ∀ n, 0 ≤ f n) : summable f ↔ ¬ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top := by rw [← not_iff_not, not_not, not_summable_iff_tendsto_nat_at_top_of_nonneg hf] lemma summable_sigma_of_nonneg {β : Π x : α, Type*} {f : (Σ x, β x) → ℝ} (hf : ∀ x, 0 ≤ f x) : summable f ↔ (∀ x, summable (λ y, f ⟨x, y⟩)) ∧ summable (λ x, ∑' y, f ⟨x, y⟩) := by { lift f to (Σ x, β x) → ℝ≥0 using hf, exact_mod_cast nnreal.summable_sigma } lemma summable_of_sum_range_le {f : ℕ → ℝ} {c : ℝ} (hf : ∀ n, 0 ≤ f n) (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : summable f := begin apply (summable_iff_not_tendsto_nat_at_top_of_nonneg hf).2 (λ H, _), rcases exists_lt_of_tendsto_at_top H 0 c with ⟨n, -, hn⟩, exact lt_irrefl _ (hn.trans_le (h n)), end lemma tsum_le_of_sum_range_le {f : ℕ → ℝ} {c : ℝ} (hf : ∀ n, 0 ≤ f n) (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : ∑' n, f n ≤ c := le_of_tendsto' ((has_sum_iff_tendsto_nat_of_nonneg hf _).1 (summable_of_sum_range_le hf h).has_sum) h section variables [emetric_space β] open ennreal filter emetric /-- In an emetric ball, the distance between points is everywhere finite -/ lemma edist_ne_top_of_mem_ball {a : β} {r : ennreal} (x y : ball a r) : edist x.1 y.1 ≠ ⊤ := lt_top_iff_ne_top.1 $ calc edist x y ≤ edist a x + edist a y : edist_triangle_left x.1 y.1 a ... < r + r : by rw [edist_comm a x, edist_comm a y]; exact add_lt_add x.2 y.2 ... ≤ ⊤ : le_top /-- Each ball in an extended metric space gives us a metric space, as the edist is everywhere finite. -/ def metric_space_emetric_ball (a : β) (r : ennreal) : metric_space (ball a r) := emetric_space.to_metric_space edist_ne_top_of_mem_ball local attribute [instance] metric_space_emetric_ball lemma nhds_eq_nhds_emetric_ball (a x : β) (r : ennreal) (h : x ∈ ball a r) : 𝓝 x = map (coe : ball a r → β) (𝓝 ⟨x, h⟩) := (map_nhds_subtype_coe_eq _ $ mem_nhds_sets emetric.is_open_ball h).symm end section variable [emetric_space α] open emetric lemma tendsto_iff_edist_tendsto_0 {l : filter β} {f : β → α} {y : α} : tendsto f l (𝓝 y) ↔ tendsto (λ x, edist (f x) y) l (𝓝 0) := by simp only [emetric.nhds_basis_eball.tendsto_right_iff, emetric.mem_ball, @tendsto_order ennreal β _ _, forall_prop_of_false ennreal.not_lt_zero, forall_const, true_and] /-- Yet another metric characterization of Cauchy sequences on integers. This one is often the most efficient. -/ lemma emetric.cauchy_seq_iff_le_tendsto_0 [nonempty β] [semilattice_sup β] {s : β → α} : cauchy_seq s ↔ (∃ (b: β → ennreal), (∀ n m N : β, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N) ∧ (tendsto b at_top (𝓝 0))) := ⟨begin assume hs, rw emetric.cauchy_seq_iff at hs, /- `s` is Cauchy sequence. The sequence `b` will be constructed by taking the supremum of the distances between `s n` and `s m` for `n m ≥ N`-/ let b := λN, Sup ((λ(p : β × β), edist (s p.1) (s p.2))''{p | p.1 ≥ N ∧ p.2 ≥ N}), --Prove that it bounds the distances of points in the Cauchy sequence have C : ∀ n m N, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N, { refine λm n N hm hn, le_Sup _, use (prod.mk m n), simp only [and_true, eq_self_iff_true, set.mem_set_of_eq], exact ⟨hm, hn⟩ }, --Prove that it tends to `0`, by using the Cauchy property of `s` have D : tendsto b at_top (𝓝 0), { refine tendsto_order.2 ⟨λa ha, absurd ha (ennreal.not_lt_zero), λε εpos, _⟩, rcases exists_between εpos with ⟨δ, δpos, δlt⟩, rcases hs δ δpos with ⟨N, hN⟩, refine filter.mem_at_top_sets.2 ⟨N, λn hn, _⟩, have : b n ≤ δ := Sup_le begin simp only [and_imp, set.mem_image, set.mem_set_of_eq, exists_imp_distrib, prod.exists], intros d p q hp hq hd, rw ← hd, exact le_of_lt (hN p q (le_trans hn hp) (le_trans hn hq)) end, simpa using lt_of_le_of_lt this δlt }, -- Conclude exact ⟨b, ⟨C, D⟩⟩ end, begin rintros ⟨b, ⟨b_bound, b_lim⟩⟩, /-b : ℕ → ℝ, b_bound : ∀ (n m N : ℕ), N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N, b_lim : tendsto b at_top (𝓝 0)-/ refine emetric.cauchy_seq_iff.2 (λε εpos, _), have : ∀ᶠ n in at_top, b n < ε := (tendsto_order.1 b_lim ).2 _ εpos, rcases filter.mem_at_top_sets.1 this with ⟨N, hN⟩, exact ⟨N, λm n hm hn, calc edist (s m) (s n) ≤ b N : b_bound m n N hm hn ... < ε : (hN _ (le_refl N)) ⟩ end⟩ lemma continuous_of_le_add_edist {f : α → ennreal} (C : ennreal) (hC : C ≠ ⊤) (h : ∀x y, f x ≤ f y + C * edist x y) : continuous f := begin refine continuous_iff_continuous_at.2 (λx, tendsto_order.2 ⟨_, _⟩), show ∀e, e < f x → ∀ᶠ y in 𝓝 x, e < f y, { assume e he, let ε := min (f x - e) 1, have : ε < ⊤ := lt_of_le_of_lt (min_le_right _ _) (by simp [lt_top_iff_ne_top]), have : 0 < ε := by simp [ε, hC, he, ennreal.zero_lt_one], have : 0 < C⁻¹ * (ε/2) := bot_lt_iff_ne_bot.2 (by simp [hC, (ne_of_lt this).symm, mul_eq_zero]), have I : C * (C⁻¹ * (ε/2)) < ε, { by_cases C_zero : C = 0, { simp [C_zero, ‹0 < ε›] }, { calc C * (C⁻¹ * (ε/2)) = (C * C⁻¹) * (ε/2) : by simp [mul_assoc] ... = ε/2 : by simp [ennreal.mul_inv_cancel C_zero hC] ... < ε : ennreal.half_lt_self (‹0 < ε›.ne') (‹ε < ⊤›.ne) }}, have : ball x (C⁻¹ * (ε/2)) ⊆ {y : α | e < f y}, { rintros y hy, by_cases htop : f y = ⊤, { simp [htop, lt_top_iff_ne_top, ne_top_of_lt he] }, { simp at hy, have : e + ε < f y + ε := calc e + ε ≤ e + (f x - e) : add_le_add_left (min_le_left _ _) _ ... = f x : by simp [le_of_lt he] ... ≤ f y + C * edist x y : h x y ... = f y + C * edist y x : by simp [edist_comm] ... ≤ f y + C * (C⁻¹ * (ε/2)) : add_le_add_left (canonically_ordered_semiring.mul_le_mul (le_refl _) (le_of_lt hy)) _ ... < f y + ε : (ennreal.add_lt_add_iff_left (lt_top_iff_ne_top.2 htop)).2 I, show e < f y, from (ennreal.add_lt_add_iff_right ‹ε < ⊤›).1 this }}, apply filter.mem_sets_of_superset (ball_mem_nhds _ (‹0 < C⁻¹ * (ε/2)›)) this }, show ∀e, f x < e → ∀ᶠ y in 𝓝 x, f y < e, { assume e he, let ε := min (e - f x) 1, have : ε < ⊤ := lt_of_le_of_lt (min_le_right _ _) (by simp [lt_top_iff_ne_top]), have : 0 < ε := by simp [ε, he, ennreal.zero_lt_one], have : 0 < C⁻¹ * (ε/2) := bot_lt_iff_ne_bot.2 (by simp [hC, (ne_of_lt this).symm, mul_eq_zero]), have I : C * (C⁻¹ * (ε/2)) < ε, { by_cases C_zero : C = 0, simp [C_zero, ‹0 < ε›], calc C * (C⁻¹ * (ε/2)) = (C * C⁻¹) * (ε/2) : by simp [mul_assoc] ... = ε/2 : by simp [ennreal.mul_inv_cancel C_zero hC] ... < ε : ennreal.half_lt_self (‹0 < ε›.ne') (‹ε < ⊤›.ne) }, have : ball x (C⁻¹ * (ε/2)) ⊆ {y : α | f y < e}, { rintros y hy, have htop : f x ≠ ⊤ := ne_top_of_lt he, show f y < e, from calc f y ≤ f x + C * edist y x : h y x ... ≤ f x + C * (C⁻¹ * (ε/2)) : add_le_add_left (canonically_ordered_semiring.mul_le_mul (le_refl _) (le_of_lt hy)) _ ... < f x + ε : (ennreal.add_lt_add_iff_left (lt_top_iff_ne_top.2 htop)).2 I ... ≤ f x + (e - f x) : add_le_add_left (min_le_left _ _) _ ... = e : by simp [le_of_lt he] }, apply filter.mem_sets_of_superset (ball_mem_nhds _ (‹0 < C⁻¹ * (ε/2)›)) this }, end theorem continuous_edist : continuous (λp:α×α, edist p.1 p.2) := begin apply continuous_of_le_add_edist 2 (by norm_num), rintros ⟨x, y⟩ ⟨x', y'⟩, calc edist x y ≤ edist x x' + edist x' y' + edist y' y : edist_triangle4 _ _ _ _ ... = edist x' y' + (edist x x' + edist y y') : by simp [edist_comm]; cc ... ≤ edist x' y' + (edist (x, y) (x', y') + edist (x, y) (x', y')) : add_le_add_left (add_le_add (le_max_left _ _) (le_max_right _ _)) _ ... = edist x' y' + 2 * edist (x, y) (x', y') : by rw [← mul_two, mul_comm] end theorem continuous.edist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, edist (f b) (g b)) := continuous_edist.comp (hf.prod_mk hg : _) theorem filter.tendsto.edist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, edist (f x) (g x)) x (𝓝 (edist a b)) := (continuous_edist.tendsto (a, b)).comp (hf.prod_mk_nhds hg) lemma cauchy_seq_of_edist_le_of_tsum_ne_top {f : ℕ → α} (d : ℕ → ennreal) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) (hd : tsum d ≠ ∞) : cauchy_seq f := begin lift d to (ℕ → nnreal) using (λ i, ennreal.ne_top_of_tsum_ne_top hd i), rw ennreal.tsum_coe_ne_top_iff_summable at hd, exact cauchy_seq_of_edist_le_of_summable d hf hd end lemma emetric.is_closed_ball {a : α} {r : ennreal} : is_closed (closed_ball a r) := is_closed_le (continuous_id.edist continuous_const) continuous_const /-- If `edist (f n) (f (n+1))` is bounded above by a function `d : ℕ → ennreal`, then the distance from `f n` to the limit is bounded by `∑'_{k=n}^∞ d k`. -/ lemma edist_le_tsum_of_edist_le_of_tendsto {f : ℕ → α} (d : ℕ → ennreal) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : edist (f n) a ≤ ∑' m, d (n + m) := begin refine le_of_tendsto (tendsto_const_nhds.edist ha) (mem_at_top_sets.2 ⟨n, λ m hnm, _⟩), refine le_trans (edist_le_Ico_sum_of_edist_le hnm (λ k _ _, hf k)) _, rw [finset.sum_Ico_eq_sum_range], exact sum_le_tsum _ (λ _ _, zero_le _) ennreal.summable end /-- If `edist (f n) (f (n+1))` is bounded above by a function `d : ℕ → ennreal`, then the distance from `f 0` to the limit is bounded by `∑'_{k=0}^∞ d k`. -/ lemma edist_le_tsum_of_edist_le_of_tendsto₀ {f : ℕ → α} (d : ℕ → ennreal) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) {a : α} (ha : tendsto f at_top (𝓝 a)) : edist (f 0) a ≤ ∑' m, d m := by simpa using edist_le_tsum_of_edist_le_of_tendsto d hf ha 0 end --section
d38e7c670d78d1c369e742b9bfca432c8d369c78
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/1598.lean
72e928e4a23c170795bc51da900456a8b5aaeb53
[ "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
75
lean
lemma notc : exists b, b = false := begin existsi 0, -- ERROR here end
f56234b490c813d9af00f158746dffd665821672
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/general_linear_group.lean
37278cb102c74dd1500f28ca588736bec3d3412b
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
8,561
lean
/- Copyright (c) 2021 Chris Birkbeck. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Birkbeck -/ import linear_algebra.matrix.nonsingular_inverse import linear_algebra.special_linear_group /-! # The General Linear group $GL(n, R)$ This file defines the elements of the General Linear group `general_linear_group n R`, consisting of all invertible `n` by `n` `R`-matrices. ## Main definitions * `matrix.general_linear_group` is the type of matrices over R which are units in the matrix ring. * `matrix.GL_pos` gives the subgroup of matrices with positive determinant (over a linear ordered ring). ## Tags matrix group, group, matrix inverse -/ namespace matrix universes u v open_locale matrix open linear_map -- disable this instance so we do not accidentally use it in lemmas. local attribute [-instance] special_linear_group.has_coe_to_fun /-- `GL n R` is the group of `n` by `n` `R`-matrices with unit determinant. Defined as a subtype of matrices-/ abbreviation general_linear_group (n : Type u) (R : Type v) [decidable_eq n] [fintype n] [comm_ring R] : Type* := (matrix n n R)ˣ notation `GL` := general_linear_group namespace general_linear_group variables {n : Type u} [decidable_eq n] [fintype n] {R : Type v} [comm_ring R] /-- The determinant of a unit matrix is itself a unit. -/ @[simps] def det : GL n R →* Rˣ := { to_fun := λ A, { val := (↑A : matrix n n R).det, inv := (↑(A⁻¹) : matrix n n R).det, val_inv := by rw [←det_mul, ←mul_eq_mul, A.mul_inv, det_one], inv_val := by rw [←det_mul, ←mul_eq_mul, A.inv_mul, det_one]}, map_one' := units.ext det_one, map_mul' := λ A B, units.ext $ det_mul _ _ } /--The `GL n R` and `general_linear_group R n` groups are multiplicatively equivalent-/ def to_lin : (GL n R) ≃* (linear_map.general_linear_group R (n → R)) := units.map_equiv to_lin_alg_equiv'.to_mul_equiv /--Given a matrix with invertible determinant we get an element of `GL n R`-/ def mk' (A : matrix n n R) (h : invertible (matrix.det A)) : GL n R := unit_of_det_invertible A /--Given a matrix with unit determinant we get an element of `GL n R`-/ noncomputable def mk'' (A : matrix n n R) (h : is_unit (matrix.det A)) : GL n R := nonsing_inv_unit A h /--Given a matrix with non-zero determinant over a field, we get an element of `GL n K`-/ def mk_of_det_ne_zero {K : Type*} [field K] (A : matrix n n K) (h : matrix.det A ≠ 0) : GL n K := mk' A (invertible_of_nonzero h) lemma ext_iff (A B : GL n R) : A = B ↔ (∀ i j, (A : matrix n n R) i j = (B : matrix n n R) i j) := units.ext_iff.trans matrix.ext_iff.symm /-- Not marked `@[ext]` as the `ext` tactic already solves this. -/ lemma ext ⦃A B : GL n R⦄ (h : ∀ i j, (A : matrix n n R) i j = (B : matrix n n R) i j) : A = B := units.ext $ matrix.ext h section coe_lemmas variables (A B : GL n R) @[simp] lemma coe_mul : ↑(A * B) = (↑A : matrix n n R) ⬝ (↑B : matrix n n R) := rfl @[simp] lemma coe_one : ↑(1 : GL n R) = (1 : matrix n n R) := rfl lemma coe_inv : ↑(A⁻¹) = (↑A : matrix n n R)⁻¹ := begin letI := A.invertible, exact inv_of_eq_nonsing_inv (↑A : matrix n n R), end /-- An element of the matrix general linear group on `(n) [fintype n]` can be considered as an element of the endomorphism general linear group on `n → R`. -/ def to_linear : general_linear_group n R ≃* linear_map.general_linear_group R (n → R) := units.map_equiv matrix.to_lin_alg_equiv'.to_ring_equiv.to_mul_equiv -- Note that without the `@` and `‹_›`, lean infers `λ a b, _inst a b` instead of `_inst` as the -- decidability argument, which prevents `simp` from obtaining the instance by unification. -- These `λ a b, _inst a b` terms also appear in the type of `A`, but simp doesn't get confused by -- them so for now we do not care. @[simp] lemma coe_to_linear : (@to_linear n ‹_› ‹_› _ _ A : (n → R) →ₗ[R] (n → R)) = matrix.mul_vec_lin A := rfl @[simp] lemma to_linear_apply (v : n → R) : (@to_linear n ‹_› ‹_› _ _ A) v = matrix.mul_vec_lin ↑A v := rfl end coe_lemmas end general_linear_group namespace special_linear_group variables {n : Type u} [decidable_eq n] [fintype n] {R : Type v} [comm_ring R] instance has_coe_to_general_linear_group : has_coe (special_linear_group n R) (GL n R) := ⟨λ A, ⟨↑A, ↑(A⁻¹), congr_arg coe (mul_right_inv A), congr_arg coe (mul_left_inv A)⟩⟩ @[simp] lemma coe_to_GL_det (g : special_linear_group n R) : (g : GL n R).det = 1 := units.ext g.prop end special_linear_group section variables {n : Type u} {R : Type v} [decidable_eq n] [fintype n] [linear_ordered_comm_ring R ] section variables (n R) /-- This is the subgroup of `nxn` matrices with entries over a linear ordered ring and positive determinant. -/ def GL_pos : subgroup (GL n R) := (units.pos_subgroup R).comap general_linear_group.det end @[simp] lemma mem_GL_pos (A : GL n R) : A ∈ GL_pos n R ↔ 0 < (A.det : R) := iff.rfl lemma GL_pos.det_ne_zero (A : GL_pos n R) : (A : matrix n n R).det ≠ 0 := ne_of_gt A.prop end section has_neg variables {n : Type u} {R : Type v} [decidable_eq n] [fintype n] [linear_ordered_comm_ring R ] [fact (even (fintype.card n))] /-- Formal operation of negation on general linear group on even cardinality `n` given by negating each element. -/ instance : has_neg (GL_pos n R) := ⟨λ g, ⟨-g, begin rw [mem_GL_pos, general_linear_group.coe_det_apply, units.coe_neg, det_neg, (fact.out $ even $ fintype.card n).neg_one_pow, one_mul], exact g.prop, end⟩⟩ @[simp] lemma GL_pos.coe_neg_GL (g : GL_pos n R) : ↑(-g) = -(g : GL n R) := rfl @[simp] lemma GL_pos.coe_neg (g : GL_pos n R) : ↑(-g) = -(g : matrix n n R) := rfl @[simp] lemma GL_pos.coe_neg_apply (g : GL_pos n R) (i j : n) : (↑(-g) : matrix n n R) i j = -((↑g : matrix n n R) i j) := rfl instance : has_distrib_neg (GL_pos n R) := subtype.coe_injective.has_distrib_neg _ GL_pos.coe_neg_GL (GL_pos n R).coe_mul end has_neg namespace special_linear_group variables {n : Type u} [decidable_eq n] [fintype n] {R : Type v} [linear_ordered_comm_ring R] /-- `special_linear_group n R` embeds into `GL_pos n R` -/ def to_GL_pos : special_linear_group n R →* GL_pos n R := { to_fun := λ A, ⟨(A : GL n R), show 0 < (↑A : matrix n n R).det, from A.prop.symm ▸ zero_lt_one⟩, map_one' := subtype.ext $ units.ext $ rfl, map_mul' := λ A₁ A₂, subtype.ext $ units.ext $ rfl } instance : has_coe (special_linear_group n R) (GL_pos n R) := ⟨to_GL_pos⟩ lemma coe_eq_to_GL_pos : (coe : special_linear_group n R → GL_pos n R) = to_GL_pos := rfl lemma to_GL_pos_injective : function.injective (to_GL_pos : special_linear_group n R → GL_pos n R) := (show function.injective ((coe : GL_pos n R → matrix n n R) ∘ to_GL_pos), from subtype.coe_injective).of_comp /-- Coercing a `special_linear_group` via `GL_pos` and `GL` is the same as coercing striaght to a matrix. -/ @[simp] lemma coe_GL_pos_coe_GL_coe_matrix (g : special_linear_group n R) : (↑(↑(↑g : GL_pos n R) : GL n R) : matrix n n R) = ↑g := rfl @[simp] lemma coe_to_GL_pos_to_GL_det (g : special_linear_group n R) : ((g : GL_pos n R) : GL n R).det = 1 := units.ext g.prop variable [fact (even (fintype.card n))] @[norm_cast] lemma coe_GL_pos_neg (g : special_linear_group n R) : ↑(-g) = -(↑g : GL_pos n R) := subtype.ext $ units.ext rfl end special_linear_group section examples /-- The matrix [a, -b; b, a] (inspired by multiplication by a complex number); it is an element of $GL_2(R)$ if `a ^ 2 + b ^ 2` is nonzero. -/ @[simps coe {fully_applied := ff}] def plane_conformal_matrix {R} [field R] (a b : R) (hab : a ^ 2 + b ^ 2 ≠ 0) : matrix.general_linear_group (fin 2) R := general_linear_group.mk_of_det_ne_zero !![a, -b; b, a] (by simpa [det_fin_two, sq] using hab) /- TODO: Add Iwasawa matrices `n_x=!![1,x; 0,1]`, `a_t=!![exp(t/2),0;0,exp(-t/2)]` and `k_θ=!![cos θ, sin θ; -sin θ, cos θ]` -/ end examples namespace general_linear_group variables {n : Type u} [decidable_eq n] [fintype n] {R : Type v} [comm_ring R] -- this section should be last to ensure we do not use it in lemmas section coe_fn_instance /-- This instance is here for convenience, but is not the simp-normal form. -/ instance : has_coe_to_fun (GL n R) (λ _, n → n → R) := { coe := λ A, A.val } @[simp] lemma coe_fn_eq_coe (A : GL n R) : ⇑A = (↑A : matrix n n R) := rfl end coe_fn_instance end general_linear_group end matrix
a7a198c115d7d1b70a88ff29c8c2334b736a3af7
b3c7090f393c11bd47c82d2f8bb4edf8213173f5
/src/bundled_group_homs.lean
5ce9b049d1a198c69263fc4e717d3d36147378e1
[]
no_license
ImperialCollegeLondon/lean-groups
964b197478f0313d826073576a3e0ae8b166a584
9a82d2a66ef7f549107fcb4e1504d734c43ebb33
refs/heads/master
1,592,371,184,330
1,567,197,270,000
1,567,197,270,000
195,810,480
4
0
null
null
null
null
UTF-8
Lean
false
false
489
lean
import algebra.group.to_additive algebra.group.basic algebra.group.hom group_theory.quotient_group namespace group_hom variables {G : Type*} [group G] {H : Type*} [group H] def mk {G H} [group G] [group H] (f : G → H) [is_group_hom f] : G →* H := { to_fun := f, map_one' := is_group_hom.map_one f, map_mul' := (is_group_hom.to_is_mul_hom f).map_mul } def map_inv [group G] [group H] (f : G →* H) (x : G) : f (x⁻¹) = (f x)⁻¹ := is_group_hom.map_inv _ x end group_hom
62b0b762b3052cebaf67211551f2d86961799913
35b83be3126daae10419b573c55e1fed009d3ae8
/_target/deps/mathlib/data/fin.lean
50ee65f1f9768008932945f631e87c14fee05ff0
[]
no_license
AHassan1024/Lean_Playground
ccb25b72029d199c0d23d002db2d32a9f2689ebc
a00b004c3a2eb9e3e863c361aa2b115260472414
refs/heads/master
1,586,221,905,125
1,544,951,310,000
1,544,951,310,000
157,934,290
0
0
null
null
null
null
UTF-8
Lean
false
false
6,891
lean
/- Copyright (c) 2017 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis More about finite numbers. -/ import data.nat.basic open fin nat /-- `fin 0` is empty -/ def fin_zero_elim {C : Sort*} : fin 0 → C := λ x, false.elim $ nat.not_lt_zero x.1 x.2 namespace fin variables {n m : ℕ} {a b : fin n} @[simp] protected lemma eta (a : fin n) (h : a.1 < n) : (⟨a.1, h⟩ : fin n) = a := by cases a; refl protected lemma ext_iff (a b : fin n) : a = b ↔ a.val = b.val := iff.intro (congr_arg _) fin.eq_of_veq lemma eq_iff_veq (a b : fin n) : a = b ↔ a.1 = b.1 := ⟨veq_of_eq, eq_of_veq⟩ instance fin_to_nat (n : ℕ) : has_coe (fin n) nat := ⟨fin.val⟩ instance {n : ℕ} : decidable_linear_order (fin n) := { le_refl := λ a, @le_refl ℕ _ _, le_trans := λ a b c, @le_trans ℕ _ _ _ _, le_antisymm := λ a b ha hb, fin.eq_of_veq $ le_antisymm ha hb, le_total := λ a b, @le_total ℕ _ _ _, lt_iff_le_not_le := λ a b, @lt_iff_le_not_le ℕ _ _ _, decidable_le := fin.decidable_le, ..fin.has_le, ..fin.has_lt } lemma zero_le (a : fin (n + 1)) : 0 ≤ a := zero_le a.1 lemma lt_iff_val_lt_val : a < b ↔ a.val < b.val := iff.refl _ lemma le_iff_val_le_val : a ≤ b ↔ a.val ≤ b.val := iff.refl _ @[simp] lemma succ_val (j : fin n) : j.succ.val = j.val.succ := by cases j; simp [fin.succ] protected theorem succ.inj (p : fin.succ a = fin.succ b) : a = b := by cases a; cases b; exact eq_of_veq (nat.succ.inj (veq_of_eq p)) @[simp] lemma pred_val (j : fin (n+1)) (h : j ≠ 0) : (j.pred h).val = j.val.pred := by cases j; simp [fin.pred] @[simp] lemma succ_pred : ∀(i : fin (n+1)) (h : i ≠ 0), (i.pred h).succ = i | ⟨0, h⟩ hi := by contradiction | ⟨n + 1, h⟩ hi := rfl @[simp] lemma pred_succ (i : fin n) {h : i.succ ≠ 0} : i.succ.pred h = i := by cases i; refl @[simp] lemma pred_inj : ∀ {a b : fin (n + 1)} {ha : a ≠ 0} {hb : b ≠ 0}, a.pred ha = b.pred hb ↔ a = b | ⟨0, _⟩ b ha hb := by contradiction | ⟨i+1, _⟩ ⟨0, _⟩ ha hb := by contradiction | ⟨i+1, hi⟩ ⟨j+1, hj⟩ ha hb := by simp [fin.eq_iff_veq] /-- The greatest value of `fin (n+1)` -/ def last (n : ℕ) : fin (n+1) := ⟨_, n.lt_succ_self⟩ /-- `cast_lt i h` embeds `i` into a `fin` where `h` proves it belongs into. -/ def cast_lt (i : fin m) (h : i.1 < n) : fin n := ⟨i.1, h⟩ /-- `cast_le h i` embeds `i` into a larger `fin` type. -/ def cast_le (h : n ≤ m) (a : fin n) : fin m := cast_lt a (lt_of_lt_of_le a.2 h) /-- `cast eq i` embeds `i` into a equal `fin` type. -/ def cast (eq : n = m): fin n → fin m := cast_le $ le_of_eq eq /-- `cast_add m i` embedds `i` in `fin (n+m)`. -/ def cast_add (m) : fin n → fin (n + m) := cast_le $ le_add_right n m /-- `cast_succ i` embedds `i` in `fin (n+1)`. -/ def cast_succ : fin n → fin (n + 1) := cast_add 1 /-- `succ_above p i` embeds into `fin (n + 1)` with a hole around `p`. -/ def succ_above (p : fin (n+1)) (i : fin n) : fin (n+1) := if i.1 < p.1 then i.cast_succ else i.succ /-- `pred_above p i h` embeds `i` into `fin n` by ignoring `p`. -/ def pred_above (p : fin (n+1)) (i : fin (n+1)) (hi : i ≠ p) : fin n := if h : i < p then i.cast_lt (lt_of_lt_of_le h $ nat.le_of_lt_succ p.2) else i.pred $ have p < i, from lt_of_le_of_ne (le_of_not_gt h) hi.symm, ne_of_gt (lt_of_le_of_lt (zero_le p) this) /-- `sub_nat i h` subtracts `m` from `i`, generalizes `fin.pred`. -/ def sub_nat (m) (i : fin (n + m)) (h : i.val ≥ m) : fin n := ⟨i.val - m, by simp [nat.sub_lt_right_iff_lt_add h, i.is_lt]⟩ /-- `add_nat i h` adds `m` on `i`, generalizes `fin.succ`. -/ def add_nat (m) (i : fin n) : fin (n + m) := ⟨i.1 + m, add_lt_add_right i.2 _⟩ theorem le_last (i : fin (n+1)) : i ≤ last n := le_of_lt_succ i.is_lt @[simp] lemma cast_succ_val (k : fin n) : k.cast_succ.val = k.val := rfl @[simp] lemma cast_lt_val (k : fin m) (h : k.1 < n) : (k.cast_lt h).val = k.val := rfl @[simp] lemma cast_succ_cast_lt (i : fin (n + 1)) (h : i.val < n): cast_succ (cast_lt i h) = i := fin.eq_of_veq rfl @[simp] lemma sub_nat_val (i : fin (n + m)) (h : i.val ≥ m) : (i.sub_nat m h).val = i.val - m := rfl @[simp] lemma add_nat_val (i : fin (n + m)) (h : i.val ≥ m) : (i.add_nat m).val = i.val + m := rfl @[simp] lemma cast_succ_inj {a b : fin n} : a.cast_succ = b.cast_succ ↔ a = b := by simp [eq_iff_veq] theorem succ_above_ne (p : fin (n+1)) (i : fin n) : p.succ_above i ≠ p := begin assume eq, unfold fin.succ_above at eq, split_ifs at eq with h; simpa [lt_irrefl, nat.lt_succ_self, eq.symm] using h end @[simp] lemma succ_above_descend : ∀(p i : fin (n+1)) (h : i ≠ p), p.succ_above (p.pred_above i h) = i | ⟨p, hp⟩ ⟨0, hi⟩ h := fin.eq_of_veq $ by simp [succ_above, pred_above]; split_ifs; simp * at * | ⟨p, hp⟩ ⟨i+1, hi⟩ h := fin.eq_of_veq begin have : i + 1 ≠ p, by rwa [(≠), fin.ext_iff] at h, unfold succ_above pred_above, split_ifs with h1 h2; simp at *, exact (this (le_antisymm h2 (le_of_not_gt h1))).elim end @[simp] lemma pred_above_succ_above (p : fin (n+1)) (i : fin n) (h : p.succ_above i ≠ p) : p.pred_above (p.succ_above i) h = i := begin unfold fin.succ_above, apply eq_of_veq, split_ifs with h₀, { simp [pred_above, h₀, lt_iff_val_lt_val], }, { unfold pred_above, split_ifs with h₁, { exfalso, rw [lt_iff_val_lt_val, succ_val] at h₁, exact h₀ (lt_trans (nat.lt_succ_self _) h₁) }, { rw [pred_succ] } } end section rec @[elab_as_eliminator] def succ_rec {C : ∀ n, fin n → Sort*} (H0 : ∀ n, C (succ n) 0) (Hs : ∀ n i, C n i → C (succ n) i.succ) : ∀ {n : ℕ} (i : fin n), C n i | 0 i := i.elim0 | (succ n) ⟨0, _⟩ := H0 _ | (succ n) ⟨succ i, h⟩ := Hs _ _ (succ_rec ⟨i, lt_of_succ_lt_succ h⟩) @[elab_as_eliminator] def succ_rec_on {n : ℕ} (i : fin n) {C : ∀ n, fin n → Sort*} (H0 : ∀ n, C (succ n) 0) (Hs : ∀ n i, C n i → C (succ n) i.succ) : C n i := i.succ_rec H0 Hs @[simp] theorem succ_rec_on_zero {C : ∀ n, fin n → Sort*} {H0 Hs} (n) : @fin.succ_rec_on (succ n) 0 C H0 Hs = H0 n := rfl @[simp] theorem succ_rec_on_succ {C : ∀ n, fin n → Sort*} {H0 Hs} {n} (i : fin n) : @fin.succ_rec_on (succ n) i.succ C H0 Hs = Hs n i (fin.succ_rec_on i H0 Hs) := by cases i; refl @[elab_as_eliminator] def cases {C : fin (succ n) → Sort*} (H0 : C 0) (Hs : ∀ i : fin n, C (i.succ)) : ∀ (i : fin (succ n)), C i | ⟨0, h⟩ := H0 | ⟨succ i, h⟩ := Hs ⟨i, lt_of_succ_lt_succ h⟩ @[simp] theorem cases_zero {n} {C : fin (succ n) → Sort*} {H0 Hs} : @fin.cases n C H0 Hs 0 = H0 := rfl @[simp] theorem cases_succ {n} {C : fin (succ n) → Sort*} {H0 Hs} (i : fin n) : @fin.cases n C H0 Hs i.succ = Hs i := by cases i; refl end rec end fin
6540d06f9b86c140987c3898d9179c88cf7924a2
aa101d73b1a3173c7ec56de02b96baa8ca64c42e
/src/solutions/06_sub_sequences.lean
5a4e8a07c643d65863cfd381dda3baf0cf33ff3f
[ "Apache-2.0" ]
permissive
gihanmarasingha/tutorials
b554d4d53866c493c4341dc13e914b01444e95a6
56617114ef0f9f7b808476faffd11e22e4380918
refs/heads/master
1,671,141,758,153
1,599,173,318,000
1,599,173,318,000
282,405,870
0
0
Apache-2.0
1,595,666,751,000
1,595,666,750,000
null
UTF-8
Lean
false
false
4,790
lean
import tuto_lib /- This file continues the elementary study of limits of sequences. It can be skipped if the previous file was too easy, it won't introduce any new tactic or trick. Remember useful lemmas: abs_le (x y : ℝ) : |x| ≤ y ↔ -y ≤ x ∧ x ≤ y abs_add (x y : ℝ) : |x + y| ≤ |x| + |y| abs_sub (x y : ℝ) : |x - y| = |y - x| ge_max_iff (p q r) : r ≥ max p q ↔ r ≥ p ∧ r ≥ q le_max_left p q : p ≤ max p q le_max_right p q : q ≤ max p q and the definition: def seq_limit (u : ℕ → ℝ) (l : ℝ) : Prop := ∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - l| ≤ ε You can also use a property proved in the previous file: unique_limit : seq_limit u l → seq_limit u l' → l = l' def extraction (φ : ℕ → ℕ) := ∀ n m, n < m → φ n < φ m -/ variable { φ : ℕ → ℕ} /- The next lemma is proved by an easy induction, but we haven't seen induction in this tutorial. If you did the natural number game then you can delete the proof below and try to reconstruct it. -/ /-- An extraction is greater than id -/ lemma id_le_extraction' : extraction φ → ∀ n, n ≤ φ n := begin intros hyp n, induction n with n hn, { exact nat.zero_le _ }, { exact nat.succ_le_of_lt (by linarith [hyp n (n+1) (by linarith)]) }, end /-- Extractions take arbitrarily large values for arbitrarily large inputs. -/ -- 0039 lemma extraction_ge : extraction φ → ∀ N N', ∃ n ≥ N', φ n ≥ N := begin -- sorry intros h N N', use max N N', split, apply le_max_right, calc N ≤ max N N' : by apply le_max_left ... ≤ φ (max N N') : by apply id_le_extraction' h -- sorry end /-- A real number `a` is a cluster point of a sequence `u` if `u` has a subsequence converging to `a`. def cluster_point (u : ℕ → ℝ) (a : ℝ) := ∃ φ, extraction φ ∧ seq_limit (u ∘ φ) a -/ variables {u : ℕ → ℝ} {a l : ℝ} /- In the exercise, we use `∃ n ≥ N, ...` which is the abbreviation of `∃ n, n ≥ N ∧ ...`. Lean can read this abbreviation, but displays it as the confusing: `∃ (n : ℕ) (H : n ≥ N)` One gets used to it. Alternatively, one can get rid of it using the lemma exists_prop {p q : Prop} : (∃ (h : p), q) ↔ p ∧ q -/ /-- If `a` is a cluster point of `u` then there are values of `u` arbitrarily close to `a` for arbitrarily large input. -/ -- 0040 lemma near_cluster : cluster_point u a → ∀ ε > 0, ∀ N, ∃ n ≥ N, |u n - a| ≤ ε := begin -- sorry intros hyp ε ε_pos N, rcases hyp with ⟨φ, φ_extr, hφ⟩, cases hφ ε ε_pos with N' hN', rcases extraction_ge φ_extr N N' with ⟨q, hq, hq'⟩, exact ⟨φ q, hq', hN' _ hq⟩, -- sorry end /- The above exercice can be done in five lines. Hint: you can use the anonymous constructor syntax when proving existential statements. -/ /-- If `u` tends to `l` then its subsequences tend to `l`. -/ -- 0041 lemma subseq_tendsto_of_tendsto' (h : seq_limit u l) (hφ : extraction φ) : seq_limit (u ∘ φ) l := begin -- sorry intros ε ε_pos, cases h ε ε_pos with N hN, use N, intros n hn, apply hN, calc N ≤ n : hn ... ≤ φ n : id_le_extraction' hφ n, -- sorry end /-- If `u` tends to `l` all its cluster points are equal to `l`. -/ -- 0042 lemma cluster_limit (hl : seq_limit u l) (ha : cluster_point u a) : a = l := begin -- sorry rcases ha with ⟨φ, φ_extr, lim_u_φ⟩, have lim_u_φ' : seq_limit (u ∘ φ) l, from subseq_tendsto_of_tendsto' hl φ_extr, exact unique_limit lim_u_φ lim_u_φ', -- sorry end /-- Cauchy_sequence sequence -/ def cauchy_sequence (u : ℕ → ℝ) := ∀ ε > 0, ∃ N, ∀ p q, p ≥ N → q ≥ N → |u p - u q| ≤ ε -- 0043 example : (∃ l, seq_limit u l) → cauchy_sequence u := begin -- sorry intro hyp, cases hyp with l hl, intros ε ε_pos, cases hl (ε/2) (by linarith) with N hN, use N, intros p q hp hq, calc |u p - u q| = |(u p - l) + (l - u q)| : by ring ... ≤ |u p - l| + |l - u q| : by apply abs_add ... = |u p - l| + |u q - l| : by rw abs_sub (u q) l ... ≤ ε : by linarith [hN p hp, hN q hq], -- sorry end /- In the next exercise, you can reuse near_cluster : cluster_point u a → ∀ ε > 0, ∀ N, ∃ n ≥ N, |u n - a| ≤ ε -/ -- 0044 example (hu : cauchy_sequence u) (hl : cluster_point u l) : seq_limit u l := begin -- sorry intros ε ε_pos, cases hu (ε/2) (by linarith) with N hN, use N, have clef : ∃ N' ≥ N, |u N' - l| ≤ ε/2, apply near_cluster hl (ε/2) (by linarith), cases clef with N' h, cases h with hNN' hN', intros n hn, calc |u n - l| = |(u n - u N') + (u N' - l)| : by ring ... ≤ |u n - u N'| + |u N' - l| : by apply abs_add ... ≤ ε : by linarith [hN n N' (by linarith) hNN'], -- sorry end
145b2b2bbc13651981bb3d4cb07edc5d9ed9a723
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/run/match1.lean
b7905c97840bbcdb713ed3058a058b1ddef4858b
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
683
lean
import data.nat open nat definition two1 : nat := 2 definition two2 : nat := succ (succ (zero)) constant f : nat → nat → nat (* local tc = type_checker_with_hints(get_env(), true) local plugin = whnf_match_plugin(tc) function tst_match(p, t) local r1, r2 = match(p, t, plugin) assert(r1) print("--------------") for i = 1, #r1 do print(" expr:#" .. i .. " := " .. tostring(r1[i])) end for i = 1, #r2 do print(" lvl:#" .. i .. " := " .. tostring(r2[i])) end end local f = Const("f") local two1 = Const("two1") local two2 = Const("two2") local succ = Const({"nat", "succ"}) tst_match(f(succ(mk_var(0)), two1), f(two2, two2)) *)
ad18e27204c7243077b2225ad4195e4bb4b10854
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/tensor_product.lean
2e031039e06180a1bbfb5712aac8f1c36ff904e9
[ "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
44,102
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro -/ import group_theory.congruence import algebra.module.submodule.bilinear /-! # Tensor product of modules over commutative semirings. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file constructs the tensor product of modules over commutative semirings. Given a semiring `R` and modules over it `M` and `N`, the standard construction of the tensor product is `tensor_product R M N`. It is also a module over `R`. It comes with a canonical bilinear map `M → N → tensor_product R M N`. Given any bilinear map `M → N → P`, there is a unique linear map `tensor_product R M N → P` whose composition with the canonical bilinear map `M → N → tensor_product R M N` is the given bilinear map `M → N → P`. We start by proving basic lemmas about bilinear maps. ## Notations This file uses the localized notation `M ⊗ N` and `M ⊗[R] N` for `tensor_product R M N`, as well as `m ⊗ₜ n` and `m ⊗ₜ[R] n` for `tensor_product.tmul R m n`. ## Tags bilinear, tensor, tensor product -/ section semiring variables {R : Type*} [comm_semiring R] variables {R' : Type*} [monoid R'] variables {R'' : Type*} [semiring R''] variables {M : Type*} {N : Type*} {P : Type*} {Q : Type*} {S : Type*} variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] [add_comm_monoid S] variables [module R M] [module R N] [module R P] [module R Q] [module R S] variables [distrib_mul_action R' M] variables [module R'' M] include R variables (M N) namespace tensor_product section -- open free_add_monoid variables (R) /-- The relation on `free_add_monoid (M × N)` that generates a congruence whose quotient is the tensor product. -/ inductive eqv : free_add_monoid (M × N) → free_add_monoid (M × N) → Prop | of_zero_left : ∀ n : N, eqv (free_add_monoid.of (0, n)) 0 | of_zero_right : ∀ m : M, eqv (free_add_monoid.of (m, 0)) 0 | of_add_left : ∀ (m₁ m₂ : M) (n : N), eqv (free_add_monoid.of (m₁, n) + free_add_monoid.of (m₂, n)) (free_add_monoid.of (m₁ + m₂, n)) | of_add_right : ∀ (m : M) (n₁ n₂ : N), eqv (free_add_monoid.of (m, n₁) + free_add_monoid.of (m, n₂)) (free_add_monoid.of (m, n₁ + n₂)) | of_smul : ∀ (r : R) (m : M) (n : N), eqv (free_add_monoid.of (r • m, n)) (free_add_monoid.of (m, r • n)) | add_comm : ∀ x y, eqv (x + y) (y + x) end end tensor_product variables (R) /-- The tensor product of two modules `M` and `N` over the same commutative semiring `R`. The localized notations are `M ⊗ N` and `M ⊗[R] N`, accessed by `open_locale tensor_product`. -/ def tensor_product : Type* := (add_con_gen (tensor_product.eqv R M N)).quotient variables {R} localized "infix (name := tensor_product.infer) ` ⊗ `:100 := tensor_product hole!" in tensor_product localized "notation (name := tensor_product) M ` ⊗[`:100 R `] `:0 N:100 := tensor_product R M N" in tensor_product namespace tensor_product section module instance : add_zero_class (M ⊗[R] N) := { .. (add_con_gen (tensor_product.eqv R M N)).add_monoid } instance : add_comm_semigroup (M ⊗[R] N) := { add_comm := λ x y, add_con.induction_on₂ x y $ λ x y, quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.add_comm _ _, .. (add_con_gen (tensor_product.eqv R M N)).add_monoid } instance : inhabited (M ⊗[R] N) := ⟨0⟩ variables (R) {M N} /-- The canonical function `M → N → M ⊗ N`. The localized notations are `m ⊗ₜ n` and `m ⊗ₜ[R] n`, accessed by `open_locale tensor_product`. -/ def tmul (m : M) (n : N) : M ⊗[R] N := add_con.mk' _ $ free_add_monoid.of (m, n) variables {R} infix ` ⊗ₜ `:100 := tmul _ notation x ` ⊗ₜ[`:100 R `] `:0 y:100 := tmul R x y @[elab_as_eliminator] protected theorem induction_on {C : (M ⊗[R] N) → Prop} (z : M ⊗[R] N) (C0 : C 0) (C1 : ∀ {x y}, C $ x ⊗ₜ[R] y) (Cp : ∀ {x y}, C x → C y → C (x + y)) : C z := add_con.induction_on z $ λ x, free_add_monoid.rec_on x C0 $ λ ⟨m, n⟩ y ih, by { rw add_con.coe_add, exact Cp C1 ih } variables (M) @[simp] lemma zero_tmul (n : N) : (0 : M) ⊗ₜ[R] n = 0 := quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_zero_left _ variables {M} lemma add_tmul (m₁ m₂ : M) (n : N) : (m₁ + m₂) ⊗ₜ n = m₁ ⊗ₜ n + m₂ ⊗ₜ[R] n := eq.symm $ quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_add_left _ _ _ variables (N) @[simp] lemma tmul_zero (m : M) : m ⊗ₜ[R] (0 : N) = 0 := quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_zero_right _ variables {N} lemma tmul_add (m : M) (n₁ n₂ : N) : m ⊗ₜ (n₁ + n₂) = m ⊗ₜ n₁ + m ⊗ₜ[R] n₂ := eq.symm $ quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_add_right _ _ _ section variables (R R' M N) /-- A typeclass for `has_smul` structures which can be moved across a tensor product. This typeclass is generated automatically from a `is_scalar_tower` instance, but exists so that we can also add an instance for `add_comm_group.int_module`, allowing `z •` to be moved even if `R` does not support negation. Note that `module R' (M ⊗[R] N)` is available even without this typeclass on `R'`; it's only needed if `tensor_product.smul_tmul`, `tensor_product.smul_tmul'`, or `tensor_product.tmul_smul` is used. -/ class compatible_smul [distrib_mul_action R' N] := (smul_tmul : ∀ (r : R') (m : M) (n : N), (r • m) ⊗ₜ n = m ⊗ₜ[R] (r • n)) end /-- Note that this provides the default `compatible_smul R R M N` instance through `mul_action.is_scalar_tower.left`. -/ @[priority 100] instance compatible_smul.is_scalar_tower [has_smul R' R] [is_scalar_tower R' R M] [distrib_mul_action R' N] [is_scalar_tower R' R N] : compatible_smul R R' M N := ⟨λ r m n, begin conv_lhs {rw ← one_smul R m}, conv_rhs {rw ← one_smul R n}, rw [←smul_assoc, ←smul_assoc], exact (quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_smul _ _ _), end⟩ /-- `smul` can be moved from one side of the product to the other .-/ lemma smul_tmul [distrib_mul_action R' N] [compatible_smul R R' M N] (r : R') (m : M) (n : N) : (r • m) ⊗ₜ n = m ⊗ₜ[R] (r • n) := compatible_smul.smul_tmul _ _ _ /-- Auxiliary function to defining scalar multiplication on tensor product. -/ def smul.aux {R' : Type*} [has_smul R' M] (r : R') : free_add_monoid (M × N) →+ M ⊗[R] N := free_add_monoid.lift $ λ p : M × N, (r • p.1) ⊗ₜ p.2 theorem smul.aux_of {R' : Type*} [has_smul R' M] (r : R') (m : M) (n : N) : smul.aux r (free_add_monoid.of (m, n)) = (r • m) ⊗ₜ[R] n := rfl variables [smul_comm_class R R' M] variables [smul_comm_class R R'' M] /-- Given two modules over a commutative semiring `R`, if one of the factors carries a (distributive) action of a second type of scalars `R'`, which commutes with the action of `R`, then the tensor product (over `R`) carries an action of `R'`. This instance defines this `R'` action in the case that it is the left module which has the `R'` action. Two natural ways in which this situation arises are: * Extension of scalars * A tensor product of a group representation with a module not carrying an action Note that in the special case that `R = R'`, since `R` is commutative, we just get the usual scalar action on a tensor product of two modules. This special case is important enough that, for performance reasons, we define it explicitly below. -/ instance left_has_smul : has_smul R' (M ⊗[R] N) := ⟨λ r, (add_con_gen (tensor_product.eqv R M N)).lift (smul.aux r : _ →+ M ⊗[R] N) $ add_con.add_con_gen_le $ λ x y hxy, match x, y, hxy with | _, _, (eqv.of_zero_left n) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_zero, smul.aux_of, smul_zero, zero_tmul] | _, _, (eqv.of_zero_right m) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_zero, smul.aux_of, tmul_zero] | _, _, (eqv.of_add_left m₁ m₂ n) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, smul.aux_of, smul_add, add_tmul] | _, _, (eqv.of_add_right m n₁ n₂) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, smul.aux_of, tmul_add] | _, _, (eqv.of_smul s m n) := (add_con.ker_rel _).2 $ by rw [smul.aux_of, smul.aux_of, ←smul_comm, smul_tmul] | _, _, (eqv.add_comm x y) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, add_comm] end⟩ instance : has_smul R (M ⊗[R] N) := tensor_product.left_has_smul protected theorem smul_zero (r : R') : (r • 0 : M ⊗[R] N) = 0 := add_monoid_hom.map_zero _ protected theorem smul_add (r : R') (x y : M ⊗[R] N) : r • (x + y) = r • x + r • y := add_monoid_hom.map_add _ _ _ protected theorem zero_smul (x : M ⊗[R] N) : (0 : R'') • x = 0 := have ∀ (r : R'') (m : M) (n : N), r • (m ⊗ₜ[R] n) = (r • m) ⊗ₜ n := λ _ _ _, rfl, tensor_product.induction_on x (by rw tensor_product.smul_zero) (λ m n, by rw [this, zero_smul, zero_tmul]) (λ x y ihx ihy, by rw [tensor_product.smul_add, ihx, ihy, add_zero]) protected theorem one_smul (x : M ⊗[R] N) : (1 : R') • x = x := have ∀ (r : R') (m : M) (n : N), r • (m ⊗ₜ[R] n) = (r • m) ⊗ₜ n := λ _ _ _, rfl, tensor_product.induction_on x (by rw tensor_product.smul_zero) (λ m n, by rw [this, one_smul]) (λ x y ihx ihy, by rw [tensor_product.smul_add, ihx, ihy]) protected theorem add_smul (r s : R'') (x : M ⊗[R] N) : (r + s) • x = r • x + s • x := have ∀ (r : R'') (m : M) (n : N), r • (m ⊗ₜ[R] n) = (r • m) ⊗ₜ n := λ _ _ _, rfl, tensor_product.induction_on x (by simp_rw [tensor_product.smul_zero, add_zero]) (λ m n, by simp_rw [this, add_smul, add_tmul]) (λ x y ihx ihy, by { simp_rw tensor_product.smul_add, rw [ihx, ihy, add_add_add_comm] }) instance : add_comm_monoid (M ⊗[R] N) := { nsmul := λ n v, n • v, nsmul_zero' := by simp [tensor_product.zero_smul], nsmul_succ' := by simp [nat.succ_eq_one_add, tensor_product.one_smul, tensor_product.add_smul], .. tensor_product.add_comm_semigroup _ _, .. tensor_product.add_zero_class _ _} instance left_distrib_mul_action : distrib_mul_action R' (M ⊗[R] N) := have ∀ (r : R') (m : M) (n : N), r • (m ⊗ₜ[R] n) = (r • m) ⊗ₜ n := λ _ _ _, rfl, { smul := (•), smul_add := λ r x y, tensor_product.smul_add r x y, mul_smul := λ r s x, tensor_product.induction_on x (by simp_rw tensor_product.smul_zero) (λ m n, by simp_rw [this, mul_smul]) (λ x y ihx ihy, by { simp_rw tensor_product.smul_add, rw [ihx, ihy] }), one_smul := tensor_product.one_smul, smul_zero := tensor_product.smul_zero } instance : distrib_mul_action R (M ⊗[R] N) := tensor_product.left_distrib_mul_action theorem smul_tmul' (r : R') (m : M) (n : N) : r • (m ⊗ₜ[R] n) = (r • m) ⊗ₜ n := rfl @[simp] lemma tmul_smul [distrib_mul_action R' N] [compatible_smul R R' M N] (r : R') (x : M) (y : N) : x ⊗ₜ (r • y) = r • (x ⊗ₜ[R] y) := (smul_tmul _ _ _).symm lemma smul_tmul_smul (r s : R) (m : M) (n : N) : (r • m) ⊗ₜ[R] (s • n) = (r * s) • (m ⊗ₜ[R] n) := by simp only [tmul_smul, smul_tmul, mul_smul] instance left_module : module R'' (M ⊗[R] N) := { smul := (•), add_smul := tensor_product.add_smul, zero_smul := tensor_product.zero_smul, ..tensor_product.left_distrib_mul_action } instance : module R (M ⊗[R] N) := tensor_product.left_module instance [module R''ᵐᵒᵖ M] [is_central_scalar R'' M] : is_central_scalar R'' (M ⊗[R] N) := { op_smul_eq_smul := λ r x, tensor_product.induction_on x (by rw [smul_zero, smul_zero]) (λ x y, by rw [smul_tmul', smul_tmul', op_smul_eq_smul]) (λ x y hx hy, by rw [smul_add, smul_add, hx, hy]) } section -- Like `R'`, `R'₂` provides a `distrib_mul_action R'₂ (M ⊗[R] N)` variables {R'₂ : Type*} [monoid R'₂] [distrib_mul_action R'₂ M] variables [smul_comm_class R R'₂ M] /-- `smul_comm_class R' R'₂ M` implies `smul_comm_class R' R'₂ (M ⊗[R] N)` -/ instance smul_comm_class_left [smul_comm_class R' R'₂ M] : smul_comm_class R' R'₂ (M ⊗[R] N) := { smul_comm := λ r' r'₂ x, tensor_product.induction_on x (by simp_rw tensor_product.smul_zero) (λ m n, by simp_rw [smul_tmul', smul_comm]) (λ x y ihx ihy, by { simp_rw tensor_product.smul_add, rw [ihx, ihy] }),} variables [has_smul R'₂ R'] /-- `is_scalar_tower R'₂ R' M` implies `is_scalar_tower R'₂ R' (M ⊗[R] N)` -/ instance is_scalar_tower_left [is_scalar_tower R'₂ R' M] : is_scalar_tower R'₂ R' (M ⊗[R] N) := ⟨λ s r x, tensor_product.induction_on x (by simp) (λ m n, by rw [smul_tmul', smul_tmul', smul_tmul', smul_assoc]) (λ x y ihx ihy, by rw [smul_add, smul_add, smul_add, ihx, ihy])⟩ variables [distrib_mul_action R'₂ N] [distrib_mul_action R' N] variables [compatible_smul R R'₂ M N] [compatible_smul R R' M N] /-- `is_scalar_tower R'₂ R' N` implies `is_scalar_tower R'₂ R' (M ⊗[R] N)` -/ instance is_scalar_tower_right [is_scalar_tower R'₂ R' N] : is_scalar_tower R'₂ R' (M ⊗[R] N) := ⟨λ s r x, tensor_product.induction_on x (by simp) (λ m n, by rw [←tmul_smul, ←tmul_smul, ←tmul_smul, smul_assoc]) (λ x y ihx ihy, by rw [smul_add, smul_add, smul_add, ihx, ihy])⟩ end /-- A short-cut instance for the common case, where the requirements for the `compatible_smul` instances are sufficient. -/ instance is_scalar_tower [has_smul R' R] [is_scalar_tower R' R M] : is_scalar_tower R' R (M ⊗[R] N) := tensor_product.is_scalar_tower_left -- or right variables (R M N) /-- The canonical bilinear map `M → N → M ⊗[R] N`. -/ def mk : M →ₗ[R] N →ₗ[R] M ⊗[R] N := linear_map.mk₂ R (⊗ₜ) add_tmul (λ c m n, by rw [smul_tmul, tmul_smul]) tmul_add tmul_smul variables {R M N} @[simp] lemma mk_apply (m : M) (n : N) : mk R M N m n = m ⊗ₜ n := rfl lemma ite_tmul (x₁ : M) (x₂ : N) (P : Prop) [decidable P] : (if P then x₁ else 0) ⊗ₜ[R] x₂ = if P then x₁ ⊗ₜ x₂ else 0 := by { split_ifs; simp } lemma tmul_ite (x₁ : M) (x₂ : N) (P : Prop) [decidable P] : x₁ ⊗ₜ[R] (if P then x₂ else 0) = if P then x₁ ⊗ₜ x₂ else 0 := by { split_ifs; simp } section open_locale big_operators lemma sum_tmul {α : Type*} (s : finset α) (m : α → M) (n : N) : (∑ a in s, m a) ⊗ₜ[R] n = ∑ a in s, m a ⊗ₜ[R] n := begin classical, induction s using finset.induction with a s has ih h, { simp, }, { simp [finset.sum_insert has, add_tmul, ih], }, end lemma tmul_sum (m : M) {α : Type*} (s : finset α) (n : α → N) : m ⊗ₜ[R] (∑ a in s, n a) = ∑ a in s, m ⊗ₜ[R] n a := begin classical, induction s using finset.induction with a s has ih h, { simp, }, { simp [finset.sum_insert has, tmul_add, ih], }, end end variables (R M N) /-- The simple (aka pure) elements span the tensor product. -/ lemma span_tmul_eq_top : submodule.span R { t : M ⊗[R] N | ∃ m n, m ⊗ₜ n = t } = ⊤ := begin ext t, simp only [submodule.mem_top, iff_true], apply t.induction_on, { exact submodule.zero_mem _, }, { intros m n, apply submodule.subset_span, use [m, n], }, { intros t₁ t₂ ht₁ ht₂, exact submodule.add_mem _ ht₁ ht₂, }, end @[simp] lemma map₂_mk_top_top_eq_top : submodule.map₂ (mk R M N) ⊤ ⊤ = ⊤ := begin rw [← top_le_iff, ← span_tmul_eq_top, submodule.map₂_eq_span_image2], exact submodule.span_mono (λ _ ⟨m, n, h⟩, ⟨m, n, trivial, trivial, h⟩), end end module section UMP variables {M N P Q} variables (f : M →ₗ[R] N →ₗ[R] P) /-- Auxiliary function to constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def lift_aux : (M ⊗[R] N) →+ P := (add_con_gen (tensor_product.eqv R M N)).lift (free_add_monoid.lift $ λ p : M × N, f p.1 p.2) $ add_con.add_con_gen_le $ λ x y hxy, match x, y, hxy with | _, _, (eqv.of_zero_left n) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_zero, free_add_monoid.lift_eval_of, f.map_zero₂] | _, _, (eqv.of_zero_right m) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_zero, free_add_monoid.lift_eval_of, (f m).map_zero] | _, _, (eqv.of_add_left m₁ m₂ n) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, free_add_monoid.lift_eval_of, f.map_add₂] | _, _, (eqv.of_add_right m n₁ n₂) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, free_add_monoid.lift_eval_of, (f m).map_add] | _, _, (eqv.of_smul r m n) := (add_con.ker_rel _).2 $ by simp_rw [free_add_monoid.lift_eval_of, f.map_smul₂, (f m).map_smul] | _, _, (eqv.add_comm x y) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, add_comm] end lemma lift_aux_tmul (m n) : lift_aux f (m ⊗ₜ n) = f m n := rfl variable {f} @[simp] lemma lift_aux.smul (r : R) (x) : lift_aux f (r • x) = r • lift_aux f x := tensor_product.induction_on x (smul_zero _).symm (λ p q, by rw [← tmul_smul, lift_aux_tmul, lift_aux_tmul, (f p).map_smul]) (λ p q ih1 ih2, by rw [smul_add, (lift_aux f).map_add, ih1, ih2, (lift_aux f).map_add, smul_add]) variable (f) /-- Constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def lift : M ⊗ N →ₗ[R] P := { map_smul' := lift_aux.smul, .. lift_aux f } variable {f} @[simp] lemma lift.tmul (x y) : lift f (x ⊗ₜ y) = f x y := rfl @[simp] lemma lift.tmul' (x y) : (lift f).1 (x ⊗ₜ y) = f x y := rfl theorem ext' {g h : (M ⊗[R] N) →ₗ[R] P} (H : ∀ x y, g (x ⊗ₜ y) = h (x ⊗ₜ y)) : g = h := linear_map.ext $ λ z, tensor_product.induction_on z (by simp_rw linear_map.map_zero) H $ λ x y ihx ihy, by rw [g.map_add, h.map_add, ihx, ihy] theorem lift.unique {g : (M ⊗[R] N) →ₗ[R] P} (H : ∀ x y, g (x ⊗ₜ y) = f x y) : g = lift f := ext' $ λ m n, by rw [H, lift.tmul] theorem lift_mk : lift (mk R M N) = linear_map.id := eq.symm $ lift.unique $ λ x y, rfl theorem lift_compr₂ (g : P →ₗ[R] Q) : lift (f.compr₂ g) = g.comp (lift f) := eq.symm $ lift.unique $ λ x y, by simp theorem lift_mk_compr₂ (f : M ⊗ N →ₗ[R] P) : lift ((mk R M N).compr₂ f) = f := by rw [lift_compr₂ f, lift_mk, linear_map.comp_id] /-- This used to be an `@[ext]` lemma, but it fails very slowly when the `ext` tactic tries to apply it in some cases, notably when one wants to show equality of two linear maps. The `@[ext]` attribute is now added locally where it is needed. Using this as the `@[ext]` lemma instead of `tensor_product.ext'` allows `ext` to apply lemmas specific to `M →ₗ _` and `N →ₗ _`. See note [partially-applied ext lemmas]. -/ theorem ext {g h : M ⊗ N →ₗ[R] P} (H : (mk R M N).compr₂ g = (mk R M N).compr₂ h) : g = h := by rw [← lift_mk_compr₂ g, H, lift_mk_compr₂] local attribute [ext] ext example : M → N → (M → N → P) → P := λ m, flip $ λ f, f m variables (R M N P) /-- Linearly constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def uncurry : (M →ₗ[R] N →ₗ[R] P) →ₗ[R] M ⊗[R] N →ₗ[R] P := linear_map.flip $ lift $ (linear_map.lflip _ _ _ _).comp (linear_map.flip linear_map.id) variables {R M N P} @[simp] theorem uncurry_apply (f : M →ₗ[R] N →ₗ[R] P) (m : M) (n : N) : uncurry R M N P f (m ⊗ₜ n) = f m n := by rw [uncurry, linear_map.flip_apply, lift.tmul]; refl variables (R M N P) /-- A linear equivalence constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def lift.equiv : (M →ₗ[R] N →ₗ[R] P) ≃ₗ[R] (M ⊗ N →ₗ[R] P) := { inv_fun := λ f, (mk R M N).compr₂ f, left_inv := λ f, linear_map.ext₂ $ λ m n, lift.tmul _ _, right_inv := λ f, ext' $ λ m n, lift.tmul _ _, .. uncurry R M N P } @[simp] lemma lift.equiv_apply (f : M →ₗ[R] N →ₗ[R] P) (m : M) (n : N) : lift.equiv R M N P f (m ⊗ₜ n) = f m n := uncurry_apply f m n @[simp] lemma lift.equiv_symm_apply (f : M ⊗[R] N →ₗ[R] P) (m : M) (n : N) : (lift.equiv R M N P).symm f m n = f (m ⊗ₜ n) := rfl /-- Given a linear map `M ⊗ N → P`, compose it with the canonical bilinear map `M → N → M ⊗ N` to form a bilinear map `M → N → P`. -/ def lcurry : (M ⊗[R] N →ₗ[R] P) →ₗ[R] M →ₗ[R] N →ₗ[R] P := (lift.equiv R M N P).symm variables {R M N P} @[simp] theorem lcurry_apply (f : M ⊗[R] N →ₗ[R] P) (m : M) (n : N) : lcurry R M N P f m n = f (m ⊗ₜ n) := rfl /-- Given a linear map `M ⊗ N → P`, compose it with the canonical bilinear map `M → N → M ⊗ N` to form a bilinear map `M → N → P`. -/ def curry (f : M ⊗ N →ₗ[R] P) : M →ₗ[R] N →ₗ[R] P := lcurry R M N P f @[simp] theorem curry_apply (f : M ⊗ N →ₗ[R] P) (m : M) (n : N) : curry f m n = f (m ⊗ₜ n) := rfl lemma curry_injective : function.injective (curry : (M ⊗[R] N →ₗ[R] P) → (M →ₗ[R] N →ₗ[R] P)) := λ g h H, ext H theorem ext_threefold {g h : (M ⊗[R] N) ⊗[R] P →ₗ[R] Q} (H : ∀ x y z, g ((x ⊗ₜ y) ⊗ₜ z) = h ((x ⊗ₜ y) ⊗ₜ z)) : g = h := begin ext x y z, exact H x y z end -- We'll need this one for checking the pentagon identity! theorem ext_fourfold {g h : ((M ⊗[R] N) ⊗[R] P) ⊗[R] Q →ₗ[R] S} (H : ∀ w x y z, g (((w ⊗ₜ x) ⊗ₜ y) ⊗ₜ z) = h (((w ⊗ₜ x) ⊗ₜ y) ⊗ₜ z)) : g = h := begin ext w x y z, exact H w x y z, end /-- Two linear maps (M ⊗ N) ⊗ (P ⊗ Q) → S which agree on all elements of the form (m ⊗ₜ n) ⊗ₜ (p ⊗ₜ q) are equal. -/ theorem ext_fourfold' {φ ψ : (M ⊗[R] N) ⊗[R] (P ⊗[R] Q) →ₗ[R] S} (H : ∀ w x y z, φ ((w ⊗ₜ x) ⊗ₜ (y ⊗ₜ z)) = ψ ((w ⊗ₜ x) ⊗ₜ (y ⊗ₜ z))) : φ = ψ := begin ext m n p q, exact H m n p q, end end UMP variables {M N} section variables (R M) /-- The base ring is a left identity for the tensor product of modules, up to linear equivalence. -/ protected def lid : R ⊗ M ≃ₗ[R] M := linear_equiv.of_linear (lift $ linear_map.lsmul R M) (mk R R M 1) (linear_map.ext $ λ _, by simp) (ext' $ λ r m, by simp; rw [← tmul_smul, ← smul_tmul, smul_eq_mul, mul_one]) end @[simp] theorem lid_tmul (m : M) (r : R) : ((tensor_product.lid R M) : (R ⊗ M → M)) (r ⊗ₜ m) = r • m := begin dsimp [tensor_product.lid], simp, end @[simp] lemma lid_symm_apply (m : M) : (tensor_product.lid R M).symm m = 1 ⊗ₜ m := rfl section variables (R M N) /-- The tensor product of modules is commutative, up to linear equivalence. -/ protected def comm : M ⊗ N ≃ₗ[R] N ⊗ M := linear_equiv.of_linear (lift (mk R N M).flip) (lift (mk R M N).flip) (ext' $ λ m n, rfl) (ext' $ λ m n, rfl) @[simp] theorem comm_tmul (m : M) (n : N) : (tensor_product.comm R M N) (m ⊗ₜ n) = n ⊗ₜ m := rfl @[simp] theorem comm_symm_tmul (m : M) (n : N) : (tensor_product.comm R M N).symm (n ⊗ₜ m) = m ⊗ₜ n := rfl end section variables (R M) /-- The base ring is a right identity for the tensor product of modules, up to linear equivalence. -/ protected def rid : M ⊗[R] R ≃ₗ[R] M := linear_equiv.trans (tensor_product.comm R M R) (tensor_product.lid R M) end @[simp] theorem rid_tmul (m : M) (r : R) : (tensor_product.rid R M) (m ⊗ₜ r) = r • m := begin dsimp [tensor_product.rid, tensor_product.comm, tensor_product.lid], simp, end @[simp] lemma rid_symm_apply (m : M) : (tensor_product.rid R M).symm m = m ⊗ₜ 1 := rfl open linear_map section variables (R M N P) /-- The associator for tensor product of R-modules, as a linear equivalence. -/ protected def assoc : (M ⊗[R] N) ⊗[R] P ≃ₗ[R] M ⊗[R] (N ⊗[R] P) := begin refine linear_equiv.of_linear (lift $ lift $ comp (lcurry R _ _ _) $ mk _ _ _) (lift $ comp (uncurry R _ _ _) $ curry $ mk _ _ _) (ext $ linear_map.ext $ λ m, ext' $ λ n p, _) (ext $ flip_inj $ linear_map.ext $ λ p, ext' $ λ m n, _); repeat { rw lift.tmul <|> rw compr₂_apply <|> rw comp_apply <|> rw mk_apply <|> rw flip_apply <|> rw lcurry_apply <|> rw uncurry_apply <|> rw curry_apply <|> rw id_apply } end end @[simp] theorem assoc_tmul (m : M) (n : N) (p : P) : (tensor_product.assoc R M N P) ((m ⊗ₜ n) ⊗ₜ p) = m ⊗ₜ (n ⊗ₜ p) := rfl @[simp] theorem assoc_symm_tmul (m : M) (n : N) (p : P) : (tensor_product.assoc R M N P).symm (m ⊗ₜ (n ⊗ₜ p)) = (m ⊗ₜ n) ⊗ₜ p := rfl /-- The tensor product of a pair of linear maps between modules. -/ def map (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : M ⊗ N →ₗ[R] P ⊗ Q := lift $ comp (compl₂ (mk _ _ _) g) f @[simp] theorem map_tmul (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (m : M) (n : N) : map f g (m ⊗ₜ n) = f m ⊗ₜ g n := rfl lemma map_range_eq_span_tmul (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (map f g).range = submodule.span R { t | ∃ m n, (f m) ⊗ₜ (g n) = t } := begin simp only [← submodule.map_top, ← span_tmul_eq_top, submodule.map_span, set.mem_image, set.mem_set_of_eq], congr, ext t, split, { rintros ⟨_, ⟨⟨m, n, rfl⟩, rfl⟩⟩, use [m, n], simp only [map_tmul], }, { rintros ⟨m, n, rfl⟩, use [m ⊗ₜ n, m, n], simp only [map_tmul], }, end /-- Given submodules `p ⊆ P` and `q ⊆ Q`, this is the natural map: `p ⊗ q → P ⊗ Q`. -/ @[simp] def map_incl (p : submodule R P) (q : submodule R Q) : p ⊗[R] q →ₗ[R] P ⊗[R] Q := map p.subtype q.subtype section variables {P' Q' : Type*} variables [add_comm_monoid P'] [module R P'] variables [add_comm_monoid Q'] [module R Q'] lemma map_comp (f₂ : P →ₗ[R] P') (f₁ : M →ₗ[R] P) (g₂ : Q →ₗ[R] Q') (g₁ : N →ₗ[R] Q) : map (f₂.comp f₁) (g₂.comp g₁) = (map f₂ g₂).comp (map f₁ g₁) := ext' $ λ _ _, rfl lemma lift_comp_map (i : P →ₗ[R] Q →ₗ[R] Q') (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (lift i).comp (map f g) = lift ((i.comp f).compl₂ g) := ext' $ λ _ _, rfl local attribute [ext] ext @[simp] lemma map_id : map (id : M →ₗ[R] M) (id : N →ₗ[R] N) = id := by { ext, simp only [mk_apply, id_coe, compr₂_apply, id.def, map_tmul], } @[simp] lemma map_one : map (1 : M →ₗ[R] M) (1 : N →ₗ[R] N) = 1 := map_id lemma map_mul (f₁ f₂ : M →ₗ[R] M) (g₁ g₂ : N →ₗ[R] N) : map (f₁ * f₂) (g₁ * g₂) = (map f₁ g₁) * (map f₂ g₂) := map_comp f₁ f₂ g₁ g₂ @[simp] protected lemma map_pow (f : M →ₗ[R] M) (g : N →ₗ[R] N) (n : ℕ) : (map f g)^n = map (f^n) (g^n) := begin induction n with n ih, { simp only [pow_zero, map_one], }, { simp only [pow_succ', ih, map_mul], }, end lemma map_add_left (f₁ f₂ : M →ₗ[R] P) (g : N →ₗ[R] Q) : map (f₁ + f₂) g = map f₁ g + map f₂ g := by {ext, simp only [add_tmul, compr₂_apply, mk_apply, map_tmul, add_apply]} lemma map_add_right (f : M →ₗ[R] P) (g₁ g₂ : N →ₗ[R] Q) : map f (g₁ + g₂) = map f g₁ + map f g₂ := by {ext, simp only [tmul_add, compr₂_apply, mk_apply, map_tmul, add_apply]} lemma map_smul_left (r : R) (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : map (r • f) g = r • map f g := by {ext, simp only [smul_tmul, compr₂_apply, mk_apply, map_tmul, smul_apply, tmul_smul]} lemma map_smul_right (r : R) (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : map f (r • g) = r • map f g := by {ext, simp only [smul_tmul, compr₂_apply, mk_apply, map_tmul, smul_apply, tmul_smul]} variables (R M N P Q) /-- The tensor product of a pair of linear maps between modules, bilinear in both maps. -/ def map_bilinear : (M →ₗ[R] P) →ₗ[R] (N →ₗ[R] Q) →ₗ[R] (M ⊗[R] N →ₗ[R] P ⊗[R] Q) := linear_map.mk₂ R map map_add_left map_smul_left map_add_right map_smul_right /-- The canonical linear map from `P ⊗[R] (M →ₗ[R] Q)` to `(M →ₗ[R] P ⊗[R] Q)` -/ def ltensor_hom_to_hom_ltensor : P ⊗[R] (M →ₗ[R] Q) →ₗ[R] (M →ₗ[R] P ⊗[R] Q) := tensor_product.lift (llcomp R M Q _ ∘ₗ mk R P Q) /-- The canonical linear map from `(M →ₗ[R] P) ⊗[R] Q` to `(M →ₗ[R] P ⊗[R] Q)` -/ def rtensor_hom_to_hom_rtensor : (M →ₗ[R] P) ⊗[R] Q →ₗ[R] (M →ₗ[R] P ⊗[R] Q) := tensor_product.lift (llcomp R M P _ ∘ₗ (mk R P Q).flip).flip /-- The linear map from `(M →ₗ P) ⊗ (N →ₗ Q)` to `(M ⊗ N →ₗ P ⊗ Q)` sending `f ⊗ₜ g` to the `tensor_product.map f g`, the tensor product of the two maps. -/ def hom_tensor_hom_map : (M →ₗ[R] P) ⊗[R] (N →ₗ[R] Q) →ₗ[R] (M ⊗[R] N →ₗ[R] P ⊗[R] Q) := lift (map_bilinear R M N P Q) variables {R M N P Q} @[simp] lemma map_bilinear_apply (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : map_bilinear R M N P Q f g = map f g := rfl @[simp] lemma ltensor_hom_to_hom_ltensor_apply (p : P) (f : M →ₗ[R] Q) (m : M) : ltensor_hom_to_hom_ltensor R M P Q (p ⊗ₜ f) m = p ⊗ₜ f m := rfl @[simp] lemma rtensor_hom_to_hom_rtensor_apply (f : M →ₗ[R] P) (q : Q) (m : M) : rtensor_hom_to_hom_rtensor R M P Q (f ⊗ₜ q) m = f m ⊗ₜ q := rfl @[simp] lemma hom_tensor_hom_map_apply (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : hom_tensor_hom_map R M N P Q (f ⊗ₜ g) = map f g := rfl end /-- If `M` and `P` are linearly equivalent and `N` and `Q` are linearly equivalent then `M ⊗ N` and `P ⊗ Q` are linearly equivalent. -/ def congr (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) : M ⊗ N ≃ₗ[R] P ⊗ Q := linear_equiv.of_linear (map f g) (map f.symm g.symm) (ext' $ λ m n, by simp; simp only [linear_equiv.apply_symm_apply]) (ext' $ λ m n, by simp; simp only [linear_equiv.symm_apply_apply]) @[simp] theorem congr_tmul (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) (m : M) (n : N) : congr f g (m ⊗ₜ n) = f m ⊗ₜ g n := rfl @[simp] theorem congr_symm_tmul (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) (p : P) (q : Q) : (congr f g).symm (p ⊗ₜ q) = f.symm p ⊗ₜ g.symm q := rfl variables (R M N P Q) /-- A tensor product analogue of `mul_left_comm`. -/ def left_comm : M ⊗[R] (N ⊗[R] P) ≃ₗ[R] N ⊗[R] (M ⊗[R] P) := let e₁ := (tensor_product.assoc R M N P).symm, e₂ := congr (tensor_product.comm R M N) (1 : P ≃ₗ[R] P), e₃ := (tensor_product.assoc R N M P) in e₁ ≪≫ₗ (e₂ ≪≫ₗ e₃) variables {M N P Q} @[simp] lemma left_comm_tmul (m : M) (n : N) (p : P) : left_comm R M N P (m ⊗ₜ (n ⊗ₜ p)) = n ⊗ₜ (m ⊗ₜ p) := rfl @[simp] lemma left_comm_symm_tmul (m : M) (n : N) (p : P) : (left_comm R M N P).symm (n ⊗ₜ (m ⊗ₜ p)) = m ⊗ₜ (n ⊗ₜ p) := rfl variables (M N P Q) /-- This special case is worth defining explicitly since it is useful for defining multiplication on tensor products of modules carrying multiplications (e.g., associative rings, Lie rings, ...). E.g., suppose `M = P` and `N = Q` and that `M` and `N` carry bilinear multiplications: `M ⊗ M → M` and `N ⊗ N → N`. Using `map`, we can define `(M ⊗ M) ⊗ (N ⊗ N) → M ⊗ N` which, when combined with this definition, yields a bilinear multiplication on `M ⊗ N`: `(M ⊗ N) ⊗ (M ⊗ N) → M ⊗ N`. In particular we could use this to define the multiplication in the `tensor_product.semiring` instance (currently defined "by hand" using `tensor_product.mul`). See also `mul_mul_mul_comm`. -/ def tensor_tensor_tensor_comm : (M ⊗[R] N) ⊗[R] (P ⊗[R] Q) ≃ₗ[R] (M ⊗[R] P) ⊗[R] (N ⊗[R] Q) := let e₁ := tensor_product.assoc R M N (P ⊗[R] Q), e₂ := congr (1 : M ≃ₗ[R] M) (left_comm R N P Q), e₃ := (tensor_product.assoc R M P (N ⊗[R] Q)).symm in e₁ ≪≫ₗ (e₂ ≪≫ₗ e₃) variables {M N P Q} @[simp] lemma tensor_tensor_tensor_comm_tmul (m : M) (n : N) (p : P) (q : Q) : tensor_tensor_tensor_comm R M N P Q ((m ⊗ₜ n) ⊗ₜ (p ⊗ₜ q)) = (m ⊗ₜ p) ⊗ₜ (n ⊗ₜ q) := rfl @[simp] lemma tensor_tensor_tensor_comm_symm : (tensor_tensor_tensor_comm R M N P Q).symm = tensor_tensor_tensor_comm R M P N Q := rfl variables (M N P Q) /-- This special case is useful for describing the interplay between `dual_tensor_hom_equiv` and composition of linear maps. E.g., composition of linear maps gives a map `(M → N) ⊗ (N → P) → (M → P)`, and applying `dual_tensor_hom_equiv.symm` to the three hom-modules gives a map `(M.dual ⊗ N) ⊗ (N.dual ⊗ P) → (M.dual ⊗ P)`, which agrees with the application of `contract_right` on `N ⊗ N.dual` after the suitable rebracketting. -/ def tensor_tensor_tensor_assoc : (M ⊗[R] N) ⊗[R] (P ⊗[R] Q) ≃ₗ[R] M ⊗[R] (N ⊗[R] P) ⊗[R] Q := (tensor_product.assoc R (M ⊗[R] N) P Q).symm ≪≫ₗ congr (tensor_product.assoc R M N P) (1 : Q ≃ₗ[R] Q) variables {M N P Q} @[simp] lemma tensor_tensor_tensor_assoc_tmul (m : M) (n : N) (p : P) (q : Q) : tensor_tensor_tensor_assoc R M N P Q ((m ⊗ₜ n) ⊗ₜ (p ⊗ₜ q)) = m ⊗ₜ (n ⊗ₜ p) ⊗ₜ q := rfl @[simp] lemma tensor_tensor_tensor_assoc_symm_tmul (m : M) (n : N) (p : P) (q : Q) : (tensor_tensor_tensor_assoc R M N P Q).symm (m ⊗ₜ (n ⊗ₜ p) ⊗ₜ q) = (m ⊗ₜ n) ⊗ₜ (p ⊗ₜ q) := rfl end tensor_product namespace linear_map variables {R} (M) {N P Q} /-- `ltensor M f : M ⊗ N →ₗ M ⊗ P` is the natural linear map induced by `f : N →ₗ P`. -/ def ltensor (f : N →ₗ[R] P) : M ⊗ N →ₗ[R] M ⊗ P := tensor_product.map id f /-- `rtensor f M : N₁ ⊗ M →ₗ N₂ ⊗ M` is the natural linear map induced by `f : N₁ →ₗ N₂`. -/ def rtensor (f : N →ₗ[R] P) : N ⊗ M →ₗ[R] P ⊗ M := tensor_product.map f id variables (g : P →ₗ[R] Q) (f : N →ₗ[R] P) @[simp] lemma ltensor_tmul (m : M) (n : N) : f.ltensor M (m ⊗ₜ n) = m ⊗ₜ (f n) := rfl @[simp] lemma rtensor_tmul (m : M) (n : N) : f.rtensor M (n ⊗ₜ m) = (f n) ⊗ₜ m := rfl open tensor_product local attribute [ext] tensor_product.ext /-- `ltensor_hom M` is the natural linear map that sends a linear map `f : N →ₗ P` to `M ⊗ f`. -/ def ltensor_hom : (N →ₗ[R] P) →ₗ[R] (M ⊗[R] N →ₗ[R] M ⊗[R] P) := { to_fun := ltensor M, map_add' := λ f g, by { ext x y, simp only [compr₂_apply, mk_apply, add_apply, ltensor_tmul, tmul_add] }, map_smul' := λ r f, by { dsimp, ext x y, simp only [compr₂_apply, mk_apply, tmul_smul, smul_apply, ltensor_tmul] } } /-- `rtensor_hom M` is the natural linear map that sends a linear map `f : N →ₗ P` to `M ⊗ f`. -/ def rtensor_hom : (N →ₗ[R] P) →ₗ[R] (N ⊗[R] M →ₗ[R] P ⊗[R] M) := { to_fun := λ f, f.rtensor M, map_add' := λ f g, by { ext x y, simp only [compr₂_apply, mk_apply, add_apply, rtensor_tmul, add_tmul] }, map_smul' := λ r f, by { dsimp, ext x y, simp only [compr₂_apply, mk_apply, smul_tmul, tmul_smul, smul_apply, rtensor_tmul] } } @[simp] lemma coe_ltensor_hom : (ltensor_hom M : (N →ₗ[R] P) → (M ⊗[R] N →ₗ[R] M ⊗[R] P)) = ltensor M := rfl @[simp] lemma coe_rtensor_hom : (rtensor_hom M : (N →ₗ[R] P) → (N ⊗[R] M →ₗ[R] P ⊗[R] M)) = rtensor M := rfl @[simp] lemma ltensor_add (f g : N →ₗ[R] P) : (f + g).ltensor M = f.ltensor M + g.ltensor M := (ltensor_hom M).map_add f g @[simp] lemma rtensor_add (f g : N →ₗ[R] P) : (f + g).rtensor M = f.rtensor M + g.rtensor M := (rtensor_hom M).map_add f g @[simp] lemma ltensor_zero : ltensor M (0 : N →ₗ[R] P) = 0 := (ltensor_hom M).map_zero @[simp] lemma rtensor_zero : rtensor M (0 : N →ₗ[R] P) = 0 := (rtensor_hom M).map_zero @[simp] lemma ltensor_smul (r : R) (f : N →ₗ[R] P) : (r • f).ltensor M = r • (f.ltensor M) := (ltensor_hom M).map_smul r f @[simp] lemma rtensor_smul (r : R) (f : N →ₗ[R] P) : (r • f).rtensor M = r • (f.rtensor M) := (rtensor_hom M).map_smul r f lemma ltensor_comp : (g.comp f).ltensor M = (g.ltensor M).comp (f.ltensor M) := by { ext m n, simp only [compr₂_apply, mk_apply, comp_apply, ltensor_tmul] } lemma ltensor_comp_apply (x : M ⊗[R] N) : (g.comp f).ltensor M x = (g.ltensor M) ((f.ltensor M) x) := by { rw [ltensor_comp, coe_comp], } lemma rtensor_comp : (g.comp f).rtensor M = (g.rtensor M).comp (f.rtensor M) := by { ext m n, simp only [compr₂_apply, mk_apply, comp_apply, rtensor_tmul] } lemma rtensor_comp_apply (x : N ⊗[R] M) : (g.comp f).rtensor M x = (g.rtensor M) ((f.rtensor M) x) := by { rw [rtensor_comp, coe_comp], } lemma ltensor_mul (f g : module.End R N) : (f * g).ltensor M = (f.ltensor M) * (g.ltensor M) := ltensor_comp M f g lemma rtensor_mul (f g : module.End R N) : (f * g).rtensor M = (f.rtensor M) * (g.rtensor M) := rtensor_comp M f g variables (N) @[simp] lemma ltensor_id : (id : N →ₗ[R] N).ltensor M = id := map_id -- `simp` can prove this. lemma ltensor_id_apply (x : M ⊗[R] N) : (linear_map.id : N →ₗ[R] N).ltensor M x = x := by {rw [ltensor_id, id_coe, id.def], } @[simp] lemma rtensor_id : (id : N →ₗ[R] N).rtensor M = id := map_id -- `simp` can prove this. lemma rtensor_id_apply (x : N ⊗[R] M) : (linear_map.id : N →ₗ[R] N).rtensor M x = x := by { rw [rtensor_id, id_coe, id.def], } variables {N} @[simp] lemma ltensor_comp_rtensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (g.ltensor P).comp (f.rtensor N) = map f g := by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id] @[simp] lemma rtensor_comp_ltensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (f.rtensor Q).comp (g.ltensor M) = map f g := by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id] @[simp] lemma map_comp_rtensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (f' : S →ₗ[R] M) : (map f g).comp (f'.rtensor _) = map (f.comp f') g := by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id] @[simp] lemma map_comp_ltensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (g' : S →ₗ[R] N) : (map f g).comp (g'.ltensor _) = map f (g.comp g') := by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id] @[simp] lemma rtensor_comp_map (f' : P →ₗ[R] S) (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (f'.rtensor _).comp (map f g) = map (f'.comp f) g := by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id] @[simp] lemma ltensor_comp_map (g' : Q →ₗ[R] S) (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (g'.ltensor _).comp (map f g) = map f (g'.comp g) := by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id] variables {M} @[simp] lemma rtensor_pow (f : M →ₗ[R] M) (n : ℕ) : (f.rtensor N)^n = (f^n).rtensor N := by { have h := tensor_product.map_pow f (id : N →ₗ[R] N) n, rwa id_pow at h, } @[simp] lemma ltensor_pow (f : N →ₗ[R] N) (n : ℕ) : (f.ltensor M)^n = (f^n).ltensor M := by { have h := tensor_product.map_pow (id : M →ₗ[R] M) f n, rwa id_pow at h, } end linear_map end semiring section ring variables {R : Type*} [comm_semiring R] variables {M : Type*} {N : Type*} {P : Type*} {Q : Type*} {S : Type*} variables [add_comm_group M] [add_comm_group N] [add_comm_group P] [add_comm_group Q] [add_comm_group S] variables [module R M] [module R N] [module R P] [module R Q] [module R S] namespace tensor_product open_locale tensor_product open linear_map variables (R) /-- Auxiliary function to defining negation multiplication on tensor product. -/ def neg.aux : free_add_monoid (M × N) →+ M ⊗[R] N := free_add_monoid.lift $ λ p : M × N, (-p.1) ⊗ₜ p.2 variables {R} theorem neg.aux_of (m : M) (n : N) : neg.aux R (free_add_monoid.of (m, n)) = (-m) ⊗ₜ[R] n := rfl instance : has_neg (M ⊗[R] N) := { neg := (add_con_gen (tensor_product.eqv R M N)).lift (neg.aux R) $ add_con.add_con_gen_le $ λ x y hxy, match x, y, hxy with | _, _, (eqv.of_zero_left n) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_zero, neg.aux_of, neg_zero, zero_tmul] | _, _, (eqv.of_zero_right m) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_zero, neg.aux_of, tmul_zero] | _, _, (eqv.of_add_left m₁ m₂ n) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, neg.aux_of, neg_add, add_tmul] | _, _, (eqv.of_add_right m n₁ n₂) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, neg.aux_of, tmul_add] | _, _, (eqv.of_smul s m n) := (add_con.ker_rel _).2 $ by simp_rw [neg.aux_of, tmul_smul s, smul_tmul', smul_neg] | _, _, (eqv.add_comm x y) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, add_comm] end } protected theorem add_left_neg (x : M ⊗[R] N) : -x + x = 0 := tensor_product.induction_on x (by { rw [add_zero], apply (neg.aux R).map_zero, }) (λ x y, by { convert (add_tmul (-x) x y).symm, rw [add_left_neg, zero_tmul], }) (λ x y hx hy, by { unfold has_neg.neg sub_neg_monoid.neg, rw add_monoid_hom.map_add, ac_change (-x + x) + (-y + y) = 0, rw [hx, hy, add_zero], }) instance : add_comm_group (M ⊗[R] N) := { neg := has_neg.neg, sub := _, sub_eq_add_neg := λ _ _, rfl, add_left_neg := λ x, by exact tensor_product.add_left_neg x, zsmul := λ n v, n • v, zsmul_zero' := by simp [tensor_product.zero_smul], zsmul_succ' := by simp [nat.succ_eq_one_add, tensor_product.one_smul, tensor_product.add_smul], zsmul_neg' := λ n x, begin change (- n.succ : ℤ) • x = - (((n : ℤ) + 1) • x), rw [← zero_add (-↑(n.succ) • x), ← tensor_product.add_left_neg (↑(n.succ) • x), add_assoc, ← add_smul, ← sub_eq_add_neg, sub_self, zero_smul, add_zero], refl, end, .. tensor_product.add_comm_monoid } lemma neg_tmul (m : M) (n : N) : (-m) ⊗ₜ n = -(m ⊗ₜ[R] n) := rfl lemma tmul_neg (m : M) (n : N) : m ⊗ₜ (-n) = -(m ⊗ₜ[R] n) := (mk R M N _).map_neg _ lemma tmul_sub (m : M) (n₁ n₂ : N) : m ⊗ₜ (n₁ - n₂) = (m ⊗ₜ[R] n₁) - (m ⊗ₜ[R] n₂) := (mk R M N _).map_sub _ _ lemma sub_tmul (m₁ m₂ : M) (n : N) : (m₁ - m₂) ⊗ₜ n = (m₁ ⊗ₜ[R] n) - (m₂ ⊗ₜ[R] n) := (mk R M N).map_sub₂ _ _ _ /-- While the tensor product will automatically inherit a ℤ-module structure from `add_comm_group.int_module`, that structure won't be compatible with lemmas like `tmul_smul` unless we use a `ℤ-module` instance provided by `tensor_product.left_module`. When `R` is a `ring` we get the required `tensor_product.compatible_smul` instance through `is_scalar_tower`, but when it is only a `semiring` we need to build it from scratch. The instance diamond in `compatible_smul` doesn't matter because it's in `Prop`. -/ instance compatible_smul.int : compatible_smul R ℤ M N := ⟨λ r m n, int.induction_on r (by simp) (λ r ih, by simpa [add_smul, tmul_add, add_tmul] using ih) (λ r ih, by simpa [sub_smul, tmul_sub, sub_tmul] using ih)⟩ instance compatible_smul.unit {S} [monoid S] [distrib_mul_action S M] [distrib_mul_action S N] [compatible_smul R S M N] : compatible_smul R Sˣ M N := ⟨λ s m n, (compatible_smul.smul_tmul (s : S) m n : _)⟩ end tensor_product namespace linear_map @[simp] lemma ltensor_sub (f g : N →ₗ[R] P) : (f - g).ltensor M = f.ltensor M - g.ltensor M := by simp only [← coe_ltensor_hom, map_sub] @[simp] lemma rtensor_sub (f g : N →ₗ[R] P) : (f - g).rtensor M = f.rtensor M - g.rtensor M := by simp only [← coe_rtensor_hom, map_sub] @[simp] lemma ltensor_neg (f : N →ₗ[R] P) : (-f).ltensor M = -(f.ltensor M) := by simp only [← coe_ltensor_hom, map_neg] @[simp] lemma rtensor_neg (f : N →ₗ[R] P) : (-f).rtensor M = -(f.rtensor M) := by simp only [← coe_rtensor_hom, map_neg] end linear_map end ring
5865b977f8c08e43e14560d7431eb336af5974f3
367134ba5a65885e863bdc4507601606690974c1
/src/data/set/constructions.lean
d9cf3138c6c88264de99f6842fbc580e59ba975c
[ "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
2,837
lean
/- Copyright (c) 2020 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import tactic import data.finset.basic /-! # Constructions involving sets of sets. ## Finite Intersections We define a structure `has_finite_inter` which asserts that a set `S` of subsets of `α` is closed under finite intersections. We define `finite_inter_closure` which, given a set `S` of subsets of `α`, is the smallest set of subsets of `α` which is closed under finite intersections. `finite_inter_closure S` is endowed with a term of type `has_finite_inter` using `finite_inter_closure_has_finite_inter`. -/ variables {α : Type*} (S : set (set α)) /-- A structure encapsulating the fact that a set of sets is closed under finite intersection. -/ structure has_finite_inter := (univ_mem : set.univ ∈ S) (inter_mem {s t} : s ∈ S → t ∈ S → s ∩ t ∈ S) namespace has_finite_inter -- Satisfying the inhabited linter... instance : inhabited (has_finite_inter ({set.univ} : set (set α))) := ⟨⟨by tauto, λ _ _ h1 h2, by finish⟩⟩ /-- The smallest set of sets containing `S` which is closed under finite intersections. -/ inductive finite_inter_closure : set (set α) | basic {s} : s ∈ S → finite_inter_closure s | univ : finite_inter_closure set.univ | inter {s t} : finite_inter_closure s → finite_inter_closure t → finite_inter_closure (s ∩ t) /-- Defines `has_finite_inter` for `finite_inter_closure S`. -/ def finite_inter_closure_has_finite_inter : has_finite_inter (finite_inter_closure S) := { univ_mem := finite_inter_closure.univ, inter_mem := λ _ _, finite_inter_closure.inter } variable {S} lemma finite_inter_mem (cond : has_finite_inter S) (F : finset (set α)) : ↑F ⊆ S → ⋂₀ (↑F : set (set α)) ∈ S := begin classical, refine finset.induction_on F (λ _, _) _, { simp [cond.univ_mem] }, { intros a s h1 h2 h3, suffices : a ∩ ⋂₀ ↑s ∈ S, by simpa, exact cond.inter_mem (h3 (finset.mem_insert_self a s)) (h2 $ λ x hx, h3 $ finset.mem_insert_of_mem hx) } end lemma finite_inter_closure_insert {A : set α} (cond : has_finite_inter S) (P ∈ finite_inter_closure (insert A S)) : P ∈ S ∨ ∃ Q ∈ S, P = A ∩ Q := begin induction H with S h T1 T2 _ _ h1 h2, { cases h, { exact or.inr ⟨set.univ, cond.univ_mem, by simpa⟩ }, { exact or.inl h } }, { exact or.inl cond.univ_mem }, { rcases h1 with (h | ⟨Q, hQ, rfl⟩); rcases h2 with (i | ⟨R, hR, rfl⟩), { exact or.inl (cond.inter_mem h i) }, { exact or.inr ⟨T1 ∩ R, cond.inter_mem h hR, by finish⟩ }, { exact or.inr ⟨Q ∩ T2, cond.inter_mem hQ i, by finish⟩ }, { exact or.inr ⟨Q ∩ R, cond.inter_mem hQ hR , by tidy⟩ } } end end has_finite_inter
4293498af293a8d6fccf060b13efbf448247bc38
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/run/typeclass_metas_internal_goals1.lean
675311dab53ede49ea88fe42e526b017c17019ad
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
340
lean
class Foo (α : Type) : Type := (u : Unit := ()) class Bar (α : Type) : Type := (u : Unit := ()) class Top : Type := (u : Unit := ()) instance FooAll (α : Type) : Foo α := {u:=()} instance BarNat : Bar Nat := {u:=()} instance FooBarToTop (α : Type) [Foo α] [Bar α] : Top := {u:=()} new_frontend set_option pp.all true #synth Top
99899bd1b73c4938494d48176515fa3c18d2e367
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/stage0/src/Init/Lean/Compiler/IR/ResetReuse.lean
9863a39b8dc3a76b62ee5fd767a924e6049c517a
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
6,094
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Control.State import Init.Control.Reader import Init.Lean.Compiler.IR.Basic import Init.Lean.Compiler.IR.LiveVars import Init.Lean.Compiler.IR.Format namespace Lean namespace IR namespace ResetReuse /- Remark: the insertResetReuse transformation is applied before we have inserted `inc/dec` instructions, and perfomed lower level optimizations that introduce the instructions `release` and `set`. -/ /- Remark: the functions `S`, `D` and `R` defined here implement the corresponding functions in the paper "Counting Immutable Beans" Here are the main differences: - We use the State monad to manage the generation of fresh variable names. - Support for join points, and `uset` and `sset` instructions for unboxed data. - `D` uses the auxiliary function `Dmain`. - `Dmain` returns a pair `(b, found)` to avoid quadratic behavior when checking the last occurrence of the variable `x`. - Because we have join points in the actual implementation, a variable may be live even if it does not occur in a function body. See example at `livevars.lean`. -/ private def mayReuse (c₁ c₂ : CtorInfo) : Bool := c₁.size == c₂.size && c₁.usize == c₂.usize && c₁.ssize == c₂.ssize && /- The following condition is a heuristic. We don't want to reuse cells from different types even when they are compatible because it produces counterintuitive behavior. -/ c₁.name.getPrefix == c₂.name.getPrefix private partial def S (w : VarId) (c : CtorInfo) : FnBody → FnBody | FnBody.vdecl x t v@(Expr.ctor c' ys) b => if mayReuse c c' then let updtCidx := c.cidx != c'.cidx; FnBody.vdecl x t (Expr.reuse w c' updtCidx ys) b else FnBody.vdecl x t v (S b) | FnBody.jdecl j ys v b => let v' := S v; if v == v' then FnBody.jdecl j ys v (S b) else FnBody.jdecl j ys v' b | FnBody.case tid x xType alts => FnBody.case tid x xType $ alts.map $ fun alt => alt.modifyBody S | b => if b.isTerminal then b else let (instr, b) := b.split; instr.setBody (S b) /- We use `Context` to track join points in scope. -/ abbrev M := ReaderT LocalContext (StateT Index Id) private def mkFresh : M VarId := do idx ← getModify (fun n => n + 1); pure { idx := idx } private def tryS (x : VarId) (c : CtorInfo) (b : FnBody) : M FnBody := do w ← mkFresh; let b' := S w c b; if b == b' then pure b else pure $ FnBody.vdecl w IRType.object (Expr.reset c.size x) b' private def Dfinalize (x : VarId) (c : CtorInfo) : FnBody × Bool → M FnBody | (b, true) => pure b | (b, false) => tryS x c b private def argsContainsVar (ys : Array Arg) (x : VarId) : Bool := ys.any $ fun arg => match arg with | Arg.var y => x == y | _ => false private def isCtorUsing (b : FnBody) (x : VarId) : Bool := match b with | (FnBody.vdecl _ _ (Expr.ctor _ ys) _) => argsContainsVar ys x | _ => false /- Given `Dmain b`, the resulting pair `(new_b, flag)` contains the new body `new_b`, and `flag == true` if `x` is live in `b`. Note that, in the function `D` defined in the paper, for each `let x := e; F`, `D` checks whether `x` is live in `F` or not. This is great for clarity but it is expensive: `O(n^2)` where `n` is the size of the function body. -/ private partial def Dmain (x : VarId) (c : CtorInfo) : FnBody → M (FnBody × Bool) | e@(FnBody.case tid y yType alts) => do ctx ← read; if e.hasLiveVar ctx x then do /- If `x` is live in `e`, we recursively process each branch. -/ alts ← alts.mapM $ fun alt => alt.mmodifyBody (fun b => Dmain b >>= Dfinalize x c); pure (FnBody.case tid y yType alts, true) else pure (e, false) | FnBody.jdecl j ys v b => do (b, found) ← adaptReader (fun (ctx : LocalContext) => ctx.addJP j ys v) (Dmain b); (v, _ /- found' -/) ← Dmain v; /- If `found' == true`, then `Dmain b` must also have returned `(b, true)` since we assume the IR does not have dead join points. So, if `x` is live in `j` (i.e., `v`), then it must also live in `b` since `j` is reachable from `b` with a `jmp`. On the other hand, `x` may be live in `b` but dead in `j` (i.e., `v`). -/ pure (FnBody.jdecl j ys v b, found) | e => do ctx ← read; if e.isTerminal then pure (e, e.hasLiveVar ctx x) else do let (instr, b) := e.split; if isCtorUsing instr x then /- If the scrutinee `x` (the one that is providing memory) is being stored in a constructor, then reuse will probably not be able to reuse memory at runtime. It may work only if the new cell is consumed, but we ignore this case. -/ pure (e, true) else do (b, found) ← Dmain b; /- Remark: it is fine to use `hasFreeVar` instead of `hasLiveVar` since `instr` is not a `FnBody.jmp` (it is not a terminal) nor it is a `FnBody.jdecl`. -/ if found || !instr.hasFreeVar x then pure (instr.setBody b, found) else do b ← tryS x c b; pure (instr.setBody b, true) private def D (x : VarId) (c : CtorInfo) (b : FnBody) : M FnBody := Dmain x c b >>= Dfinalize x c partial def R : FnBody → M FnBody | FnBody.case tid x xType alts => do alts ← alts.mapM $ fun alt => do { alt ← alt.mmodifyBody R; match alt with | Alt.ctor c b => if c.isScalar then pure alt else Alt.ctor c <$> D x c b | _ => pure alt }; pure $ FnBody.case tid x xType alts | FnBody.jdecl j ys v b => do v ← R v; b ← adaptReader (fun (ctx : LocalContext) => ctx.addJP j ys v) (R b); pure $ FnBody.jdecl j ys v b | e => do if e.isTerminal then pure e else do let (instr, b) := e.split; b ← R b; pure (instr.setBody b) end ResetReuse open ResetReuse def Decl.insertResetReuse : Decl → Decl | d@(Decl.fdecl f xs t b) => let nextIndex := d.maxIndex + 1; let b := (R b {}).run' nextIndex; Decl.fdecl f xs t b | other => other end IR end Lean
0797d4898b6d56c728318c14f3e1fc4c32e978fc
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/algebra/linear_ordered_comm_group_with_zero.lean
32d8f9c83d2d6caf81a49432da7685977125f630
[ "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
5,931
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Johan Commelin, Patrick Massot -/ import algebra.ordered_group import algebra.group_with_zero import algebra.group_with_zero_power /-! # Linearly ordered commutative groups with a zero element adjoined This file sets up a special class of linearly ordered commutative monoids that show up as the target of so-called “valuations” in algebraic number theory. Usually, in the informal literature, these objects are constructed by taking a linearly ordered commutative group Γ and formally adjoining a zero element: Γ ∪ {0}. The disadvantage is that a type such as `nnreal` is not of that form, whereas it is a very common target for valuations. The solutions is to use a typeclass, and that is exactly what we do in this file. -/ set_option old_structure_cmd true /-- A linearly ordered commutative group with a zero element. -/ class linear_ordered_comm_group_with_zero (α : Type*) extends linear_order α, comm_group_with_zero α := (mul_le_mul_left : ∀ {a b : α}, a ≤ b → ∀ c : α, c * a ≤ c * b) (zero_le_one : (0:α) ≤ 1) variables {α : Type*} [linear_ordered_comm_group_with_zero α] variables {a b c d x y z : α} local attribute [instance] classical.prop_decidable /-- Every linearly ordered commutative group with zero is an ordered commutative monoid.-/ @[priority 100] -- see Note [lower instance priority] instance linear_ordered_comm_group_with_zero.to_ordered_comm_monoid : ordered_comm_monoid α := { lt_of_mul_lt_mul_left := λ a b c h, by { contrapose! h, exact linear_ordered_comm_group_with_zero.mul_le_mul_left h a } .. ‹linear_ordered_comm_group_with_zero α› } section linear_ordered_comm_monoid /- The following facts are true more generally in a (linearly) ordered commutative monoid. -/ lemma one_le_pow_of_one_le' {n : ℕ} (H : 1 ≤ x) : 1 ≤ x^n := begin induction n with n ih, { exact le_refl 1 }, { exact one_le_mul H ih } end lemma pow_le_one_of_le_one {n : ℕ} (H : x ≤ 1) : x^n ≤ 1 := begin induction n with n ih, { exact le_refl 1 }, { exact mul_le_one' H ih } end lemma eq_one_of_pow_eq_one {n : ℕ} (hn : n ≠ 0) (H : x ^ n = 1) : x = 1 := begin rcases nat.exists_eq_succ_of_ne_zero hn with ⟨n, rfl⟩, clear hn, induction n with n ih, { simpa using H }, { cases le_total x 1 with h, all_goals { have h1 := mul_le_mul_right' h (x ^ (n + 1)), rw pow_succ at H, rw [H, one_mul] at h1 }, { have h2 := pow_le_one_of_le_one h, exact ih (le_antisymm h2 h1) }, { have h2 := one_le_pow_of_one_le' h, exact ih (le_antisymm h1 h2) } } end lemma pow_eq_one_iff {n : ℕ} (hn : n ≠ 0) : x ^ n = 1 ↔ x = 1 := ⟨eq_one_of_pow_eq_one hn, by { rintro rfl, exact one_pow _ }⟩ lemma one_le_pow_iff {n : ℕ} (hn : n ≠ 0) : 1 ≤ x^n ↔ 1 ≤ x := begin refine ⟨_, one_le_pow_of_one_le'⟩, contrapose!, intro h, apply lt_of_le_of_ne (pow_le_one_of_le_one (le_of_lt h)), rw [ne.def, pow_eq_one_iff hn], exact ne_of_lt h, end lemma pow_le_one_iff {n : ℕ} (hn : n ≠ 0) : x^n ≤ 1 ↔ x ≤ 1 := begin refine ⟨_, pow_le_one_of_le_one⟩, contrapose!, intro h, apply lt_of_le_of_ne (one_le_pow_of_one_le' (le_of_lt h)), rw [ne.def, eq_comm, pow_eq_one_iff hn], exact ne_of_gt h, end end linear_ordered_comm_monoid lemma zero_le_one' : (0 : α) ≤ 1 := linear_ordered_comm_group_with_zero.zero_le_one lemma zero_lt_one' : (0 : α) < 1 := lt_of_le_of_ne zero_le_one' zero_ne_one @[simp] lemma zero_le' : 0 ≤ a := by simpa only [mul_zero, mul_one] using mul_le_mul_left' (@zero_le_one' α _) a @[simp] lemma not_lt_zero' : ¬a < 0 := not_lt_of_le zero_le' @[simp] lemma le_zero_iff : a ≤ 0 ↔ a = 0 := ⟨λ h, le_antisymm h zero_le', λ h, h ▸ le_refl _⟩ lemma zero_lt_iff : 0 < a ↔ a ≠ 0 := ⟨ne_of_gt, λ h, lt_of_le_of_ne zero_le' h.symm⟩ lemma le_of_le_mul_right (h : c ≠ 0) (hab : a * c ≤ b * c) : a ≤ b := by simpa only [mul_inv_cancel_right' h] using (mul_le_mul_right' hab c⁻¹) lemma le_mul_inv_of_mul_le (h : c ≠ 0) (hab : a * c ≤ b) : a ≤ b * c⁻¹ := le_of_le_mul_right h (by simpa [h] using hab) lemma mul_inv_le_of_le_mul (h : c ≠ 0) (hab : a ≤ b * c) : a * c⁻¹ ≤ b := le_of_le_mul_right h (by simpa [h] using hab) lemma div_le_div' (a b c d : α) (hb : b ≠ 0) (hd : d ≠ 0) : a * b⁻¹ ≤ c * d⁻¹ ↔ a * d ≤ c * b := begin by_cases ha : a = 0, { simp [ha] }, by_cases hc : c = 0, { simp [inv_ne_zero hb, hc, hd], }, exact (div_le_div_iff' (units.mk0 a ha) (units.mk0 b hb) (units.mk0 c hc) (units.mk0 d hd)), end lemma ne_zero_of_lt (h : b < a) : a ≠ 0 := λ h1, not_lt_zero' $ show b < 0, from h1 ▸ h @[simp] lemma units.zero_lt (u : units α) : (0 : α) < u := zero_lt_iff.2 $ u.ne_zero lemma mul_lt_mul'''' (hab : a < b) (hcd : c < d) : a * c < b * d := have hb : b ≠ 0 := ne_zero_of_lt hab, have hd : d ≠ 0 := ne_zero_of_lt hcd, if ha : a = 0 then by { rw [ha, zero_mul, zero_lt_iff], exact mul_ne_zero hb hd } else if hc : c = 0 then by { rw [hc, mul_zero, zero_lt_iff], exact mul_ne_zero hb hd } else @mul_lt_mul''' _ _ (units.mk0 a ha) (units.mk0 b hb) (units.mk0 c hc) (units.mk0 d hd) hab hcd lemma mul_inv_lt_of_lt_mul' (h : x < y * z) : x * z⁻¹ < y := have hz : z ≠ 0 := (mul_ne_zero_iff.1 $ ne_zero_of_lt h).2, by { contrapose! h, simpa only [inv_inv'] using mul_inv_le_of_le_mul (inv_ne_zero hz) h } lemma mul_lt_right' (c : α) (h : a < b) (hc : c ≠ 0) : a * c < b * c := by { contrapose! h, exact le_of_le_mul_right hc h } lemma inv_lt_inv'' (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ < b⁻¹ ↔ b < a := @inv_lt_inv_iff _ _ (units.mk0 a ha) (units.mk0 b hb) lemma inv_le_inv'' (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := @inv_le_inv_iff _ _ (units.mk0 a ha) (units.mk0 b hb)
cc5fb09d870161b00bb574c0e6ab5f1f53a30a88
4727251e0cd73359b15b664c3170e5d754078599
/src/number_theory/legendre_symbol/quadratic_reciprocity.lean
9f97b90b400a40ab302f6e65776f7e82d2edf4fc
[ "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
15,251
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Michael Stoll -/ import number_theory.legendre_symbol.gauss_eisenstein_lemmas import number_theory.legendre_symbol.quadratic_char /-! # Legendre symbol and quadratic reciprocity. This file contains results about quadratic residues modulo a prime number. We define the Legendre symbol `(a / p)` as `legendre_sym p a`. Note the order of arguments! The advantage of this form is that then `legendre_sym p` is a multiplicative map. The main results are the law of quadratic reciprocity, `quadratic_reciprocity`, as well as the interpretations in terms of existence of square roots depending on the congruence mod 4, `exists_sq_eq_prime_iff_of_mod_four_eq_one`, and `exists_sq_eq_prime_iff_of_mod_four_eq_three`. Also proven are conditions for `-1` and `2` to be a square modulo a prime, `legende_sym_neg_one` and `exists_sq_eq_neg_one_iff` for `-1`, and `exists_sq_eq_two_iff` for `2` ## Implementation notes The proof of quadratic reciprocity implemented uses Gauss' lemma and Eisenstein's lemma -/ open finset nat char namespace zmod variables (p q : ℕ) [fact p.prime] [fact q.prime] /-- Euler's Criterion: A unit `x` of `zmod p` is a square if and only if `x ^ (p / 2) = 1`. -/ lemma euler_criterion_units (x : (zmod p)ˣ) : (∃ y : (zmod p)ˣ, y ^ 2 = x) ↔ x ^ (p / 2) = 1 := begin by_cases hc : p = 2, { substI hc, simp only [eq_iff_true_of_subsingleton, exists_const], }, { have h₀ := finite_field.unit_is_square_iff (by rwa ring_char_zmod_n) x, have hs : (∃ y : (zmod p)ˣ, y ^ 2 = x) ↔ is_square(x) := by { rw is_square_iff_exists_sq x, simp_rw eq_comm, }, rw hs, rwa card p at h₀, }, end /-- Euler's Criterion: a nonzero `a : zmod p` is a square if and only if `x ^ (p / 2) = 1`. -/ lemma euler_criterion {a : zmod p} (ha : a ≠ 0) : is_square (a : zmod p) ↔ a ^ (p / 2) = 1 := begin apply (iff_congr _ (by simp [units.ext_iff])).mp (euler_criterion_units p (units.mk0 a ha)), simp only [units.ext_iff, sq, units.coe_mk0, units.coe_mul], split, { rintro ⟨y, hy⟩, exact ⟨y, hy.symm⟩ }, { rintro ⟨y, rfl⟩, have hy : y ≠ 0, { rintro rfl, simpa [zero_pow] using ha, }, refine ⟨units.mk0 y hy, _⟩, simp, } end lemma exists_sq_eq_neg_one_iff : is_square (-1 : zmod p) ↔ p % 4 ≠ 3 := begin have h := @is_square_neg_one_iff (zmod p) _ _, rw card p at h, exact h, end lemma mod_four_ne_three_of_sq_eq_neg_one {y : zmod p} (hy : y ^ 2 = -1) : p % 4 ≠ 3 := begin rw pow_two at hy, exact (exists_sq_eq_neg_one_iff p).1 ⟨y, hy.symm⟩ end lemma mod_four_ne_three_of_sq_eq_neg_sq' {x y : zmod p} (hy : y ≠ 0) (hxy : x ^ 2 = - y ^ 2) : p % 4 ≠ 3 := @mod_four_ne_three_of_sq_eq_neg_one p _ (x / y) begin apply_fun (λ z, z / y ^ 2) at hxy, rwa [neg_div, ←div_pow, ←div_pow, div_self hy, one_pow] at hxy end lemma mod_four_ne_three_of_sq_eq_neg_sq {x y : zmod p} (hx : x ≠ 0) (hxy : x ^ 2 = - y ^ 2) : p % 4 ≠ 3 := begin apply_fun (λ x, -x) at hxy, rw neg_neg at hxy, exact mod_four_ne_three_of_sq_eq_neg_sq' p hx hxy.symm end lemma pow_div_two_eq_neg_one_or_one {a : zmod p} (ha : a ≠ 0) : a ^ (p / 2) = 1 ∨ a ^ (p / 2) = -1 := begin cases nat.prime.eq_two_or_odd (fact.out p.prime) with hp2 hp_odd, { substI p, revert a ha, dec_trivial }, rw [← mul_self_eq_one_iff, ← pow_add, ← two_mul, two_mul_odd_div_two hp_odd], exact pow_card_sub_one_eq_one ha end /-- The Legendre symbol of `a : ℤ` and a prime `p`, `legendre_sym p a`, is an integer defined as * `0` if `a` is `0` modulo `p`; * `1` if `a` is a square modulo `p` * `-1` otherwise. Note the order of the arguments! The advantage of the order chosen here is that `legendre_sym p` is a multiplicative function `ℤ → ℤ`. -/ def legendre_sym (p : ℕ) [fact p.prime] (a : ℤ) : ℤ := quadratic_char (zmod p) a /-- We have the congruence `legendre_sym p a ≡ a ^ (p / 2) mod p`. -/ lemma legendre_sym_eq_pow (p : ℕ) (a : ℤ) [hp : fact p.prime] : (legendre_sym p a : zmod p) = (a ^ (p / 2)) := begin rw legendre_sym, by_cases ha : (a : zmod p) = 0, { simp only [ha, zero_pow (nat.div_pos (hp.1.two_le) (succ_pos 1)), quadratic_char_zero, int.cast_zero], }, by_cases hp₁ : p = 2, { substI p, generalize : (a : (zmod 2)) = b, revert b, dec_trivial, }, { have h₁ := quadratic_char_eq_pow_of_char_ne_two (by rwa ring_char_zmod_n p) ha, rw card p at h₁, rw h₁, have h₂ := finite_field.neg_one_ne_one_of_char_ne_two (by rwa ring_char_zmod_n p), cases pow_div_two_eq_neg_one_or_one p ha with h h, { rw [if_pos h, h, int.cast_one], }, { rw [h, if_neg h₂, int.cast_neg, int.cast_one], } } end /-- If `p ∤ a`, then `legendre_sym p a` is `1` or `-1`. -/ lemma legendre_sym_eq_one_or_neg_one (p : ℕ) [fact p.prime] (a : ℤ) (ha : (a : zmod p) ≠ 0) : legendre_sym p a = 1 ∨ legendre_sym p a = -1 := quadratic_char_dichotomy ha lemma legendre_sym_eq_neg_one_iff_not_one {a : ℤ} (ha : (a : zmod p) ≠ 0) : legendre_sym p a = -1 ↔ ¬ legendre_sym p a = 1 := quadratic_char_eq_neg_one_iff_not_one ha /-- The Legendre symbol of `p` and `a` is zero iff `p ∣ a`. -/ lemma legendre_sym_eq_zero_iff (p : ℕ) [fact p.prime] (a : ℤ) : legendre_sym p a = 0 ↔ (a : zmod p) = 0 := quadratic_char_eq_zero_iff a @[simp] lemma legendre_sym_zero (p : ℕ) [fact p.prime] : legendre_sym p 0 = 0 := begin rw legendre_sym, exact quadratic_char_zero, end @[simp] lemma legendre_sym_one (p : ℕ) [fact p.prime] : legendre_sym p 1 = 1 := begin rw [legendre_sym, (by norm_cast : ((1 : ℤ) : zmod p) = 1)], exact quadratic_char_one, end /-- The Legendre symbol is multiplicative in `a` for `p` fixed. -/ lemma legendre_sym_mul (p : ℕ) [fact p.prime] (a b : ℤ) : legendre_sym p (a * b) = legendre_sym p a * legendre_sym p b := begin rw [legendre_sym, legendre_sym, legendre_sym], push_cast, exact quadratic_char_mul (a : zmod p) b, end /-- The Legendre symbol is a homomorphism of monoids with zero. -/ @[simps] def legendre_sym_hom (p : ℕ) [fact p.prime] : ℤ →*₀ ℤ := { to_fun := legendre_sym p, map_zero' := legendre_sym_zero p, map_one' := legendre_sym_one p, map_mul' := legendre_sym_mul p } /-- The square of the symbol is 1 if `p ∤ a`. -/ theorem legendre_sym_sq_one (p : ℕ) [fact p.prime] (a : ℤ) (ha : (a : zmod p) ≠ 0) : (legendre_sym p a)^2 = 1 := quadratic_char_sq_one ha /-- The Legendre symbol of `a^2` at `p` is 1 if `p ∤ a`. -/ theorem legendre_sym_sq_one' (p : ℕ) [fact p.prime] (a : ℤ) (ha : (a : zmod p) ≠ 0) : legendre_sym p (a ^ 2) = 1 := begin rw [legendre_sym], push_cast, exact quadratic_char_sq_one' ha, end /-- The Legendre symbol depends only on `a` mod `p`. -/ theorem legendre_sym_mod (p : ℕ) [fact p.prime] (a : ℤ) : legendre_sym p a = legendre_sym p (a % p) := by simp only [legendre_sym, int_cast_mod] /-- Gauss' lemma. The legendre symbol can be computed by considering the number of naturals less than `p/2` such that `(a * x) % p > p / 2` -/ lemma gauss_lemma {a : ℤ} (hp : p ≠ 2) (ha0 : (a : zmod p) ≠ 0) : legendre_sym p a = (-1) ^ ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card := begin haveI hp' : fact (p % 2 = 1) := ⟨nat.prime.mod_two_eq_one_iff_ne_two.mpr hp⟩, have : (legendre_sym p a : zmod p) = (((-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card : ℤ) : zmod p) := by { rw [legendre_sym_eq_pow, legendre_symbol.gauss_lemma_aux p ha0]; simp }, cases legendre_sym_eq_one_or_neg_one p a ha0; cases neg_one_pow_eq_or ℤ ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card; simp [*, ne_neg_self p one_ne_zero, (ne_neg_self p one_ne_zero).symm] at * end /-- When `p ∤ a`, then `legendre_sym p a = 1` iff `a` is a square mod `p`. -/ lemma legendre_sym_eq_one_iff {a : ℤ} (ha0 : (a : zmod p) ≠ 0) : legendre_sym p a = 1 ↔ is_square (a : zmod p) := quadratic_char_one_iff_is_square ha0 /-- `legendre_sym p a = -1` iff`a` is a nonsquare mod `p`. -/ lemma legendre_sym_eq_neg_one_iff {a : ℤ} : legendre_sym p a = -1 ↔ ¬ is_square (a : zmod p) := quadratic_char_neg_one_iff_not_is_square /-- The number of square roots of `a` modulo `p` is determined by the Legendre symbol. -/ lemma legendre_sym_card_sqrts (hp : p ≠ 2) (a : ℤ) : ↑{x : zmod p | x^2 = a}.to_finset.card = legendre_sym p a + 1 := begin have h : ring_char (zmod p) ≠ 2 := by { rw ring_char_zmod_n, exact hp, }, exact quadratic_char_card_sqrts h a, end /-- `legendre_sym p (-1)` is given by `χ₄ p`. -/ lemma legendre_sym_neg_one (hp : p ≠ 2) : legendre_sym p (-1) = χ₄ p := begin have h : ring_char (zmod p) ≠ 2 := by { rw ring_char_zmod_n, exact hp, }, have h₁ := quadratic_char_neg_one h, rw card p at h₁, exact_mod_cast h₁, end open_locale big_operators lemma eisenstein_lemma (hp : p ≠ 2) {a : ℕ} (ha1 : a % 2 = 1) (ha0 : (a : zmod p) ≠ 0) : legendre_sym p a = (-1)^∑ x in Ico 1 (p / 2).succ, (x * a) / p := begin haveI hp' : fact (p % 2 = 1) := ⟨nat.prime.mod_two_eq_one_iff_ne_two.mpr hp⟩, have ha0' : ((a : ℤ) : zmod p) ≠ 0 := by { norm_cast, exact ha0 }, rw [neg_one_pow_eq_pow_mod_two, gauss_lemma p hp ha0', neg_one_pow_eq_pow_mod_two, (by norm_cast : ((a : ℤ) : zmod p) = (a : zmod p)), show _ = _, from legendre_symbol.eisenstein_lemma_aux p ha1 ha0] end /-- **Quadratic reciprocity theorem** -/ theorem quadratic_reciprocity (hp1 : p ≠ 2) (hq1 : q ≠ 2) (hpq : p ≠ q) : legendre_sym q p * legendre_sym p q = (-1) ^ ((p / 2) * (q / 2)) := have hpq0 : (p : zmod q) ≠ 0, from prime_ne_zero q p hpq.symm, have hqp0 : (q : zmod p) ≠ 0, from prime_ne_zero p q hpq, by rw [eisenstein_lemma q hq1 (nat.prime.mod_two_eq_one_iff_ne_two.mpr hp1) hpq0, eisenstein_lemma p hp1 (nat.prime.mod_two_eq_one_iff_ne_two.mpr hq1) hqp0, ← pow_add, legendre_symbol.sum_mul_div_add_sum_mul_div_eq_mul q p hpq0, mul_comm] lemma legendre_sym_two (hp2 : p ≠ 2) : legendre_sym p 2 = (-1) ^ (p / 4 + p / 2) := begin have hp1 := nat.prime.mod_two_eq_one_iff_ne_two.mpr hp2, have hp22 : p / 2 / 2 = _ := legendre_symbol.div_eq_filter_card (show 0 < 2, from dec_trivial) (nat.div_le_self (p / 2) 2), have hcard : (Ico 1 (p / 2).succ).card = p / 2, by simp, have hx2 : ∀ x ∈ Ico 1 (p / 2).succ, (2 * x : zmod p).val = 2 * x, from λ x hx, have h2xp : 2 * x < p, from calc 2 * x ≤ 2 * (p / 2) : mul_le_mul_of_nonneg_left (le_of_lt_succ $ (mem_Ico.mp hx).2) dec_trivial ... < _ : by conv_rhs {rw [← div_add_mod p 2, hp1]}; exact lt_succ_self _, by rw [← nat.cast_two, ← nat.cast_mul, val_cast_of_lt h2xp], have hdisj : disjoint ((Ico 1 (p / 2).succ).filter (λ x, p / 2 < ((2 : ℕ) * x : zmod p).val)) ((Ico 1 (p / 2).succ).filter (λ x, x * 2 ≤ p / 2)), from disjoint_filter.2 (λ x hx, by simp [hx2 _ hx, mul_comm]), have hunion : ((Ico 1 (p / 2).succ).filter (λ x, p / 2 < ((2 : ℕ) * x : zmod p).val)) ∪ ((Ico 1 (p / 2).succ).filter (λ x, x * 2 ≤ p / 2)) = Ico 1 (p / 2).succ, begin rw [filter_union_right], conv_rhs {rw [← @filter_true _ (Ico 1 (p / 2).succ)]}, exact filter_congr (λ x hx, by simp [hx2 _ hx, lt_or_le, mul_comm]) end, have hp2' := prime_ne_zero p 2 hp2, rw (by norm_cast : ((2 : ℕ) : zmod p) = (2 : ℤ)) at *, erw [gauss_lemma p hp2 hp2', neg_one_pow_eq_pow_mod_two, @neg_one_pow_eq_pow_mod_two _ _ (p / 4 + p / 2)], refine congr_arg2 _ rfl ((eq_iff_modeq_nat 2).1 _), rw [show 4 = 2 * 2, from rfl, ← nat.div_div_eq_div_mul, hp22, nat.cast_add, ← sub_eq_iff_eq_add', sub_eq_add_neg, neg_eq_self_mod_two, ← nat.cast_add, ← card_disjoint_union hdisj, hunion, hcard] end lemma exists_sq_eq_two_iff (hp1 : p ≠ 2) : is_square (2 : zmod p) ↔ p % 8 = 1 ∨ p % 8 = 7 := begin have hp2 : ((2 : ℤ) : zmod p) ≠ 0, from prime_ne_zero p 2 (λ h, by simpa [h] using hp1), have hpm4 : p % 4 = p % 8 % 4, from (nat.mod_mul_left_mod p 2 4).symm, have hpm2 : p % 2 = p % 8 % 2, from (nat.mod_mul_left_mod p 4 2).symm, rw [show (2 : zmod p) = (2 : ℤ), by simp, ← legendre_sym_eq_one_iff p hp2], erw [legendre_sym_two p hp1, neg_one_pow_eq_one_iff_even (show (-1 : ℤ) ≠ 1, from dec_trivial), even_add, even_div, even_div], have := nat.mod_lt p (show 0 < 8, from dec_trivial), have hp := nat.prime.mod_two_eq_one_iff_ne_two.mpr hp1, revert this hp, erw [hpm4, hpm2], generalize hm : p % 8 = m, unfreezingI {clear_dependent p}, dec_trivial!, end lemma exists_sq_eq_prime_iff_of_mod_four_eq_one (hp1 : p % 4 = 1) (hq1 : q ≠ 2) : is_square (q : zmod p) ↔ is_square (p : zmod q) := if hpq : p = q then by substI hpq else have h1 : ((p / 2) * (q / 2)) % 2 = 0, from (dvd_iff_mod_eq_zero _ _).1 (dvd_mul_of_dvd_left ((dvd_iff_mod_eq_zero _ _).2 $ by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp1]; refl) _), begin have hp_odd : p ≠ 2 := by { by_contra, simp [h] at hp1, norm_num at hp1, }, have hpq0 : ((p : ℤ) : zmod q) ≠ 0 := prime_ne_zero q p (ne.symm hpq), have hqp0 : ((q : ℤ) : zmod p) ≠ 0 := prime_ne_zero p q hpq, have := quadratic_reciprocity p q hp_odd hq1 hpq, rw [neg_one_pow_eq_pow_mod_two, h1, pow_zero] at this, rw [(by norm_cast : (p : zmod q) = (p : ℤ)), (by norm_cast : (q : zmod p) = (q : ℤ)), ← legendre_sym_eq_one_iff _ hpq0, ← legendre_sym_eq_one_iff _ hqp0], cases (legendre_sym_eq_one_or_neg_one p q hqp0) with h h, { simp only [h, eq_self_iff_true, true_iff, mul_one] at this ⊢, exact this, }, { simp only [h, mul_neg, mul_one] at this ⊢, rw eq_neg_of_eq_neg this.symm, }, end lemma exists_sq_eq_prime_iff_of_mod_four_eq_three (hp3 : p % 4 = 3) (hq3 : q % 4 = 3) (hpq : p ≠ q) : is_square (q : zmod p) ↔ ¬ is_square (p : zmod q) := have h1 : ((p / 2) * (q / 2)) % 2 = 1, from nat.odd_mul_odd (by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp3]; refl) (by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hq3]; refl), begin have hp_odd : p ≠ 2 := by { by_contra, simp [h] at hp3, norm_num at hp3, }, have hq_odd : q ≠ 2 := by { by_contra, simp [h] at hq3, norm_num at hq3, }, have hpq0 : ((p : ℤ) : zmod q) ≠ 0 := prime_ne_zero q p (ne.symm hpq), have hqp0 : ((q : ℤ) : zmod p) ≠ 0 := prime_ne_zero p q hpq, have := quadratic_reciprocity p q hp_odd hq_odd hpq, rw [neg_one_pow_eq_pow_mod_two, h1, pow_one] at this, rw [(by norm_cast : (p : zmod q) = (p : ℤ)), (by norm_cast : (q : zmod p) = (q : ℤ)), ← legendre_sym_eq_one_iff _ hpq0, ← legendre_sym_eq_one_iff _ hqp0], cases (legendre_sym_eq_one_or_neg_one q p hpq0) with h h, { simp only [h, eq_self_iff_true, not_true, iff_false, one_mul] at this ⊢, simp only [this], norm_num, }, { simp only [h, neg_mul, one_mul, neg_inj] at this ⊢, simp only [this, eq_self_iff_true, true_iff], norm_num, }, end end zmod
f2fc8df771c9b7b58c5fab07e97e130002e73b6a
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/eta_tac.lean
da49a5f8f3a5e8911c9e92ee64dc4916ba942135
[ "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
526
lean
open tactic set_option pp.binder_types true set_option pp.implicit true set_option pp.notation false example (a : nat) : true := by do mk_const `has_add.add >>= head_eta_expand >>= trace, mk_const `nat.succ >>= head_eta_expand >>= trace, to_expr ```(has_add.add a) >>= head_eta_expand >>= trace, to_expr ``(λ x : nat, has_add.add x) >>= head_eta_expand >>= trace, to_expr ``(λ x : nat, has_add.add x) >>= head_eta >>= trace, to_expr ```(has_add.add a) >>= head_eta_expand >>= head_eta >>= trace, constructor
4012fe2195993d43d7d39271c130490ffc78d687
c31182a012eec69da0a1f6c05f42b0f0717d212d
/src/for_mathlib/rational_cones.lean
34a56cdd18cd713bc89833d4f3ee681bfb8916ea
[]
no_license
Ja1941/lean-liquid
fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc
8e80ed0cbdf5145d6814e833a674eaf05a1495c1
refs/heads/master
1,689,437,983,362
1,628,362,719,000
1,628,362,719,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,586
lean
import polyhedral_lattice.basic import linear_algebra.dual import for_mathlib.nnrat universe u variables {Λ : Type u} [add_comm_group Λ] variable {ι : Type*} open_locale big_operators open_locale nnreal variable {α : Type*} def nnrat_module {Λ : Type*} [add_comm_group Λ] [module ℚ Λ] : module (ℚ≥0) Λ := restrict_scalars.module (ℚ≥0) ℚ Λ local attribute [instance] nnrat_module instance nnrat_tower [module ℚ Λ] : is_scalar_tower (ℚ≥0) ℚ Λ := { smul_assoc := λ x y z, begin rcases x with ⟨x, hx⟩, change (x • y) • z = x • _, simp [mul_smul], end } variable [module ℚ Λ] open module def index_up_one (l : ι → Λ) : submodule (ℚ≥0) (dual ℚ Λ) := { carrier := {x | ∀ i, 0 ≤ x (l i)}, zero_mem' := λ i, le_rfl, add_mem' := λ x y hx hy i, by simpa only [linear_map.add_apply] using add_nonneg (hx _) (hy _), smul_mem' := λ c x hx i, mul_nonneg c.2 (hx i) } @[simp] lemma mem_index_up_one (l : ι → Λ) (x : dual ℚ Λ) : x ∈ index_up_one l ↔ ∀ i, 0 ≤ x (l i) := iff.rfl def set_up_one (s : set Λ) : submodule (ℚ≥0) (dual ℚ Λ) := index_up_one (coe : s → Λ) lemma set_up_one_def (s : set Λ) : set_up_one s = index_up_one (coe : s → Λ) := rfl lemma index_up_one_eq_set_up_one_range (l : ι → Λ) : index_up_one l = set_up_one (set.range l) := begin ext φ, split, { rintro hφ ⟨_, i, rfl⟩, apply hφ i }, { rintro hφ i, apply hφ ⟨_, i, rfl⟩ }, end @[simp] lemma mem_set_up_one (s : set Λ) (x : dual ℚ Λ) : x ∈ set_up_one s ↔ ∀ i ∈ s, 0 ≤ x i := begin change x ∈ index_up_one _ ↔ _, simp, end lemma set_up_one_antitone (s t : set Λ) : s ≤ t → set_up_one t ≤ set_up_one s := begin rintro h f hf ⟨i, hi⟩, apply hf ⟨_, h hi⟩, end /-- The submodule given by the intersection of the given functionals -/ def index_down_one (l : ι → Λ →ₗ[ℚ] ℚ) : submodule (ℚ≥0) Λ := { carrier := {x | ∀ i, 0 ≤ l i x}, zero_mem' := λ i, by simp only [linear_map.map_zero], add_mem' := λ x y hx hy i, by simpa only [linear_map.map_add] using add_nonneg (hx i) (hy i), smul_mem' := λ c x (hx : ∀ i, 0 ≤ l i x) i, begin rw linear_map.map_smul_of_tower, apply mul_nonneg c.2 (hx i), end } @[simp] lemma mem_index_down_one (l : ι → dual ℚ Λ) (x : Λ) : x ∈ index_down_one l ↔ ∀ i, 0 ≤ l i x := iff.rfl def set_down_one (s : set (dual ℚ Λ)) : submodule (ℚ≥0) Λ := index_down_one (coe : s → dual ℚ Λ) lemma set_down_one_def (s : set (dual ℚ Λ)) : set_down_one s = index_down_one (coe : s → dual ℚ Λ) := rfl lemma index_down_one_eq_set_down_one_range (l : ι → dual ℚ Λ) : index_down_one l = set_down_one (set.range l) := begin ext φ, split, { rintro hφ ⟨_, i, rfl⟩, apply hφ i }, { rintro hφ i, apply hφ ⟨_, i, rfl⟩ }, end @[simp] lemma mem_set_down_one (s : set (dual ℚ Λ)) (x : Λ) : x ∈ set_down_one s ↔ ∀ (i : dual ℚ Λ), i ∈ s → 0 ≤ i x := begin change x ∈ index_down_one _ ↔ _, simp, end lemma set_down_one_antitone (s t : set (dual ℚ Λ)) : s ≤ t → set_down_one t ≤ set_down_one s := begin rintro h f hf ⟨i, hi⟩, apply hf ⟨_, h hi⟩, end lemma set_up_one_span (s : set Λ) : set_up_one (submodule.span (ℚ≥0) s : set Λ) = set_up_one s := begin ext f, simp only [mem_set_up_one, set_like.mem_coe], split, { intros t y hy, apply t _ (submodule.subset_span hy) }, { intros hf y hy, apply submodule.span_induction hy hf (by simp), { intros l₁ l₂ hl₁ hl₂, simp only [linear_map.map_add], apply add_nonneg hl₁ hl₂ }, { intros q y hy, simp only [linear_map.map_smul_of_tower], apply mul_nonneg q.2 hy } } end lemma set_down_one_span (s : set (dual ℚ Λ)) : set_down_one (submodule.span (ℚ≥0) s : set (dual ℚ Λ)) = set_down_one s := begin ext x, simp only [mem_set_down_one, set_like.mem_coe], split, { intros t y hy, apply t _ (submodule.subset_span hy) }, { intros hx y hy, apply submodule.span_induction hy hx (by simp), { intros l₁ l₂ hl₁ hl₂, apply add_nonneg hl₁ hl₂ }, { intros q f hf, simp only [linear_map.smul_apply], apply mul_nonneg q.2 hf } } end lemma le_up_down (l : set (dual ℚ Λ)) : l ≤ set_up_one (set_down_one l : set Λ) := begin rintro x hx ⟨i, hi⟩, apply hi ⟨_, hx⟩, end lemma le_down_up (l : set Λ) : l ≤ set_down_one (set_up_one l : set (dual ℚ Λ)) := begin rintro x hx ⟨i, hi⟩, apply hi ⟨_, hx⟩, end noncomputable def down_two [finite_dimensional ℚ Λ] : submodule (ℚ≥0) (dual ℚ (dual ℚ Λ)) → submodule (ℚ≥0) Λ := submodule.comap (linear_equiv.restrict_scalars (ℚ≥0) (eval_equiv ℚ Λ)) noncomputable def up_two [finite_dimensional ℚ Λ] : submodule (ℚ≥0) Λ → submodule (ℚ≥0) (dual ℚ (dual ℚ Λ)) := submodule.map (linear_equiv.restrict_scalars (ℚ≥0) (eval_equiv ℚ Λ)) lemma down_two_up [finite_dimensional ℚ Λ] (C : submodule (ℚ≥0) Λ) : down_two (up_two C) = C := begin dunfold up_two down_two, rw linear_equiv.map_eq_comap, rw ←submodule.comap_comp, simp only [linear_equiv.refl_to_linear_map, linear_equiv.trans_symm, linear_equiv.comp_coe, submodule.comap_id], end lemma up_two_down [finite_dimensional ℚ Λ] (C : submodule (ℚ≥0) (dual ℚ (dual ℚ Λ))) : up_two (down_two C) = C := begin dunfold up_two down_two, rw linear_equiv.map_eq_comap, rw ←submodule.comap_comp, simp [submodule.comap_id], end lemma down_two_index_up_one [finite_dimensional ℚ Λ] (l : ι → dual ℚ Λ) : down_two (index_up_one l) = index_down_one l := begin ext x, simp only [down_two, submodule.mem_comap, linear_equiv.coe_coe, linear_equiv.restrict_scalars_apply, mem_index_up_one, mem_index_down_one], refl end lemma down_two_set_up_one [finite_dimensional ℚ Λ] (l : set (dual ℚ Λ)) : down_two (set_up_one l) = set_down_one l := down_two_index_up_one _ lemma up_two_index_down_one [finite_dimensional ℚ Λ] (l : ι → dual ℚ Λ) : up_two (index_down_one l) = index_up_one l := begin rw ←down_two_index_up_one, simp only [up_two_down], end lemma up_two_set_down_one [finite_dimensional ℚ Λ] (l : set (dual ℚ Λ)) : up_two (set_down_one l) = set_up_one l := up_two_index_down_one _ lemma down_up_down_eq (l : set (dual ℚ Λ)) : set_down_one (set_up_one (set_down_one l : set Λ) : set (dual ℚ Λ)) = set_down_one l := begin apply le_antisymm, { apply set_down_one_antitone, apply le_up_down }, { apply le_down_up } end lemma up_down_up_eq (l : set Λ) : set_up_one (set_down_one (set_up_one l : set (dual ℚ Λ)) : set Λ) = set_up_one l := begin apply le_antisymm, { apply set_up_one_antitone, apply le_down_up }, { apply le_up_down } end lemma down_two_up_one_up_one [finite_dimensional ℚ Λ] (C : submodule (ℚ≥0) Λ) (hC : ∃ (l : set (dual ℚ Λ)), C = set_down_one l) : down_two (set_up_one (set_up_one (C : set Λ) : set (dual ℚ Λ))) = C := begin rw down_two_set_up_one, rcases hC with ⟨l, rfl⟩, rw down_up_down_eq end lemma down_eval_eq [finite_dimensional ℚ Λ] (C : set Λ) : set_down_one (eval_equiv ℚ Λ '' C) = set_up_one C := begin ext x, simp only [and_imp, set.mem_image, mem_set_down_one, mem_set_up_one, forall_apply_eq_imp_iff₂, exists_imp_distrib], refl end lemma down_one_up_two [finite_dimensional ℚ Λ] (C : submodule (ℚ≥0) Λ) : set_down_one (up_two C : set (dual ℚ (dual ℚ Λ))) = set_up_one C := down_eval_eq _ lemma up_one_down_two [finite_dimensional ℚ Λ] (C : submodule (ℚ≥0) (dual ℚ (dual ℚ Λ))) : set_up_one (down_two C : set Λ) = set_down_one C := begin simp only [←down_one_up_two], simp only [up_two_down], end lemma up_one_down_one [finite_dimensional ℚ Λ] (C : set (dual ℚ Λ)) : set_up_one (set_down_one C : set Λ) = set_down_one (set_up_one C) := begin rw ←down_two_set_up_one, simp only [up_one_down_two], end /-- A submodule is polyhedral if it is the intersection of finitely many half spaces. -/ def is_polyhedral_cone (C : submodule (ℚ≥0) Λ) : Prop := ∃ (ι : Type u) [fintype ι] (l : ι → Λ →ₗ[ℚ] ℚ), C = index_down_one l lemma is_polyhedral_cone_iff_finset (C : submodule (ℚ≥0) Λ) : is_polyhedral_cone C ↔ ∃ (s : finset (dual ℚ Λ)), C = set_down_one s := begin classical, split, { rintro ⟨ι, hι, l, rfl⟩, resetI, refine ⟨finset.univ.image l, _⟩, rw index_down_one_eq_set_down_one_range l, simp }, { rintro ⟨s, rfl⟩, exact ⟨(s : set (dual ℚ Λ)), infer_instance, _, set_down_one_def _⟩ } end lemma down_two_up_one_up_one_cone [finite_dimensional ℚ Λ] (C : submodule (ℚ≥0) Λ) (hC : is_polyhedral_cone C) : down_two (set_up_one (set_up_one (C : set Λ) : set (dual ℚ Λ))) = C := begin apply down_two_up_one_up_one, rw is_polyhedral_cone_iff_finset at hC, rcases hC with ⟨_, rfl⟩, refine ⟨_, rfl⟩, end lemma is_polyhedral_cone_of_equiv {Λ' : Type u} [add_comm_group Λ'] [module ℚ Λ'] (e : Λ ≃ₗ[ℚ] Λ') (C : submodule (ℚ≥0) Λ) (hC : is_polyhedral_cone C) : is_polyhedral_cone (submodule.map (e.to_linear_map.restrict_scalars (ℚ≥0)) C) := begin rcases hC with ⟨ι, hι, l, rfl⟩, refine ⟨ι, hι, λ i, _, _⟩, apply (l i).comp e.symm.to_linear_map, ext x, simp only [submodule.mem_map, function.comp_app, linear_map.coe_comp, mem_index_down_one, linear_equiv.coe_to_linear_map, linear_map.coe_restrict_scalars_eq_coe], split, { rintro ⟨y, hy, rfl⟩, simpa }, { intro t, refine ⟨e.symm x, t, by simp⟩ } end lemma is_polyhedral_cone_bot_aux [fintype α] : is_polyhedral_cone (⊥ : submodule (ℚ≥0) (α → ℚ)) := ⟨α ⊕ α, sum.fintype α α, sum.elim (λ i, ⟨λ f, f i, λ x y, rfl, λ _ _, rfl⟩) (λ i, -⟨λ f, f i, λ x y, rfl, λ _ _, rfl⟩), begin ext, simp only [linear_map.coe_proj, sum.elim_inl, function.eval_apply, linear_map.neg_apply, sum.elim_inr, mem_index_down_one, sum.forall, submodule.mem_bot, neg_nonneg], split, { rintro rfl, simp only [linear_map.map_zero, and_self], intro a, apply le_rfl }, { rintro ⟨h₁, h₂⟩, ext i, apply le_antisymm, { apply h₂ i }, { apply h₁ i } } end⟩ lemma is_polyhedral_cone_bot [finite_dimensional ℚ Λ] : is_polyhedral_cone (⊥ : submodule (ℚ≥0) Λ) := begin let l := (basis.of_vector_space ℚ Λ).equiv_fun, have := is_polyhedral_cone_of_equiv l.symm ⊥ is_polyhedral_cone_bot_aux, simpa using this, end lemma coe_min' (s : finset (ℚ≥0)) (hs : s.nonempty) : (coe (s.min' hs) : ℚ) = (s.image coe).min' (hs.image _) := begin revert hs, apply finset.induction_on s, { simp }, { intros x s hx ih t, rcases finset.eq_empty_or_nonempty s with (rfl | hs), { simp }, -- simp only [finset.min'_insert x _ hs], simp_rw [finset.image_insert], rw [finset.min'_insert, ←ih hs, ←nnrat.coe_min], congr' 1, convert finset.min'_insert x s hs } end def extended_half_spaces_index {ι : Type*} (s : ι → Λ →ₗ[ℚ] ℚ) (x : Λ) : Type* := {i : ι // 0 ≤ s i x} ⊕ ({i : ι // 0 < s i x} × {i : ι // s i x < 0}) noncomputable instance {ι : Type*} [fintype ι] (s : ι → Λ →ₗ[ℚ] ℚ) (x : Λ) : fintype (extended_half_spaces_index s x) := begin rw extended_half_spaces_index, apply_instance end noncomputable def extended_half_spaces {ι : Type*} (s : ι → Λ →ₗ[ℚ] ℚ) (x : Λ) : extended_half_spaces_index s x → Λ →ₗ[ℚ] ℚ := sum.elim (s ∘ coe) (λ ij, (s ij.1 x) • s ij.2 - (s ij.2 x) • s ij.1) lemma span_le_extended [decidable_eq Λ] {ι : Type*} {s : ι → Λ →ₗ[ℚ] ℚ} {l : finset Λ} (hs : submodule.span ℚ≥0 (l : set Λ) = index_down_one s) {x : Λ} (hx : x ∉ l) : submodule.span ℚ≥0 ↑(insert x l) ≤ index_down_one (extended_half_spaces s x) := begin rw submodule.span_le, intros f hf, simp only [finset.coe_insert, set.mem_insert_iff, finset.mem_coe] at hf, simp only [set_like.mem_coe, mem_index_down_one, extended_half_spaces], rcases hf with (rfl | hf), { rintro (⟨i, hi⟩ | ⟨⟨i, hi⟩, j, hj⟩), { simpa }, { simp [mul_comm] } }, { have f_mem : f ∈ index_down_one s, { rw ←hs, exact submodule.subset_span hf }, rintro (⟨i, hi⟩ | ⟨⟨i, hi⟩, j, hj⟩), { simpa using f_mem i }, { have : 0 ≤ s i f, by apply f_mem, have : 0 ≤ s j f, by apply f_mem, simp only [algebra.id.smul_eq_mul, sub_nonneg, linear_map.smul_apply, sum.elim_inr, subtype.coe_mk, linear_map.sub_apply], nlinarith } }, end lemma extended_le_span [decidable_eq Λ] {ι : Type*} [fintype ι] {s : ι → Λ →ₗ[ℚ] ℚ} {l : finset Λ} (hs : submodule.span ℚ≥0 (l : set Λ) = index_down_one s) {x : Λ} (hx : x ∉ l) : index_down_one (extended_half_spaces s x) ≤ submodule.span ℚ≥0 ↑(insert x l) := begin intros y hy, simp only [finset.coe_insert, submodule.mem_span_insert, exists_prop, hs], suffices : ∃ (t : ℚ≥0), y - t • x ∈ index_down_one s, { rcases this with ⟨a, ha⟩, refine ⟨a, _, ha, by simp⟩ }, simp only [mem_index_down_one] at hy, have y_nonneg : ∀ i, 0 ≤ s i x → 0 ≤ s i y, { intros i hi, apply hy (sum.inl ⟨i, hi⟩) }, have y_neg : ∀ i j, 0 < s i x → s j x < 0 → s j x * s i y ≤ s i x * s j y, { intros i j hi hj, simpa [extended_half_spaces] using hy (sum.inr ⟨⟨i, hi⟩, ⟨j, hj⟩⟩) }, let a : {i // 0 < s i x} → ℚ≥0 := λ i, ⟨s i.1 y, y_nonneg _ i.2.le⟩ / ⟨s i.1 x, i.2.le⟩, let as : finset (ℚ≥0) := finset.univ.image a, let b : {i // s i x < 0} → ℚ := λ i, s i.1 y / s i.1 x, let bs : finset ℚ := finset.univ.image b, by_cases h : nonempty {i // 0 < s i x}, { have : as.nonempty, { rwa [finset.nonempty.image_iff, finset.univ_nonempty_iff] }, refine ⟨as.min' ‹as.nonempty›, _⟩, rw [mem_index_down_one], intros i, rw [linear_map.map_sub, sub_nonneg], simp only [linear_map.map_smul_of_tower, subtype.val_eq_coe], change (coe (_ : ℚ≥0)) * (s i x) ≤ s i y, rcases lt_trichotomy 0 (s i x) with (lt | eq | gt), { rw [coe_min', ←le_div_iff lt], apply finset.min'_le, simp only [finset.mem_univ, finset.mem_image, exists_prop], refine ⟨_, ⟨⟨i, lt⟩, ⟨⟩, rfl⟩, _⟩, simp }, { rw [←eq, mul_zero], apply y_nonneg _ (eq.le) }, { rw [coe_min', ←div_le_iff_of_neg gt], apply finset.le_min', simp only [and_imp, exists_prop, finset.mem_univ, bex_imp_distrib, finset.mem_image, exists_true_left, subtype.exists, exists_imp_distrib], rintro _ _ j hj ⟨⟨⟩, rfl⟩ rfl, simp only [nnrat.coe_div, subtype.coe_mk], have := y_neg _ _ hj gt, rwa [div_le_iff_of_neg gt, ←mul_div_right_comm, mul_comm, div_le_iff' hj] } }, by_cases h' : nonempty {i // s i x < 0}, { have : bs.nonempty, { rwa [finset.nonempty.image_iff, finset.univ_nonempty_iff] }, refine ⟨nnrat.of_rat (bs.max' ‹bs.nonempty›), _⟩, intros i, rw [linear_map.map_sub, sub_nonneg], simp only [linear_map.map_smul_of_tower, subtype.val_eq_coe], rcases lt_trichotomy 0 (s i x) with (lt | eq | gt), { exfalso, apply h, refine ⟨⟨_, lt⟩⟩ }, { rw [←eq, smul_zero], apply y_nonneg, apply eq.le, }, change max _ _ * _ ≤ _, rw ←div_le_iff_of_neg gt, rw le_max_iff, left, apply finset.le_max', simp only [finset.mem_univ, finset.mem_image, exists_true_left, subtype.exists], refine ⟨i, gt, finset.mem_univ _, rfl⟩ }, refine ⟨0, _⟩, intros i, rw [linear_map.map_sub, sub_nonneg, zero_smul, linear_map.map_zero], simp only [linear_map.map_smul_of_tower, subtype.val_eq_coe], rcases le_or_lt 0 (s i x) with (lt | lt), { apply y_nonneg _ lt }, { exfalso, apply h', refine ⟨⟨_, lt⟩⟩ }, end lemma eliminate_inductive_step [decidable_eq Λ] (ι : Type u) [fintype ι] (s : ι → Λ →ₗ[ℚ] ℚ) {l : finset Λ} (hs : submodule.span ℚ≥0 (l : set Λ) = index_down_one s) (x : Λ) (hx : x ∉ l) : is_polyhedral_cone (submodule.span ℚ≥0 (coe (insert x l) : set Λ)) := begin refine ⟨extended_half_spaces_index s x, infer_instance, extended_half_spaces _ _, _⟩, apply le_antisymm, apply span_le_extended hs hx, apply extended_le_span hs hx, end lemma elimination_aux [finite_dimensional ℚ Λ] (l : finset Λ) : is_polyhedral_cone (submodule.span (ℚ≥0) (l : set Λ)) := begin classical, apply finset.induction_on l, { simp only [finset.coe_empty, submodule.span_empty], apply is_polyhedral_cone_bot }, { clear l, rintro x l hx ⟨ι, hι, s, hs⟩, resetI, convert eliminate_inductive_step ι s hs x hx } end lemma is_polyhedral_cone_of_fg [finite_dimensional ℚ Λ] (C : submodule (ℚ≥0) Λ) (hC : C.fg) : is_polyhedral_cone C := begin rcases hC with ⟨l, rfl⟩, apply elimination_aux end lemma one_sixteen_c [finite_dimensional ℚ Λ] (ι : Type u) [fintype ι] (l : ι → Λ →ₗ[ℚ] ℚ) : set_up_one (index_down_one l : set Λ) = submodule.span (ℚ≥0) (set.range l) := begin set C : submodule (ℚ≥0) Λ := index_down_one l, set C_star := set_up_one (C : set Λ), set C' : submodule _ (dual ℚ Λ) := submodule.span (ℚ≥0) (set.range l), let C'_star := down_two (set_up_one (C' : set (dual ℚ Λ))), have C_eq : C = C'_star, { change C = down_two (set_up_one (C' : set (dual ℚ Λ))), rw down_two_set_up_one, rw set_down_one_span, apply index_down_one_eq_set_down_one_range }, have C'pc : is_polyhedral_cone C', { apply is_polyhedral_cone_of_fg, classical, refine ⟨finset.univ.image l, _⟩, simp }, change set_up_one (C : set Λ) = _, rw C_eq, change set_up_one (down_two (set_up_one (C' : set (dual ℚ Λ))) : set Λ) = _, rw down_two_set_up_one, rw is_polyhedral_cone_iff_finset at C'pc, clear_value C', clear' C C_star C'_star C_eq l, rcases C'pc with ⟨s, rfl⟩, simp_rw [up_one_down_one (set_down_one (s : set (dual ℚ (dual ℚ Λ))) : set (dual ℚ Λ))], rw down_up_down_eq, end lemma dual_fg_of_cone [finite_dimensional ℚ Λ] (C : submodule (ℚ≥0) Λ) (hC : is_polyhedral_cone C) : (set_up_one (C : set Λ) : submodule (ℚ≥0) (dual ℚ Λ)).fg := begin rcases hC with ⟨ι, hι, l, rfl⟩, resetI, simp only [one_sixteen_c], classical, refine ⟨finset.univ.image l, by simp⟩, end lemma fg_of_is_polyhedral_cone [finite_dimensional ℚ Λ] (C : submodule (ℚ≥0) Λ) (hC : is_polyhedral_cone C) : C.fg := begin have t := dual_fg_of_cone _ (is_polyhedral_cone_of_fg _ (dual_fg_of_cone _ hC)), have t2 : (submodule.map (((eval_equiv ℚ Λ).restrict_scalars (ℚ≥0)).symm : dual ℚ (dual ℚ Λ) →ₗ[ℚ≥0] Λ) _).fg := submodule.fg_map t, rw linear_equiv.map_eq_comap at t2, simp only [linear_equiv.symm_symm] at t2, change (down_two _).fg at t2, rw down_two_up_one_up_one_cone _ hC at t2, assumption end lemma fg_iff_is_polyhedral_cone [finite_dimensional ℚ Λ] (C : submodule (ℚ≥0) Λ) : is_polyhedral_cone C ↔ C.fg := ⟨fg_of_is_polyhedral_cone C, is_polyhedral_cone_of_fg C⟩
4dbd2443fe9dcad16d5cf0b65da0b126f07d9917
9bb72db9297f7837f673785604fb89b3184e13f8
/library/init/meta/expr.lean
ece737c7346860a7038e16d1dfd32b3ca0a9a7e1
[ "Apache-2.0" ]
permissive
dselsam/lean
ec83d7592199faa85687d884bbaaa570b62c1652
6b0bd5bc2e07e13880d332c89093fe3032bb2469
refs/heads/master
1,621,807,064,966
1,611,454,685,000
1,611,975,642,000
42,734,348
3
3
null
1,498,748,560,000
1,442,594,289,000
C++
UTF-8
Lean
false
false
23,520
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.level init.control.monad init.meta.rb_map universes u v open native /-- Column and line position in a Lean source file. -/ structure pos := (line : nat) (column : nat) instance : decidable_eq pos | ⟨l₁, c₁⟩ ⟨l₂, c₂⟩ := if h₁ : l₁ = l₂ then if h₂ : c₁ = c₂ then is_true (eq.rec_on h₁ (eq.rec_on h₂ rfl)) else is_false (λ contra, pos.no_confusion contra (λ e₁ e₂, absurd e₂ h₂)) else is_false (λ contra, pos.no_confusion contra (λ e₁ e₂, absurd e₁ h₁)) meta instance : has_to_format pos := ⟨λ ⟨l, c⟩, "⟨" ++ l ++ ", " ++ c ++ "⟩"⟩ /-- Auxiliary annotation for binders (Lambda and Pi). This information is only used for elaboration. The difference between `{}` and `⦃⦄` is how implicit arguments are treated that are *not* followed by explicit arguments. `{}` arguments are applied eagerly, while `⦃⦄` arguments are left partially applied: ```lean def foo {x : ℕ} : ℕ := x def bar ⦃x : ℕ⦄ : ℕ := x #check foo -- foo : ℕ #check bar -- bar : Π ⦃x : ℕ⦄, ℕ ``` -/ inductive binder_info /- `(x : α)` -/ | default /- `{x : α}` -/ | implicit /- `⦃x:α⦄` -/ | strict_implicit /- `[x : α]`. Should be inferred with typeclass resolution. -/ | inst_implicit /- Auxiliary internal attribute used to mark local constants representing recursive functions in recursive equations and `match` statements. -/ | aux_decl instance : has_repr binder_info := ⟨λ bi, match bi with | binder_info.default := "default" | binder_info.implicit := "implicit" | binder_info.strict_implicit := "strict_implicit" | binder_info.inst_implicit := "inst_implicit" | binder_info.aux_decl := "aux_decl" end⟩ /-- Macros are basically "promises" to build an expr by some C++ code, you can't build them in Lean. You can unfold a macro and force it to evaluate. They are used for - `sorry`. - Term placeholders (`_`) in `pexpr`s. - Expression annotations. See `expr.is_annotation`. - Meta-recursive calls. Eg: ``` meta def Y : (α → α) → α | f := f (Y f) ``` The `Y` that appears in `f (Y f)` is a macro. - Builtin projections: ``` structure foo := (mynat : ℕ) #print foo.mynat -- @[reducible] -- def foo.mynat : foo → ℕ := -- λ (c : foo), [foo.mynat c] ``` The thing in square brackets is a macro. - Ephemeral structures inside certain specialised C++ implemented tactics. -/ meta constant macro_def : Type /-- An expression. eg ```(4+5)```. The `elab` flag is indicates whether the `expr` has been elaborated and doesn't contain any placeholder macros. For example the equality `x = x` is represented in `expr ff` as ``app (app (const `eq _) x) x`` while in `expr tt` it is represented as ``app (app (app (const `eq _) t) x) x`` (one more argument). The VM replaces instances of this datatype with the C++ implementation. -/ meta inductive expr (elaborated : bool := tt) /- A bound variable with a de-Bruijn index. -/ | var : nat → expr /- A type universe: `Sort u` -/ | sort : level → expr /- A global constant. These include definitions, constants and inductive type stuff present in the environment as well as hard-coded definitions. -/ | const : name → list level → expr /- [WARNING] Do not trust the types for `mvar` and `local_const`, they are sometimes dummy values. Use `tactic.infer_type` instead. -/ /- An `mvar` is a 'hole' yet to be filled in by the elaborator or tactic state. -/ | mvar (unique : name) (pretty : name) (type : expr) : expr /- A local constant. For example, if our tactic state was `h : P ⊢ Q`, `h` would be a local constant. -/ | local_const (unique : name) (pretty : name) (bi : binder_info) (type : expr) : expr /- Function application. -/ | app : expr → expr → expr /- Lambda abstraction. eg ```(λ a : α, x)`` -/ | lam (var_name : name) (bi : binder_info) (var_type : expr) (body : expr) : expr /- Pi type constructor. eg ```(Π a : α, x)`` and ```(α → β)`` -/ | pi (var_name : name) (bi : binder_info) (var_type : expr) (body : expr) : expr /- An explicit let binding. -/ | elet (var_name : name) (type : expr) (assignment : expr) (body : expr) : expr /- A macro, see the docstring for `macro_def`. The list of expressions are local constants and metavariables that the macro depends on. -/ | macro : macro_def → list expr → expr variable {elab : bool} meta instance : inhabited expr := ⟨expr.sort level.zero⟩ /-- Get the name of the macro definition. -/ meta constant expr.macro_def_name (d : macro_def) : name meta def expr.mk_var (n : nat) : expr := expr.var n /-- Expressions can be annotated using an annotation macro during compilation. For example, a `have x:X, from p, q` expression will be compiled to `(λ x:X,q)(p)`, but nested in an annotation macro with the name `"have"`. These annotations have no real semantic meaning, but are useful for helping Lean's pretty printer. -/ meta constant expr.is_annotation : expr elab → option (name × expr elab) meta constant expr.is_string_macro : expr elab → option (expr elab) /-- Remove all macro annotations from the given `expr`. -/ meta def expr.erase_annotations : expr elab → expr elab | e := match e.is_annotation with | some (_, a) := expr.erase_annotations a | none := e end /-- Compares expressions, including binder names. -/ meta constant expr.has_decidable_eq : decidable_eq expr attribute [instance] expr.has_decidable_eq /-- Compares expressions while ignoring binder names. -/ meta constant expr.alpha_eqv : expr → expr → bool notation a ` =ₐ `:50 b:50 := expr.alpha_eqv a b = bool.tt protected meta constant expr.to_string : expr elab → string meta instance : has_to_string (expr elab) := ⟨expr.to_string⟩ meta instance : has_to_format (expr elab) := ⟨λ e, e.to_string⟩ /-- Coercion for letting users write (f a) instead of (expr.app f a) -/ meta instance : has_coe_to_fun (expr elab) := { F := λ e, expr elab → expr elab, coe := λ e, expr.app e } /-- Each expression created by Lean carries a hash. This is calculated upon creation of the expression. Two structurally equal expressions will have the same hash. -/ meta constant expr.hash : expr → nat /-- Compares expressions, ignoring binder names, and sorting by hash. -/ meta constant expr.lt : expr → expr → bool /-- Compares expressions, ignoring binder names. -/ meta constant expr.lex_lt : expr → expr → bool /-- `expr.fold e a f`: Traverses each subexpression of `e`. The `nat` passed to the folder `f` is the binder depth. -/ meta constant expr.fold {α : Type} : expr → α → (expr → nat → α → α) → α /-- `expr.replace e f` Traverse over an expr `e` with a function `f` which can decide to replace subexpressions or not. For each subexpression `s` in the expression tree, `f s n` is called where `n` is how many binders are present above the given subexpression `s`. If `f s n` returns `none`, the children of `s` will be traversed. Otherwise if `some s'` is returned, `s'` will replace `s` and this subexpression will not be traversed further. -/ meta constant expr.replace : expr → (expr → nat → option expr) → expr /-- `abstract_local e n` replaces each instance of the local constant with unique (not pretty) name `n` in `e` with a de-Bruijn variable. -/ meta constant expr.abstract_local : expr → name → expr /-- Multi version of `abstract_local`. Note that the given expression will only be traversed once, so this is not the same as `list.foldl expr.abstract_local`.-/ meta constant expr.abstract_locals : expr → list name → expr /-- `abstract e x` Abstracts the expression `e` over the local constant `x`. -/ meta def expr.abstract : expr → expr → expr | e (expr.local_const n m bi t) := e.abstract_local n | e _ := e /-- Expressions depend on `level`s, and these may depend on universe parameters which have names. `instantiate_univ_params e [(n₁,l₁), ...]` will traverse `e` and replace any universe parameters with name `nᵢ` with the corresponding level `lᵢ`. -/ meta constant expr.instantiate_univ_params : expr → list (name × level) → expr /-- `instantiate_nth_var n a b` takes the `n`th de-Bruijn variable in `a` and replaces each occurrence with `b`. -/ meta constant expr.instantiate_nth_var : nat → expr → expr → expr /-- `instantiate_var a b` takes the 0th de-Bruijn variable in `a` and replaces each occurrence with `b`. -/ meta constant expr.instantiate_var : expr → expr → expr /-- ``instantiate_vars `(#0 #1 #2) [x,y,z] = `(%%x %%y %%z)`` -/ meta constant expr.instantiate_vars : expr → list expr → expr /-- Same as `instantiate_vars` except lifts and shifts the vars by the given amount. ``instantiate_vars_core `(#0 #1 #2 #3) 0 [x,y] = `(x y #0 #1)`` ``instantiate_vars_core `(#0 #1 #2 #3) 1 [x,y] = `(#0 x y #1)`` ``instantiate_vars_core `(#0 #1 #2 #3) 2 [x,y] = `(#0 #1 x y)`` -/ meta constant expr.instantiate_vars_core : expr → nat → list expr → expr /-- Perform beta-reduction if the left expression is a lambda, or construct an application otherwise. That is: ``expr.subst `(λ x, %%Y) Z = Y[x/Z]``, and ``expr.subst X Z = X.app Z`` otherwise -/ protected meta constant expr.subst : expr elab → expr elab → expr elab /-- `get_free_var_range e` returns one plus the maximum de-Bruijn value in `e`. Eg `get_free_var_range `(#1 #0)` yields `2` -/ meta constant expr.get_free_var_range : expr → nat /-- `has_var e` returns true iff e has free variables. -/ meta constant expr.has_var : expr → bool /-- `has_var_idx e n` returns true iff `e` has a free variable with de-Bruijn index `n`. -/ meta constant expr.has_var_idx : expr → nat → bool /-- `has_local e` returns true if `e` contains a local constant. -/ meta constant expr.has_local : expr → bool /-- `has_meta_var e` returns true iff `e` contains a metavariable. -/ meta constant expr.has_meta_var : expr → bool /-- `lower_vars e s d` lowers the free variables >= s in `e` by `d`. Note that this can cause variable clashes. examples: - ``lower_vars `(#2 #1 #0) 1 1 = `(#1 #0 #0)`` - ``lower_vars `(λ x, #2 #1 #0) 1 1 = `(λ x, #1 #1 #0 )`` -/ meta constant expr.lower_vars : expr → nat → nat → expr /-- Lifts free variables. `lift_vars e s d` will lift all free variables with index `≥ s` in `e` by `d`. -/ meta constant expr.lift_vars : expr → nat → nat → expr /-- Get the position of the given expression in the Lean source file, if anywhere. -/ protected meta constant expr.pos : expr elab → option pos /-- `copy_pos_info src tgt` copies position information from `src` to `tgt`. -/ meta constant expr.copy_pos_info : expr → expr → expr /-- Returns `some n` when the given expression is a constant with the name `..._cnstr.n` ``` is_internal_cnstr : expr → option unsigned |(const (mk_numeral n (mk_string "_cnstr" _)) _) := some n |_ := none ``` [NOTE] This is not used anywhere in core Lean. -/ meta constant expr.is_internal_cnstr : expr → option unsigned /-- There is a macro called a "nat_value_macro" holding a natural number which are used during compilation. This function extracts that to a natural number. [NOTE] This is not used anywhere in Lean. -/ meta constant expr.get_nat_value : expr → option nat /-- Get a list of all of the universe parameters that the given expression depends on. -/ meta constant expr.collect_univ_params : expr → list name /-- `occurs e t` returns `tt` iff `e` occurs in `t` up to α-equivalence. Purely structural: no unification or definitional equality. -/ meta constant expr.occurs : expr → expr → bool /-- Returns true if any of the names in the given `name_set` are present in the given `expr`. -/ meta constant expr.has_local_in : expr → name_set → bool /-- Computes the number of sub-expressions (constant time). -/ meta constant expr.get_weight : expr → ℕ /-- Computes the maximum depth of the expression (constant time). -/ meta constant expr.get_depth : expr → ℕ /-- `mk_delayed_abstraction m ls` creates a delayed abstraction on the metavariable `m` with the unique names of the local constants `ls`. If `m` is not a metavariable then this is equivalent to `abstract_locals`. -/ meta constant expr.mk_delayed_abstraction : expr → list name → expr /-- If the given expression is a delayed abstraction macro, return `some ls` where `ls` is a list of unique names of locals that will be abstracted. -/ meta constant expr.get_delayed_abstraction_locals : expr → option (list name) /-- (reflected a) is a special opaque container for a closed `expr` representing `a`. It can only be obtained via type class inference, which will use the representation of `a` in the calling context. Local constants in the representation are replaced by nested inference of `reflected` instances. The quotation expression `` `(a) `` (outside of patterns) is equivalent to `reflect a` and thus can be used as an explicit way of inferring an instance of `reflected a`. -/ @[class] meta def reflected {α : Sort u} : α → Type := λ _, expr @[inline] meta def reflected.to_expr {α : Sort u} {a : α} : reflected a → expr := id @[inline] meta def reflected.subst {α : Sort v} {β : α → Sort u} {f : Π a : α, β a} {a : α} : reflected f → reflected a → reflected (f a) := expr.subst attribute [irreducible] reflected reflected.subst reflected.to_expr @[instance] protected meta constant expr.reflect (e : expr elab) : reflected e @[instance] protected meta constant string.reflect (s : string) : reflected s @[inline] meta instance {α : Sort u} (a : α) : has_coe (reflected a) expr := ⟨reflected.to_expr⟩ protected meta def reflect {α : Sort u} (a : α) [h : reflected a] : reflected a := h meta instance {α} (a : α) : has_to_format (reflected a) := ⟨λ h, to_fmt h.to_expr⟩ namespace expr open decidable meta def lt_prop (a b : expr) : Prop := expr.lt a b = tt meta instance : decidable_rel expr.lt_prop := λ a b, bool.decidable_eq _ _ /-- Compares expressions, ignoring binder names, and sorting by hash. -/ meta instance : has_lt expr := ⟨ expr.lt_prop ⟩ meta def mk_true : expr := const `true [] meta def mk_false : expr := const `false [] /-- Returns the sorry macro with the given type. -/ meta constant mk_sorry (type : expr) : expr /-- Checks whether e is sorry, and returns its type. -/ meta constant is_sorry (e : expr) : option expr /-- Replace each instance of the local constant with name `n` by the expression `s` in `e`. -/ meta def instantiate_local (n : name) (s : expr) (e : expr) : expr := instantiate_var (abstract_local e n) s meta def instantiate_locals (s : list (name × expr)) (e : expr) : expr := instantiate_vars (abstract_locals e (list.reverse (list.map prod.fst s))) (list.map prod.snd s) meta def is_var : expr → bool | (var _) := tt | _ := ff meta def app_of_list : expr → list expr → expr | f [] := f | f (p::ps) := app_of_list (f p) ps meta def is_app : expr → bool | (app f a) := tt | e := ff meta def app_fn : expr → expr | (app f a) := f | a := a meta def app_arg : expr → expr | (app f a) := a | a := a meta def get_app_fn : expr elab → expr elab | (app f a) := get_app_fn f | a := a meta def get_app_num_args : expr → nat | (app f a) := get_app_num_args f + 1 | e := 0 meta def get_app_args_aux : list expr → expr → list expr | r (app f a) := get_app_args_aux (a::r) f | r e := r meta def get_app_args : expr → list expr := get_app_args_aux [] meta def mk_app : expr → list expr → expr | e [] := e | e (x::xs) := mk_app (e x) xs meta def mk_binding (ctor : name → binder_info → expr → expr → expr) (e : expr) : Π (l : expr), expr | (local_const n pp_n bi ty) := ctor pp_n bi ty (e.abstract_local n) | _ := e /-- (bind_pi e l) abstracts and pi-binds the local `l` in `e` -/ meta def bind_pi := mk_binding pi /-- (bind_lambda e l) abstracts and lambda-binds the local `l` in `e` -/ meta def bind_lambda := mk_binding lam meta def ith_arg_aux : expr → nat → expr | (app f a) 0 := a | (app f a) (n+1) := ith_arg_aux f n | e _ := e meta def ith_arg (e : expr) (i : nat) : expr := ith_arg_aux e (get_app_num_args e - i - 1) meta def const_name : expr elab → name | (const n ls) := n | e := name.anonymous meta def is_constant : expr elab → bool | (const n ls) := tt | e := ff meta def is_local_constant : expr → bool | (local_const n m bi t) := tt | e := ff meta def local_uniq_name : expr → name | (local_const n m bi t) := n | e := name.anonymous meta def local_pp_name : expr elab → name | (local_const x n bi t) := n | e := name.anonymous meta def local_type : expr elab → expr elab | (local_const _ _ _ t) := t | e := e meta def is_aux_decl : expr → bool | (local_const _ _ binder_info.aux_decl _) := tt | _ := ff meta def is_constant_of : expr elab → name → bool | (const n₁ ls) n₂ := n₁ = n₂ | e n := ff meta def is_app_of (e : expr) (n : name) : bool := is_constant_of (get_app_fn e) n /-- The same as `is_app_of` but must also have exactly `n` arguments. -/ meta def is_napp_of (e : expr) (c : name) (n : nat) : bool := is_app_of e c ∧ get_app_num_args e = n meta def is_false : expr → bool | `(false) := tt | _ := ff meta def is_not : expr → option expr | `(not %%a) := some a | `(%%a → false) := some a | e := none meta def is_and : expr → option (expr × expr) | `(and %%α %%β) := some (α, β) | _ := none meta def is_or : expr → option (expr × expr) | `(or %%α %%β) := some (α, β) | _ := none meta def is_iff : expr → option (expr × expr) | `((%%a : Prop) ↔ %%b) := some (a, b) | _ := none meta def is_eq : expr → option (expr × expr) | `((%%a : %%_) = %%b) := some (a, b) | _ := none meta def is_ne : expr → option (expr × expr) | `((%%a : %%_) ≠ %%b) := some (a, b) | _ := none meta def is_bin_arith_app (e : expr) (op : name) : option (expr × expr) := if is_napp_of e op 4 then some (app_arg (app_fn e), app_arg e) else none meta def is_lt (e : expr) : option (expr × expr) := is_bin_arith_app e ``has_lt.lt meta def is_gt (e : expr) : option (expr × expr) := is_bin_arith_app e ``gt meta def is_le (e : expr) : option (expr × expr) := is_bin_arith_app e ``has_le.le meta def is_ge (e : expr) : option (expr × expr) := is_bin_arith_app e ``ge meta def is_heq : expr → option (expr × expr × expr × expr) | `(@heq %%α %%a %%β %%b) := some (α, a, β, b) | _ := none meta def is_lambda : expr → bool | (lam _ _ _ _) := tt | e := ff meta def is_pi : expr → bool | (pi _ _ _ _) := tt | e := ff meta def is_arrow : expr → bool | (pi _ _ _ b) := bnot (has_var b) | e := ff meta def is_let : expr → bool | (elet _ _ _ _) := tt | e := ff /-- The name of the bound variable in a pi, lambda or let expression. -/ meta def binding_name : expr → name | (pi n _ _ _) := n | (lam n _ _ _) := n | (elet n _ _ _) := n | e := name.anonymous /-- The binder info of a pi or lambda expression. -/ meta def binding_info : expr → binder_info | (pi _ bi _ _) := bi | (lam _ bi _ _) := bi | e := binder_info.default /-- The domain (type of bound variable) of a pi, lambda or let expression. -/ meta def binding_domain : expr → expr | (pi _ _ d _) := d | (lam _ _ d _) := d | (elet _ d _ _) := d | e := e /-- The body of a pi, lambda or let expression. This definition doesn't instantiate bound variables, and therefore produces a term that is open. See note [open expressions] in mathlib. -/ meta def binding_body : expr → expr | (pi _ _ _ b) := b | (lam _ _ _ b) := b | (elet _ _ _ b) := b | e := e /-- `nth_binding_body n e` iterates `binding_body` `n` times to an iterated pi expression `e`. This definition doesn't instantiate bound variables, and therefore produces a term that is open. See note [open expressions] in mathlib. -/ meta def nth_binding_body : ℕ → expr → expr | (n + 1) (pi _ _ _ b) := nth_binding_body n b | _ e := e meta def is_macro : expr → bool | (macro d a) := tt | e := ff meta def is_numeral : expr → bool | `(@has_zero.zero %%α %%s) := tt | `(@has_one.one %%α %%s) := tt | `(@bit0 %%α %%s %%v) := is_numeral v | `(@bit1 %%α %%s₁ %%s₂ %%v) := is_numeral v | _ := ff meta def pi_arity : expr → ℕ | (pi _ _ _ b) := pi_arity b + 1 | _ := 0 meta def lam_arity : expr → ℕ | (lam _ _ _ b) := lam_arity b + 1 | _ := 0 meta def imp (a b : expr) : expr := pi `_ binder_info.default a b /-- `lambdas cs e` lambda binds `e` with each of the local constants in `cs`. -/ meta def lambdas : list expr → expr → expr | (local_const uniq pp info t :: es) f := lam pp info t (abstract_local (lambdas es f) uniq) | _ f := f /-- Same as `expr.lambdas` but with `pi`. -/ meta def pis : list expr → expr → expr | (local_const uniq pp info t :: es) f := pi pp info t (abstract_local (pis es f) uniq) | _ f := f meta def extract_opt_auto_param : expr → expr | `(@opt_param %%t _) := extract_opt_auto_param t | `(@auto_param %%t _) := extract_opt_auto_param t | e := e open format private meta def p := λ xs, paren (format.join (list.intersperse " " xs)) meta def to_raw_fmt : expr elab → format | (var n) := p ["var", to_fmt n] | (sort l) := p ["sort", to_fmt l] | (const n ls) := p ["const", to_fmt n, to_fmt ls] | (mvar n m t) := p ["mvar", to_fmt n, to_fmt m, to_raw_fmt t] | (local_const n m bi t) := p ["local_const", to_fmt n, to_fmt m, to_raw_fmt t] | (app e f) := p ["app", to_raw_fmt e, to_raw_fmt f] | (lam n bi e t) := p ["lam", to_fmt n, repr bi, to_raw_fmt e, to_raw_fmt t] | (pi n bi e t) := p ["pi", to_fmt n, repr bi, to_raw_fmt e, to_raw_fmt t] | (elet n g e f) := p ["elet", to_fmt n, to_raw_fmt g, to_raw_fmt e, to_raw_fmt f] | (macro d args) := sbracket (format.join (list.intersperse " " ("macro" :: to_fmt (macro_def_name d) :: args.map to_raw_fmt))) /-- Fold an accumulator `a` over each subexpression in the expression `e`. The `nat` passed to `fn` is the number of binders above the subexpression. -/ meta def mfold {α : Type} {m : Type → Type} [monad m] (e : expr) (a : α) (fn : expr → nat → α → m α) : m α := fold e (return a) (λ e n a, a >>= fn e n) end expr /-- An dictionary from `data` to expressions. -/ @[reducible] meta def expr_map (data : Type) := rb_map expr data namespace expr_map export native.rb_map (hiding mk) meta def mk (data : Type) : expr_map data := rb_map.mk expr data end expr_map meta def mk_expr_map {data : Type} : expr_map data := expr_map.mk data @[reducible] meta def expr_set := rb_set expr meta def mk_expr_set : expr_set := mk_rb_set
2138447f292c547d88e06f87c6f83cd9870e4467
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/periodic.lean
442c4cafb585bfb42bf89d69e75271c2d0e0b2b6
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
20,017
lean
/- Copyright (c) 2021 Benjamin Davidson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Benjamin Davidson -/ import algebra.field.opposite import algebra.module.basic import algebra.order.archimedean import data.int.parity import group_theory.coset /-! # Periodicity In this file we define and then prove facts about periodic and antiperiodic functions. ## Main definitions * `function.periodic`: A function `f` is *periodic* if `∀ x, f (x + c) = f x`. `f` is referred to as periodic with period `c` or `c`-periodic. * `function.antiperiodic`: A function `f` is *antiperiodic* if `∀ x, f (x + c) = -f x`. `f` is referred to as antiperiodic with antiperiod `c` or `c`-antiperiodic. Note that any `c`-antiperiodic function will necessarily also be `2*c`-periodic. ## Tags period, periodic, periodicity, antiperiodic -/ variables {α β γ : Type*} {f g : α → β} {c c₁ c₂ x : α} open_locale big_operators namespace function /-! ### Periodicity -/ /-- A function `f` is said to be `periodic` with period `c` if for all `x`, `f (x + c) = f x`. -/ @[simp] def periodic [has_add α] (f : α → β) (c : α) : Prop := ∀ x : α, f (x + c) = f x lemma periodic.funext [has_add α] (h : periodic f c) : (λ x, f (x + c)) = f := funext h lemma periodic.comp [has_add α] (h : periodic f c) (g : β → γ) : periodic (g ∘ f) c := by simp * at * lemma periodic.comp_add_hom [has_add α] [has_add γ] (h : periodic f c) (g : add_hom γ α) (g_inv : α → γ) (hg : right_inverse g_inv g) : periodic (f ∘ g) (g_inv c) := λ x, by simp only [hg c, h (g x), add_hom.map_add, comp_app] @[to_additive] lemma periodic.mul [has_add α] [has_mul β] (hf : periodic f c) (hg : periodic g c) : periodic (f * g) c := by simp * at * @[to_additive] lemma periodic.div [has_add α] [has_div β] (hf : periodic f c) (hg : periodic g c) : periodic (f / g) c := by simp * at * @[to_additive] lemma _root_.list.periodic_prod [has_add α] [comm_monoid β] (l : list (α → β)) (hl : ∀ f ∈ l, periodic f c) : periodic l.prod c := begin induction l with g l ih hl, { simp, }, { simp only [list.mem_cons_iff, forall_eq_or_imp] at hl, obtain ⟨hg, hl⟩ := hl, simp only [list.prod_cons], exact hg.mul (ih hl), }, end @[to_additive] lemma _root_.multiset.periodic_prod [has_add α] [comm_monoid β] (s : multiset (α → β)) (hs : ∀ f ∈ s, periodic f c) : periodic s.prod c := s.prod_to_list ▸ s.to_list.periodic_prod $ λ f hf, hs f $ multiset.mem_to_list.mp hf @[to_additive] lemma _root_.finset.periodic_prod [has_add α] [comm_monoid β] {ι : Type*} {f : ι → α → β} (s : finset ι) (hs : ∀ i ∈ s, periodic (f i) c) : periodic (∏ i in s, f i) c := s.prod_to_list f ▸ (s.to_list.map f).periodic_prod (by simpa [-periodic]) @[to_additive] lemma periodic.smul [has_add α] [has_smul γ β] (h : periodic f c) (a : γ) : periodic (a • f) c := by simp * at * lemma periodic.const_smul [add_monoid α] [group γ] [distrib_mul_action γ α] (h : periodic f c) (a : γ) : periodic (λ x, f (a • x)) (a⁻¹ • c) := λ x, by simpa only [smul_add, smul_inv_smul] using h (a • x) lemma periodic.const_smul₀ [add_comm_monoid α] [division_ring γ] [module γ α] (h : periodic f c) (a : γ) : periodic (λ x, f (a • x)) (a⁻¹ • c) := begin intro x, by_cases ha : a = 0, { simp only [ha, zero_smul] }, simpa only [smul_add, smul_inv_smul₀ ha] using h (a • x), end lemma periodic.const_mul [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (a * x)) (a⁻¹ * c) := h.const_smul₀ a lemma periodic.const_inv_smul [add_monoid α] [group γ] [distrib_mul_action γ α] (h : periodic f c) (a : γ) : periodic (λ x, f (a⁻¹ • x)) (a • c) := by simpa only [inv_inv] using h.const_smul a⁻¹ lemma periodic.const_inv_smul₀ [add_comm_monoid α] [division_ring γ] [module γ α] (h : periodic f c) (a : γ) : periodic (λ x, f (a⁻¹ • x)) (a • c) := by simpa only [inv_inv] using h.const_smul₀ a⁻¹ lemma periodic.const_inv_mul [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (a⁻¹ * x)) (a * c) := h.const_inv_smul₀ a lemma periodic.mul_const [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (x * a)) (c * a⁻¹) := h.const_smul₀ $ mul_opposite.op a lemma periodic.mul_const' [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (x * a)) (c / a) := by simpa only [div_eq_mul_inv] using h.mul_const a lemma periodic.mul_const_inv [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (x * a⁻¹)) (c * a) := h.const_inv_smul₀ $ mul_opposite.op a lemma periodic.div_const [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (x / a)) (c * a) := by simpa only [div_eq_mul_inv] using h.mul_const_inv a lemma periodic.add_period [add_semigroup α] (h1 : periodic f c₁) (h2 : periodic f c₂) : periodic f (c₁ + c₂) := by simp [*, ← add_assoc] at * lemma periodic.sub_eq [add_group α] (h : periodic f c) (x : α) : f (x - c) = f x := by simpa only [sub_add_cancel] using (h (x - c)).symm lemma periodic.sub_eq' [add_comm_group α] (h : periodic f c) : f (c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h (-x) lemma periodic.neg [add_group α] (h : periodic f c) : periodic f (-c) := by simpa only [sub_eq_add_neg, periodic] using h.sub_eq lemma periodic.sub_period [add_comm_group α] (h1 : periodic f c₁) (h2 : periodic f c₂) : periodic f (c₁ - c₂) := let h := h2.neg in by simp [*, sub_eq_add_neg, add_comm c₁, ← add_assoc] at * lemma periodic.const_add [add_semigroup α] (h : periodic f c) (a : α) : periodic (λ x, f (a + x)) c := λ x, by simpa [add_assoc] using h (a + x) lemma periodic.add_const [add_comm_semigroup α] (h : periodic f c) (a : α) : periodic (λ x, f (x + a)) c := λ x, by simpa [add_assoc x c a, add_comm c, ←add_assoc x a c] using h (x + a) lemma periodic.const_sub [add_comm_group α] (h : periodic f c) (a : α) : periodic (λ x, f (a - x)) c := begin rw [←neg_neg c], refine periodic.neg _, intro x, simpa [sub_add_eq_sub_sub] using h (a - x) end lemma periodic.sub_const [add_comm_group α] (h : periodic f c) (a : α) : periodic (λ x, f (x - a)) c := λ x, by simpa [add_comm x c, add_sub_assoc, add_comm c (x - a)] using h (x - a) lemma periodic.nsmul [add_monoid α] (h : periodic f c) (n : ℕ) : periodic f (n • c) := by induction n; simp [nat.succ_eq_add_one, add_nsmul, ← add_assoc, zero_nsmul, *] at * lemma periodic.nat_mul [semiring α] (h : periodic f c) (n : ℕ) : periodic f (n * c) := by simpa only [nsmul_eq_mul] using h.nsmul n lemma periodic.neg_nsmul [add_group α] (h : periodic f c) (n : ℕ) : periodic f (-(n • c)) := (h.nsmul n).neg lemma periodic.neg_nat_mul [ring α] (h : periodic f c) (n : ℕ) : periodic f (-(n * c)) := (h.nat_mul n).neg lemma periodic.sub_nsmul_eq [add_group α] (h : periodic f c) (n : ℕ) : f (x - n • c) = f x := by simpa only [sub_eq_add_neg] using h.neg_nsmul n x lemma periodic.sub_nat_mul_eq [ring α] (h : periodic f c) (n : ℕ) : f (x - n * c) = f x := by simpa only [nsmul_eq_mul] using h.sub_nsmul_eq n lemma periodic.nsmul_sub_eq [add_comm_group α] (h : periodic f c) (n : ℕ) : f (n • c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h.nsmul n (-x) lemma periodic.nat_mul_sub_eq [ring α] (h : periodic f c) (n : ℕ) : f (n * c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h.nat_mul n (-x) lemma periodic.zsmul [add_group α] (h : periodic f c) (n : ℤ) : periodic f (n • c) := begin cases n, { simpa only [int.of_nat_eq_coe, coe_nat_zsmul] using h.nsmul n }, { simpa only [zsmul_neg_succ_of_nat] using (h.nsmul n.succ).neg }, end lemma periodic.int_mul [ring α] (h : periodic f c) (n : ℤ) : periodic f (n * c) := by simpa only [zsmul_eq_mul] using h.zsmul n lemma periodic.sub_zsmul_eq [add_group α] (h : periodic f c) (n : ℤ) : f (x - n • c) = f x := (h.zsmul n).sub_eq x lemma periodic.sub_int_mul_eq [ring α] (h : periodic f c) (n : ℤ) : f (x - n * c) = f x := (h.int_mul n).sub_eq x lemma periodic.zsmul_sub_eq [add_comm_group α] (h : periodic f c) (n : ℤ) : f (n • c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h.zsmul n (-x) lemma periodic.int_mul_sub_eq [ring α] (h : periodic f c) (n : ℤ) : f (n * c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h.int_mul n (-x) lemma periodic.eq [add_zero_class α] (h : periodic f c) : f c = f 0 := by simpa only [zero_add] using h 0 lemma periodic.neg_eq [add_group α] (h : periodic f c) : f (-c) = f 0 := h.neg.eq lemma periodic.nsmul_eq [add_monoid α] (h : periodic f c) (n : ℕ) : f (n • c) = f 0 := (h.nsmul n).eq lemma periodic.nat_mul_eq [semiring α] (h : periodic f c) (n : ℕ) : f (n * c) = f 0 := (h.nat_mul n).eq lemma periodic.zsmul_eq [add_group α] (h : periodic f c) (n : ℤ) : f (n • c) = f 0 := (h.zsmul n).eq lemma periodic.int_mul_eq [ring α] (h : periodic f c) (n : ℤ) : f (n * c) = f 0 := (h.int_mul n).eq /-- If a function `f` is `periodic` with positive period `c`, then for all `x` there exists some `y ∈ Ico 0 c` such that `f x = f y`. -/ lemma periodic.exists_mem_Ico₀ [linear_ordered_add_comm_group α] [archimedean α] (h : periodic f c) (hc : 0 < c) (x) : ∃ y ∈ set.Ico 0 c, f x = f y := let ⟨n, H, _⟩ := exists_unique_zsmul_near_of_pos' hc x in ⟨x - n • c, H, (h.sub_zsmul_eq n).symm⟩ /-- If a function `f` is `periodic` with positive period `c`, then for all `x` there exists some `y ∈ Ico a (a + c)` such that `f x = f y`. -/ lemma periodic.exists_mem_Ico [linear_ordered_add_comm_group α] [archimedean α] (h : periodic f c) (hc : 0 < c) (x a) : ∃ y ∈ set.Ico a (a + c), f x = f y := let ⟨n, H, _⟩ := exists_unique_add_zsmul_mem_Ico hc x a in ⟨x + n • c, H, (h.zsmul n x).symm⟩ /-- If a function `f` is `periodic` with positive period `c`, then for all `x` there exists some `y ∈ Ioc a (a + c)` such that `f x = f y`. -/ lemma periodic.exists_mem_Ioc [linear_ordered_add_comm_group α] [archimedean α] (h : periodic f c) (hc : 0 < c) (x a) : ∃ y ∈ set.Ioc a (a + c), f x = f y := let ⟨n, H, _⟩ := exists_unique_add_zsmul_mem_Ioc hc x a in ⟨x + n • c, H, (h.zsmul n x).symm⟩ lemma periodic.image_Ioc [linear_ordered_add_comm_group α] [archimedean α] (h : periodic f c) (hc : 0 < c) (a : α) : f '' set.Ioc a (a + c) = set.range f := (set.image_subset_range _ _).antisymm $ set.range_subset_iff.2 $ λ x, let ⟨y, hy, hyx⟩ := h.exists_mem_Ioc hc x a in ⟨y, hy, hyx.symm⟩ lemma periodic_with_period_zero [add_zero_class α] (f : α → β) : periodic f 0 := λ x, by rw add_zero lemma periodic.map_vadd_zmultiples [add_comm_group α] (hf : periodic f c) (a : add_subgroup.zmultiples c) (x : α) : f (a +ᵥ x) = f x := by { rcases a with ⟨_, m, rfl⟩, simp [add_subgroup.vadd_def, add_comm _ x, hf.zsmul m x] } lemma periodic.map_vadd_multiples [add_comm_monoid α] (hf : periodic f c) (a : add_submonoid.multiples c) (x : α) : f (a +ᵥ x) = f x := by { rcases a with ⟨_, m, rfl⟩, simp [add_submonoid.vadd_def, add_comm _ x, hf.nsmul m x] } /-- Lift a periodic function to a function from the quotient group. -/ def periodic.lift [add_group α] (h : periodic f c) (x : α ⧸ add_subgroup.zmultiples c) : β := quotient.lift_on' x f $ λ a b h', (begin rw quotient_add_group.left_rel_apply at h', obtain ⟨k, hk⟩ := h', exact (h.zsmul k _).symm.trans (congr_arg f (add_eq_of_eq_neg_add hk)), end) @[simp] lemma periodic.lift_coe [add_group α] (h : periodic f c) (a : α) : h.lift (a : α ⧸ add_subgroup.zmultiples c) = f a := rfl /-! ### Antiperiodicity -/ /-- A function `f` is said to be `antiperiodic` with antiperiod `c` if for all `x`, `f (x + c) = -f x`. -/ @[simp] def antiperiodic [has_add α] [has_neg β] (f : α → β) (c : α) : Prop := ∀ x : α, f (x + c) = -f x lemma antiperiodic.funext [has_add α] [has_neg β] (h : antiperiodic f c) : (λ x, f (x + c)) = -f := funext h lemma antiperiodic.funext' [has_add α] [has_involutive_neg β] (h : antiperiodic f c) : (λ x, -f (x + c)) = f := (eq_neg_iff_eq_neg.mp h.funext).symm /-- If a function is `antiperiodic` with antiperiod `c`, then it is also `periodic` with period `2 * c`. -/ lemma antiperiodic.periodic [semiring α] [has_involutive_neg β] (h : antiperiodic f c) : periodic f (2 * c) := by simp [two_mul, ← add_assoc, h _] lemma antiperiodic.eq [add_zero_class α] [has_neg β] (h : antiperiodic f c) : f c = -f 0 := by simpa only [zero_add] using h 0 lemma antiperiodic.nat_even_mul_periodic [semiring α] [has_involutive_neg β] (h : antiperiodic f c) (n : ℕ) : periodic f (n * (2 * c)) := h.periodic.nat_mul n lemma antiperiodic.nat_odd_mul_antiperiodic [semiring α] [has_involutive_neg β] (h : antiperiodic f c) (n : ℕ) : antiperiodic f (n * (2 * c) + c) := λ x, by rw [← add_assoc, h, h.periodic.nat_mul] lemma antiperiodic.int_even_mul_periodic [ring α] [has_involutive_neg β] (h : antiperiodic f c) (n : ℤ) : periodic f (n * (2 * c)) := h.periodic.int_mul n lemma antiperiodic.int_odd_mul_antiperiodic [ring α] [has_involutive_neg β] (h : antiperiodic f c) (n : ℤ) : antiperiodic f (n * (2 * c) + c) := λ x, by rw [← add_assoc, h, h.periodic.int_mul] lemma antiperiodic.nat_mul_eq_of_eq_zero [comm_semiring α] [neg_zero_class β] (h : antiperiodic f c) (hi : f 0 = 0) (n : ℕ) : f (n * c) = 0 := begin induction n with k hk, { simp [hi] }, { simp [hk, add_mul, h (k * c)] } end lemma antiperiodic.int_mul_eq_of_eq_zero [comm_ring α] [subtraction_monoid β] (h : antiperiodic f c) (hi : f 0 = 0) (n : ℤ) : f (n * c) = 0 := begin rcases int.even_or_odd n with ⟨k, rfl⟩ | ⟨k, rfl⟩; have hk : (k : α) * (2 * c) = 2 * k * c := by rw [mul_left_comm, ← mul_assoc], { simpa [← two_mul, hk, hi] using (h.int_even_mul_periodic k).eq }, { simpa [add_mul, hk, hi] using (h.int_odd_mul_antiperiodic k).eq }, end lemma antiperiodic.sub_eq [add_group α] [has_involutive_neg β] (h : antiperiodic f c) (x : α) : f (x - c) = -f x := by simp only [eq_neg_iff_eq_neg.mp (h (x - c)), sub_add_cancel] lemma antiperiodic.sub_eq' [add_comm_group α] [has_neg β] (h : antiperiodic f c) : f (c - x) = -f (-x) := by simpa only [sub_eq_neg_add] using h (-x) lemma antiperiodic.neg [add_group α] [has_involutive_neg β] (h : antiperiodic f c) : antiperiodic f (-c) := by simpa only [sub_eq_add_neg, antiperiodic] using h.sub_eq lemma antiperiodic.neg_eq [add_group α] [has_involutive_neg β] (h : antiperiodic f c) : f (-c) = -f 0 := by simpa only [zero_add] using h.neg 0 lemma antiperiodic.const_add [add_semigroup α] [has_neg β] (h : antiperiodic f c) (a : α) : antiperiodic (λ x, f (a + x)) c := λ x, by simpa [add_assoc] using h (a + x) lemma antiperiodic.add_const [add_comm_semigroup α] [has_neg β] (h : antiperiodic f c) (a : α) : antiperiodic (λ x, f (x + a)) c := λ x, by simpa [add_assoc x c a, add_comm c, ←add_assoc x a c] using h (x + a) lemma antiperiodic.const_sub [add_comm_group α] [has_involutive_neg β] (h : antiperiodic f c) (a : α) : antiperiodic (λ x, f (a - x)) c := begin rw [←neg_neg c], refine antiperiodic.neg _, intro x, simpa [sub_add_eq_sub_sub] using h (a - x) end lemma antiperiodic.sub_const [add_comm_group α] [has_neg β] (h : antiperiodic f c) (a : α) : antiperiodic (λ x, f (x - a)) c := λ x, by simpa [add_comm x c, add_sub_assoc, add_comm c (x - a)] using h (x - a) lemma antiperiodic.smul [has_add α] [monoid γ] [add_group β] [distrib_mul_action γ β] (h : antiperiodic f c) (a : γ) : antiperiodic (a • f) c := by simp * at * lemma antiperiodic.const_smul [add_monoid α] [has_neg β] [group γ] [distrib_mul_action γ α] (h : antiperiodic f c) (a : γ) : antiperiodic (λ x, f (a • x)) (a⁻¹ • c) := λ x, by simpa only [smul_add, smul_inv_smul] using h (a • x) lemma antiperiodic.const_smul₀ [add_comm_monoid α] [has_neg β] [division_ring γ] [module γ α] (h : antiperiodic f c) {a : γ} (ha : a ≠ 0) : antiperiodic (λ x, f (a • x)) (a⁻¹ • c) := λ x, by simpa only [smul_add, smul_inv_smul₀ ha] using h (a • x) lemma antiperiodic.const_mul [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (a * x)) (a⁻¹ * c) := h.const_smul₀ ha lemma antiperiodic.const_inv_smul [add_monoid α] [has_neg β] [group γ] [distrib_mul_action γ α] (h : antiperiodic f c) (a : γ) : antiperiodic (λ x, f (a⁻¹ • x)) (a • c) := by simpa only [inv_inv] using h.const_smul a⁻¹ lemma antiperiodic.const_inv_smul₀ [add_comm_monoid α] [has_neg β] [division_ring γ] [module γ α] (h : antiperiodic f c) {a : γ} (ha : a ≠ 0) : antiperiodic (λ x, f (a⁻¹ • x)) (a • c) := by simpa only [inv_inv] using h.const_smul₀ (inv_ne_zero ha) lemma antiperiodic.const_inv_mul [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (a⁻¹ * x)) (a * c) := h.const_inv_smul₀ ha lemma antiperiodic.mul_const [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (x * a)) (c * a⁻¹) := h.const_smul₀ $ (mul_opposite.op_ne_zero_iff a).mpr ha lemma antiperiodic.mul_const' [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (x * a)) (c / a) := by simpa only [div_eq_mul_inv] using h.mul_const ha lemma antiperiodic.mul_const_inv [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (x * a⁻¹)) (c * a) := h.const_inv_smul₀ $ (mul_opposite.op_ne_zero_iff a).mpr ha lemma antiperiodic.div_inv [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (x / a)) (c * a) := by simpa only [div_eq_mul_inv] using h.mul_const_inv ha lemma antiperiodic.add [add_group α] [has_involutive_neg β] (h1 : antiperiodic f c₁) (h2 : antiperiodic f c₂) : periodic f (c₁ + c₂) := by simp [*, ← add_assoc] at * lemma antiperiodic.sub [add_comm_group α] [has_involutive_neg β] (h1 : antiperiodic f c₁) (h2 : antiperiodic f c₂) : periodic f (c₁ - c₂) := let h := h2.neg in by simp [*, sub_eq_add_neg, add_comm c₁, ← add_assoc] at * lemma periodic.add_antiperiod [add_group α] [has_neg β] (h1 : periodic f c₁) (h2 : antiperiodic f c₂) : antiperiodic f (c₁ + c₂) := by simp [*, ← add_assoc] at * lemma periodic.sub_antiperiod [add_comm_group α] [has_involutive_neg β] (h1 : periodic f c₁) (h2 : antiperiodic f c₂) : antiperiodic f (c₁ - c₂) := let h := h2.neg in by simp [*, sub_eq_add_neg, add_comm c₁, ← add_assoc] at * lemma periodic.add_antiperiod_eq [add_group α] [has_neg β] (h1 : periodic f c₁) (h2 : antiperiodic f c₂) : f (c₁ + c₂) = -f 0 := (h1.add_antiperiod h2).eq lemma periodic.sub_antiperiod_eq [add_comm_group α] [has_involutive_neg β] (h1 : periodic f c₁) (h2 : antiperiodic f c₂) : f (c₁ - c₂) = -f 0 := (h1.sub_antiperiod h2).eq lemma antiperiodic.mul [has_add α] [has_mul β] [has_distrib_neg β] (hf : antiperiodic f c) (hg : antiperiodic g c) : periodic (f * g) c := by simp * at * lemma antiperiodic.div [has_add α] [division_monoid β] [has_distrib_neg β] (hf : antiperiodic f c) (hg : antiperiodic g c) : periodic (f / g) c := by simp [*, neg_div_neg_eq] at * end function lemma int.fract_periodic (α) [linear_ordered_ring α] [floor_ring α] : function.periodic int.fract (1 : α) := by exact_mod_cast λ a, int.fract_add_int a 1
f1f05f7d1a825dedceb3089655a59c842df06f86
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/group_theory/coset.lean
a97463113e5a8e518a0afac03caa093fffb8cedd
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
9,208
lean
/- Copyright (c) 2018 Mitchell Rowett. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mitchell Rowett, Scott Morrison -/ import deprecated.subgroup open set function variable {α : Type*} @[to_additive left_add_coset] def left_coset [has_mul α] (a : α) (s : set α) : set α := (λ x, a * x) '' s @[to_additive right_add_coset] def right_coset [has_mul α] (s : set α) (a : α) : set α := (λ x, x * a) '' s localized "infix ` *l `:70 := left_coset" in coset localized "infix ` +l `:70 := left_add_coset" in coset localized "infix ` *r `:70 := right_coset" in coset localized "infix ` +r `:70 := right_add_coset" in coset section coset_mul variable [has_mul α] @[to_additive mem_left_add_coset] lemma mem_left_coset {s : set α} {x : α} (a : α) (hxS : x ∈ s) : a * x ∈ a *l s := mem_image_of_mem (λ b : α, a * b) hxS @[to_additive mem_right_add_coset] lemma mem_right_coset {s : set α} {x : α} (a : α) (hxS : x ∈ s) : x * a ∈ s *r a := mem_image_of_mem (λ b : α, b * a) hxS @[to_additive left_add_coset_equiv] def left_coset_equiv (s : set α) (a b : α) := a *l s = b *l s @[to_additive left_add_coset_equiv_rel] lemma left_coset_equiv_rel (s : set α) : equivalence (left_coset_equiv s) := mk_equivalence (left_coset_equiv s) (λ a, rfl) (λ a b, eq.symm) (λ a b c, eq.trans) end coset_mul section coset_semigroup variable [semigroup α] @[simp] lemma left_coset_assoc (s : set α) (a b : α) : a *l (b *l s) = (a * b) *l s := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] attribute [to_additive left_add_coset_assoc] left_coset_assoc @[simp] lemma right_coset_assoc (s : set α) (a b : α) : s *r a *r b = s *r (a * b) := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] attribute [to_additive right_add_coset_assoc] right_coset_assoc @[to_additive left_add_coset_right_add_coset] lemma left_coset_right_coset (s : set α) (a b : α) : a *l s *r b = a *l (s *r b) := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] end coset_semigroup section coset_monoid variables [monoid α] (s : set α) @[simp] lemma one_left_coset : 1 *l s = s := set.ext $ by simp [left_coset] attribute [to_additive zero_left_add_coset] one_left_coset @[simp] lemma right_coset_one : s *r 1 = s := set.ext $ by simp [right_coset] attribute [to_additive right_add_coset_zero] right_coset_one end coset_monoid section coset_submonoid open submonoid variables [monoid α] (s : submonoid α) @[to_additive mem_own_left_add_coset] lemma mem_own_left_coset (a : α) : a ∈ a *l s := suffices a * 1 ∈ a *l s, by simpa, mem_left_coset a (one_mem s) @[to_additive mem_own_right_add_coset] lemma mem_own_right_coset (a : α) : a ∈ (s : set α) *r a := suffices 1 * a ∈ (s : set α) *r a, by simpa, mem_right_coset a (one_mem s) @[to_additive mem_left_add_coset_left_add_coset] lemma mem_left_coset_left_coset {a : α} (ha : a *l s = s) : a ∈ s := by rw [←submonoid.mem_coe, ←ha]; exact mem_own_left_coset s a @[to_additive mem_right_add_coset_right_add_coset] lemma mem_right_coset_right_coset {a : α} (ha : (s : set α) *r a = s) : a ∈ s := by rw [←submonoid.mem_coe, ←ha]; exact mem_own_right_coset s a end coset_submonoid section coset_group variables [group α] {s : set α} {x : α} @[to_additive mem_left_add_coset_iff] lemma mem_left_coset_iff (a : α) : x ∈ a *l s ↔ a⁻¹ * x ∈ s := iff.intro (assume ⟨b, hb, eq⟩, by simp [eq.symm, hb]) (assume h, ⟨a⁻¹ * x, h, by simp⟩) @[to_additive mem_right_add_coset_iff] lemma mem_right_coset_iff (a : α) : x ∈ s *r a ↔ x * a⁻¹ ∈ s := iff.intro (assume ⟨b, hb, eq⟩, by simp [eq.symm, hb]) (assume h, ⟨x * a⁻¹, h, by simp⟩) end coset_group section coset_subgroup open submonoid open is_subgroup variables [group α] (s : set α) [is_subgroup s] @[to_additive left_add_coset_mem_left_add_coset] lemma left_coset_mem_left_coset {a : α} (ha : a ∈ s) : a *l s = s := set.ext $ by simp [mem_left_coset_iff, mul_mem_cancel_left s (inv_mem ha)] @[to_additive right_add_coset_mem_right_add_coset] lemma right_coset_mem_right_coset {a : α} (ha : a ∈ s) : s *r a = s := set.ext $ assume b, by simp [mem_right_coset_iff, mul_mem_cancel_right s (inv_mem ha)] @[to_additive normal_of_eq_add_cosets] theorem normal_of_eq_cosets [normal_subgroup s] (g : α) : g *l s = s *r g := set.ext $ assume a, by simp [mem_left_coset_iff, mem_right_coset_iff]; rw [mem_norm_comm_iff] @[to_additive eq_add_cosets_of_normal] theorem eq_cosets_of_normal (h : ∀ g, g *l s = s *r g) : normal_subgroup s := ⟨assume a ha g, show g * a * g⁻¹ ∈ s, by rw [← mem_right_coset_iff, ← h]; exact mem_left_coset g ha⟩ @[to_additive normal_iff_eq_add_cosets] theorem normal_iff_eq_cosets : normal_subgroup s ↔ ∀ g, g *l s = s *r g := ⟨@normal_of_eq_cosets _ _ s _, eq_cosets_of_normal s⟩ end coset_subgroup run_cmd to_additive.map_namespace `quotient_group `quotient_add_group namespace quotient_group @[to_additive] def left_rel [group α] (s : set α) [is_subgroup s] : setoid α := ⟨λ x y, x⁻¹ * y ∈ s, assume x, by simp [is_submonoid.one_mem], assume x y hxy, have (x⁻¹ * y)⁻¹ ∈ s, from is_subgroup.inv_mem hxy, by simpa using this, assume x y z hxy hyz, have x⁻¹ * y * (y⁻¹ * z) ∈ s, from is_submonoid.mul_mem hxy hyz, by simpa [mul_assoc] using this⟩ /-- `quotient s` is the quotient type representing the left cosets of `s`. If `s` is a normal subgroup, `quotient s` is a group -/ @[to_additive] def quotient [group α] (s : set α) [is_subgroup s] : Type* := quotient (left_rel s) variables [group α] {s : set α} [is_subgroup s] @[to_additive] def mk (a : α) : quotient s := quotient.mk' a @[elab_as_eliminator, to_additive] lemma induction_on {C : quotient s → Prop} (x : quotient s) (H : ∀ z, C (quotient_group.mk z)) : C x := quotient.induction_on' x H @[to_additive] instance : has_coe_t α (quotient s) := ⟨mk⟩ -- note [use has_coe_t] @[elab_as_eliminator, to_additive] lemma induction_on' {C : quotient s → Prop} (x : quotient s) (H : ∀ z : α, C z) : C x := quotient.induction_on' x H @[to_additive] instance [group α] (s : set α) [is_subgroup s] : inhabited (quotient s) := ⟨((1 : α) : quotient s)⟩ @[to_additive quotient_add_group.eq] protected lemma eq {a b : α} : (a : quotient s) = b ↔ a⁻¹ * b ∈ s := quotient.eq' @[to_additive] lemma eq_class_eq_left_coset [group α] (s : set α) [is_subgroup s] (g : α) : {x : α | (x : quotient s) = g} = left_coset g s := set.ext $ λ z, by rw [mem_left_coset_iff, set.mem_set_of_eq, eq_comm, quotient_group.eq] end quotient_group namespace is_subgroup open quotient_group variables [group α] {s : set α} @[to_additive] def left_coset_equiv_subgroup (g : α) : left_coset g s ≃ s := ⟨λ x, ⟨g⁻¹ * x.1, (mem_left_coset_iff _).1 x.2⟩, λ x, ⟨g * x.1, x.1, x.2, rfl⟩, λ ⟨x, hx⟩, subtype.eq $ by simp, λ ⟨g, hg⟩, subtype.eq $ by simp⟩ @[to_additive] noncomputable def group_equiv_quotient_times_subgroup (hs : is_subgroup s) : α ≃ quotient s × s := calc α ≃ Σ L : quotient s, {x : α // (x : quotient s)= L} : (equiv.sigma_preimage_equiv quotient_group.mk).symm ... ≃ Σ L : quotient s, left_coset (quotient.out' L) s : equiv.sigma_congr_right (λ L, begin rw ← eq_class_eq_left_coset, show {x // quotient.mk' x = L} ≃ {x : α // quotient.mk' x = quotient.mk' _}, simp [-quotient.eq'] end) ... ≃ Σ L : quotient s, s : equiv.sigma_congr_right (λ L, left_coset_equiv_subgroup _) ... ≃ quotient s × s : equiv.sigma_equiv_prod _ _ end is_subgroup namespace quotient_group variables [group α] noncomputable def preimage_mk_equiv_subgroup_times_set (s : set α) [is_subgroup s] (t : set (quotient s)) : quotient_group.mk ⁻¹' t ≃ s × t := have h : ∀ {x : quotient s} {a : α}, x ∈ t → a ∈ s → (quotient.mk' (quotient.out' x * a) : quotient s) = quotient.mk' (quotient.out' x) := λ x a hx ha, quotient.sound' (show (quotient.out' x * a)⁻¹ * quotient.out' x ∈ s, from (is_subgroup.inv_mem_iff _).1 $ by rwa [mul_inv_rev, inv_inv, ← mul_assoc, inv_mul_self, one_mul]), { to_fun := λ ⟨a, ha⟩, ⟨⟨(quotient.out' (quotient.mk' a))⁻¹ * a, @quotient.exact' _ (left_rel s) _ _ $ (quotient.out_eq' _)⟩, ⟨quotient.mk' a, ha⟩⟩, inv_fun := λ ⟨⟨a, ha⟩, ⟨x, hx⟩⟩, ⟨quotient.out' x * a, show quotient.mk' _ ∈ t, by simp [h hx ha, hx]⟩, left_inv := λ ⟨a, ha⟩, subtype.eq $ show _ * _ = a, by simp, right_inv := λ ⟨⟨a, ha⟩, ⟨x, hx⟩⟩, show (_, _) = _, by simp [h hx ha] } end quotient_group /-- We use the class `has_coe_t` instead of `has_coe` if the first argument is a variable, or if the second argument is a variable not occurring in the first. Using `has_coe` would cause looping of type-class inference. See <https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/remove.20all.20instances.20with.20variable.20domain> -/ library_note "use has_coe_t"
60e6ab083d5f620560add30deec512c3a825357f
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/lie/abelian.lean
839f700ca0978f4383d4076818e566b9dc02546c
[ "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
10,811
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.of_associative import algebra.lie.ideal_operations /-! # Trivial Lie modules and Abelian Lie algebras The action of a Lie algebra `L` on a module `M` is trivial if `⁅x, m⁆ = 0` for all `x ∈ L` and `m ∈ M`. In the special case that `M = L` with the adjoint action, triviality corresponds to the concept of an Abelian Lie algebra. In this file we define these concepts and provide some related definitions and results. ## Main definitions * `lie_module.is_trivial` * `is_lie_abelian` * `commutative_ring_iff_abelian_lie_ring` * `lie_module.ker` * `lie_module.max_triv_submodule` * `lie_algebra.center` ## Tags lie algebra, abelian, commutative, center -/ universes u v w w₁ w₂ /-- A Lie (ring) module is trivial iff all brackets vanish. -/ class lie_module.is_trivial (L : Type v) (M : Type w) [has_bracket L M] [has_zero M] : Prop := (trivial : ∀ (x : L) (m : M), ⁅x, m⁆ = 0) @[simp] lemma trivial_lie_zero (L : Type v) (M : Type w) [has_bracket L M] [has_zero M] [lie_module.is_trivial L M] (x : L) (m : M) : ⁅x, m⁆ = 0 := lie_module.is_trivial.trivial x m /-- A Lie algebra is Abelian iff it is trivial as a Lie module over itself. -/ abbreviation is_lie_abelian (L : Type v) [has_bracket L L] [has_zero L] : Prop := lie_module.is_trivial L L instance lie_ideal.is_lie_abelian_of_trivial (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] (I : lie_ideal R L) [h : lie_module.is_trivial L I] : is_lie_abelian I := { trivial := λ x y, by apply h.trivial } lemma function.injective.is_lie_abelian {R : Type u} {L₁ : Type v} {L₂ : Type w} [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_algebra R L₁] [lie_algebra R L₂] {f : L₁ →ₗ⁅R⁆ L₂} (h₁ : function.injective f) (h₂ : is_lie_abelian L₂) : is_lie_abelian L₁ := { trivial := λ x y, h₁ $ calc f ⁅x,y⁆ = ⁅f x, f y⁆ : lie_hom.map_lie f x y ... = 0 : trivial_lie_zero _ _ _ _ ... = f 0 : f.map_zero.symm } lemma function.surjective.is_lie_abelian {R : Type u} {L₁ : Type v} {L₂ : Type w} [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_algebra R L₁] [lie_algebra R L₂] {f : L₁ →ₗ⁅R⁆ L₂} (h₁ : function.surjective f) (h₂ : is_lie_abelian L₁) : is_lie_abelian L₂ := { trivial := λ x y, begin obtain ⟨u, rfl⟩ := h₁ x, obtain ⟨v, rfl⟩ := h₁ y, rw [← lie_hom.map_lie, trivial_lie_zero, lie_hom.map_zero], end } lemma lie_abelian_iff_equiv_lie_abelian {R : Type u} {L₁ : Type v} {L₂ : Type w} [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_algebra R L₁] [lie_algebra R L₂] (e : L₁ ≃ₗ⁅R⁆ L₂) : is_lie_abelian L₁ ↔ is_lie_abelian L₂ := ⟨e.symm.injective.is_lie_abelian, e.injective.is_lie_abelian⟩ lemma commutative_ring_iff_abelian_lie_ring {A : Type v} [ring A] : is_commutative A (*) ↔ is_lie_abelian A := have h₁ : is_commutative A (*) ↔ ∀ (a b : A), a * b = b * a := ⟨λ h, h.1, λ h, ⟨h⟩⟩, have h₂ : is_lie_abelian A ↔ ∀ (a b : A), ⁅a, b⁆ = 0 := ⟨λ h, h.1, λ h, ⟨h⟩⟩, by simp only [h₁, h₂, lie_ring.of_associative_ring_bracket, sub_eq_zero] lemma lie_algebra.is_lie_abelian_bot (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] : is_lie_abelian (⊥ : lie_ideal R L) := ⟨λ ⟨x, hx⟩ _, by convert zero_lie _⟩ section center variables (R : Type u) (L : Type v) (M : Type w) (N : Type w₁) variables [comm_ring R] [lie_ring L] [lie_algebra R L] variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M] variables [add_comm_group N] [module R N] [lie_ring_module L N] [lie_module R L N] namespace lie_module /-- The kernel of the action of a Lie algebra `L` on a Lie module `M` as a Lie ideal in `L`. -/ protected def ker : lie_ideal R L := (to_endomorphism R L M).ker @[simp] protected lemma mem_ker (x : L) : x ∈ lie_module.ker R L M ↔ ∀ (m : M), ⁅x, m⁆ = 0 := by simp only [lie_module.ker, lie_hom.mem_ker, linear_map.ext_iff, linear_map.zero_apply, to_endomorphism_apply_apply] /-- The largest submodule of a Lie module `M` on which the Lie algebra `L` acts trivially. -/ def max_triv_submodule : lie_submodule R L M := { carrier := { m | ∀ (x : L), ⁅x, m⁆ = 0 }, zero_mem' := λ x, lie_zero x, add_mem' := λ x y hx hy z, by rw [lie_add, hx, hy, add_zero], smul_mem' := λ c x hx y, by rw [lie_smul, hx, smul_zero], lie_mem := λ x m hm y, by rw [hm, lie_zero], } @[simp] lemma mem_max_triv_submodule (m : M) : m ∈ max_triv_submodule R L M ↔ ∀ (x : L), ⁅x, m⁆ = 0 := iff.rfl instance : is_trivial L (max_triv_submodule R L M) := { trivial := λ x m, subtype.ext (m.property x), } lemma trivial_iff_le_maximal_trivial (N : lie_submodule R L M) : is_trivial L N ↔ N ≤ max_triv_submodule R L M := ⟨ λ h m hm x, is_trivial.dcases_on h (λ h, subtype.ext_iff.mp (h x ⟨m, hm⟩)), λ h, { trivial := λ x m, subtype.ext (h m.2 x) }⟩ lemma is_trivial_iff_max_triv_eq_top : is_trivial L M ↔ max_triv_submodule R L M = ⊤ := begin split, { rintros ⟨h⟩, ext, simp only [mem_max_triv_submodule, h, forall_const, true_iff, eq_self_iff_true], }, { intros h, constructor, intros x m, revert x, rw [← mem_max_triv_submodule R L M, h], exact lie_submodule.mem_top m, }, end variables {R L M N} /-- `max_triv_submodule` is functorial. -/ def max_triv_hom (f : M →ₗ⁅R,L⁆ N) : max_triv_submodule R L M →ₗ⁅R,L⁆ max_triv_submodule R L N := { to_fun := λ m, ⟨f m, λ x, (lie_module_hom.map_lie _ _ _).symm.trans $ (congr_arg f (m.property x)).trans (lie_module_hom.map_zero _)⟩, map_add' := λ m n, by simpa, map_smul' := λ t m, by simpa, map_lie' := λ x m, by simp, } @[norm_cast, simp] lemma coe_max_triv_hom_apply (f : M →ₗ⁅R,L⁆ N) (m : max_triv_submodule R L M) : (max_triv_hom f m : N) = f m := rfl /-- The maximal trivial submodules of Lie-equivalent Lie modules are Lie-equivalent. -/ def max_triv_equiv (e : M ≃ₗ⁅R,L⁆ N) : max_triv_submodule R L M ≃ₗ⁅R,L⁆ max_triv_submodule R L N := { to_fun := max_triv_hom (e : M →ₗ⁅R,L⁆ N), inv_fun := max_triv_hom (e.symm : N →ₗ⁅R,L⁆ M), left_inv := λ m, by { ext, simp, }, right_inv := λ n, by { ext, simp, }, .. max_triv_hom (e : M →ₗ⁅R,L⁆ N), } @[norm_cast, simp] lemma coe_max_triv_equiv_apply (e : M ≃ₗ⁅R,L⁆ N) (m : max_triv_submodule R L M) : (max_triv_equiv e m : N) = e ↑m := rfl @[simp] lemma max_triv_equiv_of_refl_eq_refl : max_triv_equiv (lie_module_equiv.refl : M ≃ₗ⁅R,L⁆ M) = lie_module_equiv.refl := by { ext, simp only [coe_max_triv_equiv_apply, lie_module_equiv.refl_apply], } @[simp] lemma max_triv_equiv_of_equiv_symm_eq_symm (e : M ≃ₗ⁅R,L⁆ N) : (max_triv_equiv e).symm = max_triv_equiv e.symm := rfl /-- A linear map between two Lie modules is a morphism of Lie modules iff the Lie algebra action on it is trivial. -/ def max_triv_linear_map_equiv_lie_module_hom : (max_triv_submodule R L (M →ₗ[R] N)) ≃ₗ[R] (M →ₗ⁅R,L⁆ N) := { to_fun := λ f, { to_linear_map := f.val, map_lie' := λ x m, by { have hf : ⁅x, f.val⁆ m = 0, { rw [f.property x, linear_map.zero_apply], }, rw [lie_hom.lie_apply, sub_eq_zero, ← linear_map.to_fun_eq_coe] at hf, exact hf.symm, }, }, map_add' := λ f g, by { ext, simp, }, map_smul' := λ F G, by { ext, simp, }, inv_fun := λ F, ⟨F, λ x, by { ext, simp, }⟩, left_inv := λ f, by simp, right_inv := λ F, by simp, } @[simp] lemma coe_max_triv_linear_map_equiv_lie_module_hom (f : max_triv_submodule R L (M →ₗ[R] N)) : ((max_triv_linear_map_equiv_lie_module_hom f) : M → N) = f := by { ext, refl, } @[simp] lemma coe_max_triv_linear_map_equiv_lie_module_hom_symm (f : M →ₗ⁅R,L⁆ N) : ((max_triv_linear_map_equiv_lie_module_hom.symm f) : M → N) = f := rfl @[simp] lemma coe_linear_map_max_triv_linear_map_equiv_lie_module_hom (f : max_triv_submodule R L (M →ₗ[R] N)) : ((max_triv_linear_map_equiv_lie_module_hom f) : M →ₗ[R] N) = (f : M →ₗ[R] N) := by { ext, refl, } @[simp] lemma coe_linear_map_max_triv_linear_map_equiv_lie_module_hom_symm (f : M →ₗ⁅R,L⁆ N) : ((max_triv_linear_map_equiv_lie_module_hom.symm f) : M →ₗ[R] N) = (f : M →ₗ[R] N) := rfl end lie_module namespace lie_algebra /-- The center of a Lie algebra is the set of elements that commute with everything. It can be viewed as the maximal trivial submodule of the Lie algebra as a Lie module over itself via the adjoint representation. -/ abbreviation center : lie_ideal R L := lie_module.max_triv_submodule R L L instance : is_lie_abelian (center R L) := infer_instance @[simp] lemma ad_ker_eq_self_module_ker : (ad R L).ker = lie_module.ker R L L := rfl @[simp] lemma self_module_ker_eq_center : lie_module.ker R L L = center R L := begin ext y, simp only [lie_module.mem_max_triv_submodule, lie_module.mem_ker, ← lie_skew _ y, neg_eq_zero], end lemma abelian_of_le_center (I : lie_ideal R L) (h : I ≤ center R L) : is_lie_abelian I := begin haveI : lie_module.is_trivial L I := (lie_module.trivial_iff_le_maximal_trivial R L L I).mpr h, exact lie_ideal.is_lie_abelian_of_trivial R L I, end lemma is_lie_abelian_iff_center_eq_top : is_lie_abelian L ↔ center R L = ⊤ := lie_module.is_trivial_iff_max_triv_eq_top R L L end lie_algebra end center section ideal_operations open lie_submodule lie_subalgebra variables {R : Type u} {L : Type v} {M : Type w} variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M] variables [lie_ring_module L M] [lie_module R L M] variables (N N' : lie_submodule R L M) (I J : lie_ideal R L) @[simp] lemma lie_submodule.trivial_lie_oper_zero [lie_module.is_trivial L M] : ⁅I, N⁆ = ⊥ := begin suffices : ⁅I, N⁆ ≤ ⊥, from le_bot_iff.mp this, rw [lie_ideal_oper_eq_span, lie_submodule.lie_span_le], rintros m ⟨x, n, h⟩, rw trivial_lie_zero at h, simp [← h], end lemma lie_submodule.lie_abelian_iff_lie_self_eq_bot : is_lie_abelian I ↔ ⁅I, I⁆ = ⊥ := begin simp only [_root_.eq_bot_iff, lie_ideal_oper_eq_span, lie_submodule.lie_span_le, lie_submodule.bot_coe, set.subset_singleton_iff, set.mem_set_of_eq, exists_imp_distrib], refine ⟨λ h z x y hz, hz.symm.trans ((lie_subalgebra.coe_bracket _ _ _).symm.trans ((coe_zero_iff_zero _ _).mpr (by apply h.trivial))), λ h, ⟨λ x y, (coe_zero_iff_zero _ _).mp (h _ x y rfl)⟩⟩, end end ideal_operations
cc490882bb56d44aac33240802c81ec21e65d560
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/tests/lean/run/doNotation2.lean
684f0f4608b92a5429bf80441c235ca30857ab6f
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,046
lean
def f (x : Nat) : IO Nat := do IO.println "hello world" let aux (y : Nat) (z : Nat) : IO Nat := do IO.println "aux started" IO.println s!"y: {y}, z: {z}" pure (x+y) aux x (x + 1) -- It is part of the application since it is indented aux x (x -- parentheses use `withoutPosition` -1) aux x x; aux x x #eval f 10 def g (xs : List Nat) : StateT Nat Id Nat := do let mut xs := xs if xs.isEmpty then xs := [← get] dbgTrace! ">>> xs: {xs}" return xs.length #eval g [1, 2, 3] $.run' 10 #eval g [] $.run' 10 theorem ex1 : (g [1, 2, 4, 5] $.run' 0) = 4 := rfl theorem ex2 : (g [] $.run' 0) = 1 := rfl def h (x : Nat) (y : Nat) : Nat := do let mut x := x let mut y := y if x > 0 then let y := x + 1 -- this is a new `y` that shadows the one above x := y else y := y + 1 return x + y theorem ex3 (y : Nat) : h 0 y = 0 + (y + 1) := rfl theorem ex4 (y : Nat) : h 1 y = (1 + 1) + y := rfl def sumOdd (xs : List Nat) (threshold : Nat) : Nat := do let mut sum := 0 for x in xs do if x % 2 == 1 then sum := sum + x if sum > threshold then break unless x % 2 == 1 do continue dbgTrace! ">> x: {x}" return sum #eval sumOdd [1, 2, 3, 4, 5, 6, 7, 9, 11, 101] 10 theorem ex5 : sumOdd [1, 2, 3, 4, 5, 6, 7, 9, 11, 101] 10 = 16 := rfl -- We need `Id.run` because we still have `Monad Option` def find? (xs : List Nat) (p : Nat → Bool) : Option Nat := Id.run do let mut result := none for x in xs do if p x then result := x break return result def sumDiff (ps : List (Nat × Nat)) : Nat := do let mut sum := 0 for (x, y) in ps do sum := sum + x - y return sum theorem ex7 : sumDiff [(2, 1), (10, 5)] = 6 := rfl def f1 (x : Nat) : IO Unit := do let rec loop : Nat → IO Unit | 0 => pure () | x+1 => do IO.println x; loop x loop x #eval f1 10 partial def f2 (x : Nat) : IO Unit := do let rec isEven : Nat → Bool | 0 => true | x+1 => isOdd x, isOdd : Nat → Bool | 0 => false | x+1 => isEven x IO.println ("isOdd(" ++ toString x ++ "): " ++ toString (isOdd x)) #eval f2 11 #eval f2 10 def split (xs : List Nat) : List Nat × List Nat := do let mut evens := [] let mut odds := [] for x in xs.reverse do if x % 2 == 0 then evens := x :: evens else odds := x :: odds return (evens, odds) theorem ex8 : split [1, 2, 3, 4] = ([2, 4], [1, 3]) := rfl def f3 (x : Nat) : IO Bool := do let y ← cond (x == 0) (do IO.println "hello"; true) false; !y def f4 (x y : Nat) : Nat × Nat := do let mut (x, y) := (x, y) match x with | 0 => y := y + 1 | _ => x := x + y return (x, y) #eval f4 0 10 #eval f4 5 10 theorem ex9 (y : Nat) : f4 0 y = (0, y+1) := rfl theorem ex10 (x y : Nat) : f4 (x+1) y = ((x+1)+y, y) := rfl def f5 (x y : Nat) : Nat × Nat := do let mut (x, y) := (x, y) match x with | 0 => y := y + 1 | z+1 => dbgTrace! "z: {z}"; x := x + y return (x, y) #eval f5 5 6 theorem ex11 (x y : Nat) : f5 (x+1) y = ((x+1)+y, y) := rfl def f6 (x : Nat) : Nat := do let mut x := x if x > 10 then return 0 x := x + 1 return x theorem ex12 : f6 11 = 0 := rfl theorem ex13 : f6 5 = 6 := rfl def findOdd (xs : List Nat) : Nat := do for x in xs do if x % 2 == 1 then return x return 0 theorem ex14 : findOdd [2, 4, 5, 8, 7] = 5 := rfl theorem ex15 : findOdd [2, 4, 8, 10] = 0 := rfl def f7 (ref : IO.Ref (Option (Nat × Nat))) : IO Nat := do let some (x, y) ← ref.get | pure 100 IO.println (toString x ++ ", " ++ toString y) return x+y def f7Test : IO Unit := do unless (← f7 (← IO.mkRef (some (10, 20)))) == 30 do throw $ IO.userError "unexpected" unless (← f7 (← IO.mkRef none)) == 100 do throw $ IO.userError "unexpected" #eval f7Test def f8 (x : Nat) : IO Nat := do let y ← if x == 0 then IO.println "x is zero" return 100 -- returns from the `do`-block else pure (x + 1) IO.println ("y: " ++ toString y) return y def f8Test : IO Unit := do unless (← f8 0) == 100 do throw $ IO.userError "unexpected" unless (← f8 1) == 2 do throw $ IO.userError "unexpected" #eval f8Test
5bd740b61bd32bf34acf34ce69a2607351f43e5a
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Init.lean
40dcc8541cbc55559db4fc2baafd7eb7afce9782
[ "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
553
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Prelude import Init.Notation import Init.Tactics import Init.Core import Init.Control import Init.Data.Basic import Init.WF import Init.WFTactics import Init.Data import Init.System import Init.Util import Init.Dynamic import Init.ShareCommon import Init.Meta import Init.NotationExtra import Init.SimpLemmas import Init.Hints import Init.Conv import Init.SizeOfLemmas